chore: 项目基线(基于 WeKnora 定制版,整理文件忽略规则)

This commit is contained in:
runny committed 2026-11-13 17:54:56 +08:00
commit 9097ee699d
5769 files changed
+1446466

No files matched your search

+49
View File
@@ -0,0 +1,49 @@
root = "."
testdata_dir = "testdata"
tmp_dir = "tmp"
[build]
args_bin = []
bin = "./tmp/main"
cmd = "go build -tags \"${GO_BUILD_TAGS}\" -ldflags=\"$(./scripts/get_version.sh ldflags) -X 'google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=warn'\" -o ./tmp/main ./cmd/server"
delay = 1000
exclude_dir = ["assets", "tmp", "vendor", "testdata", "frontend", "migrations", "node_modules", "docs", "logs", "data", "WeKnora-Chrome-Extension", "Formula", "dataset", "docreader", "docker", "llm_debug", "web", "mcp-server", "misc", "scripts", "dist", "client", "helm", "website-docs"]
exclude_file = []
exclude_regex = ["_test.go"]
exclude_unchanged = false
follow_symlink = false
# 使用 full_bin 来设置环境变量(从父进程继承)
full_bin = ""
include_dir = []
include_ext = ["go", "tpl", "tmpl", "html", "yaml"]
include_file = []
kill_delay = "2s"
log = "build-errors.log"
poll = false
poll_interval = 0
rerun = false
rerun_delay = 500
send_interrupt = false
stop_on_error = false
[color]
app = ""
build = "yellow"
main = "magenta"
runner = "green"
watcher = "cyan"
[log]
main_only = false
time = false
[misc]
clean_on_exit = true
[screen]
clear_on_rebuild = false
keep_scroll = true
[cmd]
# 重启前执行的清理命令
stop = "sudo lsof -t -i :18080 | xargs -r sudo kill -9"
+76
View File
@@ -0,0 +1,76 @@
# VCS / CI
.git/
.github/
.gitignore
.gitattributes
# 编辑器 / IDE 本地配置
.cursor/
.claude/
.codebuddy/
.vscode/
.idea/
*.swp
*.swo
.DS_Store
# Python 虚拟环境 / 缓存
**/.venv/
.venv_proto/
**/.python-version
**/__pycache__/
**/*.pyc
# Node / 前端
# 注意:build-ui 用的 context 是 ./frontend,根 .dockerignore 对它无效,
# 其它镜像(app/docreader/sandbox)的 Dockerfile 都不引用 frontend/,
# 所以这里可以直接排除整个 frontend/ 目录。
**/node_modules/
frontend/
WeKnora-Chrome-Extension/
# 日志 / 临时文件
logs/
tmp/
temp/
*.log
*.pid
# 本地构建产物 / 二进制
WeKnora
WeKnora-lite
/server
/dist/
/build/
cmd/desktop/build/bin/
# 本地数据 / 模型文件
/models/
data/files/
data/*.db
data/*.db-wal
data/*.db-shm
test/data/mswag.txt
# 敏感文件
.env
.env.lite
*.pem
*.key
*.crt
*_key
*_secret
# 大的归档/压缩包
packages/protoc-*.zip
!packages/protoc-*-linux-x86_64.zip
!packages/protoc-*-linux-aarch_64.zip
!packages/protoc-*-linux-arm.zip
# 本地测试脚本
configure-ollama.sh
fix-docker.sh
/scripts/scale_dev_jobs.sh
# 注意:不要排除 docs/ —— 里面的 docs.go / swagger.json 是 Go 代码依赖的 swagger 包
# 注意:不要用 *.md 通配排除 —— skills/preloaded/**/SKILL.md 会被打进镜像给 agent 用
+884
View File
@@ -0,0 +1,884 @@
# =====================================================================
# WeKnora 环境变量配置示例
# ---------------------------------------------------------------------
# 使用说明:
# 1. 复制此文件为 .env:cp .env.example .env
# 2. 替换所有占位符为实际值(尤其标 ⚠️ 必填 的项)
# 3. 确保 .env 不会被提交到版本控制
#
# 配置注入机制:
# - app 服务通过 env_file: .env 读取本文件全部变量;
# - docreader / mcp / frontend / odl-hybrid 服务无 env_file,仅消费各自
# environment 段显式列出的变量(见 docker-compose.yml)。
#
# 分组顺序:
# A. 部署基础 镜像、运行时、网络
# B. 数据与存储 数据库、Redis、文件存储、对象存储
# C. 检索与图谱 向量库、知识图谱
# D. 模型 LLM/VLM/Ollama、内置模型
# E. 文档解析 Docreader、任务超时
# F. 认证与空间隔离 JWT/AES、注册、RBAC、OIDC
# G. Agent 与沙箱 Sandbox、Skills、Agent 超时
# H. 可选集成 网络搜索、MCP Server
# I. 可观测性 Langfuse
# J. 安全与调优 SSRF、代理、并发
# =====================================================================
# #####################################################################
# A. 部署基础
# #####################################################################
# ========== A1. 镜像版本与构建 ==========
# WeKnora 镜像版本标签:latest(稳定版)/ main(最新开发版)。升级到固定版本时,请填写目标 release 的 git tag(如 v0.7.0,注意 v 前缀),并执行 docker compose pull 拉取对应镜像。
WEKNORA_VERSION=latest
# Debian APT 镜像源主机名(构建 app 镜像用,留空用默认源;国内可设 mirrors.tencent.com 加速)。
APK_MIRROR_ARG=mirrors.tencent.com
# 构建 app 镜像时是否链接 anydoc 进程内解析引擎(默认 1)。设 0 可跳过 Rust 工具链、缩短构建时间,引擎在设置页显示为不可用。
# WITH_ANYDOC=1
# docreader 镜像构建时 apt 镜像源(留空用默认源)。
# APT_MIRROR=
# docreader 镜像构建时 Playwright 浏览器制品源(留空用官方 CDN)。
# PLAYWRIGHT_DOWNLOAD_HOST=
# 仅覆盖 WebKit 制品源,设置后优先于 PLAYWRIGHT_DOWNLOAD_HOST。
# PLAYWRIGHT_WEBKIT_DOWNLOAD_HOST=
# 从源码构建 frontend 镜像时写入系统信息页的短 commit。make docker-build-frontend
# 与 start_all.sh --no-pull 会从 git 自动填充;直接 docker compose build 时请自行导出,否则显示 unknown。
# VITE_FRONTEND_COMMIT=
# 构建 frontend 镜像时的 npm registry(留空用默认源;国内可设 https://registry.npmmirror.com)。
# NPM_REGISTRY=
# Vite 构建 Node 堆上限(MB)。Docker Desktop 分配内存较小时可降到 2048。
# NODE_MAX_OLD_SPACE_SIZE=4096
# ========== A2. 运行时基础 ==========
# gin 运行模式:debug(开发,详细日志 + Swagger)/ release(生产,禁用 Swagger)。
GIN_MODE=release
# 日志级别:debug / info / warn / error / fatal,默认 debug。
# LOG_LEVEL=debug
# 日志文件路径(留空只输出 stdout);LLM_DEBUG_LOG 开启时同目录写 llm_debug.log。
# LOG_PATH=
# 自定义日志格式模板,必须包含 %msg(留空用内置默认格式;不支持 json 关键字)。
# 未设置时兼容旧 LOG_FORMAT;显式设置为空可禁用旧变量。
# WEKNORA_LOG_FORMAT=
# LLM 调试日志:把每次大模型调用的完整请求/响应写入独立文件,排查上下文问题用。
# 可选值:true(写 LOG_PATH 同目录 llm_debug.log)/ false/空(关闭)/ 指定文件路径。
# LLM_DEBUG_LOG=true
# 时区,默认 Asia/Shanghai。影响系统时间显示与日志时间戳。
# 常用值:Asia/Shanghai, Asia/Tokyo, America/New_York, Europe/London, UTC。
TZ=Asia/Shanghai
# 系统默认语言(BCP-47),用于 Prompt 中 {{language}} 占位符回退。
# 优先级:Accept-Language 请求头 > 此变量 > 内置默认值 (en-US)。
# WEKNORA_LANGUAGE=zh-CN
# 前端界面默认语言(BCP-47)。可选:zh-CN | zh-TW | en-US | ru-RU | ko-KR | ja-JP。
# 优先级:用户已选语言(localStorage) > 此变量 > 内置默认 zh-CN。
# 仅影响首次访问/未手动切换语言的用户;改完重启 frontend 容器即生效,无需重建镜像。
# DEFAULT_LOCALE=en-US
# 构建前端镜像时的默认语言回退(仅在不使用 Docker 运行时 config.js 时生效)。
# VITE_DEFAULT_LOCALE=en-US
# 启动时自动执行数据库迁移;设 false 禁用(默认启用)。
AUTO_MIGRATE=true
# 自动恢复脏数据迁移状态(默认 true)。
AUTO_RECOVER_DIRTY=true
# 启动时自动把指定 email 的用户提升为系统管理员(幂等;仅 PROMOTE 从不 DEMOTE)。
# 适用于 docker-compose/k8s 首次自举;后续提权/撤销走 SystemAdmin 管理页。
# WEKNORA_BOOTSTRAP_SYSTEM_ADMIN_EMAIL=
# ========== A3. 网络与外部地址 ==========
# 应用服务主机名,默认 app(Docker 内部服务名);远程后端可设远程地址。
APP_HOST=app
# 应用服务宿主机映射端口,默认 8080(仅影响宿主机访问,不影响容器间通信)。
APP_PORT=8080
# NGINX 代理到后端的目标端口,默认 8080(App 容器内部监听端口)。
# 本地部署保持默认;远程部署设为远程 App 服务的实际端口。
# APP_BACKEND_PORT=8080
# NGINX 代理到后端的协议,默认 http;远程后端为 HTTPS 时设 https。
# APP_SCHEME=http
# 前端服务端口,默认 80。
FRONTEND_PORT=80
# Docreader 地址(app 连接 docreader 用)。
DOCREADER_ADDR=docreader:50051
# Docreader 连接方式:grpc / http / https。
DOCREADER_TRANSPORT=grpc
# 应用外部访问地址(影响 IM 渠道的图片/文件外链)。
# 设为 WeKnora 实例「IM 平台/客户端公网可达」的 URL,如 https://weknora.example.com。
# IM 要显示知识库图片,需让 IM 端能通过公网 http URL 拿到图,二选一:
# (A) 存储后端本身公网可达(对象存储用公网 endpoint,或 MINIO_ENDPOINT 设为公网 host);
# 此时 resource:// 回退到后端预签名 URL,无需本变量。
# (B) 设本变量,resource:// 图片改写成 <APP_EXTERNAL_URL>/r/<token> 走 WeKnora(需 nginx 代理 /r/)。
# 默认 MinIO 部署(minio:9000 为内网)走 (B) 最简单;local 后端只能走 (B)。
# 内网 IP 和 localhost 对飞书/企微/Slack 等 IM 平台不可达;本地开发请用 ngrok/cloudflared/frp。
# APP_EXTERNAL_URL=
# 前端外部 origin,用于邀请链接等绝对 URL(留空走 host-relative)。
# FRONTEND_BASE_URL=
# API 响应里文件引用的默认形式:handle(默认)/ public。
# handle — 返回内部 resource://<handle>,客户端需再调用带鉴权的 /files 代理取图。
# public — 直接返回可加载的 http(s) 链接,第三方 App 拿到即可渲染,无需二次请求。
# 单次请求可用 ?resource_urls=handle|public 覆盖本变量,覆盖范围见 README「API 参考」。
# public 依赖上面的 APP_EXTERNAL_URL(或存储后端本身公网可达)才能生成外链;
# 无法生成时该引用保持 resource:// 原样,客户端仍可回退到 /files。
# 注意:public 会为每个被引用文件签发限时(WeKnora 2 小时 / MinIO 24 小时)的匿名可读链接。
# 匿名的 embed 渠道与限定知识库的 API Key 不受本变量影响,始终返回 handle。
# 建议同时配置 SYSTEM_AES_KEY,以便复用 grant 行、稳定直链 URL 并降低读接口的写入压力。
# RESOURCE_URL_MODE=handle
# 对外暴露的 MCP Server 端口(默认 8082)。
# MCP_PORT=8082
# #####################################################################
# B. 数据与存储
# #####################################################################
# ========== B1. 数据库 ⚠️ 必填 ==========
# 主数据库类型:postgres / sqlite。sqlite 供 Lite 模式使用,见 DB_PATH。
DB_DRIVER=postgres
# 数据库主机地址。
DB_HOST=postgres
# 数据库端口。
DB_PORT=5432
# 数据库用户名。
DB_USER=postgres
# 数据库密码。
DB_PASSWORD=postgres123!@#
# 数据库名称。
DB_NAME=WeKnora
# SQLite 驱动时使用(DB_DRIVER=sqlite),postgres 驱动忽略。
# DB_PATH=./data/weknora.db
# ========== B2. Redis / 流处理 / Asynq 队列 ==========
# --- 流处理后端与 Redis 连接 ---
# 流处理后端:memory / redis。redis 模式下 Asynq 任务队列也依赖此 Redis。
STREAM_MANAGER_TYPE=redis
# Redis 地址(留空表示禁用 Redis,Lite 模式用 memory)。
REDIS_ADDR=redis:6379
# Redis 用户名(Redis 6.0+ ACL,可选)。
# REDIS_USERNAME=
# Redis 密码,未设置可留空。
REDIS_PASSWORD=redis123!@#
# Redis 数据库索引,默认 0。
REDIS_DB=0
# Redis key 前缀,用于命名空间隔离。
REDIS_PREFIX=stream:
# Redis 频道命名空间后缀(多部署共享同一 Redis 时隔离用)。
# WEKNORA_REDIS_NAMESPACE=
# Asynq 客户端 Redis 读写超时(毫秒,默认 500,写可扩到 1000)。
# WEKNORA_REDIS_OP_TIMEOUT_MS=500
# --- Redis TLS(托管 Redis 加密传输,如 AWS ElastiCache;默认关闭)---
# 是否启用 TLS。
# REDIS_USE_TLS=false
# TLS 证书校验与 SNI 的服务器名(地址为 IP 时有用)。
# REDIS_TLS_SERVER_NAME=
# 跳过服务器证书校验。不安全,仅开发/自签证书用,生产禁用。
# REDIS_TLS_INSECURE_SKIP_VERIFY=false
# --- Asynq worker 并发 ---
# 每个 pool 是独立 asynq.Server,硬隔离;留空或 <1 走代码默认。值为「每实例保底并发」,多副本部署按副本数累加。也可在系统设置(asynq.*_concurrency)运行时调整,无需重启。格式:变量 = 默认值 — 消费的队列 / 说明
# default + chat_attachment(文档解析主链路;chat_attachment 权重更高,避免被批量导入挤占)
# WEKNORA_ASYNQ_CORE_CONCURRENCY=8
# postprocess(解析后的知识库后处理/fan-out;独立成池避免排在长耗时 DocReader 后,需低延迟)
# WEKNORA_ASYNQ_POSTPROCESS_CONCURRENCY=2
# summary / multimodal / graph / question(摘要、图片多模态、图谱 chunk 抽取、问题生成;LLM/VLM 重,按 provider 预算调)
# WEKNORA_ASYNQ_ENRICHMENT_CONCURRENCY=12
# sync + low(数据源同步、FAQ 导入、KB 克隆/删除、批量重解析、知识移动;长耗时,不参与 shared 借用)
# WEKNORA_ASYNQ_MAINTENANCE_CONCURRENCY=4
# 弹性池,可借用 CORE/ENRICHMENT 队列(atomic dequeue 安全);不消费 POSTPROCESS/MAINTENANCE
# WEKNORA_ASYNQ_SHARED_CONCURRENCY=6
# Wiki 生成专用池(LLM 绑定,按 provider 并发预算调整)
# WEKNORA_WIKI_ASYNQ_CONCURRENCY=8
# 后台任务每模型并发上限(0/负数禁用;交互 chat 不受其限制)
# WEKNORA_MODEL_MAX_CONCURRENCY=32
# ========== B3. 文件存储(通用)==========
# 文件存储类型:local / minio / cos / tos / s3 / obs / oss / dummy。
STORAGE_TYPE=local
# 允许用户使用的存储类型白名单(逗号分隔,留空允许全部)。
# STORAGE_ALLOW_LIST=local,minio,cos,tos,s3,obs,oss
# 本地存储根目录(STORAGE_TYPE=local 时用)。
LOCAL_STORAGE_BASE_DIR=/data/files
# 本地存储路径前缀(legacy 回填用,一般留空)。
# LOCAL_STORAGE_PATH_PREFIX=
# 统一文件大小限制(MB,默认 50)。影响知识库/附件单文件上传、docreader gRPC 消息、浏览器知识库校验。属部署期配置:Go/Nginx/docreader/浏览器四层启动时读一次,运行中改不生效,改后须同步重启四层。
# MAX_FILE_SIZE_MB=50
# 技能 zip 上传与 GitHub/ClawHub 来源下载上限(MB,默认 256)。与知识库上传分开:ppt-master 一类技能包会超过 50MB。GitHub zipball 按整仓压缩包计,不是 SKILL.md 子树;仓过大仍会在下载阶段被拒。未设置时不低于 MAX_FILE_SIZE_MB,且不超过 512。Nginx 只对 POST /api/v1/skills/catalog 与 POST /api/v1/sandbox-configs/{id}/skills 放宽到这个值,/install、PATCH 等子路径仍是 MAX_FILE_SIZE_MB。改后须重启 app 与 frontend。
# MAX_SKILL_BUNDLE_SIZE_MB=256
# ========== B4. 对象存储 provider(按 STORAGE_TYPE 选其一)==========
# ----- MinIO(STORAGE_TYPE=minio)-----
# MinIO 端点(host:port)。IM 渠道时必须是 IM 平台公网可达的 host(不能用 minio:9000)。
# MINIO_ENDPOINT=minio:9000
# MINIO_ACCESS_KEY_ID=your_minio_access_key
# MINIO_SECRET_ACCESS_KEY=your_minio_secret_key
# MINIO_BUCKET_NAME=your_minio_bucket_name
# MINIO_PATH_PREFIX=
# MINIO_USE_SSL=false
# MinIO 端口(compose 映射用)。
# MINIO_PORT=9000
# MINIO_CONSOLE_PORT=9001
# ----- 腾讯云 COS(STORAGE_TYPE=cos)-----
# COS_SECRET_ID=your_cos_secret_id
# COS_SECRET_KEY=your_cos_secret_key
# COS_REGION=ap-guangzhou
# COS_BUCKET_NAME=your_cos_bucket_name
# COS_APP_ID=your_cos_app_id
# COS_PATH_PREFIX=your_cos_path_prefix
# COS_TEMP_BUCKET_NAME=your_cos_temp_bucket_name
# COS_TEMP_REGION=your_cos_temp_region
# ----- 火山引擎 TOS(STORAGE_TYPE=tos)-----
# TOS_ENDPOINT=https://tos-cn-beijing.volces.com
# TOS_REGION=cn-beijing
# TOS_ACCESS_KEY=your_tos_access_key
# TOS_SECRET_KEY=your_tos_secret_key
# TOS_BUCKET_NAME=your_tos_bucket_name
# TOS_PATH_PREFIX=your_tos_path_prefix
# TOS_TEMP_BUCKET_NAME=your_tos_temp_bucket_name
# TOS_TEMP_REGION=your_tos_temp_region
# 如果使用AWS S3作为文件存储,需要配置以下参数
# AWS S3的访问端点(可选;留空使用 Region 对应的 AWS 标准端点,例如 https://s3.amazonaws.com)
# ----- AWS S3(STORAGE_TYPE=s3)-----
# S3_ENDPOINT=https://s3.amazonaws.com
# S3_REGION=us-east-1
# AWS S3访问密钥 Access Key(可选;AK/SK 同时留空时使用 AWS SDK 默认凭证链,
# 支持 EC2/ECS/EKS IAM Role、IRSA/Web Identity、环境变量和共享配置文件)
# AWS S3访问密钥 Secret Key(必须与 Access Key 同时填写或同时留空)
# S3_SECRET_KEY=your_s3_secret_key
# S3_ACCESS_KEY=your_s3_access_key
# S3_BUCKET_NAME=your_s3_bucket_name
# S3_PATH_PREFIX=weknora/
# S3_USE_SSL=true
# S3_FORCE_PATH_STYLE=false
# ----- 华为云 OBS(STORAGE_TYPE=obs)-----
# OBS_ENDPOINT=obs.cn-north-4.myhuaweicloud.com
# OBS_REGION=cn-north-4
# OBS_ACCESS_KEY=your_obs_access_key
# OBS_SECRET_KEY=your_obs_secret_key
# OBS_BUCKET_NAME=your_obs_bucket_name
# OBS_PATH_PREFIX=weknora/
# OBS_USE_SSL=true
# OBS_PROXY_DOMAIN=https://your-domain.com/obs
# ----- 阿里云 OSS(STORAGE_TYPE=oss)-----
# OSS_ENDPOINT=oss-cn-hangzhou.aliyuncs.com
# OSS_REGION=cn-hangzhou
# OSS_ACCESS_KEY=your_oss_access_key
# OSS_SECRET_KEY=your_oss_secret_key
# OSS_BUCKET_NAME=your_oss_bucket_name
# OSS_PATH_PREFIX=weknora/
# OSS_TEMP_BUCKET_NAME=your_oss_temp_bucket_name
# OSS_TEMP_REGION=your_oss_temp_region
# #####################################################################
# C. 检索与图谱
# #####################################################################
# ========== C1. 向量库 / 检索引擎 ==========
# 向量存储类型(逗号分隔可多驱动):postgres / elasticsearch_v7 / elasticsearch_v8 /
# opensearch / qdrant / milvus / weaviate / doris / tencent_vectordb。
RETRIEVE_DRIVER=postgres
# 多向量库并行检索超时(秒,RETRIEVE_DRIVER 含多个驱动时生效)。
# MULTI_STORE_RETRIEVE_TIMEOUT_SEC=
# ----- Elasticsearch v7/v8 -----
# ELASTICSEARCH_ADDR=http://localhost:9200
# ELASTICSEARCH_USERNAME=your_elasticsearch_username
# ELASTICSEARCH_PASSWORD=your_elasticsearch_password
# ELASTICSEARCH_INDEX=WeKnora
# ----- OpenSearch(dev compose 自带单节点 profile)-----
# OPENSEARCH_ADDR=http://opensearch:9200
# OPENSEARCH_USERNAME=
# OPENSEARCH_PASSWORD=
# OPENSEARCH_INSECURE_SKIP_VERIFY=false
# OPENSEARCH_INDEX=WeKnora
# ----- Qdrant -----
# QDRANT_HOST=qdrant
# QDRANT_PORT=6334
# QDRANT_REST_PORT=6333
# QDRANT_COLLECTION=weknora_embeddings
# QDRANT_API_KEY=your_qdrant_api_key
# QDRANT_USE_TLS=false
# ----- Milvus -----
# MILVUS_ADDRESS=milvus:19530
# MILVUS_COLLECTION=weknora_embeddings
# MILVUS_METRIC_TYPE=IP # IP(默认)/COSINE/L2,改后需重建 collection。
# 新版 Collection 会为 content 配置 english/chinese/default 多语言分析器;
# 旧 Collection 请先运行 go run ./cmd/milvus-migrate(metric 沿用源 Collection),
# 再把 MILVUS_COLLECTION 改为目标前缀,不要改 MILVUS_METRIC_TYPE。
# MILVUS_USERNAME=your_milvus_username
# MILVUS_PASSWORD=your_milvus_password
# MILVUS_DB_NAME=your_milvus_db_name
# ----- Weaviate -----
# 容器内访问用 service:port(不要用 localhost/宿主机映射端口)。
# WEAVIATE_HOST=weaviate:8080
# WEAVIATE_GRPC_ADDRESS=weaviate:50051
# WEAVIATE_SCHEME=http
# WEAVIATE_AUTH_ENABLED=false # 启用 APIKey/OIDC 时再设 true 并配 WEAVIATE_API_KEY。
# WEAVIATE_API_KEY=your_secret_key
# WEAVIATE_COLLECTION=your_weaviate_db_name
# ----- Apache Doris 4.1+ -----
# DORIS_ADDR=doris-fe:9030 # FE MySQL 协议地址。
# DORIS_HTTP_PORT=8030 # FE HTTP,Stream Load partial update 入口。
# DORIS_DATABASE=weknora
# DORIS_USERNAME=root
# DORIS_PASSWORD=
# DORIS_TABLE_PREFIX=weknora_embeddings
# DORIS_COMPAT_MODE=auto # auto(探测)/legacy(cosine_distance)/inner_product_duplicate;建表后不可互换。
# compose 端口。
# DORIS_FE_HTTP_PORT=8030
# DORIS_FE_MYSQL_PORT=9030
# DORIS_BE_HTTP_PORT=8040
# ----- 腾讯云 Tencent VectorDB -----
# TENCENT_VECTORDB_ADDR=http://your-instance.tencentvectordb.com
# TENCENT_VECTORDB_USERNAME=root
# TENCENT_VECTORDB_API_KEY=your_tencent_vectordb_api_key
# TENCENT_VECTORDB_DATABASE=weknora
# TENCENT_VECTORDB_COLLECTION=weknora_embeddings
# TENCENT_VECTORDB_REPLICA_NUMBER=1
# ========== C2. 知识图谱(Neo4j,可选)==========
# 知识图谱唯一全局开关。非 true 则禁用图谱构建与检索(构建阶段需调用大模型,耗时较长)。
# 注:ENABLE_GRAPH_RAG 自 v0.1.6 起已被 NEO4J_ENABLE 取代,Go 主应用不再读取,已移除。
# NEO4J_ENABLE=false
# Neo4j 连接 URI。bolt:// 直连单机(推荐,无路由开销);neo4j:// 走集群路由发现(单机也能用但多一次探测)。
# WeKnora 默认部署单机 Neo4j,故用 bolt://。
# NEO4J_URI=bolt://neo4j:7687
# NEO4J_USERNAME=neo4j
# NEO4J_PASSWORD=password
# #####################################################################
# D. 模型
# #####################################################################
# ========== D1. LLM / VLM / Ollama ==========
# Ollama 不可用时仅告警不阻断(true 时生效,默认不阻断,避免未配 Ollama 就启动失败)。
OLLAMA_OPTIONAL=true
# 本地 Ollama 的唯一地址。source=local 的向量模型与对话模型共用这一进程,
# 不需要为 embedding 再起一个 Ollama。未设置时进程回退到 http://localhost:11434。
# 向量模型名不是环境变量:在「设置 → 模型」、CLI 或初始化接口里把 Embedding
# 模型的 name 设为 Ollama 模型名(如 nomic-embed-text)。见 README 的 Ollama 说明。
OLLAMA_BASE_URL=http://host.docker.internal:11434
# 批量 embedding 大小(留空走代码默认)。
# BATCH_EMBED_SIZE=
# 知识库描述生成的补全 token 预算(留空走代码默认 2048)。推理型模型即使关闭思考
# 也可能耗尽小预算导致描述生成失败(报 no gist),遇到时可调大此值。
# KNOWLEDGE_BASE_PROFILE_MAX_TOKENS=
# VLM 单次 HTTP 请求超时(秒,默认 180;慢端点超时报 context deadline 时调大)。
# VLM_HTTP_TIMEOUT_SECONDS=180
# LLM 流原始转储(排查上下文问题;1 启用,默认目录 ~/.weknora/investigate/llm-stream)。
# WEKNORA_LLM_STREAM_RAW_DUMP=
# WEKNORA_LLM_STREAM_RAW_DUMP_DIR=
# ========== D2. 内置模型声明式配置(可选)==========
# 启用 config/builtin_models.yaml(见 config/builtin_models.yaml.example)后,YAML 中的
# ${NAME} 占位符会在应用启动期从这里读取真实值。变量名由 YAML 自定,下面给出常见命名参考。
# 详见 website-docs/03-features/06-models.md。
#
# 内置对话模型
# LLM_MODEL_NAME=
# LLM_BASE_URL=
# LLM_API_KEY=
# LLM_PROVIDER=openai
#
# 内置向量模型。下面的名字只有写进 builtin_models.yaml 的 ${...} 才会被读取。
# 本地 Ollama 向量模型用 source: local,name 用 ${EMBEDDING_MODEL_NAME}(Ollama 模型名);
# 地址仍是上面的 OLLAMA_BASE_URL。EMBEDDING_BASE_URL 只用于 source: remote 的 API。
# 示例见 config/builtin_models.yaml.example 的 “one local Ollama” 段。
# EMBEDDING_MODEL_NAME=
# EMBEDDING_BASE_URL=
# EMBEDDING_API_KEY=
# EMBEDDING_PROVIDER=openai
#
# 内置 Rerank 模型
# RERANK_MODEL_NAME=
# RERANK_BASE_URL=
# RERANK_API_KEY=
# RERANK_PROVIDER=generic
# #####################################################################
# E. 文档解析
# #####################################################################
# ========== E1. Docreader gRPC 与解析通用 ==========
# ----- gRPC 服务端 TLS / 认证(docreader 与 app 共用,客户端/服务端需配相同值)-----
# 启用 gRPC TLS 加密传输。默认 false(docreader 仅在 compose 内网供 app 调用,明文即可)。
# GRPC_TLS_ENABLED=false
# 服务端证书 / 客户端证书(mTLS 时填)。server 启用 TLS 时必填。
# GRPC_TLS_CERT=/path/to/server.crt
# 证书对应私钥。
# GRPC_TLS_KEY=/path/to/server.key
# CA 证书:client 用于校验 server 证书;server 端 mTLS 时用于签发客户端证书的 CA。
# GRPC_TLS_CA=/path/to/ca.crt
# TLS SNI / 证书校验名。DOCREADER_ADDR 用 IP、或与证书 CN 不一致时,设为证书里的 hostname。
# GRPC_TLS_SERVER_NAME=
# server 端:true 时强制要求客户端提供证书(双向 TLS / mTLS)。
# GRPC_MTLS_REQUIRE_CLIENT_CERT=false
# gRPC per-RPC 认证 token(客户端/服务端需一致)。启用时强烈建议同时开 TLS,
# 否则 token 会明文随每次 RPC 传输;GRPC_TLS_ENABLED=true 时客户端会拒绝在不安全连接上发送 token。
# GRPC_AUTH_TOKEN=your-secret-token-at-least-16-bytes
# ----- gRPC 服务参数 -----
# gRPC server 最大并发 worker 数(默认 4)。
# DOCREADER_GRPC_MAX_WORKERS=4
# Optional RapidOCR preprocessing: the knowledge-base switch defaults to off.
# Limits are per docreader replica; memory is per child (MiB). Busy/limited jobs use the original image.
# Detection runs on a copy capped at PROBE_EDGE; the crop is taken from the original and capped at MAX_EDGE.
# DOCREADER_PREPROCESS_MAX_WORKERS=1
# DOCREADER_PREPROCESS_TIMEOUT_SECONDS=30
# DOCREADER_PREPROCESS_THREADS=2
# DOCREADER_PREPROCESS_MEMORY_MB=2048
# DOCREADER_PREPROCESS_MAX_PIXELS=16000000
# DOCREADER_PREPROCESS_MAX_EDGE=2000
# DOCREADER_PREPROCESS_PROBE_EDGE=2000
# gRPC 单条消息大小上限(MB,默认 50)。通常跟随 MAX_FILE_SIZE_MB;过大扫描件图可能超此值。
# DOCREADER_GRPC_MAX_FILE_SIZE_MB=50
# gRPC 监听端口(默认 50051)一般无需修改,需要与docker-compose中的docreader port保持一致。
# DOCREADER_GRPC_PORT=50051
# ----- 解析通用 -----
# DOCX 解析最大页数(默认 0=不限制)。设正整数(如 500)可限制超大 Word 文档解析开销。
# DOCREADER_DOCX_MAX_PAGES=0
# MarkItDown(重型解析器)并发 worker 数。0 关闭限流;默认 1 适合单机/GPU 受限。
# DOCREADER_MARKITDOWN_MAX_WORKERS=1
# 上传的 HTML 文件是否只索引正文(trafilatura 抽取,抽取不足时回退整页转换)。
# 默认 false:整页转换,导航/侧栏/页脚也会进索引(与升级前一致)。
# DOCREADER_HTML_MAIN_CONTENT=false
# ----- XLSX / Excel -----
# 按显示格式物化百分比单元格。Excel 的百分比是显示格式而非存储值:单元格实存 0.6112,
# 靠 "0.00%" 渲染成 61.12%,而 pandas/openpyxl 只读到分数,报表里的 61.12% 变成 0.6112
# (100 倍偏差)。开启后百分比单元格变成字面量文本 "61.12%"。默认 false:开启会使单元格
# 由数值变为字符串,改变下游排序/计算看到的内容;关闭时读取行为与升级前完全一致。
# 单次上传可用 parser_engine_overrides.xlsx_percent_as_text 覆盖(true/false)。
# DOCREADER_XLSX_PERCENT_AS_TEXT=false
# 兜底:同一行有 >= N 个显式百分比格式单元格时,把该行漏标格式的 0<|v|<1 数字也按百分比
# 处理(源文件偶有漏刷格式的格子,每命中一次打 INFO 日志)。仅在上一开关开启时生效;
# 0=关闭该兜底(默认)。
# DOCREADER_XLSX_PCT_ROW_HINT_MIN=0
# 出站 HTTP/HTTPS 代理(抓取网页 / 远程图片时用)。
# DOCREADER_EXTERNAL_HTTP_PROXY=
# DOCREADER_EXTERNAL_HTTPS_PROXY=
# ========== E2. OpenDataLoader hybrid(可选,知识库 parser_engine_rules 指定 engine: opendataloader)==========
# ODL 重型解析器并发(默认 1)。
# DOCREADER_ODL_MAX_WORKERS=1
# hybrid 模式开关:off(默认,纯 fast 本地解析)/ docling-fast 等(需另起 odl-hybrid 容器)。
# DOCREADER_ODL_HYBRID=off
# odl-hybrid 服务地址。代码默认 http://127.0.0.1:5002;docker compose 注入 http://odl-hybrid:5002。
# DOCREADER_ODL_HYBRID_URL=http://odl-hybrid:5002
# hybrid 模式选择(auto),一般无需改。
# DOCREADER_ODL_HYBRID_MODE=auto
# hybrid 失败时是否回退到 fast 模式(默认 false)。
# DOCREADER_ODL_HYBRID_FALLBACK=false
# hybrid 输出 markdown 是否保留 HTML(默认 false)。
# DOCREADER_ODL_MARKDOWN_WITH_HTML=false
# ----- odl-hybrid 容器参数(仅 --profile odl-hybrid 时用)-----
# 传给 odl-hybrid 的额外参数。默认 --no-ocr(数字 PDF);扫描件用 --force-ocr(需 EasyOCR+libGL)。
# ODL_HYBRID_EXTRA_ARGS=--no-ocr
# odl-hybrid 对外端口(dev compose 映射用)。
# ODL_HYBRID_PORT=5002
# app 启动时等待 odl-hybrid 就绪的最长时间(秒)。
# ODL_HYBRID_STARTUP_WAIT_SEC=180
# ========== E3. PDF 渲染 ==========
# PDF 渲染 worker 数(跨文档并发,默认 1)。
# DOCREADER_PDF_RENDER_MAX_WORKERS=1
# 单个 PDF 内部「扫描页渲染」的并行进程数(pdfium 非线程安全,按进程并行)。默认随 CPU 取min(4, cpu);大体量扫描件串行渲染在 CPU 受限容器上可能耗时数小时,调大可显著缩短(实测874 页 117s->30s/4 进程 ->17s/8 进程)。容器需分配足够 CPU 才能吃到加速。
# DOCREADER_PDF_RENDER_PARALLELISM=4
# 渲染 DPI(默认 200)。
# DOCREADER_PDF_RENDER_DPI=200
# 渲染图 JPEG 质量(默认 85)。
# DOCREADER_PDF_JPEG_QUALITY=85
# 渲染页图的最大长边像素(默认 2000)。防止超大页面渲染出 100+MP 图撑爆 gRPC 消息上限;调小可进一步减小图片体积,过小会影响 OCR 识别(密集中文建议 >=1600)。
# DOCREADER_PDF_RENDER_MAX_EDGE=2000
# ========== E4. PDF 扫描件判定与强制 ==========
# 强制所有 PDF 全页按扫描件解析(渲染成图片再走 OCR/VLM)。适合文本层质量差但页面可 OCR 的PDF;开启后速度和模型调用成本都会上升。默认 false(由下方阈值自动判定)。
# DOCREADER_PDF_FORCE_SCANNED=false
# 自动判定:一页的图片对象覆盖面积 >= 此比例视为扫描页(默认 0.5)。
# DOCREADER_PDF_SCAN_IMAGE_RATIO=0.5
# 自动判定:一页文本字符数少于此值视为「无可用文本层」(默认 10)。
# DOCREADER_PDF_SCAN_MIN_CHARS=10
# ========== E5. PDF 版式 / 文本抽取(原生文本页)==========
# 版式感知文本抽取:重建可读阅读顺序(默认 true)。
# DOCREADER_PDF_LAYOUT_ORDERING=true
# glyph 无显式空格定位时(OCR/搜索文本常见),间距超过 median 字宽的多少倍时插空格(默认 0.4)。
# DOCREADER_PDF_WORD_GAP_WIDTH_RATIO=0.4
# 丢弃窄边栏(arXiv 侧栏水印、页码标签)的页宽比例阈值(默认 0.12)。
# DOCREADER_PDF_MARGIN_COL_WIDTH_RATIO=0.12
# 一行至少多少字符才允许字体大小启发式将其提升为 markdown 标题(默认 8)。
# DOCREADER_PDF_MIN_HEADING_LINE_CHARS=8
# 把视觉上较大的行提升为 markdown 标题(用 rect 高度做字体大小代理,默认 true)。
# DOCREADER_PDF_DETECT_HEADINGS=true
# 丢弃不可见文本(render-mode 3)、页外文本和退化文本,防 hidden-text 注入(默认 true)。
# DOCREADER_PDF_FILTER_HIDDEN_TEXT=true
# 清理 pdfium 占位符(U+FFFE)和软连字符;剥离矢量图坐标轴/图例文字(默认 true)。
# DOCREADER_PDF_SANITIZE_TEXT=true
# 剥离图表区碎片文本(与 SANITIZE_TEXT 配合,默认 true)。
# DOCREADER_PDF_STRIP_CHART_DEBRIS=true
# ========== E6. PDF 嵌入图片抽取(原生文本页)==========
# 抽取原生页面里的嵌入位图供 VLM/OCR 分析(默认 true)。
# DOCREADER_PDF_EXTRACT_EMBEDDED_IMAGES=true
# 嵌入图片保留的最小像素宽与高(默认 80,低于则丢弃)。
# DOCREADER_PDF_EMBED_MIN_PIXELS=80
# 嵌入图片占页面面积的最小比例,低于则丢弃(默认 0.01)。
# DOCREADER_PDF_EMBED_MIN_AREA_RATIO=0.01
# 同一张图在文本页中出现比例 >= 此值时视为页眉页脚等运行项并去重(默认 0.5)。
# DOCREADER_PDF_EMBED_REPEAT_PAGE_FRAC=0.5
# 每篇文档抽取嵌入图片的硬上限(默认 50)。
# DOCREADER_PDF_EMBED_MAX_IMAGES=50
# ========== E7. PDF 图表区识别(矢量图区域)==========
# 把检测到的矢量图表区(无嵌入位图)渲染成 JPEG 供 VLM/OCR(默认 true)。
# DOCREADER_PDF_RENDER_VECTOR_FIGURES=true
# 一个区域被视为图表所需的每行最少字符数(默认 18)。
# DOCREADER_PDF_MIN_CHART_REGION_CHARS=18
# 一个区域被视为图表所需的最小面积占比(默认 0.015)。
# DOCREADER_PDF_MIN_CHART_REGION_AREA=0.015
# 一个区域被视为图表的最大面积占比(超过则不当图表,默认 0.42)。
# DOCREADER_PDF_MAX_CHART_REGION_AREA=0.42
# 图形高度占页高的最大比例,超过则不当作独立图表(默认 0.38)。
# DOCREADER_PDF_MAX_FIGURE_HEIGHT_RATIO=0.38
# ========== E8. 文档处理 / 任务超时 ==========
# 单文档处理任务总超时(Go duration,默认 2h;大文件可调大)。
# WEKNORA_DOCUMENT_PROCESS_TIMEOUT=2h
# 单次 DocReader RPC 超时(默认 30m,须小于上一项)。
# WEKNORA_DOCREADER_CALL_TIMEOUT=30m
# 自建 PaddleOCR-VL HTTP 请求超时(正数 Go duration,默认 1000s;无效值回退默认值)。
# 大文件示例:本项 90m、DocReader 100m、单文档任务 2h,外层超时需留余量。
# WEKNORA_PADDLEOCR_VL_TIMEOUT=1000s
# 自建 MinerU 单次解析超时(正数 Go duration,默认 1000s;无效值回退默认值)。
# 超大 PDF 同样需要外层留余量,例如本项 90m、DocReader 100m、单文档任务 2h。
# WEKNORA_MINERU_TIMEOUT=1000s
# MinerU 云端(mineru.net)轮询解析结果的最长时间(正数 Go duration,默认 600s)。
# WEKNORA_MINERU_CLOUD_TIMEOUT=600s
# PaddleOCR-VL 云端(AI Studio)轮询解析结果的最长时间(正数 Go duration,默认 600s)。
# WEKNORA_PADDLEOCR_VL_CLOUD_TIMEOUT=600s
# WeKnoraCloud 托管 docreader 轮询任务结果的最长时间(正数 Go duration,默认 20m;应小于 WEKNORA_DOCREADER_CALL_TIMEOUT)。
# WEKNORA_WEKNORACLOUD_TIMEOUT=20m
# 知识库巡检回收(回收卡在 processing 的脏数据;false 禁用,不建议)。
# WEKNORA_HOUSEKEEPING_ENABLED=true
# 聊天附件解析产物保留时长(小时,默认 24)。
# WEKNORA_CHAT_ATTACHMENT_TTL_HOURS=24
# 单轮问答等待附件解析完成的最长时间(秒,默认 60;大/扫描件调大)。
# WEKNORA_CHAT_ATTACHMENT_WAIT_TIMEOUT_SEC=60
# 附件 VLM OCR 调优(扫描件/图片型文档):并发数 / 最大页数。
# WEKNORA_CHAT_ATTACHMENT_OCR_CONCURRENCY=8
# WEKNORA_CHAT_ATTACHMENT_OCR_MAX_PAGES=8
# ========== E9. 飞书云文档解析模式(已废弃,仅一个版本的兼容) ==========
# 解析模式已改为在知识库 → 数据源编辑页按数据源配置(settings.parse_mode,默认
# blocks)。此环境变量仅在数据源未配置 parse_mode 时作为回退读取,并打印弃用
# 警告,后续版本将移除。已显式设为 export 的部署升级后行为不变;新部署请直接
# 在数据源编辑页选择解析模式。
# FEISHU_DOCX_PARSE_MODE=export
# 飞书导出创建 / 查询 / 下载、Wiki 子节点列表分别按应用共享配额(单进程)。
# 默认每个接口 80 次/分钟,平滑发送、不积累突发额度;正整数可覆盖默认值。
# FEISHU_API_REQUESTS_PER_MINUTE=80
# 限流响应没有有效等待提示时的等待时长(Go duration,默认 10s)。
# FEISHU_RATE_LIMIT_RETRY_WAIT=10s
# 每次共享冷却的最大等待时长,包含响应头提示和上述默认等待(Go duration)。
# FEISHU_RATE_LIMIT_MAX_WAIT=5m
# 导出任务最多轮询次数;限流重试及排队不消耗轮询次数,任务上下文仍可取消。
# FEISHU_EXPORT_MAX_POLLS=30
# 导出任务两次轮询之间的间隔(Go duration)。
# FEISHU_EXPORT_POLL_INTERVAL=2s
# #####################################################################
# F. 认证与空间隔离
# #####################################################################
# ========== F1. 密钥 ⚠️ 必填(生产务必改默认值)==========
# JWT 签名密钥,用于前端登录刷新 Token(留空则启动时随机生成)。
# Generate once: openssl rand -hex 32
JWT_SECRET=
# AES-256 主密钥,用于数据库中 API Key 等敏感字段落盘加密(必须为 32 字节)。
# 加密范围:tenants.api_key、模型 API key、向量库凭证、web search provider key、
# WeKnoraCloud.AppSecret 等。缺失或长度不对时已加密字段无法解密(UI 显示为空,需重填)。
# 生产必须显式设置且妥善保管,丢失则所有加密数据不可恢复。
# 注:TENANT_AES_KEY / CRYPTO_MASTER_KEY / CRYPTO_SALT 已废弃。v0.4.0 起 CryptoService(PBKDF2)被移除,加密统一改用 SYSTEM_AES_KEY。这三个变量 Go 主应用不再读取,已移除。
# Generate once: openssl rand -hex 16 (32 ASCII bytes); retain existing keys on upgrade.
SYSTEM_AES_KEY=
# Optional independent signing key for embed sessions and presigned URLs.
# Generate once: openssl rand -hex 32. Falls back to a valid SYSTEM_AES_KEY.
SYSTEM_SIGNING_KEY=
# ========== F2. 注册与空间策略 ==========
# 禁止新用户注册(生产建议 true)。
# DISABLE_REGISTRATION=false
# 开启后密码必须包含大小写字母、数字和特殊字符,特殊字符包含:!@#$%^&*()_+-=[]{}|;:,.<>?
# WEKNORA_AUTH_COMPLEX_PASSWORD_ENABLED=false
# 公开注册后的默认空间策略:create_personal(默认,自动创建个人空间)/ tenantless。
# WEKNORA_AUTH_DEFAULT_TENANT_MODE=create_personal
# 是否允许普通用户登录后主动创建空间(默认 true;false 仅能邀请加入,超管不受影响)。
# WEKNORA_TENANT_SELF_SERVICE_CREATION_ENABLED=true
# 启用空间级 RBAC(true 默认强制鉴权 / false 观察模式:空间内角色检查仅记录不拦截;跨空间访问始终拦截)。
# WEKNORA_TENANT_ENABLE_RBAC=true
# 启用跨空间访问(需配合用户的 CanAccessAllTenants 权限;默认 false)。如需跨空间管理员,需要手动修改数据库,为对应用户授予跨空间管理权限
# WEKNORA_TENANT_ENABLE_CROSS_TENANT_ACCESS=false
# 单个非超管用户可自助创建空间数上限(>0 强制限额;=0 走默认;<0 关闭限额)。
# WEKNORA_TENANT_MAX_OWNED_PER_USER=
# 创建空间时是否自动生成 full_access API Key 并在响应中返回 token(默认 false,兼容旧版回退开关)。
# WEKNORA_TENANT_AUTO_CREATE_API_KEY=false
# 新建空间默认存储配额(GB,默认 10)。
# WEKNORA_TENANT_DEFAULT_STORAGE_QUOTA_GB=10
# 空间邀请链接 TTL(Go duration,默认 168h=7 天)。
# WEKNORA_INVITATION_TTL=168h
# 全局开关:邀请已注册用户时直接加入空间。默认 false,可在系统设置页修改。
# WEKNORA_TENANT_AUTO_ACCEPT_INVITATION=false
# 审计日志保留天数(0 禁用清理,默认 90)。
# WEKNORA_AUDIT_RETENTION_DAYS=90
# ========== F3. OIDC 认证(可选,OIDC_AUTH_ENABLE=true 启用)==========
# OIDC_AUTH_ENABLE=false
# OIDC_AUTH_ISSUER_URL=http://127.0.0.1:5556/dex
# OIDC_AUTH_DISCOVERY_URL=http://127.0.0.1:5556/dex/.well-known/openid-configuration
# OIDC_AUTH_PROVIDER_DISPLAY_NAME=OIDC
# OIDC_AUTH_CLIENT_ID=client_id_for_oidc_client
# OIDC_AUTH_CLIENT_SECRET=secret_for_oidc_client
# 若 OIDC_AUTH_DISCOVERY_URL 已填,以下端点可留空。即使显式填写了授权/Token 端点,
# 只要 jwks_uri 或 issuer 为空,仍会走 discovery 补全,用于校验 id_token。
# OIDC_AUTH_AUTHORIZATION_ENDPOINT=http://127.0.0.1:5556/dex/auth
# OIDC_AUTH_TOKEN_ENDPOINT=http://127.0.0.1:5556/dex/token
# OIDC_AUTH_USER_INFO_ENDPOINT=http://127.0.0.1:5556/dex/userinfo
# OIDC_AUTH_JWKS_URI=http://127.0.0.1:5556/dex/keys
# OIDC_AUTH_SCOPES="openid profile email"
# OIDC 首次自动开户后的空间策略与本地注册共用 WEKNORA_AUTH_DEFAULT_TENANT_MODE。
# 另有独立开关:开启后 OIDC 开户用户自动加入本部署最早 OIDC 用户的主空间
# (contributor),同源用户视为同一组织;被移除成员与待接受邀请不受影响。
# 也可在管理界面「系统管理 → 全局设置 → 访问控制」中修改。
# WEKNORA_AUTH_OIDC_AUTO_JOIN_SHARED_SPACE=false
# OIDC_USER_INFO_MAPPING_USER_NAME=name
# OIDC_USER_INFO_MAPPING_EMAIL=email
# 工号式 IdP(如 Casdoor 用户 name=工号必填、email 选填)的兜底域:provider 未返回
# email claim 时,用已验签的 sub 合成 <sub>@<兜底域> 作为账号唯一键
# (如 built-in/10001 → built-in_10001@casdoor.local)。留空保持 email 必填
# (缺失则 OIDC 登录失败)。合成后即为永久账号键,启用后勿中途更换兜底域。
# OIDC_AUTH_EMAIL_FALLBACK_DOMAIN=
# 工号密码表单直登(password grant,气泡图同款模式):登录页「工号登录」tab 直接提交
# 工号+密码,后端转发 IdP token 端点校验(浏览器不接触 client_secret),不跳 IdP 托管页。
# 前置:Casdoor 应用 grantTypes 必须勾选 password(enablePassword 托管页开关与此无关,
# 未勾选时登录返回 503「IdP 未开放 password grant」)。总开关 OIDC_AUTH_ENABLE 仍须为 true。
# OIDC_AUTH_PASSWORD_LOGIN_ENABLED=false
# #####################################################################
# G. Agent 与沙箱
# #####################################################################
# ========== G1. Agent Skills Sandbox ==========
# Sandbox 后端、凭据、模板、超时和私网访问策略全部在「设置 → 沙箱后端」
# 按空间维护。唯一的部署级开关是 Docker 后端:默认关闭,因为本机
# docker.sock 等同宿主机 root;私有化单机需要时改为 true,或由系统管理员在
# 「设置 → 系统设置 → 网络安全」打开(立即生效,无需重启)。
WEKNORA_SANDBOX_DOCKER_ENABLED=false
# 多实例仍应配置通用 REDIS_ADDR,以共享 session→sandbox binding。
# 用户模式沙箱分配(同一合格用户的会话共用一台沙箱,目录按会话隔离)。
# 设为 enabled 打开;还要求 REDIS_ADDR 已配置,多副本靠它协调同一台机器。
# 升级顺序:所有实例都跑上新版本后,再在所有实例上设置,避免旧实例仍按
# 每会话一台分配。未设置或 Redis 缺失时,沙箱配置里的「分配模式」不可
# 保存为用户模式,已保存的用户模式配置在分配时回退为每会话一台。
# WEKNORA_SANDBOX_USER_ALLOCATION=
# 智能体大模型调用默认超时(秒,默认 120;复杂推理调大如 300/600)。
# 注:全局默认;单个智能体在数据库配独立 llm_call_timeout 时以其为准。
# WEKNORA_AGENT_LLM_TIMEOUT=300
# web_fetch 单页抓取预算(默认 3m)。HTTP 与 chromedp 共用这一预算,不叠加。
# 支持 Go duration(150s、3m)或纯数字秒(180)。空值、无效值或非正数使用默认值。
# 工具包装层再多等 5 秒,以便返回工具自己的超时结果。快速回答管道仍为 15s,不使用此项。
# WEKNORA_WEB_FETCH_TIMEOUT=3m
# MCP 工具人工审核等待超时(秒,默认 600;支持 Go duration 如 30s/5m/1h)。
# WEKNORA_AGENT_TOOL_APPROVAL_TIMEOUT=600
# MCP 工具人工审批失败时是否放行(true 放行 / 默认 fail-close 拒绝)。
# WEKNORA_AGENT_TOOL_APPROVAL_FAIL_OPEN=
# #####################################################################
# H. 可选集成
# #####################################################################
# ========== H1. 网络搜索(SearXNG / Tavily)==========
# ===== SearXNG(可选自建网络搜索)=====
# 启用:`docker compose --profile searxng up -d`。
# SEARXNG_SECRET 不设时使用 docker-compose 中的写死默认值,足够本机/loopback 部署使用;
# 如果改 SEARXNG_BIND=0.0.0.0 把实例暴露到 LAN/公网,请务必用 openssl rand -hex 32 生成
# 并显式设置 SEARXNG_SECRET,否则默认值会被任何人用于签名 image-proxy URL。
#
# 后端访问方式(容器化部署):控制台中 Provider 类型选 "SearXNG",
# Instance URL 填 http://searxng:8080;docker compose 已默认把 searxng 主机名注入
# SSRF_WHITELIST_EXTRA,无需额外配置。
#
# 本地开发(go run + docker compose -f docker-compose.dev.yml --profile searxng up):
# 后端跑在宿主机,需走 published 端口;Instance URL 填 http://127.0.0.1:8888,
# 并把 127.0.0.1 加入下方 SSRF_WHITELIST。
#
# 端口默认仅监听 127.0.0.1,避免把开了 limiter:false 的实例暴露到 LAN。
# 如需对内网开放,显式覆盖 SEARXNG_BIND=0.0.0.0 并自行加固。
# SEARXNG_PORT=8888
# Do not set SEARXNG_PORT to the same value as APP_PORT (default 8080).
# On Linux, binding SearXNG to 127.0.0.1:8080 while the app also publishes
# :8080 makes localhost:8080 hit SearXNG first — POST /api/v1/auth/login
# then returns SearXNG's HTML 404 even though DISABLE_REGISTRATION only
# closes registration (see discussion on issue #3296). Keep SearXNG on 8888
# (or another free port).
# SEARXNG_BIND=127.0.0.1
# SEARXNG_SECRET=
# Tavily Search API Key(可选,启用 Tavily 网页搜索提供者)。
# TAVILY_API_KEY=tvly-your_tavily_api_key
# ========== H2. MCP Server(可选,--profile full 时启动)==========
# MCP Server 访问 WeKnora REST API 用的 API Key(在前端「设置 -> API Keys」生成)。
# WEKNORA_API_KEY=
# HTTP/SSE 传输必填:mcp-server 启动时若缺少此项会拒绝启动(客户端以 Authorization: Bearer 携带)。
# MCP_SERVER_AUTH_TOKEN=
# 调用 WeKnora REST 的读超时(秒,默认 300)。
# WEKNORA_CHAT_TIMEOUT=300
# 是否校验 WeKnora 后端 TLS 证书(默认 true;自签证书可设 false)。
# WEKNORA_VERIFY_SSL=true
# 允许上传的目录白名单(逗号分隔;留空禁用文件上传工具)。
# MCP_ALLOWED_UPLOAD_DIRS=
# #####################################################################
# I. 可观测性(Langfuse,可选)
# #####################################################################
# ========== I1. Langfuse 接入(追踪 chat/embedding/rerank/VLM/ASR 模型调用,统计 token 消耗)==========
# 详细说明:website-docs/03-features/16-observability.md
#
# 方案 A:接入 Langfuse Cloud(最简单)
# 1) 登录 https://cloud.langfuse.com 生成 API Key
# 2) 填入下方 PUBLIC_KEY / SECRET_KEY
# 3) docker compose up -d app
#
# 方案 B:自建 Langfuse(局域网/内网环境)
# 1) 启动自建栈:docker compose --profile langfuse up -d
# 首次启动后 ClickHouse 迁移约 1-2 分钟,耐心等待 langfuse-web 健康
# 2) 浏览器打开 http://localhost:3000 注册管理员账号并生成 API Key
# 3) 取消注释下方 LANGFUSE_HOST=http://langfuse-web:3000,填入刚生成的 PUBLIC_KEY / SECRET_KEY
# 4) docker compose up -d app
#
# 只要同时设置 PUBLIC_KEY + SECRET_KEY 就会自动启用,无需显式开关。
LANGFUSE_PUBLIC_KEY=pk-lf-xxxxxxxx
LANGFUSE_SECRET_KEY=sk-lf-xxxxxxxx
LANGFUSE_HOST=http://langfuse-web:3000
# 自建模式下改成:LANGFUSE_HOST=http://langfuse-web:3000
# 可选:显式开关(true/false,默认根据 key 自动判断)。
# LANGFUSE_ENABLED=true
# 可选:版本 / 环境标签,便于在 Langfuse UI 过滤。
# LANGFUSE_RELEASE=v0.4.2
# LANGFUSE_ENVIRONMENT=production
# 可选:批量上报与采样策略(生产高流量建议调大 FLUSH_AT、降低 SAMPLE_RATE)。
# LANGFUSE_FLUSH_AT=15
# LANGFUSE_FLUSH_INTERVAL=3s
# LANGFUSE_QUEUE_SIZE=2048
# LANGFUSE_REQUEST_TIMEOUT=10s
# LANGFUSE_SAMPLE_RATE=1.0
# LANGFUSE_DEBUG=false
# ========== I2. Langfuse 自建栈配置(仅在使用 --profile langfuse 时需要)==========
# 设计说明:为最小化资源占用,Langfuse 自建栈会**复用** WeKnora 已有的
# - postgres:创建独立的 "langfuse" 数据库(由 langfuse-db-init 容器一次性创建)
# - redis :使用独立的 Redis DB 号(默认 1,WeKnora 用 0)
# 真正新增的只有 3 个常驻容器:langfuse-web、langfuse-worker、langfuse-clickhouse
# + 1 个专用 S3:langfuse-minio
# + 1 个一次性 init:langfuse-db-init
# Langfuse Web UI 对外端口。
# LANGFUSE_WEB_PORT=3000
# Langfuse 专用 MinIO 端口(避免和 WeKnora 主 MinIO 9000/9001 冲突)。
# LANGFUSE_MINIO_S3_PORT=9100
# LANGFUSE_MINIO_CONSOLE_PORT=9101
# 媒体上传外部 endpoint(浏览器直连 Langfuse MinIO),默认指向宿主机映射的 9100 端口。
# LANGFUSE_S3_MEDIA_UPLOAD_ENDPOINT=http://localhost:9100
# 在 WeKnora-postgres 中创建的 Langfuse 库名。
# LANGFUSE_DB_NAME=langfuse
# 在 WeKnora-redis 中使用的 DB 号(1~15,不要和 WeKnora 的 0 冲突)。
# LANGFUSE_REDIS_DB=1
# ClickHouse / Langfuse 专用 MinIO 凭证(生产请务必修改)。
# LANGFUSE_CLICKHOUSE_USER=clickhouse
# LANGFUSE_CLICKHOUSE_PASSWORD=clickhouse
# LANGFUSE_MINIO_USER=langfuseminio
# LANGFUSE_MINIO_PASSWORD=langfuseminiosecret
# Langfuse 核心安全字段,生产必须重新生成:
# LANGFUSE_SALT=$(openssl rand -base64 32)
# LANGFUSE_ENCRYPTION_KEY=$(openssl rand -hex 32)
# LANGFUSE_NEXTAUTH_SECRET=$(openssl rand -base64 32)
# LANGFUSE_SALT=
# LANGFUSE_ENCRYPTION_KEY=
# LANGFUSE_NEXTAUTH_SECRET=
# LANGFUSE_NEXTAUTH_URL=http://localhost:3000
# LANGFUSE_TELEMETRY_ENABLED=false
# 可选:自动化首次启动(填写后直接注入管理员+项目,跳过 UI 注册)。
# LANGFUSE_INIT_ORG_ID=WeKnora
# LANGFUSE_INIT_ORG_NAME=WeKnora
# LANGFUSE_INIT_PROJECT_ID=WeKnora
# LANGFUSE_INIT_PROJECT_NAME=WeKnora
# LANGFUSE_INIT_PROJECT_PUBLIC_KEY=pk-lf-weknora-init
# LANGFUSE_INIT_PROJECT_SECRET_KEY=sk-lf-weknora-init
# LANGFUSE_INIT_USER_EMAIL=admin@example.com
# LANGFUSE_INIT_USER_NAME=Admin
# LANGFUSE_INIT_USER_PASSWORD=change-me-please
# #####################################################################
# J. 安全与部署调优
# #####################################################################
# ========== J1. SSRF 防护 ==========
# SSRF 校验白名单(可选)。逗号分隔;每条可为:精确域名(api.internal)、通配域名(*.example.com)、
# IPv4(203.0.113.5)、IPv6(2001:db8::1,不带方括号)或 CIDR(10.0.0.0/8, 2001:db8::/32)。
# 列入者会在 URL 校验等地方绕过常规 SSRF 规则,生产环境请谨慎配置。
# SSRF_WHITELIST=internal.service,*.corp.example,172.16.0.0/12,2001:db8::1,fd00::/8
#
# 仅允许白名单出站(默认关闭)。设为 true 时白名单就是全部出站策略:不在 SSRF_WHITELIST /
# SSRF_WHITELIST_EXTRA 里的主机(含 IP 直连)在发起 DNS 查询之前直接拒绝,域名只按名字匹配、
# 不再通过解析结果匹配 CIDR。离线或内网部署建议开启,并把模型、向量库、对象存储等地址全部列入白名单。
# SSRF_DNS_WHITELIST_ONLY=false
#
# 出站拨号超时(Go duration,默认 5s):模型、连接器等外部端点在此时间内连不上即失败。
# 冷启动较慢的 serverless 端点可调大,例如 15s。
# WEKNORA_OUTBOUND_DIAL_TIMEOUT=5s
#
# ===== 向量库地址的 SSRF 校验 =====
# 通过 API 创建/测试向量库连接时,地址会经过 SSRF 校验。docker-compose 内置服务
# (qdrant, milvus, weaviate, doris-fe, doris-be, searxng, minio)已通过 SSRF_WHITELIST_EXTRA 默认放行。
# 如使用外部私网地址或被拦截端口(5432, 9200 等),请将主机加入 SSRF_WHITELIST_EXTRA
# (注意:自定义该变量会覆盖 compose 默认值,需重新包含内置服务名),例如:
# SSRF_WHITELIST_EXTRA=searxng,qdrant,milvus,weaviate,doris-fe,doris-be,minio,my-opensearch.internal
#
# Doris Stream Load:FE 会将请求 307 重定向到 BE;docker compose 默认放行
# doris-fe 与 doris-be(见 SSRF_WHITELIST_EXTRA)。
#
# 本地开发(go run + docker-compose.dev.yml --profile opensearch):后端跑在宿主机,
# OpenSearch 经 published 端口 http://localhost:9200 访问;通过 API 创建该向量库前,
# 需把 localhost 加入 SSRF_WHITELIST(9200 是被拦截端口,localhost 是受限主机名):
# SSRF_WHITELIST=localhost
# 保留原始 URL 的图片域名白名单(可选,逗号分隔)。配置后这些域名的图片仍会被下载分析
# (OCR/字幕),但 markdown 中保留原始 URL,不替换为对象存储的 provider:// URL。
# IMAGE_HOST_KEEP_URL=mineru.internal.example.com
# ========== J2. 代理与并发 ==========
# gin 信任的代理 CIDR(逗号分隔)。默认信任 loopback + 私网段(容器网络内 nginx 已覆盖)。
# 显式设为空字符串则禁用代理信任(ClientIP 返回直连对端)。生产部署在多层代理后需按实际填写。
# WEKNORA_TRUSTED_PROXIES=
# ants 协程池大小(Embedding 并发,出现 429 时调小)。
CONCURRENCY_POOL_SIZE=5
# ========== J3. BrowserSkill 本机浏览器(可选) ==========
# 用户通过 Chrome 扩展连接;部署与限制见 website-docs/05-clients/09-local-browser.md。
# Docker app 镜像已内置 bsk 和配套扩展,默认从用户当前页面自动生成连接地址,无需配置 PUBLIC_URL。
# 原生部署还需构建产物并配置下面两个文件路径;显式设置 BROWSERSKILL_BINARY= 可关闭此功能。
# 后端所在系统/架构的官方 bsk 可执行文件绝对路径(Docker 已预设,不必重复配置)。
# BROWSERSKILL_BINARY=/opt/weknora/browserskill/bsk
# 可选覆盖:仅在网关使用独立域名/路径等特殊部署时设置;远程部署必须使用 WSS(包括内网)。
# BROWSERSKILL_PUBLIC_URL=wss://weknora.example.com/api/v1/local-browser/extension
# 单应用实例共用一个 daemon;最多保留的用户配对记录数(默认 32,非实测承载量)。
# BROWSERSKILL_MAX_CONNECTIONS=32
# 供个人设置下载的配套扩展 ZIP(服务器本地绝对路径,Docker 已预设)。
# BROWSERSKILL_EXTENSION_PATH=/opt/weknora/browserskill/browser-skill-weknora-0.3.1.zip
# 多副本:每个节点填写可被其他节点直接访问的地址,不要使用负载均衡地址。
# BROWSERSKILL_INTERNAL_URL=http://10.0.0.12:8080
# 所有副本使用相同的随机密钥(至少 32 字符),从 Secret 注入,不提交到仓库。
# BROWSERSKILL_CLUSTER_SECRET=
# 姓名所在 claim(映射到 users.display_name,OIDC 开户写入、登录刷新)。
# Casdoor 的 claims 集合无 nickname,姓名通常在 displayName(显示名)。
# OIDC_USER_INFO_MAPPING_DISPLAY_NAME=displayName
+95
View File
@@ -0,0 +1,95 @@
# WeKnora Lite 配置模板
# 复制此文件为 .env.lite 并按需修改
# cp .env.lite.example .env.lite
GIN_MODE=debug
# 日志级别,可选值:debug, info, warn, error, fatal
LOG_LEVEL=debug
# 可选:日志文件绝对路径;未配置时,macOS .app 默认写入
# ~/Library/Logs/WeKnora Lite/WeKnora Lite.log
# LOG_PATH=/absolute/path/to/weknora-lite.log
# === 数据库 ===
# macOS .app 中相对路径会自动重定向到
# ~/Library/Application Support/WeKnora Lite/data/
DB_DRIVER=sqlite
DB_PATH=./data/weknora.db
# === 检索引擎(FTS5 + sqlite-vec)===
RETRIEVE_DRIVER=sqlite
# === 文件存储 ===
STORAGE_TYPE=local
LOCAL_STORAGE_BASE_DIR=./data/files
# === 流管理(内存,无 Redis)===
STREAM_MANAGER_TYPE=memory
# === LLM 服务 ===
# Ollama 本地服务(默认地址,按需修改)。
# source=local 的向量模型与对话模型共用这一地址,不必为 embedding 再起一个 Ollama。
# 向量模型名在模型配置里填写(如 nomic-embed-text),不是单独的环境变量。
OLLAMA_BASE_URL=http://127.0.0.1:11434
# 如使用其他 OpenAI 兼容服务,取消注释:
# OPENAI_API_KEY=sk-xxx
# OPENAI_BASE_URL=https://api.openai.com/v1
# === 安全配置(生产环境请务必修改!)===
# Native desktop generates and persists its signing key automatically.
# For encrypted credential storage, generate once: openssl rand -hex 16
SYSTEM_AES_KEY=
JWT_SECRET=
# === 功能开关 ===
NEO4J_ENABLE=false
WEKNORA_SANDBOX_MODE=disabled
ENABLE_GRAPH_RAG=false
DISABLE_REGISTRATION=false
# 保留原始 URL 的图片域名白名单(可选)
# IMAGE_HOST_KEEP_URL=mineru.internal.example.com
# === Langfuse 可观测性(可选) ===
# 追踪 chat / embedding / rerank / VLM / ASR 的 prompt、响应与 token 消耗。
# 同时填了 PUBLIC_KEY 和 SECRET_KEY 就会自动启用,详见 website-docs/03-features/16-observability.md。
# LANGFUSE_PUBLIC_KEY=pk-lf-xxxxxxxx
# LANGFUSE_SECRET_KEY=sk-lf-xxxxxxxx
# LANGFUSE_HOST=https://cloud.langfuse.com
# === 性能 ===
CONCURRENCY_POOL_SIZE=3
# 聊天附件解析产物保留时长(小时),默认 24 小时
# WEKNORA_CHAT_ATTACHMENT_TTL_HOURS=24
# 单轮问答等待附件解析完成的最长时间(秒),超时后未完成的附件会被跳过。
# 大文件 / 扫描件解析较慢时可调大,默认 60 秒。智能体里的「附件解析等待超时」> 0 时优先于此全局值。
# WEKNORA_CHAT_ATTACHMENT_WAIT_TIMEOUT_SEC=60
# 附件 VLM OCR 调优(扫描件 / 图片型文档)。解析慢的瓶颈是逐页 VLM OCR,而非文档解析器。
# OCR_CONCURRENCY 为并行 OCR 的页数(默认 8,与页数上限一致,让扫描件一波跑完;调大会加重 VLM 负载,
# 所有智能体共享 VLM 后端,故保持全局);OCR_MAX_PAGES 为扫描件送入 VLM 的最大页数(默认 8),
# 智能体里的「扫描件 OCR 最大页数」> 0 时优先于此全局值。
# WEKNORA_CHAT_ATTACHMENT_OCR_CONCURRENCY=8
# WEKNORA_CHAT_ATTACHMENT_OCR_MAX_PAGES=8
# Docreader 地址
DOCREADER_ADDR=127.0.0.1:50051
# Docreader 传输方式
DOCREADER_TRANSPORT=grpc
# gRPC TLS 配置(可选)
# GRPC_TLS_ENABLED=false
# GRPC_TLS_CERT=/path/to/server.crt # server: 必填;client: mTLS 时填
# GRPC_TLS_KEY=/path/to/server.key # 同上
# GRPC_TLS_CA=/path/to/ca.crt # client: 校验 server 证书用;server: mTLS 时签发客户端证书的 CA
# GRPC_TLS_SERVER_NAME= # 可选;当 DOCREADER_ADDR 用 IP/与证书 CN 不一致时设为证书的 hostname
# GRPC_MTLS_REQUIRE_CLIENT_CERT=false # server 端:true 时强制要求客户端证书(mTLS)
# gRPC 认证 Token(可选,客户端和服务端需配置相同的值)
# 注意:启用 GRPC_AUTH_TOKEN 时强烈建议同时启用 TLS,否则 token 会以明文随
# 每次 RPC 在网络上传输。当 GRPC_TLS_ENABLED=true 时客户端会拒绝在不安全
# 的连接上发送 token。
# GRPC_AUTH_TOKEN=your-secret-token-at-least-16-bytes
+20
View File
@@ -0,0 +1,20 @@
*.sh text eol=lf
# Force LF on Go source + JSON golden fixtures so Windows checkouts
# (with default core.autocrlf=true) don't trip byte-equal comparisons in
# acceptance/contract envelope tests.
*.go text eol=lf
cli/acceptance/testdata/**/*.json text eol=lf
# Trellis: append-only developer journals should merge cleanly across
# parallel sessions/worktrees — each session only appends a new block, so
# there is nothing to actually conflict on.
#
# Do NOT add a rule for workspace/*/index.md here — it is fully regenerated
# every session, so a real conflict there is expected and safe to resolve by
# picking either side (task state lives in task.json, not index.md). See
# .trellis/spec/cli/backend/directory-structure.md for details.
.trellis/workspace/*/journal-*.md merge=union
# Unified diffs use a space to mark empty context lines.
patches/browserskill/*.patch whitespace=-blank-at-eol
+130
View File
@@ -0,0 +1,130 @@
name: 🐛 Bug Report
description: Report a bug or issue
title: "[Bug]: "
labels: ["bug", "needs-triage"]
body:
- type: markdown
attributes:
value: |
Thanks for reporting a bug! Please fill in the information below to help us locate and fix the issue quickly.
- type: dropdown
id: component
attributes:
label: Affected Component
description: Select the component where the issue occurs
options:
- Frontend UI
- Backend Service & API
- Document Reader Service
- Vector Database
- Model Service
- Other
validations:
required: true
- type: textarea
id: description
attributes:
label: Bug Description
description: A clear and concise description of the issue
placeholder: "Describe what the bug looks like..."
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to Reproduce
description: Minimal steps that reliably reproduce the problem
placeholder: |
1. Go to '...'
2. Click on '...'
3. Send request '...'
4. See error
validations:
required: true
- type: textarea
id: expected
attributes:
label: Expected Behavior
description: Describe what you expected to happen
placeholder: "What should have happened..."
validations:
required: true
- type: textarea
id: actual
attributes:
label: Actual Behavior
description: Describe what actually happened (error messages, screenshots, etc.)
placeholder: "What actually happened..."
validations:
required: true
- type: input
id: version
attributes:
label: WeKnora Version
description: |
Please provide the concrete version number you are running, **not** `latest`, `main` or `master`.
You can find it on the **Settings → System Info** page (both "App Version" and "UI Version" — if they differ, please report both).
If you built from source, include the commit SHA instead.
placeholder: "e.g., App Version: v0.6.0, UI Version: v0.6.0 (or commit abc1234)"
validations:
required: true
- type: dropdown
id: deployment
attributes:
label: Deployment Method
description: How are you running WeKnora?
options:
- Docker Compose
- Build from source
- Lite (single binary)
- Desktop app
- Kubernetes (Helm)
- Other
validations:
required: true
- type: input
id: os
attributes:
label: Operating System
description: The operating system you are using
placeholder: "e.g., macOS 13.0, Ubuntu 20.04, Windows 11"
validations:
required: true
- type: markdown
attributes:
value: |
## 📋 Log Collection Guide
Please collect logs and paste them into the field below. Pick the command matching your deployment:
- Docker Compose:
```bash
docker compose logs -f --tail=1000 app docreader postgres
```
- Lite / Desktop / build from source: include the console output or log files (e.g., `logs/*.log`).
- type: textarea
id: logs
attributes:
label: Relevant Logs
description: Paste relevant logs or error messages here
placeholder: "Paste logs or error messages..."
render: shell
- type: checkboxes
id: terms
attributes:
label: Confirmation
description: Please confirm the following
options:
- label: I have searched existing issues and confirmed this is a new one
required: true
+8
View File
@@ -0,0 +1,8 @@
blank_issues_enabled: false
contact_links:
- name: WeKnora Documentation
url: https://weknora.weixin.qq.com/docs/01-getting-started/05-troubleshooting
about: Check WeKnora FAQ
- name: Discussions
url: https://github.com/Tencent/WeKnora/discussions
about: Ask questions or share ideas in Discussions
@@ -0,0 +1,88 @@
name: ✨ Feature Request
description: Suggest a new feature or improvement
title: "[Feature]: "
labels: ["enhancement", "needs-triage"]
body:
- type: markdown
attributes:
value: |
Thanks for the feature request! Please describe your idea in detail so we can better understand your needs.
- type: dropdown
id: component
attributes:
label: Affected Component
description: Select the component related to this request
options:
- Frontend UI
- Backend Service & API
- Document Reader Service
- Vector Database
- Model Service
- Configuration Management
- Other
validations:
required: true
- type: textarea
id: problem
attributes:
label: Problem Description
description: Describe the problem or limitation of the current feature
placeholder: "What is wrong or missing today?"
validations:
required: true
- type: textarea
id: solution
attributes:
label: Proposed Solution
description: Describe the feature or improvement you would like to see
placeholder: "How would you like to solve it?"
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives
description: Describe alternative solutions you have considered
placeholder: "Any alternatives you considered?"
- type: dropdown
id: impact
attributes:
label: Impact
description: Who is affected by the absence of this feature?
options:
- Just me / a personal preference
- My team or a small group
- Many users would benefit
- Blocking adoption of WeKnora
validations:
required: true
- type: textarea
id: usecase
attributes:
label: Use Case
description: Describe the specific use case for this feature
placeholder: "When would you use this feature?"
- type: textarea
id: additional
attributes:
label: Additional Information
description: Any other context, screenshots, or links
placeholder: "Add any other relevant information..."
- type: checkboxes
id: terms
attributes:
label: Confirmation
description: Please confirm the following
options:
- label: I have searched existing issues and confirmed this is a new request
required: true
- label: I understand this request may need discussion and evaluation
required: true
+103
View File
@@ -0,0 +1,103 @@
name: ❓ Question
description: Ask a question about WeKnora or seek help
title: "[Question]: "
labels: ["question", "needs-triage"]
body:
- type: markdown
attributes:
value: |
Welcome! Please provide enough information so we can help you effectively.
- type: dropdown
id: category
attributes:
label: Question Category
description: Select the category of your question
options:
- Installation & Deployment
- Configuration
- Usage
- Performance
- Integration
- Other
validations:
required: true
- type: textarea
id: question
attributes:
label: Question Description
description: Please describe your question in detail
placeholder: "What problem did you encounter? What help do you need?"
validations:
required: true
- type: textarea
id: context
attributes:
label: Context
description: Please provide relevant context
placeholder: |
- What are you trying to do?
- What outcome do you expect?
- What have you tried so far?
- type: input
id: os
attributes:
label: Operating System
description: The operating system you are using
placeholder: "e.g., macOS 13.0, Ubuntu 20.04, Windows 11"
validations:
required: true
- type: textarea
id: environment
attributes:
label: Other Environment Info
description: Please provide other relevant environment information
placeholder: |
- WeKnora App Version: [concrete version from Settings → System Info, e.g., v0.6.0 — NOT "latest"]
- WeKnora UI Version: [concrete version from Settings → System Info, e.g., v0.6.0]
- Deployment: [e.g., Docker, build from source]
- Other relevant info...
- type: markdown
attributes:
value: |
## 📋 Log Collection Guide (if needed)
If the issue involves errors or requires debugging, please collect logs:
```bash
docker compose logs -f --tail=1000 app docreader postgres
```
- type: textarea
id: logs
attributes:
label: Relevant Logs
description: Paste relevant logs or error messages here if available
placeholder: "Paste logs or error messages..."
render: shell
- type: textarea
id: research
attributes:
label: Resources Already Checked
description: List the docs, issues or other resources you've already checked
placeholder: |
- Docs checked: [e.g., README.md, API.md]
- Issues checked: [e.g., #123, #456]
- Other resources: [e.g., official docs, Stack Overflow]
- type: checkboxes
id: terms
attributes:
label: Confirmation
description: Please confirm the following
options:
- label: I have searched existing issues and documentation
required: true
- label: I have provided enough information to help understand the question
required: true
+144
View File
@@ -0,0 +1,144 @@
# Dependabot configuration for the WeKnora repository.
#
# Policy:
# * `/cli` is the only ecosystem that receives routine version updates
# (monthly, grouped into one minor/patch PR and one major PR). It's
# a standalone Go binary with a small, well-scoped dependency surface
# where staying current is cheap.
# * Every other ecosystem (server gomod, /client, frontend npm,
# miniprogram npm, docreader pip, github-actions) is configured as
# "security-only" — no scheduled version PRs, but CVE security
# updates still open PRs automatically.
#
# Security-only pattern (mirrors fluent/fluentd-kubernetes-daemonset and
# the dependabot docs for "Disabling Dependabot version updates"):
#
# open-pull-requests-limit: 0 # primary kill-switch for version PRs
# ignore: # belt-and-suspenders: drop every
# - dependency-name: "*" # non-security update at the source.
# update-types: ["version-update"]
# groups: # collapse simultaneous CVE PRs into
# security-updates: # ONE PR per ecosystem so a noisy
# applies-to: security-updates
# patterns: ["*"]
#
# Why both `open-pull-requests-limit: 0` AND `ignore`:
# The official docs treat `limit: 0` as the canonical way to disable
# version updates, but dependabot-core#7353 shows it has historically
# been ignored for some ecosystems. Adding the wildcard `ignore` rule
# guarantees zero scheduled version PRs even if the limit gets
# regressed upstream. Security updates are unaffected by either knob.
#
# Prerequisite: "Dependabot security updates" must be enabled in
# Settings → Code security and analysis. Without it, no CVE PRs are
# opened regardless of this file.
#
# Conventions applied to `/cli`:
# * Monthly schedule (one batch / month).
# * Two groups so per-dep PRs never flood:
# - `cli-deps` bundles minor + patch → ONE PR / month.
# - `cli-deps-major` bundles semver-major bumps the same way so
# breaking changes surface as a single
# review-required PR rather than silently
# accumulating.
# * `open-pull-requests-limit: 3` as a safety net against stalled queues.
# * `commit-message.prefix: "chore(deps)"` to match the repo's
# Conventional Commits convention.
version: 2
updates:
# ─── Go modules ───
- package-ecosystem: gomod
directory: "/"
schedule:
interval: monthly
open-pull-requests-limit: 0
ignore:
- dependency-name: "*"
update-types: ["version-update:semver-major", "version-update:semver-minor", "version-update:semver-patch"]
groups:
server-security:
applies-to: security-updates
patterns: ["*"]
- package-ecosystem: gomod
directory: "/cli"
schedule:
interval: monthly
open-pull-requests-limit: 3
commit-message:
prefix: "chore(deps)"
groups:
cli-deps:
patterns: ["*"]
update-types: ["minor", "patch"]
cli-deps-major:
patterns: ["*"]
update-types: ["major"]
- package-ecosystem: gomod
directory: "/client"
schedule:
interval: monthly
open-pull-requests-limit: 0
ignore:
- dependency-name: "*"
update-types: ["version-update:semver-major", "version-update:semver-minor", "version-update:semver-patch"]
groups:
client-security:
applies-to: security-updates
patterns: ["*"]
# ─── npm ───
- package-ecosystem: npm
directory: "/frontend"
schedule:
interval: monthly
open-pull-requests-limit: 0
ignore:
- dependency-name: "*"
update-types: ["version-update:semver-major", "version-update:semver-minor", "version-update:semver-patch"]
groups:
frontend-security:
applies-to: security-updates
patterns: ["*"]
- package-ecosystem: npm
directory: "/miniprogram"
schedule:
interval: monthly
open-pull-requests-limit: 0
ignore:
- dependency-name: "*"
update-types: ["version-update:semver-major", "version-update:semver-minor", "version-update:semver-patch"]
groups:
miniprogram-security:
applies-to: security-updates
patterns: ["*"]
# ─── Python ───
- package-ecosystem: pip
directory: "/docreader"
schedule:
interval: monthly
open-pull-requests-limit: 0
ignore:
- dependency-name: "*"
update-types: ["version-update:semver-major", "version-update:semver-minor", "version-update:semver-patch"]
groups:
docreader-security:
applies-to: security-updates
patterns: ["*"]
# ─── GitHub Actions ───
- package-ecosystem: github-actions
directory: "/"
schedule:
interval: monthly
open-pull-requests-limit: 0
ignore:
- dependency-name: "*"
update-types: ["version-update:semver-major", "version-update:semver-minor", "version-update:semver-patch"]
groups:
gha-security:
applies-to: security-updates
patterns: ["*"]
+42
View File
@@ -0,0 +1,42 @@
<!-- Title should follow Conventional Commits, e.g. `feat: ...`, `fix: ...`, `docs: ...` -->
## Description
<!-- Briefly describe the purpose and changes of this PR -->
## Type of Change
<!-- Check applicable items -->
- [ ] 🐛 Bug fix
- [ ] ✨ New feature
- [ ] 💥 Breaking change
- [ ] 📚 Documentation update
- [ ] 🎨 Refactor
- [ ] ⚡ Performance improvement
- [ ] 🧪 Test
- [ ] 🔧 Configuration / Build / CI
## Related Issue
<!-- If this PR resolves an issue, use "Fixes #123" or "Closes #123" -->
Fixes #
## Testing
<!-- Describe how these changes were tested. Include reproduction or verification steps. -->
<!--
For a focused change, run checks scoped to the files/packages you changed.
See the Contributing section in README.md for examples. If a full-repository
check is blocked by unrelated baseline or environment failures, record the
exact command and failure here.
-->
## Checklist
- [ ] `git diff --check origin/main...HEAD` passes
- [ ] Changed source files are formatted
- [ ] Targeted tests for the changed packages/components pass
- [ ] Diff-scoped lint passes where applicable (for Go: `golangci-lint run --new-from-rev=origin/main ./...`)
- [ ] Full-repository checks were run, or any unrelated/environment-dependent failures are documented above
- [ ] Self-reviewed the code
- [ ] Added/updated tests covering the change
- [ ] Updated related documentation (README, `website-docs/`, Swagger annotations, etc.)
- [ ] Breaking changes are clearly called out in the description above
## Screenshots / Recordings
<!-- Required for user-visible UI changes -->
+81
View File
@@ -0,0 +1,81 @@
name: Anydoc
# Compiles the vendored Rust archive, audits it, and exercises the `anydoc`
# build tag. That is minutes of rustc + cargo-audit, so this workflow stays
# off PRs that only touch migrations, frontend, CLI, or unrelated Go packages.
on:
push:
branches: [main]
paths:
- "third_party/anydoc-go/**"
- "scripts/build-anydoc-lib.sh"
- "internal/infrastructure/docparser/**"
- ".github/workflows/anydoc.yml"
pull_request:
paths:
- "third_party/anydoc-go/**"
- "scripts/build-anydoc-lib.sh"
- "internal/infrastructure/docparser/**"
- ".github/workflows/anydoc.yml"
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
env:
GO_VERSION: "1.26"
GOPROXY: https://proxy.golang.org,direct
jobs:
anydoc:
name: anydoc parser engine
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v6
- uses: actions/setup-go@v6
with:
go-version: ${{ env.GO_VERSION }}
cache: true
- uses: dtolnay/rust-toolchain@stable
- name: Cache cargo-audit
id: cargo-audit-cache
uses: actions/cache@v4
with:
path: ~/.cargo/bin/cargo-audit
key: cargo-audit-${{ runner.os }}
- name: Install cargo-audit
if: steps.cargo-audit-cache.outputs.cache-hit != 'true'
run: cargo install cargo-audit --locked
# The archive is a build artifact, not a committed blob, so CI is what
# keeps the vendored bindings in third_party/anydoc-go compiling.
# This also materializes patched-anydoc/ (gitignored); cargo audit below
# cannot load the crates-io patch until that tree exists.
- name: Build the anydoc static archive
run: ./scripts/build-anydoc-lib.sh
# The vendored bindings pull anydoc and its PDF stack from crates.io, and
# WeKnora parses untrusted uploads in-process. A Rust advisory there (as
# in RUSTSEC-2026-0187, an uncatchable abort on a hostile PDF) has to
# break the build, not wait for someone to notice. Vulnerabilities fail
# the job; unmaintained-crate warnings only report, since a transitive
# crate going unmaintained is not something this repo can act on.
- name: Audit the vendored dependency tree
working-directory: third_party/anydoc-go
run: cargo audit
- name: Vet, test, and build with the engine linked in
run: |
go vet -tags anydoc ./internal/infrastructure/docparser/...
go test -tags anydoc -count=1 ./internal/infrastructure/docparser/...
go build -tags anydoc ./cmd/server
+147
View File
@@ -0,0 +1,147 @@
name: App
# Anydoc (Rust archive + `anydoc` build tag) lives in anydoc.yml so a
# migrations-only or unrelated Go PR does not compile the parser engine.
on:
push:
branches: [main]
paths:
- "**/*.go"
- "!cli/**"
- "!client/**"
- "!docreader/**"
- "!third_party/anydoc-go/**"
- "go.mod"
- "go.sum"
- "Makefile"
- "config/**"
- "migrations/**"
- "skills/preloaded/**"
- "testdata/**"
- "website-docs/0*/**"
- "website-docs/.vitepress/config.mts"
- "docker/Dockerfile.app"
- "LICENSE"
- "THIRD_PARTY_NOTICES.md"
- "licenses/**"
- "internal/textconv/data/**"
- "internal/models/catalog/data/**"
- "internal/models/parity/testdata/**"
- "internal/models/providers/assets/**"
- "scripts/model-catalog/**"
- "scripts/*license*.sh"
- "scripts/git-hooks/**"
- "scripts/test-git-hooks.sh"
- "cmd/desktop/build/windows/installer/project.nsi"
- ".github/workflows/app.yml"
pull_request:
paths:
- "**/*.go"
- "!cli/**"
- "!client/**"
- "!docreader/**"
- "!third_party/anydoc-go/**"
- "go.mod"
- "go.sum"
- "Makefile"
- "config/**"
- "migrations/**"
- "skills/preloaded/**"
- "testdata/**"
- "website-docs/0*/**"
- "website-docs/.vitepress/config.mts"
- "docker/Dockerfile.app"
- "LICENSE"
- "THIRD_PARTY_NOTICES.md"
- "licenses/**"
- "internal/textconv/data/**"
- "internal/models/catalog/data/**"
- "internal/models/parity/testdata/**"
- "internal/models/providers/assets/**"
- "scripts/model-catalog/**"
- "scripts/*license*.sh"
- "scripts/git-hooks/**"
- "scripts/test-git-hooks.sh"
- "cmd/desktop/build/windows/installer/project.nsi"
- ".github/workflows/app.yml"
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
env:
GO_VERSION: "1.26"
GOPROXY: https://proxy.golang.org,direct
# Keep tests independent of a developer machine's custom log template.
WEKNORA_LOG_FORMAT: ""
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.before }}
jobs:
verify:
name: Format, vet, test, and build
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
- uses: actions/setup-go@v6
with:
go-version: ${{ env.GO_VERSION }}
cache: true
# v6 defaults to go.mod for the cache key (more stable than go.sum).
- name: Download modules
run: go mod download
- name: Verify third-party notices and source bundle
run: |
bash ./scripts/check-license-bundle.sh
bash ./scripts/test-license-bundle.sh
- name: Check formatting
shell: bash
run: |
if [ "${{ github.event_name }}" = "pull_request" ]; then
# Compare base..head, not the PR merge commit, so files changed only
# on main after the branch point are not attributed to this PR.
diff_range="${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }}"
else
base="$BASE_SHA"
if [ -z "$base" ] || [[ "$base" =~ ^0+$ ]]; then
base=$(git rev-parse HEAD^)
fi
diff_range="$base..$GITHUB_SHA"
fi
unformatted=$(
git diff --name-only --diff-filter=ACMR -z "$diff_range" -- '*.go' ':!cli/**' |
xargs -0 -r gofmt -l
)
if [ -n "$unformatted" ]; then
echo "The following Go files are not gofmt-formatted:"
echo "$unformatted"
exit 1
fi
- name: Verify generated model catalog
run: python3 scripts/model-catalog/generate.py --check
- name: Verify Git hook test coverage
run: bash ./scripts/test-git-hooks.sh
- name: Vet and test
shell: bash
run: |
mapfile -t pkgs < <(go list ./... | grep -v '/docreader/')
go vet "${pkgs[@]}"
go test "${pkgs[@]}"
go test -tags desktop ./internal/container
- name: Build server
run: go build ./cmd/server
+66
View File
@@ -0,0 +1,66 @@
name: CLI E2E
# Runs the cli/acceptance/e2e/ suite against a real WeKnora server.
# Cost-gated so it doesn't fire on every PR:
# - workflow_dispatch: maintainer can trigger manually
# - pull_request labeled "acceptance-e2e": adding the label kicks a run
#
# Required repo secrets (only set on Tencent/WeKnora; cross-fork PRs have no
# access and the job exits early via the secrets-present guard):
# WEKNORA_E2E_HOST - https URL of the test server
# WEKNORA_E2E_TOKEN - bearer token / API key for that host
#
# Mirrors gh acceptance/ trigger pattern: env-gated, opt-in, single matrix.
on:
workflow_dispatch:
pull_request:
types: [labeled, synchronize]
paths:
- 'cli/**'
- '.github/workflows/cli-e2e.yml'
defaults:
run:
working-directory: cli
shell: bash
permissions:
contents: read
jobs:
e2e:
name: rag full loop
# Skip auto-trigger on label-add unless the label is exactly "acceptance-e2e".
# Manual workflow_dispatch always runs.
if: |
github.event_name == 'workflow_dispatch' ||
(github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'acceptance-e2e'))
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v6
- uses: actions/setup-go@v6
with:
go-version: '1.26'
cache-dependency-path: cli/go.sum
- name: secrets present
id: secrets
env:
E2E_HOST: ${{ secrets.WEKNORA_E2E_HOST }}
E2E_TOKEN: ${{ secrets.WEKNORA_E2E_TOKEN }}
run: |
if [ -z "$E2E_HOST" ] || [ -z "$E2E_TOKEN" ]; then
echo "::warning::WEKNORA_E2E_HOST or WEKNORA_E2E_TOKEN not set; skipping e2e."
echo "skip=true" >> "$GITHUB_OUTPUT"
else
echo "skip=false" >> "$GITHUB_OUTPUT"
fi
- name: go test -tags=acceptance_e2e
if: steps.secrets.outputs.skip == 'false'
env:
WEKNORA_E2E_HOST: ${{ secrets.WEKNORA_E2E_HOST }}
WEKNORA_E2E_TOKEN: ${{ secrets.WEKNORA_E2E_TOKEN }}
run: go test -tags=acceptance_e2e -v -timeout=8m ./acceptance/e2e/...
+58
View File
@@ -0,0 +1,58 @@
name: CLI
# Builds and tests the cli/ Go module on every push / PR that touches it.
# Foundation PR (PR-1) gates: 3-platform `go build` + `go test ./...` green.
on:
push:
branches: [main]
paths:
- 'cli/**'
- '.github/workflows/cli.yml'
pull_request:
paths:
- 'cli/**'
- '.github/workflows/cli.yml'
defaults:
run:
working-directory: cli
# Windows default is PowerShell, which tokenizes `go test -coverprofile=coverage.out ./...`
# in a way that detaches `.out` as a separate positional package arg.
# Force bash everywhere so the run lines parse identically across platforms
# (Git Bash is preinstalled on windows-latest runners).
shell: bash
permissions:
contents: read
jobs:
test:
name: test (${{ matrix.os }} / go ${{ matrix.go }})
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
go: ['1.26']
steps:
- uses: actions/checkout@v6
- uses: actions/setup-go@v6
with:
go-version: ${{ matrix.go }}
cache-dependency-path: cli/go.sum
- name: go build
run: go build ./...
- name: go test
run: go test -race -coverprofile=coverage.out ./...
- name: go vet
run: go vet ./...
- name: Check agent-facing doc wire vocabulary
if: runner.os == 'Linux'
run: scripts/check-skill-wire-vocab.sh
- name: Check for committed credentials in docs
if: runner.os == 'Linux'
run: scripts/check-secret-tokens.sh
- name: coverage report
if: matrix.os == 'ubuntu-latest'
run: go tool cover -func=coverage.out
+321
View File
@@ -0,0 +1,321 @@
name: Build and Push Docker Image
on:
push:
tags:
- "v*"
branches:
- main
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: false
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
jobs:
build-ui:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v6
- name: Prepare version info
id: version
run: |
eval "$(./scripts/get_version.sh env)"
echo "commit_id=$COMMIT_ID" >> $GITHUB_OUTPUT
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_PASSWORD }}
- name: Docker meta
id: meta
uses: docker/metadata-action@v6
with:
images: ${{ secrets.DOCKERHUB_USERNAME }}/weknora-ui
- name: Build ui Image
uses: docker/build-push-action@v7
with:
push: true
platforms: linux/amd64,linux/arm64
file: frontend/Dockerfile
context: ./frontend
build-args: |
VITE_FRONTEND_COMMIT=${{ steps.version.outputs.commit_id }}
labels: ${{ steps.meta.outputs.labels }}
tags: ${{ steps.meta.outputs.tags }}
cache-from: type=gha,scope=build-ui
cache-to: type=gha,scope=build-ui,mode=max
build-docreader:
runs-on: ubuntu-latest
steps:
- name: Free Disk Space
uses: jlumbroso/free-disk-space@main
with:
# this might remove tools that are actually needed,
# if set to "true" but frees about 6 GB
tool-cache: false
# all of these default to true, but feel free to set to
# "false" if necessary for your workflow
android: true
dotnet: true
haskell: true
large-packages: true
docker-images: true
swap-storage: true
- name: Checkout code
uses: actions/checkout@v6
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_PASSWORD }}
- name: Docker meta
id: meta
uses: docker/metadata-action@v6
with:
images: ${{ secrets.DOCKERHUB_USERNAME }}/weknora-docreader
- name: Build docreader Image
uses: docker/build-push-action@v7
with:
push: true
platforms: linux/amd64,linux/arm64
file: docker/Dockerfile.docreader
context: .
labels: ${{ steps.meta.outputs.labels }}
tags: ${{ steps.meta.outputs.tags }}
cache-from: type=gha,scope=build-docreader
cache-to: type=gha,scope=build-docreader,mode=max
build-sandbox:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v6
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_PASSWORD }}
- name: Docker meta
id: meta
uses: docker/metadata-action@v6
with:
images: ${{ secrets.DOCKERHUB_USERNAME }}/weknora-sandbox
- name: Build sandbox Image
uses: docker/build-push-action@v7
with:
push: true
platforms: linux/amd64,linux/arm64
file: docker/Dockerfile.sandbox
target: sandbox
context: .
labels: ${{ steps.meta.outputs.labels }}
tags: ${{ steps.meta.outputs.tags }}
cache-from: type=gha,scope=build-sandbox
cache-to: type=gha,scope=build-sandbox,mode=max
# Cube builds templates straight from the image and gates the build on
# GET :49983/health, so it needs the variant with envd baked in.
- name: Docker meta (Cube variant)
id: meta-cube
uses: docker/metadata-action@v6
with:
images: ${{ secrets.DOCKERHUB_USERNAME }}/weknora-sandbox
flavor: |
suffix=-cube,onlatest=true
- name: Build sandbox Cube Image
uses: docker/build-push-action@v7
with:
push: true
platforms: linux/amd64,linux/arm64
file: docker/Dockerfile.sandbox
target: cube
context: .
labels: ${{ steps.meta-cube.outputs.labels }}
tags: ${{ steps.meta-cube.outputs.tags }}
cache-from: type=gha,scope=build-sandbox-cube
cache-to: type=gha,scope=build-sandbox-cube,mode=max
- name: Docker meta (desktop variant)
id: meta-desktop
uses: docker/metadata-action@v6
with:
images: ${{ secrets.DOCKERHUB_USERNAME }}/weknora-sandbox
flavor: |
suffix=-desktop,onlatest=true
- name: Build sandbox desktop Image
uses: docker/build-push-action@v7
with:
push: true
platforms: linux/amd64,linux/arm64
file: docker/Dockerfile.sandbox
target: desktop
context: .
labels: ${{ steps.meta-desktop.outputs.labels }}
tags: ${{ steps.meta-desktop.outputs.tags }}
cache-from: type=gha,scope=build-sandbox-desktop
cache-to: type=gha,scope=build-sandbox-desktop,mode=max
- name: Docker meta (desktop Cube variant)
id: meta-desktop-cube
uses: docker/metadata-action@v6
with:
images: ${{ secrets.DOCKERHUB_USERNAME }}/weknora-sandbox
flavor: |
suffix=-desktop-cube,onlatest=true
- name: Build sandbox desktop Cube Image
uses: docker/build-push-action@v7
with:
push: true
platforms: linux/amd64,linux/arm64
file: docker/Dockerfile.sandbox
target: desktop-cube
context: .
labels: ${{ steps.meta-desktop-cube.outputs.labels }}
tags: ${{ steps.meta-desktop-cube.outputs.tags }}
cache-from: type=gha,scope=build-sandbox-desktop-cube
cache-to: type=gha,scope=build-sandbox-desktop-cube,mode=max
build-app:
strategy:
matrix:
include:
- arch: amd64
platform: linux/amd64
runs: ubuntu-latest
- arch: arm64
platform: linux/arm64
runs: ubuntu-24.04-arm
runs-on: ${{ matrix.runs }}
timeout-minutes: 60
steps:
- name: Checkout code
uses: actions/checkout@v6
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_PASSWORD }}
- name: Docker meta
id: meta
uses: docker/metadata-action@v6
with:
images: ${{ secrets.DOCKERHUB_USERNAME }}/weknora-app
- name: Prepare version info
id: version
run: |
# 使用统一的版本管理脚本
eval "$(./scripts/get_version.sh env)"
echo "version=$VERSION" >> $GITHUB_OUTPUT
echo "commit_id=$COMMIT_ID" >> $GITHUB_OUTPUT
echo "build_time=$BUILD_TIME" >> $GITHUB_OUTPUT
echo "go_version=$GO_VERSION" >> $GITHUB_OUTPUT
platform=${{ matrix.platform }}
echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
# 显示版本信息
./scripts/get_version.sh info
- name: Build app Image
id: build
uses: docker/build-push-action@v7
with:
push: true
platforms: ${{ matrix.platform }}
file: docker/Dockerfile.app
context: .
build-args: |
${{ format('VERSION_ARG={0}', steps.version.outputs.version) }}
${{ format('COMMIT_ID_ARG={0}', steps.version.outputs.commit_id) }}
${{ format('BUILD_TIME_ARG={0}', steps.version.outputs.build_time) }}
${{ format('GO_VERSION_ARG={0}', steps.version.outputs.go_version) }}
WITH_ANYDOC=1
labels: ${{ steps.meta.outputs.labels }}
tags: ${{ secrets.DOCKERHUB_USERNAME }}/weknora-app
cache-from: type=gha,scope=build-app-${{ env.PLATFORM_PAIR }}
cache-to: type=gha,scope=build-app-${{ env.PLATFORM_PAIR }},mode=max
outputs: type=image,push-by-digest=true,name-canonical=true,push=true
- name: Export digest
run: |
mkdir -p ${{ runner.temp }}/digests
digest="${{ steps.build.outputs.digest }}"
touch "${{ runner.temp }}/digests/${digest#sha256:}"
- name: Upload digest
uses: actions/upload-artifact@v7
with:
name: digests-${{ env.PLATFORM_PAIR }}
path: ${{ runner.temp }}/digests/*
if-no-files-found: error
retention-days: 1
merge:
runs-on: ubuntu-latest
needs:
- build-app
steps:
- name: Download digests
uses: actions/download-artifact@v8
with:
path: ${{ runner.temp }}/digests
pattern: digests-*
merge-multiple: true
- name: Login to Docker Hub
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_PASSWORD }}
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Docker meta
id: meta
uses: docker/metadata-action@v6
with:
images: ${{ secrets.DOCKERHUB_USERNAME }}/weknora-app
- name: Create manifest list and push
working-directory: ${{ runner.temp }}/digests
run: |
docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
$(printf '${{ secrets.DOCKERHUB_USERNAME }}/weknora-app@sha256:%s ' *)
- name: Inspect image
run: |
docker buildx imagetools inspect ${{ secrets.DOCKERHUB_USERNAME }}/weknora-app:${{ steps.meta.outputs.version }}
+105
View File
@@ -0,0 +1,105 @@
name: DocReader
on:
push:
branches: [main]
paths:
- "docreader/**"
- "go.mod"
- "go.sum"
- "testdata/**"
- "docker/Dockerfile.docreader"
- "docker/Dockerfile.odl-hybrid"
- ".github/workflows/docreader.yml"
pull_request:
paths:
- "docreader/**"
- "go.mod"
- "go.sum"
- "testdata/**"
- "docker/Dockerfile.docreader"
- "docker/Dockerfile.odl-hybrid"
- ".github/workflows/docreader.yml"
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
env:
PYTHON_VERSION: "3.10.18"
GO_VERSION: "1.26"
GOPROXY: https://proxy.golang.org,direct
jobs:
verify:
name: Python tests and Go client tests
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v6
- uses: actions/setup-python@v6
with:
python-version: ${{ env.PYTHON_VERSION }}
- name: Install uv
uses: astral-sh/setup-uv@v4
with:
enable-cache: true
cache-dependency-glob: docreader/uv.lock
- name: Install Python dependencies
run: uv sync --project docreader --locked --no-dev --python ${{ env.PYTHON_VERSION }}
- name: Compile Python sources
run: uv run --project docreader --python ${{ env.PYTHON_VERSION }} python -m compileall -q docreader
# Both the Python proxy integration tests and Go TestReadURL launch
# WebKit, so install the browser and system libraries before either suite.
- name: Cache Playwright browsers
uses: actions/cache@v4
with:
path: ~/.cache/ms-playwright
key: ${{ runner.os }}-playwright-webkit-${{ hashFiles('docreader/uv.lock') }}
- name: Install Playwright WebKit
run: uv run --project docreader --python ${{ env.PYTHON_VERSION }} python -m playwright install --with-deps webkit
- name: Run Python tests
run: uv run --project docreader --python ${{ env.PYTHON_VERSION }} python -m unittest discover -s docreader/tests -p "test_*.py" -v
- uses: actions/setup-go@v6
with:
go-version: ${{ env.GO_VERSION }}
cache: true
- name: Download Go modules
run: go mod download
- name: Start DocReader gRPC server
run: |
uv run --project docreader --python ${{ env.PYTHON_VERSION }} python -m docreader.main &
echo $! > /tmp/docreader.pid
for i in $(seq 1 30); do
if nc -z 127.0.0.1 50051 2>/dev/null; then
echo "DocReader gRPC server is ready"
exit 0
fi
sleep 1
done
echo "DocReader gRPC server failed to start"
exit 1
- name: Run Go client tests
run: go test ./docreader/client ./docreader/proto
- name: Stop DocReader gRPC server
if: always()
run: |
if [ -f /tmp/docreader.pid ]; then
kill "$(cat /tmp/docreader.pid)" 2>/dev/null || true
fi
+268
View File
@@ -0,0 +1,268 @@
name: Build & Publish (dsh-weknora)
# Build, test, and publish the DeepSeek Harness plugin (packages/dsh-weknora/) to npm.
#
# Three jobs:
# test typecheck, unit tests, both halves of the contract, and a
# packaging check
# e2e install the package into a throwaway dsh profile and drive real
# tool calls through the harness agent loop against a mock backend
# publish on a `dsh-weknora-v*` tag only, publish to npm with provenance
#
# The e2e job pins the harness version so a plugin change is the only thing that
# can turn it red. The weekly drift job runs the same check against dsh@latest and
# is allowed to fail: it exists to notice a harness breaking change early, since
# dsh is in developer preview.
on:
push:
branches: [main]
tags:
- "dsh-weknora-v*"
paths:
- "packages/dsh-weknora/**"
- ".github/workflows/dsh-plugin.yml"
pull_request:
paths:
- "packages/dsh-weknora/**"
- ".github/workflows/dsh-plugin.yml"
schedule:
# Monday 03:00 UTC: catch a harness release that breaks the plugin.
- cron: "0 3 * * 1"
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
env:
# The harness release this plugin is verified against. Bump it together with
# the compatibility note in packages/dsh-weknora/README.md.
DSH_PINNED_SPEC: "@deepseek-ai/dsh@0.1.0-rc.8"
# The contract's Go half lives in this repository's module. app.yml runs it
# only for a Go diff, so a change to the fixture or to the plugin alone would
# otherwise skip the side that checks WeKnora still serves those calls.
GO_VERSION: "1.26"
# `dsh plugin add` shells out to pnpm to install into the profile, and the
# runner image ships only npm and yarn. The profile it writes carries its
# settings in pnpm-workspace.yaml, which pnpm 10 is the first to read.
PNPM_VERSION: "10"
jobs:
test:
name: Typecheck, test, pack
runs-on: ubuntu-latest
timeout-minutes: 15
defaults:
run:
working-directory: packages/dsh-weknora
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v4
with:
node-version: "24"
cache: npm
cache-dependency-path: packages/dsh-weknora/package-lock.json
- name: Install dependencies
run: npm ci || npm install
- name: Typecheck
run: npm run typecheck
- name: Build
run: npm run build
- name: Unit and contract tests
run: node --test "test/*.test.mjs"
- uses: actions/setup-go@v6
with:
go-version: ${{ env.GO_VERSION }}
cache: true
- name: Contract tests against WeKnora's Go types
working-directory: ${{ github.workspace }}
run: go test ./packages/dsh-weknora/contract/...
- name: Pack and verify the published file list
run: |
set -e
npm pack --dry-run --json > pack.json
node -e "
const files = require('./pack.json')[0].files.map(f => f.path);
const required = ['dist/index.js', 'dist/index.d.ts', 'cordis.patch.yml', 'README.md', 'package.json'];
const missing = required.filter(name => !files.includes(name));
if (missing.length > 0) {
console.error('missing from the tarball: ' + missing.join(', '));
process.exit(1);
}
const leaked = files.filter(name => name.startsWith('test/') || name.startsWith('src/'));
if (leaked.length > 0) {
console.error('unexpected files in the tarball: ' + leaked.join(', '));
process.exit(1);
}
console.log('tarball contents verified: ' + files.length + ' files');
"
rm pack.json
e2e:
name: End-to-end inside dsh (pinned)
runs-on: ubuntu-latest
# Cold cache: npm install @deepseek-ai/dsh takes ~15 min; keep headroom.
timeout-minutes: 25
defaults:
run:
working-directory: packages/dsh-weknora
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v4
with:
node-version: "24"
cache: npm
cache-dependency-path: packages/dsh-weknora/package-lock.json
- uses: pnpm/action-setup@v4
with:
version: ${{ env.PNPM_VERSION }}
# The e2e script installs @deepseek-ai/dsh on first run (~15 min uncached).
# Reuse the install across workflow runs; bump DSH_PINNED_SPEC to refresh.
- name: Cache pinned dsh install
uses: actions/cache@v4
with:
path: .cache/dsh-e2e-install
key: dsh-e2e-${{ env.DSH_PINNED_SPEC }}
- name: Install dependencies
run: npm ci || npm install
- name: Build
run: npm run build
- name: Run the plugin inside a real dsh profile
env:
DSH_PACKAGE_SPEC: ${{ env.DSH_PINNED_SPEC }}
DSH_INSTALL_DIR: ${{ github.workspace }}/.cache/dsh-e2e-install
DSH_E2E_LOG: ${{ runner.temp }}/dsh-weknora-e2e.log
run: node test/e2e/run-in-dsh.mjs
- name: Upload the transcript
if: always()
uses: actions/upload-artifact@v4
with:
name: dsh-weknora-e2e-transcript
path: ${{ runner.temp }}/dsh-weknora-e2e.log
if-no-files-found: ignore
drift:
name: End-to-end inside dsh (latest, advisory)
if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
timeout-minutes: 25
continue-on-error: true
defaults:
run:
working-directory: packages/dsh-weknora
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v4
with:
node-version: "24"
cache: npm
cache-dependency-path: packages/dsh-weknora/package-lock.json
- uses: pnpm/action-setup@v4
with:
version: ${{ env.PNPM_VERSION }}
- name: Week id for dsh@latest cache
id: week
run: echo "id=$(date -u +%G-W%V)" >> "$GITHUB_OUTPUT"
# dsh@latest moves; refresh the cache weekly.
- name: Cache latest dsh install
uses: actions/cache@v4
with:
path: .cache/dsh-e2e-install-latest
key: dsh-e2e-latest-${{ steps.week.outputs.id }}
- name: Install dependencies
run: npm ci || npm install
- name: Build
run: npm run build
- name: Run against the latest harness release
env:
DSH_PACKAGE_SPEC: "@deepseek-ai/dsh@latest"
DSH_INSTALL_DIR: ${{ github.workspace }}/.cache/dsh-e2e-install-latest
run: node test/e2e/run-in-dsh.mjs
publish:
name: Publish to npm
needs: [test, e2e]
if: startsWith(github.ref, 'refs/tags/dsh-weknora-v')
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: read
id-token: write
environment:
name: npm-publish
url: https://www.npmjs.com/package/@wxg-prc-cpg/dsh-weknora
defaults:
run:
working-directory: packages/dsh-weknora
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v4
with:
node-version: "24"
registry-url: "https://registry.npmjs.org"
cache: npm
cache-dependency-path: packages/dsh-weknora/package-lock.json
- name: Install dependencies
run: npm ci || npm install
- name: Build
run: npm run build
- name: Check the tag names the packaged version
run: |
set -e
version="$(node -p "require('./package.json').version")"
expected="dsh-weknora-v${version}"
if [ "$GITHUB_REF_NAME" != "$expected" ]; then
echo "::error::tag $GITHUB_REF_NAME does not name the packaged version $version (expected $expected)."
echo "::error::Bump packages/dsh-weknora/package.json, or retag — publishing here would ship a version the tag does not name."
exit 1
fi
- name: Check whether this version is already published
id: check_npm
run: |
set -e
name="$(node -p "require('./package.json').name")"
version="$(node -p "require('./package.json').version")"
echo "packaged: $name@$version"
if npm view "$name@$version" version >/dev/null 2>&1; then
echo "should_publish=false" >> "$GITHUB_OUTPUT"
echo "::warning::$name $version is already on npm; skipping publish. Bump package.json to release."
else
echo "should_publish=true" >> "$GITHUB_OUTPUT"
fi
- name: Publish
if: steps.check_npm.outputs.should_publish == 'true'
run: npm publish --provenance --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
+75
View File
@@ -0,0 +1,75 @@
name: Frontend
on:
push:
branches: [main]
paths:
- "frontend/**"
- "scripts/build_frontend_dist.sh"
- "scripts/test_embed_nginx.py"
- ".github/workflows/frontend.yml"
pull_request:
paths:
- "frontend/**"
- "scripts/build_frontend_dist.sh"
- "scripts/test_embed_nginx.py"
- ".github/workflows/frontend.yml"
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
env:
NODE_VERSION: "24"
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
jobs:
verify:
name: Test, type-check, and build
runs-on: ubuntu-latest
timeout-minutes: 20
defaults:
run:
working-directory: frontend
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
with:
node-version: ${{ env.NODE_VERSION }}
cache: npm
cache-dependency-path: frontend/package-lock.json
- name: Install dependencies
run: npm ci --no-audit --no-fund
- name: Run tests
run: npm test
- name: Type-check
run: npm run type-check
- name: Build
run: npm run build
docker-image:
name: Docker multi-stage image
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v6
- name: Build UI image
run: |
docker build \
-f frontend/Dockerfile \
--build-arg VITE_FRONTEND_COMMIT="${GITHUB_SHA::7}" \
-t weknora-ui:ci \
frontend/
- name: Test embed and MCP proxy routes
run: python3 scripts/test_embed_nginx.py weknora-ui:ci
+59
View File
@@ -0,0 +1,59 @@
name: Go Lint Cache
# Action caches written by a pull request run are scoped to that pull request,
# so only runs on the default branch produce caches every pull request can
# restore. Without this workflow each pull request would recompile the whole
# package graph from scratch (~6 minutes for the root module, versus ~40s warm).
#
# This lives apart from go-lint.yml rather than as a conditional job inside it:
# a job skipped by `if` still surfaces as a check on every pull request, and
# GitHub renders its name with the matrix expression unexpanded.
on:
push:
branches: [main]
paths:
- "**/*.go"
- "**/go.mod"
- "**/go.sum"
- ".golangci.yml"
- ".github/workflows/go-lint-cache.yml"
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
env:
GO_VERSION: "1.26"
GOLANGCI_LINT_VERSION: "v2.12.2"
GOPROXY: https://proxy.golang.org,direct
jobs:
warm-cache:
name: warm lint cache (${{ matrix.module }})
runs-on: ubuntu-latest
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
module: [".", "cli", "client"]
steps:
- uses: actions/checkout@v6
- uses: actions/setup-go@v6
with:
go-version: ${{ env.GO_VERSION }}
cache-dependency-path: ${{ matrix.module }}/go.sum
- uses: golangci/golangci-lint-action@v9
with:
version: ${{ env.GOLANGCI_LINT_VERSION }}
working-directory: ${{ matrix.module }}
# This workflow exists for its cache side effect only; the backlog of
# existing findings must not turn main red. The run still prints the
# full report, which makes a manual dispatch a useful backlog view.
args: --issues-exit-code=0
+115
View File
@@ -0,0 +1,115 @@
name: Go Lint
# The repository carries a large backlog of pre-existing golangci-lint findings,
# so pull requests are only judged on the code they introduce. The filter needs
# a pull request diff, which is why this workflow has no other trigger; the
# companion go-lint-cache.yml keeps the caches this job restores from warm on
# main.
#
# The filter is golangci-lint's own `--new-from-merge-base` rather than the
# action's `only-new-issues`, because that option asks the GitHub API for the
# pull request patch and the API refuses any diff over 20000 lines
# ("code": "too_large"). On a large pull request the action silently falls back
# to linting everything, which reports the entire backlog and can never pass.
# Computing the merge base from git has no size limit, and `fetch-depth: 0`
# below is what makes the base commit available to do it.
on:
pull_request:
paths:
- "**/*.go"
- "**/go.mod"
- "**/go.sum"
- ".golangci.yml"
- ".github/workflows/go-lint.yml"
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
env:
GO_VERSION: "1.26"
GOLANGCI_LINT_VERSION: "v2.12.2"
GOPROXY: https://proxy.golang.org,direct
jobs:
# Path filters above start this workflow for any Go change; the matrix still
# used to lint all three modules. Detect which modules the PR actually
# touches so a root-only change (migrations test, handler, …) does not queue
# cli/ and client/ runners. Changing .golangci.yml or this workflow still
# lints every module, since they share the root config.
changes:
name: detect lint modules
runs-on: ubuntu-latest
outputs:
modules: ${{ steps.detect.outputs.modules }}
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Detect changed modules
id: detect
shell: bash
run: |
diff_range="${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }}"
modules=()
if git diff --name-only --diff-filter=ACMR "$diff_range" -- \
.golangci.yml .github/workflows/go-lint.yml | grep -q .; then
modules=("." "cli" "client")
else
if git diff --name-only --diff-filter=ACMR "$diff_range" -- \
'*.go' ':!cli/**' ':!client/**' go.mod go.sum | grep -q .; then
modules+=(".")
fi
if git diff --name-only --diff-filter=ACMR "$diff_range" -- 'cli/**' | grep -q .; then
modules+=("cli")
fi
if git diff --name-only --diff-filter=ACMR "$diff_range" -- 'client/**' | grep -q .; then
modules+=("client")
fi
fi
json="["
first=1
for m in "${modules[@]}"; do
if [ "$first" -eq 1 ]; then
first=0
else
json+=","
fi
json+="\"${m}\""
done
json+="]"
echo "modules=${json}" >> "$GITHUB_OUTPUT"
echo "Lint modules: ${json}"
golangci:
name: golangci-lint (${{ matrix.module }})
needs: changes
if: needs.changes.outputs.modules != '[]'
runs-on: ubuntu-latest
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
module: ${{ fromJSON(needs.changes.outputs.modules) }}
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
- uses: actions/setup-go@v6
with:
go-version: ${{ env.GO_VERSION }}
cache-dependency-path: ${{ matrix.module }}/go.sum
- uses: golangci/golangci-lint-action@v9
with:
version: ${{ env.GOLANGCI_LINT_VERSION }}
working-directory: ${{ matrix.module }}
# Deliberately off: see the note at the top of this file. The same
# filtering is done below, from git.
only-new-issues: false
args: --new-from-merge-base=${{ github.event.pull_request.base.sha }}
+72
View File
@@ -0,0 +1,72 @@
name: Helm
on:
push:
branches:
- main
paths:
- "helm/**"
- ".github/workflows/helm.yml"
pull_request:
paths:
- "helm/**"
- ".github/workflows/helm.yml"
permissions:
contents: read
jobs:
chart:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Set up Helm
uses: azure/setup-helm@v4
with:
version: v3.19.0
- name: Lint chart
run: helm lint ./helm
- name: Set up Python
uses: actions/setup-python@v6
with:
python-version: '3.12'
- name: Verify App rollout and storage examples
run: |
python -m pip install PyYAML
python -m unittest discover -s helm/tests -v
- name: Verify application image tags
shell: bash
run: |
set -euo pipefail
render_image() {
local template="$1"
shift
helm template weknora ./helm \
--show-only "$template" \
--set secrets.dbPassword=test \
--set secrets.redisPassword=test \
--set secrets.jwtSecret=test \
"$@" \
| awk '$1 == "image:" { print $2; exit }'
}
app_image="$(render_image templates/app.yaml)"
frontend_image="$(render_image templates/frontend.yaml)"
docreader_image="$(render_image templates/docreader.yaml)"
app_tag="${app_image##*:}"
test "${frontend_image##*:}" = "$app_tag"
test "${docreader_image##*:}" = "$app_tag"
frontend_override="$(render_image templates/frontend.yaml --set frontend.image.tag=ui-test)"
docreader_override="$(render_image templates/docreader.yaml --set docreader.image.tag=reader-test)"
test "$frontend_override" = "wechatopenai/weknora-ui:ui-test"
test "$docreader_override" = "wechatopenai/weknora-docreader:reader-test"
+149
View File
@@ -0,0 +1,149 @@
name: Build & Publish (mcp-server)
# Build, test, and publish the Python MCP server (mcp-server/) to PyPI.
# Publishing uses PyPI Trusted Publishing (OIDC) — no API token required,
# only the GitHub→PyPI OIDC trust configured on the repo.
#
# Release policy: publishing does NOT depend on tags. Bump the version in
# mcp-server/pyproject.toml (and the synced version strings in setup.py,
# __init__.py, weknora_mcp_server.py server_version, main.py --version),
# merge to main, and the pipeline builds + publishes automatically.
# A pre-publish check queries PyPI and skips upload if that version is
# already published, so re-running on an unchanged version stays green.
# Releases also still trigger on mcp-server-v* tags (back-compat).
on:
push:
branches: [main]
tags:
- "mcp-server-v*"
paths:
- "mcp-server/**"
- ".github/workflows/mcp-server.yml"
pull_request:
paths:
- "mcp-server/**"
- ".github/workflows/mcp-server.yml"
workflow_dispatch:
permissions:
contents: read
jobs:
test:
name: Test (Python ${{ matrix.python-version }})
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ["3.10", "3.11", "3.12", "3.13"]
defaults:
run:
working-directory: mcp-server
steps:
- uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v4
- name: Set up Python ${{ matrix.python-version }}
run: uv python install ${{ matrix.python-version }}
- name: Install dependencies (test extras)
run: uv sync --python ${{ matrix.python-version }} --extra test
- name: Run tests
# unittest avoids pytest importing __init__.py as a broken package root.
# Manual diagnostics live in check_imports.py (not matched by test_*.py).
run: uv run --python ${{ matrix.python-version }} python -m unittest discover -s . -p "test_*.py" -v
build:
name: Build sdist + wheel
needs: test
runs-on: ubuntu-latest
# Build on push to main, manual runs, and release tags — but never on PRs.
if: github.event_name != 'pull_request'
defaults:
run:
working-directory: mcp-server
steps:
- uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v4
- name: Set up Python
run: uv python install 3.12
- name: Build package
run: uv build
- name: Verify wheel contains upload_paths.py (regression guard)
run: |
set -e
if ! python3 -c "import glob, zipfile, sys; whl=glob.glob('dist/*.whl')[0]; z=zipfile.ZipFile(whl); sys.exit(0 if 'upload_paths.py' in z.namelist() else 1)"; then
echo "::error::upload_paths.py is missing from the wheel — check py-modules in pyproject.toml/setup.py"
exit 1
fi
echo "upload_paths.py present in wheel ✓"
- name: Upload artifacts
uses: actions/upload-artifact@v4
with:
name: dist
path: mcp-server/dist/
publish:
name: Publish to PyPI
needs: build
runs-on: ubuntu-latest
# Publish on push to main, manual runs (main/tags only), and release tags — never on PRs.
if: >-
github.event_name != 'pull_request' &&
(github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/mcp-server-v'))
permissions:
id-token: write
environment:
name: pypi
url: https://pypi.org/project/tencent-weknora-mcp/
steps:
- uses: actions/checkout@v4
- name: Check if version is already published
id: check_pypi
working-directory: mcp-server
# Read the version from pyproject.toml and query PyPI. If that exact
# version already exists, skip publishing (so re-runs on an unchanged
# version stay green instead of failing with "File already exists").
run: |
set -e
version="$(python3 -c 'import tomllib; print(tomllib.load(open("pyproject.toml","rb"))["project"]["version"])')"
echo "packaged version: $version"
exists="$(python3 -c '
import json, sys, urllib.request
v = sys.argv[1]
try:
d = json.load(urllib.request.urlopen("https://pypi.org/pypi/tencent-weknora-mcp/json"))
print("true" if v in d.get("releases", {}) else "false")
except Exception:
# If PyPI is unreachable or the project is brand-new (404), treat as unpublished.
print("false")
' "$version")"
echo "already on PyPI: $exists"
if [ "$exists" = "true" ]; then
echo "should_publish=false" >> "$GITHUB_OUTPUT"
echo "::warning::tencent-weknora-mcp $version is already on PyPI; skipping publish. Bump pyproject.toml (and synced version strings) to release new changes."
else
echo "should_publish=true" >> "$GITHUB_OUTPUT"
fi
- name: Download artifacts
if: steps.check_pypi.outputs.should_publish == 'true'
uses: actions/download-artifact@v4
with:
name: dist
path: dist/
- name: Publish to PyPI
if: steps.check_pypi.outputs.should_publish == 'true'
uses: pypa/gh-action-pypi-publish@release/v1
+452
View File
@@ -0,0 +1,452 @@
name: Release Lite Binaries
on:
# push:
# tags:
# - "v*"
workflow_dispatch:
inputs:
tag:
description: "Release tag (e.g. v0.2.0)"
required: true
concurrency:
group: release-lite-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: write
env:
GO_VERSION: "1.24"
NODE_VERSION: "22"
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
jobs:
# ── 1. Build frontend once, share as artifact (for Web CLI) ──
build-frontend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
with:
node-version: ${{ env.NODE_VERSION }}
cache: npm
cache-dependency-path: frontend/package-lock.json
- name: Build frontend
working-directory: frontend
run: |
npm ci
npm run build
- uses: actions/upload-artifact@v7
with:
name: frontend-dist
path: frontend/dist/
retention-days: 1
# ── 2a. Build Web CLI binary per platform (native CGO) ──
build-binary:
needs: build-frontend
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
goos: linux
goarch: amd64
- os: ubuntu-24.04-arm
goos: linux
goarch: arm64
- os: macos-14
goos: darwin
goarch: amd64
- os: macos-14
goos: darwin
goarch: arm64
runs-on: ${{ matrix.os }}
env:
CGO_ENABLED: 1
steps:
- uses: actions/checkout@v6
- uses: actions/setup-go@v6
with:
go-version: ${{ env.GO_VERSION }}
cache: true
- uses: actions/download-artifact@v8
with:
name: frontend-dist
path: web/
- name: Resolve version
id: ver
run: |
if [ -n "${{ inputs.tag }}" ]; then
VERSION="${{ inputs.tag }}"
else
VERSION="${GITHUB_REF#refs/tags/}"
fi
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
echo "Building ${VERSION} for ${{ matrix.goos }}/${{ matrix.goarch }}"
- name: Build
run: |
export EDITION=lite
eval "$(./scripts/get_version.sh env)"
LDFLAGS="-w -s $(./scripts/get_version.sh ldflags)"
export CGO_CFLAGS="-Wno-deprecated-declarations"
if [ "${{ matrix.goos }}" = "darwin" ]; then
export CGO_LDFLAGS="-Wl,-no_warn_duplicate_libraries"
fi
go build -tags "sqlite_fts5" -ldflags="${LDFLAGS}" \
-o WeKnora-lite ./cmd/server
- name: Package tarball
run: |
ARCHIVE="WeKnora-lite_${{ steps.ver.outputs.version }}_${{ matrix.goos }}_${{ matrix.goarch }}"
mkdir -p "${ARCHIVE}/web"
cp WeKnora-lite "${ARCHIVE}/"
bash ./scripts/copy-licenses.sh "${ARCHIVE}"
cp -r web/* "${ARCHIVE}/web/"
cp .env.lite.example "${ARCHIVE}/"
cp docs/LITE.md "${ARCHIVE}/README.md"
if [ -d config ]; then
cp -r config "${ARCHIVE}/config"
fi
if [ -d migrations/sqlite ]; then
mkdir -p "${ARCHIVE}/migrations/sqlite"
cp -r migrations/sqlite/* "${ARCHIVE}/migrations/sqlite/"
fi
if [ -f deploy/weknora-lite.service ]; then
cp deploy/weknora-lite.service "${ARCHIVE}/"
fi
tar czf "${ARCHIVE}.tar.gz" "${ARCHIVE}"
shasum -a 256 "${ARCHIVE}.tar.gz" > "${ARCHIVE}.tar.gz.sha256"
- uses: actions/upload-artifact@v7
with:
name: release-${{ matrix.goos }}-${{ matrix.goarch }}
path: |
WeKnora-lite_*.tar.gz
WeKnora-lite_*.tar.gz.sha256
retention-days: 3
# ── 2b. Build Desktop APP per platform (Wails) ──
build-desktop-app:
strategy:
fail-fast: false
matrix:
include:
- os: macos-14
platform: darwin/universal
arch_label: macOS_universal
artifact_name: desktop-macos-universal
- os: macos-14
platform: darwin/amd64
arch_label: macOS_amd64
artifact_name: desktop-macos-amd64
- os: macos-14
platform: darwin/arm64
arch_label: macOS_arm64
artifact_name: desktop-macos-arm64
- os: ubuntu-latest
platform: linux/amd64
arch_label: linux_amd64
artifact_name: desktop-linux-amd64
- os: windows-latest
platform: windows/amd64
arch_label: windows_amd64
artifact_name: desktop-windows-amd64
runs-on: ${{ matrix.os }}
env:
CGO_ENABLED: 1
steps:
- uses: actions/checkout@v6
- uses: actions/setup-go@v6
with:
go-version: ${{ env.GO_VERSION }}
cache: true
- uses: actions/setup-node@v6
with:
node-version: ${{ env.NODE_VERSION }}
cache: npm
cache-dependency-path: frontend/package-lock.json
- name: Install Wails CLI
run: go install github.com/wailsapp/wails/v2/cmd/wails@latest
- name: Install Linux dependencies
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.1-dev
- name: Install NSIS (Windows)
if: runner.os == 'Windows'
run: choco install nsis -y
- name: Resolve version
id: ver
shell: bash
run: |
if [ -n "${{ inputs.tag }}" ]; then
VERSION="${{ inputs.tag }}"
else
VERSION="${GITHUB_REF#refs/tags/}"
fi
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
- name: Pre-compile Go packages (Windows)
if: runner.os == 'Windows'
shell: bash
run: |
export GOLANG_PROTOBUF_REGISTRATION_CONFLICT=warn
export CGO_CFLAGS="-Wno-deprecated-declarations"
cd cmd/desktop
go build -p 1 -buildvcs=false -tags "desktop,sqlite_fts5,production" -o _prebuild_tmp.exe . || true
rm -f _prebuild_tmp.exe
- name: Build desktop app
shell: bash
run: |
export EDITION=lite
export GOLANG_PROTOBUF_REGISTRATION_CONFLICT=warn
eval "$(./scripts/get_version.sh env)"
LDFLAGS="$(./scripts/get_version.sh ldflags) -X 'google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=warn'"
export CGO_CFLAGS="-Wno-deprecated-declarations"
BUILD_TAGS="sqlite_fts5"
NSIS_FLAG=""
if [ "${{ runner.os }}" = "Linux" ]; then
BUILD_TAGS="sqlite_fts5 webkit2_41"
fi
if [ "${{ runner.os }}" = "macOS" ]; then
export CGO_LDFLAGS="-Wl,-no_warn_duplicate_libraries"
fi
if [ "${{ runner.os }}" = "Windows" ]; then
NSIS_FLAG="-nsis"
fi
bash ./scripts/check-license-bundle.sh
cd cmd/desktop
wails build -clean \
-tags "${BUILD_TAGS}" \
-platform "${{ matrix.platform }}" \
${NSIS_FLAG} \
-ldflags="${LDFLAGS}" \
-o "WeKnora Lite"
# ── macOS: bundle .app with resources, then create DMG ──
- name: Package macOS app
if: runner.os == 'macOS'
run: |
APP_BUNDLE="WeKnora Lite.app"
SRC="cmd/desktop/build/bin/${APP_BUNDLE}"
RESOURCES="${SRC}/Contents/Resources"
mkdir -p "${RESOURCES}/config"
mkdir -p "${RESOURCES}/migrations/sqlite"
bash ./scripts/copy-licenses.sh "${RESOURCES}"
if [ -f .env.lite.example ]; then
cp .env.lite.example "${RESOURCES}/.env"
fi
if [ -d migrations/sqlite ]; then
cp -r migrations/sqlite/* "${RESOURCES}/migrations/sqlite/"
fi
if [ -d config ]; then
cp -r config/* "${RESOURCES}/config/"
fi
DMG_NAME="WeKnora-Lite-App_${{ steps.ver.outputs.version }}_${{ matrix.arch_label }}"
DMG_SRC="dmg_staging"
mkdir -p "${DMG_SRC}"
cp -R "cmd/desktop/build/bin/${APP_BUNDLE}" "${DMG_SRC}/"
ln -s /Applications "${DMG_SRC}/Applications"
hdiutil create -volname "WeKnora Lite" \
-srcfolder "${DMG_SRC}" \
-ov -format UDZO \
"${DMG_NAME}.dmg"
shasum -a 256 "${DMG_NAME}.dmg" > "${DMG_NAME}.dmg.sha256"
# ── Linux: package tarball ──
- name: Package Linux app
if: runner.os == 'Linux'
run: |
ARCHIVE="WeKnora-Lite-App_${{ steps.ver.outputs.version }}_${{ matrix.arch_label }}"
mkdir -p "${ARCHIVE}"
cp "cmd/desktop/build/bin/WeKnora Lite" "${ARCHIVE}/"
bash ./scripts/copy-licenses.sh "${ARCHIVE}"
if [ -f .env.lite.example ]; then
cp .env.lite.example "${ARCHIVE}/"
fi
cp docs/LITE.md "${ARCHIVE}/README.md"
if [ -d config ]; then
cp -r config "${ARCHIVE}/config"
fi
if [ -d migrations/sqlite ]; then
mkdir -p "${ARCHIVE}/migrations/sqlite"
cp -r migrations/sqlite/* "${ARCHIVE}/migrations/sqlite/"
fi
tar czf "${ARCHIVE}.tar.gz" "${ARCHIVE}"
shasum -a 256 "${ARCHIVE}.tar.gz" > "${ARCHIVE}.tar.gz.sha256"
# ── Windows: NSIS installer includes licenses and corresponding source ──
- name: Package Windows app
if: runner.os == 'Windows'
shell: bash
run: |
ARCHIVE="WeKnora-Lite-App_${{ steps.ver.outputs.version }}_${{ matrix.arch_label }}"
INSTALLER="cmd/desktop/build/bin/WeKnora Lite-amd64-installer.exe"
# Do not publish a bare executable if NSIS was unavailable: the
# installer also carries the notices/source and supports auto-update.
test -f "$INSTALLER"
cp "$INSTALLER" "${ARCHIVE}_setup.exe"
sha256sum "${ARCHIVE}_setup.exe" > "${ARCHIVE}_setup.exe.sha256"
- uses: actions/upload-artifact@v7
with:
name: ${{ matrix.artifact_name }}
path: |
WeKnora-Lite-App_*
retention-days: 3
# ── 3. Create GitHub Release ──
release:
needs: [build-binary, build-desktop-app]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/download-artifact@v8
with:
pattern: release-*
merge-multiple: true
- uses: actions/download-artifact@v8
with:
pattern: desktop-*
merge-multiple: true
- name: Resolve version
id: ver
run: |
if [ -n "${{ inputs.tag }}" ]; then
VERSION="${{ inputs.tag }}"
else
VERSION="${GITHUB_REF#refs/tags/}"
fi
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
- name: Generate release notes
id: notes
run: |
cat > notes.md << 'NOTES'
## WeKnora Lite ${{ steps.ver.outputs.version }}
### Web CLI 版(命令行 / 服务器部署)
单二进制部署,零外部依赖(无需 Docker / PostgreSQL / Redis)。
```bash
# 1. 解压
tar xzf WeKnora-lite_${{ steps.ver.outputs.version }}_<os>_<arch>.tar.gz
cd WeKnora-lite_${{ steps.ver.outputs.version }}_<os>_<arch>
# 2. 配置
cp .env.lite.example .env.lite
# 编辑 .env.lite,至少确认 OLLAMA_BASE_URL 正确
# 3. 启动 Ollama(如尚未运行)
ollama serve &
ollama pull qwen2.5:7b
ollama pull nomic-embed-text
# 4. 运行
set -a && source .env.lite && set +a
./WeKnora-lite
# 访问 http://localhost:8080
```
| 文件 | 平台 |
|------|------|
| `WeKnora-lite_*_linux_amd64.tar.gz` | Linux x86_64 |
| `WeKnora-lite_*_linux_arm64.tar.gz` | Linux ARM64 |
| `WeKnora-lite_*_darwin_amd64.tar.gz` | macOS Intel |
| `WeKnora-lite_*_darwin_arm64.tar.gz` | macOS Apple Silicon |
---
### 桌面 APP 版(开箱即用,无需命令行)
原生桌面应用,内置 Web 服务,双击即可运行。
| 文件 | 平台 |
|------|------|
| `WeKnora-Lite-App_*_macOS_universal.dmg` | macOS (Intel + Apple Silicon) |
| `WeKnora-Lite-App_*_macOS_amd64.dmg` | macOS Intel |
| `WeKnora-Lite-App_*_macOS_arm64.dmg` | macOS Apple Silicon |
| `WeKnora-Lite-App_*_linux_amd64.tar.gz` | Linux x86_64 |
| `WeKnora-Lite-App_*_windows_amd64_setup.exe` | Windows x86_64 (安装包) |
详细文档见 [LITE.md](docs/LITE.md)。
NOTES
- name: Create release
env:
GH_TOKEN: ${{ github.token }}
run: |
gh release create "${{ steps.ver.outputs.version }}" \
--title "WeKnora Lite ${{ steps.ver.outputs.version }}" \
--notes-file notes.md \
WeKnora-lite_*.tar.gz \
WeKnora-lite_*.tar.gz.sha256 \
WeKnora-Lite-App_* || true
# ── 4. Update Homebrew Formula ──
update-homebrew:
needs: release
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
with:
ref: main
token: ${{ secrets.GITHUB_TOKEN }}
- name: Resolve version
id: ver
run: |
if [ -n "${{ inputs.tag }}" ]; then
VERSION="${{ inputs.tag }}"
else
VERSION="${GITHUB_REF#refs/tags/}"
fi
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
- name: Wait for release assets to be available
run: sleep 15
- name: Update Formula
run: ./scripts/update-homebrew-formula.sh "${{ steps.ver.outputs.version }}"
- name: Commit and push
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add Formula/weknora-lite.rb
if git diff --cached --quiet; then
echo "No changes to Formula"
else
git commit -m "formula: update weknora-lite to ${{ steps.ver.outputs.version }}"
git push origin main
fi
+76
View File
@@ -0,0 +1,76 @@
# 忽略所有隐藏文件和目录
.*
# 但不忽略特定隐藏文件和目录
!.env.example
!.env.lite.example
!.gitignore
!.gitattributes
!.github/
!.dockerignore
!.golangci.yml
!.air.toml
# 敏感文件(真实环境配置只保留在本地,不入库;模板 .env.example 可入库)
*.pem
*_key
*_secret
*.key
*.crt
# IDE和编辑器文件
*.swp
*.swo
# 构建和依赖文件
node_modules/
dist/
build/
*.log
# 临时文件
tmp/
temp/
logs/
*.pid
# 本机构建产物(不入库)
artifacts/
WeKnora
Academy
WeKnora-lite
Academy-lite
cmd/desktop/build/bin/
/models/
test/data/mswag.txt
data/files/
data/weknora.db
data/weknora.db-wal
data/weknora.db-shm
skills-lock.json
web/
**/__pycache__
/scripts/scale_dev_jobs.sh
/server
frontend/.vite
frontend/chrome-extension/
WeKnora-Chrome-Extension
Academy-Chrome-Extension
packages/protoc-3.19.4-linux-x86_64.zip
Claude.md
# 本地测试脚本
configure-ollama.sh
fix-docker.sh
# WeChat Mini Program local/private configuration
miniprogram/project.private.config.json
# Staging dir for the Docker sandbox self-check probe (removed after each run)
.weknora-sandbox-check-*
.academy-sandbox-check-*
# Locally built BrowserSkill runtime and extension bundles
/artifacts/browserskill/
+24
View File
@@ -0,0 +1,24 @@
version: "2"
linters:
enable:
- lll # 控制行宽
- govet
- revive
settings:
lll:
line-length: 120
tab-width: 4
exclusions:
paths:
# swag embeds OpenAPI as single-line JSON strings; line-length is not meaningful.
- docs/docs\.go$
rules:
# swag annotations and struct tags cannot wrap, so a parameter with its
# enum list, a composed response type or a field's swag tags have to
# stay on one line.
- linters: [lll]
source: '^\s*// @(Param|Success|Failure|x-)|(swaggertype|extensions):"'
formatters:
enable:
- gofmt
- gofumpt
+1791
View File
File diff suppressed because it is too large. Load diff
+118
View File
@@ -0,0 +1,118 @@
class WeknoraLite < Formula
desc "Knowledge base management system — single-binary Lite edition"
homepage "https://github.com/Tencent/WeKnora"
version "0.3.6-test"
license "Apache-2.0"
on_macos do
on_arm do
url "https://github.com/Tencent/WeKnora/releases/download/v#{version}/WeKnora-lite_v#{version}_darwin_arm64.tar.gz"
sha256 "1da2d4eef99e5cf8aa7a58501baa059e9e20482e1bd65a36a82321a89926c104"
end
on_intel do
url "https://github.com/Tencent/WeKnora/releases/download/v#{version}/WeKnora-lite_v#{version}_darwin_amd64.tar.gz"
sha256 "c187e16ac7671a615f012c82ebd89786e11fcf67cccc773eff175e4bdf7c9c06"
end
end
on_linux do
on_arm do
url "https://github.com/Tencent/WeKnora/releases/download/v#{version}/WeKnora-lite_v#{version}_linux_arm64.tar.gz"
sha256 "bc4e184da005b60d1e8c037a61c58e643ebdc9bf14470fae6cd6227f52f02f1c"
end
on_intel do
url "https://github.com/Tencent/WeKnora/releases/download/v#{version}/WeKnora-lite_v#{version}_linux_amd64.tar.gz"
sha256 "cb34c50fb5b05555fca16084ffc7710524ff78badb3b1b82474eb89d21545d6e"
end
end
def install
libexec.install "WeKnora-lite"
pkgshare.install "web" if File.directory?("web")
pkgshare.install "config" if File.directory?("config")
pkgshare.install ".env.lite.example"
doc.install "README.md"
pkgshare.install "migrations" if File.directory?("migrations")
(bin/"weknora-lite").write <<~SH
#!/bin/bash
CONFIG_DIR="${WEKNORA_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/weknora}"
DATA_DIR="${WEKNORA_DATA_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/weknora}"
mkdir -p "$DATA_DIR/files" "$CONFIG_DIR/config" 2>/dev/null
if [ ! -f "$CONFIG_DIR/config/config.yaml" ]; then
cp -r "#{pkgshare}/config/" "$CONFIG_DIR/config/"
fi
if [ ! -d "$CONFIG_DIR/migrations" ] && [ -d "#{pkgshare}/migrations" ]; then
ln -sf "#{pkgshare}/migrations" "$CONFIG_DIR/migrations"
fi
if [ ! -f "$CONFIG_DIR/.env.lite" ]; then
cp "#{pkgshare}/.env.lite.example" "$CONFIG_DIR/.env.lite"
sed -i '' "s|DB_PATH=.*|DB_PATH=$DATA_DIR/weknora.db|" "$CONFIG_DIR/.env.lite"
sed -i '' "s|LOCAL_STORAGE_BASE_DIR=.*|LOCAL_STORAGE_BASE_DIR=$DATA_DIR/files|" "$CONFIG_DIR/.env.lite"
rm -f "$CONFIG_DIR/.env.lite-e"
echo ""
echo "已创建配置文件: $CONFIG_DIR/.env.lite"
echo "请根据需要编辑(如修改 LLM 地址、安全密钥等)。"
echo ""
fi
set -a
source "$CONFIG_DIR/.env.lite"
set +a
export DB_PATH="${DB_PATH:-$DATA_DIR/weknora.db}"
export LOCAL_STORAGE_BASE_DIR="${LOCAL_STORAGE_BASE_DIR:-$DATA_DIR/files}"
export WEKNORA_WEB_DIR="${WEKNORA_WEB_DIR:-#{pkgshare}/web}"
cd "$CONFIG_DIR"
exec "#{libexec}/WeKnora-lite" "$@"
SH
end
def post_install
(var/"weknora").mkpath
(var/"log").mkpath
end
service do
run [bin/"weknora-lite"]
keep_alive true
working_dir var/"weknora"
log_path var/"log/weknora-lite.log"
error_log_path var/"log/weknora-lite.log"
end
def caveats
<<~EOS
前台运行:
weknora-lite
后台服务(推荐):
brew services start weknora-lite # 启动并开机自启
brew services stop weknora-lite # 停止
brew services restart weknora-lite # 重启
brew services info weknora-lite # 查看状态
日志:
#{var}/log/weknora-lite.log
首次运行会自动创建配置文件:
~/.config/weknora/.env.lite
数据存储在:
~/.local/share/weknora/
如需修改配置(LLM 服务地址、安全密钥等):
$EDITOR ~/.config/weknora/.env.lite
brew services restart weknora-lite
EOS
end
test do
assert_predicate bin/"weknora-lite", :executable?
end
end
+283
View File
@@ -0,0 +1,283 @@
Tencent is pleased to support the open source community by making WeKnora available.
Copyright (C) 2026 Tencent. All rights reserved.
The open-source software included in this distribution may have been modified by Tencent (“Tencent Modifications”). All Tencent Modifications are Copyright (C) Tencent.
WeKnora is licensed under the MIT except for the third-party components listed below.
Terms of the MIT:
--------------------------------------------------------------------
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Dependencies and Licenses:
This open-source project, WeKnora, builds upon the following open-source software components, each of which remains licensed under its original license. Certain software may include modifications made by Tencent (“Tencent Modifications”), which are Copyright (C) Tencent.
In case you believe there have been errors in the attribution below, you may submit the concerns to us for review and correction.
Open Source Software Licensed under the Apache-2.0
--------------------------------------------------------------------
1. github.com/longbridgeapp/opencc
Copyright (c) github.com/longbridgeapp/opencc authors.
You may obtain the source code and detailed information about this component at https://pkg.go.dev/github.com/longbridgeapp/opencc.
Terms of the Apache-2.0
--------------------------------------------------------------------
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Open Source Software Licensed under the MIT
--------------------------------------------------------------------
1. anydoc
Copyright (c) 2026 Sideguide Technologies Inc.
Please note this software has been modified by Tencent in this distribution.
2. github.com/wailsapp/wails/v2
Copyright (c) github.com/wailsapp/wails/v2 authors.
You may obtain the source code and detailed information about this component at https://pkg.go.dev/github.com/wailsApp/wails/v2.
Terms of the MIT
--------------------------------------------------------------------
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+380
View File
@@ -0,0 +1,380 @@
.PHONY: help build run test clean docker-build-app docker-build-docreader docker-build-frontend docker-build-all docker-run migrate-up migrate-down docker-restart docker-stop start-all stop-all start-ollama stop-ollama build-images build-images-app build-images-docreader build-images-frontend clean-images check-env list-containers pull-images show-platform dev-start dev-stop dev-restart dev-logs dev-status dev-app dev-frontend docs install-swagger build-lite run-lite package-lite anydoc-lib build-anydoc
# Show help
help:
@echo "WeKnora Makefile 帮助"
@echo ""
@echo "基础命令:"
@echo " build 构建应用"
@echo " run 运行应用"
@echo " test 运行测试"
@echo " anydoc-lib 构建 anydoc 静态库(需要 Rust 工具链)"
@echo " build-anydoc 构建带 anydoc 解析引擎的应用"
@echo " clean 清理构建文件"
@echo ""
@echo "Docker 命令:"
@echo " docker-build-app 构建应用 Docker 镜像 (wechatopenai/weknora-app)"
@echo " docker-build-docreader 构建文档读取器镜像 (wechatopenai/weknora-docreader)"
@echo " docker-build-frontend 构建前端镜像 (wechatopenai/weknora-ui)"
@echo " docker-build-all 构建所有 Docker 镜像"
@echo " docker-run 运行 Docker 容器"
@echo " docker-stop 停止 Docker 容器"
@echo " docker-restart 重启 Docker 容器"
@echo ""
@echo "服务管理:"
@echo " start-all 启动所有服务"
@echo " stop-all 停止所有服务"
@echo " start-ollama 仅启动 Ollama 服务"
@echo ""
@echo "镜像构建:"
@echo " build-images 从源码构建所有镜像"
@echo " build-images-app 从源码构建应用镜像"
@echo " build-images-docreader 从源码构建文档读取器镜像"
@echo " build-images-frontend 从源码构建前端镜像"
@echo " clean-images 清理本地镜像"
@echo ""
@echo "数据库:"
@echo " migrate-up 执行数据库迁移"
@echo " migrate-down 回滚数据库迁移"
@echo ""
@echo "开发工具:"
@echo " fmt 格式化代码"
@echo " lint 代码检查"
@echo " deps 安装依赖"
@echo " docs 生成 Swagger API 文档"
@echo " install-swagger 安装 swag 工具"
@echo ""
@echo "模型厂商目录:"
@echo " model-catalog-check 校验厂商目录(不变量 + 新旧行为对照 + 厂商测试)"
@echo " model-catalog-diff 对比 models.dev,输出模型元数据差异报告(需人工审阅)"
@echo " 可选: make model-catalog-diff VENDOR=deepseek"
@echo ""
@echo "环境检查:"
@echo " check-env 检查环境配置"
@echo " list-containers 列出运行中的容器"
@echo " pull-images 拉取最新镜像"
@echo " show-platform 显示当前构建平台"
@echo ""
@echo "开发模式(推荐):"
@echo " dev-start 启动开发环境基础设施(仅启动依赖服务)"
@echo " 可选: make dev-start DEV_ARGS=--odl-hybrid"
@echo " dev-stop 停止开发环境"
@echo " dev-restart 重启开发环境"
@echo " dev-logs 查看开发环境日志"
@echo " dev-status 查看开发环境状态"
@echo " dev-app 启动后端应用(本地运行,需先运行 dev-start)"
@echo " 已 make anydoc-lib 时自动链接 anydoc 引擎"
@echo " dev-frontend 启动前端(本地运行,需先运行 dev-start)"
@echo ""
@echo "Lite 模式(零外部依赖):"
@echo " build-lite 构建 Lite 版本(先构建前端到 web/,再构建 Go;SKIP_FRONTEND=1 跳过前端)"
@echo " run-lite 构建并启动 Lite 版本"
@echo " package-lite 构建并打包 Lite 发行包(tarball)"
@echo " package-mac-app 构建并打包 macOS 桌面应用 (.app)"
# Go related variables
BINARY_NAME=WeKnora
MAIN_PATH=./cmd/server
# Docker related variables
DOCKER_IMAGE=wechatopenai/weknora-app
DOCKER_TAG=latest
# Platform detection
ifeq ($(shell uname -m),x86_64)
PLATFORM=linux/amd64
else ifeq ($(shell uname -m),aarch64)
PLATFORM=linux/arm64
else ifeq ($(shell uname -m),arm64)
PLATFORM=linux/arm64
else
PLATFORM=linux/amd64
endif
# Build the application
build:
go build -o $(BINARY_NAME) $(MAIN_PATH)
# Build the anydoc static archive (Rust) that the `anydoc` build tag links.
# Override the platform with TARGET=<rust-target-triple>.
anydoc-lib:
./scripts/build-anydoc-lib.sh
# Build the application with the in-process anydoc parser engine linked in.
build-anydoc: anydoc-lib
go build -tags anydoc -o $(BINARY_NAME) $(MAIN_PATH)
# Run the application
run: build
./$(BINARY_NAME)
# Run tests
test:
go test -v ./...
# Generate reviewed metadata + protocol overrides, then verify every model.
.PHONY: model-catalog-generate model-catalog-check
model-catalog-generate:
python3 scripts/model-catalog/generate.py
model-catalog-check:
python3 scripts/model-catalog/generate.py --check
go test ./internal/models/...
# Vendor catalog: report where our model metadata differs from models.dev.
# Development aid only — nothing is fetched at runtime and nothing is written
# automatically; review each line against the vendor's own documentation.
.PHONY: model-catalog-diff
model-catalog-diff:
@python3 scripts/model_catalog_diff.py $(if $(VENDOR),--vendor $(VENDOR),)
# Clean build artifacts
clean:
go clean
rm -f $(BINARY_NAME)
# Build Docker image
docker-build-app:
@echo "获取版本信息..."
@eval $$(./scripts/get_version.sh env); \
./scripts/get_version.sh info; \
docker build --platform $(PLATFORM) \
--build-arg VERSION_ARG="$$VERSION" \
--build-arg COMMIT_ID_ARG="$$COMMIT_ID" \
--build-arg BUILD_TIME_ARG="$$BUILD_TIME" \
--build-arg GO_VERSION_ARG="$$GO_VERSION" \
--build-arg WITH_ANYDOC=$${WITH_ANYDOC:-1} \
-f docker/Dockerfile.app -t $(DOCKER_IMAGE):$(DOCKER_TAG) .
# Build docreader Docker image
docker-build-docreader:
docker build --platform $(PLATFORM) -f docker/Dockerfile.docreader -t wechatopenai/weknora-docreader:latest .
# Build frontend Docker image (multi-stage: npm runs inside the builder stage)
docker-build-frontend:
@eval $$(./scripts/get_version.sh env); \
docker build --platform $(PLATFORM) \
--build-arg VITE_FRONTEND_COMMIT="$$COMMIT_ID" \
-f frontend/Dockerfile -t wechatopenai/weknora-ui:latest frontend/
# Build all Docker images
docker-build-all: docker-build-app docker-build-docreader docker-build-frontend
# Run Docker container (传统方式)
# Touch .env if missing — docker-compose.yml's `env_file: [.env]` is required
# for ${ENV} interpolation in builtin_models.yaml and would otherwise refuse
# to parse on fresh clones. `start-all` handles this via check_env_file; this
# direct path needs its own guard.
docker-run:
@[ -f .env ] || ([ -f .env.example ] && cp .env.example .env || touch .env)
docker-compose up
# 使用新脚本启动所有服务
start-all:
./scripts/start_all.sh
# 使用新脚本仅启动Ollama服务
start-ollama:
./scripts/start_all.sh --ollama
# 使用新脚本仅启动Docker容器
start-docker:
./scripts/start_all.sh --docker
# 使用新脚本停止所有服务
stop-all:
./scripts/start_all.sh --stop
# Stop Docker container (传统方式)
docker-stop:
docker-compose down
# 从源码构建镜像相关命令
build-images:
./scripts/build_images.sh
build-images-app:
./scripts/build_images.sh --app
build-images-docreader:
./scripts/build_images.sh --docreader
build-images-frontend:
./scripts/build_images.sh --frontend
clean-images:
./scripts/build_images.sh --clean
# Restart Docker container (stop, start)
docker-restart:
@[ -f .env ] || ([ -f .env.example ] && cp .env.example .env || touch .env)
docker-compose stop -t 60
docker-compose up
# Database migrations
migrate-up:
./scripts/migrate.sh up
migrate-down:
./scripts/migrate.sh down
migrate-version:
./scripts/migrate.sh version
migrate-create:
@if [ -z "$(name)" ]; then \
echo "Error: migration name is required"; \
echo "Usage: make migrate-create name=your_migration_name"; \
exit 1; \
fi
./scripts/migrate.sh create $(name)
migrate-force:
@if [ -z "$(version)" ]; then \
echo "Error: version is required"; \
echo "Usage: make migrate-force version=4"; \
exit 1; \
fi
./scripts/migrate.sh force $(version)
migrate-goto:
@if [ -z "$(version)" ]; then \
echo "Error: version is required"; \
echo "Usage: make migrate-goto version=3"; \
exit 1; \
fi
./scripts/migrate.sh goto $(version)
# Generate API documentation (Swagger)
#
# internal/localsandbox is excluded because cmd/server does not depend on it
# (its importers are behind the `desktop` build tag). Without the exclude,
# swag walks into the directory, follows its `const X = core.X` aliases and
# loads internal/localsandbox/core a second time through go/loader; that
# second load re-registers every model under its short name without enum
# values, so definitions lose their package-qualified names and
# docs/swagger_contract_test.go fails.
docs:
@echo "生成 Swagger API 文档..."
swag init -g $(MAIN_PATH)/main.go -o ./docs --parseDependency --parseInternal \
--exclude ./internal/localsandbox --overridesFile ./docs/swag.overrides
@echo "文档已生成到 ./docs 目录"
@echo "启动服务后访问 http://localhost:8080/swagger/index.html 查看文档"
# Install swagger tool
install-swagger:
go install github.com/swaggo/swag/cmd/swag@latest
# Format code
fmt:
go fmt ./...
# Lint code
lint:
golangci-lint run
# Install dependencies
deps:
go mod download
# Build for production
# google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=warn for qdrant milvus proto conflict
# GO_BUILD_TAGS adds optional build tags, e.g. GO_BUILD_TAGS=anydoc to link the
# in-process office document parser (run `make anydoc-lib` first).
build-prod:
VERSION=$$(git describe --tags --abbrev=0 2>/dev/null || echo "$${VERSION:-unknown}"); \
COMMIT_ID=$${COMMIT_ID:-unknown}; \
CGO_ENABLED=1 \
CGO_CFLAGS="-Wno-deprecated-declarations" \
CGO_LDFLAGS="$$(if [ "$$(uname)" = 'Darwin' ]; then echo '-Wl,-no_warn_duplicate_libraries'; fi)" \
BUILD_TIME=$${BUILD_TIME:-unknown}; \
GO_VERSION=$${GO_VERSION:-unknown}; \
LDFLAGS="-X 'github.com/Tencent/WeKnora/internal/handler.Version=$$VERSION' -X 'github.com/Tencent/WeKnora/internal/handler.Edition=standard' -X 'github.com/Tencent/WeKnora/internal/handler.CommitID=$$COMMIT_ID' -X 'github.com/Tencent/WeKnora/internal/handler.BuildTime=$$BUILD_TIME' -X 'github.com/Tencent/WeKnora/internal/handler.GoVersion=$$GO_VERSION' -X 'google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=warn'"; \
go build -tags "$(GO_BUILD_TAGS)" -ldflags="-w -s $$LDFLAGS" -o $(BINARY_NAME) $(MAIN_PATH)
# Build Lite version (single binary, SQLite + in-memory queue)
# 会先构建前端到 web/,再构建 Go 二进制;SKIP_FRONTEND=1 可跳过前端
build-lite:
@if [ -f frontend/package.json ] && [ "$${SKIP_FRONTEND:-}" != "1" ]; then \
echo ">> Building frontend for Lite..."; \
(cd frontend && npm ci --prefer-offline && npm run build) && \
rm -rf web && cp -r frontend/dist web; \
elif [ "$${SKIP_FRONTEND:-}" = "1" ]; then \
echo ">> Skipping frontend (SKIP_FRONTEND=1)"; \
else \
echo ">> No frontend/package.json, skipping frontend"; \
fi
export EDITION=lite; \
eval "$$(./scripts/get_version.sh env)"; \
LDFLAGS="$$(./scripts/get_version.sh ldflags) -X 'google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=warn'"; \
CGO_ENABLED=1 \
CGO_CFLAGS="-Wno-deprecated-declarations" \
CGO_LDFLAGS="$$(if [ "$$(uname)" = 'Darwin' ]; then echo '-Wl,-no_warn_duplicate_libraries'; fi)" \
go build -tags "sqlite_fts5" -ldflags="-w -s $$LDFLAGS" -o $(BINARY_NAME)-lite $(MAIN_PATH)
# Run Lite version with .env.lite defaults
run-lite: build-lite
@if [ ! -f .env.lite ]; then echo "Error: .env.lite not found"; exit 1; fi
@set -a && . ./.env.lite && set +a && ./$(BINARY_NAME)-lite
# Package Lite version into distributable tarball
package-lite:
./scripts/package-lite.sh
# Package Mac App
package-mac-app:
./scripts/package-mac-app.sh
download_spatial:
go run cmd/download/duckdb/duckdb.go
clean-db:
@echo "Cleaning database..."
@if [ $$(docker volume ls -q -f name=weknora_postgres-data) ]; then \
docker volume rm weknora_postgres-data; \
fi
@if [ $$(docker volume ls -q -f name=weknora_minio_data) ]; then \
docker volume rm weknora_minio_data; \
fi
@if [ $$(docker volume ls -q -f name=weknora_redis_data) ]; then \
docker volume rm weknora_redis_data; \
fi
# Environment check
check-env:
./scripts/start_all.sh --check
# List containers
list-containers:
./scripts/start_all.sh --list
# Pull latest images
pull-images:
./scripts/start_all.sh --pull
# Show current platform
show-platform:
@echo "当前系统架构: $(shell uname -m)"
@echo "Docker构建平台: $(PLATFORM)"
# Development mode commands
dev-start:
./scripts/dev.sh start $(DEV_ARGS)
dev-stop:
./scripts/dev.sh stop
dev-restart:
./scripts/dev.sh restart
dev-logs:
./scripts/dev.sh logs
dev-status:
./scripts/dev.sh status
dev-app:
./scripts/dev.sh app
dev-frontend:
./scripts/dev.sh frontend
+441
View File
@@ -0,0 +1,441 @@
<p align="center">
<a href="https://weknora.weixin.qq.com">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/hero-en-dark.svg">
<img src="./docs/images/readme/hero-en-light.svg" alt="WeKnora: find the answers, and put knowledge to work. Tencent's open-source knowledge management framework for Q&A, tasks and wikis." width="100%">
</picture>
</a>
</p>
<p align="center">
<a href="https://weknora.weixin.qq.com"><img alt="Website" src="https://img.shields.io/badge/website-weknora.weixin.qq.com-b8863b?style=flat-square&labelColor=101f38"></a>
<a href="https://weknora.weixin.qq.com/docs/"><img alt="Docs" src="https://img.shields.io/badge/docs-read-b8863b?style=flat-square&labelColor=101f38"></a>
<a href="./CHANGELOG.md"><img alt="Release" src="https://img.shields.io/badge/release-v0.8.3-b8863b?style=flat-square&labelColor=101f38"></a>
<a href="./LICENSE"><img alt="License" src="https://img.shields.io/badge/license-MIT-b8863b?style=flat-square&labelColor=101f38"></a>
<a href="https://github.com/Tencent/WeKnora/stargazers"><img alt="Stars" src="https://img.shields.io/github/stars/Tencent/WeKnora?style=flat-square&labelColor=101f38&color=b8863b"></a>
<br/>
<a href="https://chatbot.weixin.qq.com"><img alt="WeChat Dialog Open Platform" src="https://img.shields.io/badge/WeChat_Dialog-Open_Platform-07c160?style=flat-square&labelColor=101f38&logo=wechat&logoColor=white"></a>
<a href="https://chromewebstore.google.com/detail/jpemjbopikggjlmikmclgbmkhhopjdgd"><img alt="Chrome Extension" src="https://img.shields.io/badge/Chrome-extension-4285f4?style=flat-square&labelColor=101f38&logo=googlechrome&logoColor=white"></a>
<a href="https://clawhub.ai/lyingbug/weknora"><img alt="ClawHub Skill" src="https://img.shields.io/badge/ClawHub-skill-ff6b35?style=flat-square&labelColor=101f38"></a>
<a href="https://www.npmjs.com/package/@wxg-prc-cpg/dsh-weknora"><img alt="npm @wxg-prc-cpg/dsh-weknora" src="https://img.shields.io/npm/v/@wxg-prc-cpg/dsh-weknora?style=flat-square&label=dsh-weknora&labelColor=101f38&color=cb3837&logo=npm&logoColor=white"></a>
</p>
<p align="center">
<b>English</b> · <a href="./README_CN.md">简体中文</a> · <a href="./README_JA.md">日本語</a> · <a href="./README_KO.md">한국어</a>
</p>
<p align="center">
<a href="#overview">Overview</a> ·
<a href="#quick-start">Quick Start</a> ·
<a href="#whats-new">What's New</a> ·
<a href="#features">Features</a> ·
<a href="#clients-and-integrations">Clients</a> ·
<a href="#documentation">Docs</a> ·
<a href="#development">Development</a>
</p>
<p align="center">
<a href="https://trendshift.io/repositories/15289"><img src="https://trendshift.io/api/badge/repositories/15289" alt="Tencent/WeKnora | Trendshift" width="220" height="48"/></a>
</p>
## Overview
[WeKnora](https://weknora.weixin.qq.com) is an open-source, LLM-powered knowledge framework for enterprise document understanding, semantic retrieval and reasoning. It brings a team's documents together so they can be searched, reasoned over and kept up to date.
https://github.com/user-attachments/assets/5722b10d-d04d-49ed-a6cc-635a8c77d91f
<p align="center"><sub>1:52 · 1080p · No narration, English on-screen text</sub></p>
Use RAG to look things up, the agent for multi-step tasks, and the wiki to organize knowledge. All three work on the same knowledge bases.
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/capabilities-en-dark.svg">
<img src="./docs/images/readme/capabilities-en-light.svg" alt="01 RAG: answers you can check, with hybrid search, multimodal parsing and citations. 02 Agent: tasks done with knowledge and tools, with multi-step reasoning, skills and sandbox, the local browser, MCP tools and memory. 03 Wiki: documents organized into a wiki, with a knowledge graph and rollback." width="100%">
</picture>
**The agent's toolbox.** Skills installed from ClawHub / SkillHub / Git / ZIP run in session-persistent Docker / E2B / Cube sandboxes, with an interactive terminal and graphical desktop beside the chat. Through the BrowserSkill extension the agent operates the user's own Chrome or Edge, and external MCP services (OAuth included) can be connected and enabled tool by tool.
Beyond the three modes:
- **Memory and curation**: cross-session long-term memory keeps the profile, preferences and facts a user has confirmed. Folder uploads keep their directory tree, and retrieval chunks can be edited, diffed and rolled back.
- **Data sources and formats**: auto-sync from Feishu wiki / Feishu Drive / Confluence / GitLab / Tencent IMA / Notion / Yuque / DingTalk Docs / Seafile / RSS, with more on the way. 10+ document formats including PDF, Word, images, Excel and XMind; Office files are parsed in-process by anydoc.
- **Channels and integrations**: Q&A in WeCom, Feishu, Slack, Telegram and other IM apps; an embed widget for external websites; a built-in MCP Server for Cursor, Claude and other AI tools; scoped API keys with a principal model for programmatic access.
- **Models**: 29 built-in vendors with a generated model catalog, including OpenAI, DeepSeek, Qwen (Alibaba Cloud), Zhipu, Hunyuan, Gemini, MiniMax, NVIDIA, LiteLLM and Ollama.
- **Permissions and operations**: multi-workspace RBAC (four roles, per-resource ownership, per-workspace audit log), several storage instances per workspace, a runtime task-queue dashboard with worker-pool governance, and Langfuse tracing for agent steps, token usage and pipelines.
- **Deployment**: LLMs, vector databases and storage backends are all swappable. Deploy locally or on a private cloud and keep the data in your own environment.
## Quick Start
<table>
<tr>
<td width="33%" valign="top">
<img src="./website-docs/homepage/public/docs/_home/brands/wechat-dialog.png" width="28" height="28" alt=""><br/>
<sub>ONLINE</sub><br/>
<b>WeChat Dialog Open Platform</b><br/>
Manage knowledge bases online and connect Q&A to Official Accounts, Mini Programs and other WeChat scenarios.<br/><br/>
<a href="https://chatbot.weixin.qq.com/login">Open the platform →</a>
</td>
<td width="33%" valign="top">
<img src="./website-docs/homepage/public/docs/_home/brands/tencent-cloud.ico" width="28" height="28" alt=""><br/>
<sub>CLOUD</sub><br/>
<b>Tencent Cloud Lighthouse</b><br/>
Deploy WeKnora from an application template and run it on your own cloud server.<br/><br/>
<a href="https://mc.tencent.com/s69nKCVz">Deploy on Tencent Cloud →</a>
</td>
<td width="33%" valign="top">
<img src="./docs/images/readme/icons/server.svg" width="28" height="28" alt=""><br/>
<sub>SELF-HOSTED</sub><br/>
<b>Your own environment</b><br/>
Deploy with Docker or Kubernetes and configure models, storage and networking yourself.<br/><br/>
<a href="#run-with-docker-compose">Run with Docker Compose ↓</a>
</td>
</tr>
</table>
### Run with Docker Compose
Requires [Docker](https://www.docker.com/), [Docker Compose](https://docs.docker.com/compose/) and [Git](https://git-scm.com/).
```bash
git clone https://github.com/Tencent/WeKnora.git
cd WeKnora
cp .env.example .env # Edit .env as needed, see comments in the file
docker compose pull # Pull the latest images
docker compose up -d # Start core services
```
Then open **http://localhost** and follow the onboarding guide. A walkthrough with sample data is in the [Quickstart](https://weknora.weixin.qq.com/docs/01-getting-started/03-quickstart).
> [!TIP]
> To use a local Ollama model, run `ollama serve > /dev/null 2>&1 &` first. For the Ollama embedding model name, `OLLAMA_BASE_URL`, and RAM notes, see [Configuration](https://weknora.weixin.qq.com/docs/01-getting-started/04-configuration).
| Service | URL |
|---------|-----|
| Web UI | `http://localhost` |
| Backend API | `http://localhost:8080` |
| Langfuse Tracing | `http://localhost:3000` |
### Optional services
Add `--profile` flags to enable additional components; multiple profiles can be combined.
| Profile | Adds |
|---------|------|
| _(default)_ | Core services |
| `full` | All features |
| `neo4j` | Knowledge Graph (Neo4j) |
| `minio` | Object Storage (MinIO) |
| `langfuse` | Tracing (Langfuse) |
```bash
docker compose --profile neo4j --profile minio pull
docker compose --profile neo4j --profile minio up -d
docker compose down # Stop services
```
### Upgrading
If you already have WeKnora running and downloaded a newer release:
```bash
# Set WEKNORA_VERSION in .env to the target release (e.g. 0.8.3), or keep latest
docker compose pull # Pull images matching WEKNORA_VERSION
docker compose up -d # Recreate containers with new images
```
> [!NOTE]
> `docker compose up -d` alone reuses locally cached images and may leave the UI version out of sync with the release you downloaded. Read the [upgrade notes](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#upgrade-notes) before upgrading. Deployments older than v0.8.2 should also read the [v0.8.2 notes](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#upgrade-notes).
### Other ways to deploy
| Option | When to use it |
|--------|----------------|
| **Docker Compose** | The standard deployment above: all features, multiple services |
| **Kubernetes (Helm)** | Production clusters; the chart is in [`helm/`](./helm) |
| **Lite single binary** | Local or low-resource use with no external dependencies (SQLite + in-memory queue); see [Lite vs. standard](./docs/LITE.md) |
| **Desktop app** | The Lite runtime with a GUI, login-free start and a macOS host sandbox; no installer is published yet, so build it from source |
All options, hardware requirements and deployment topologies: [Installation guide](https://weknora.weixin.qq.com/docs/01-getting-started/02-installation).
> [!WARNING]
> WeKnora ships with login authentication, but for production deployments we strongly recommend that you:
> - deploy it in an internal / private network rather than on the public internet;
> - avoid exposing the service directly to public networks, to prevent information leakage;
> - configure proper firewall rules and access controls for the deployment environment;
> - regularly update to the latest version for security patches and improvements.
## What's New
### v0.8.3 <sub>· 2026-10-14 · [release notes](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3)</sub>
- **[Image gallery](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#images)**: browse document images and filter by source, caption, OCR and image attributes.
- **[Multimodal Embedding](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#multimodal-embedding)**: support for multimodal embedding models that encode text and images into a shared vector space, including Tencent WeMM-Embedding and Qwen3-VL-Embedding, with opt-in image-vector retrieval and compatible image-aware reranking.
- **[Wiki graph](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#wiki-graph)**: clearer group layouts and theme captions, with group focus, switching and return to the full graph.
- **[Source citations](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#conversation)**: navigate from an answer to the cited passage in the original document.
- **[Chat and tools](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#tools)**: on-demand attachment reading without a sandbox, unread replies, @ mention search, Docker terminals, Lite host skills and MCP interoperability updates.
- **[Administration and integrations](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#administration)**: platform user management, invitation-only signup mode, administrator model catalog, WeMM embeddings, TEI/Pinecone/Cohere reranking, Seafile and Traditional Chinese.
- **[Reliability](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#other-changes)**: broad retrieval, parsing, datasource, Wiki, OAuth and CLI fixes. Review [upgrade requirements](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#upgrade-notes) for registration modes, empty tool lists, database migrations and reindexing.
### v0.8.2 <sub>· 2026-09-24 · [release notes](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2)</sub>
Agents can operate the browser on your computer, knowledge bases can be published to other AI tools over MCP, and a running conversation can be steered, forked or rewound.
- **[Local Browser (BrowserSkill)](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#local-browser)**: agents drive the user's own Chrome / Edge through the open-source BrowserSkill extension, with a live task preview, pause / resume and hand-off for logins and CAPTCHAs.
- **[Built-in MCP Server](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#mcp-server)**: per-workspace `/mcp/<endpoint_id>` endpoints over Streamable HTTP, each with its own token, knowledge-base scope, rate limit and tool groups. The Python `mcp-server/` is deprecated.
- **[Conversation control](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#conversation-control)**: append requirements to a running turn, fork from any earlier question, rewind in place with sandbox checkpoints, and pick reasoning effort per session. Generated files are collected in a new artifacts library.
- **[Sandbox](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#sandbox)**: interactive terminal and graphical desktop; macOS Lite host sandbox with project folders; a sidebar Toolbox for skills, MCP services and the browser connection.
- **[Models](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#models)**: rebuilt model catalog (27 built-in vendors with generated context-window, max-output, reasoning and vision metadata). Agent retrieval tools are consolidated into `search_knowledge` / `read_document` / `list_documents`.
- **[Knowledge and platform](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#knowledge)**: Confluence and DingTalk Docs data sources; Bocha and Serply web search; Japanese UI; per-channel IM reply language; whitelist-only outbound mode.
> [!IMPORTANT]
> **Breaking:** DingTalk channels are Stream-only, and sandbox commands run as `root`. See the [upgrade notes](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#upgrade-notes).
### v0.8.0 <sub>· [release notes](https://weknora.weixin.qq.com/docs/07-releases/v0.8.0)</sub>
- **Skill sandbox runtime**: session-persistent Docker / E2B / Cube backends with per-tenant network policy; the Local host-process backend is removed and Docker is opt-in.
- **Tenant skill catalog**: install from ClawHub / SkillHub / git / zip, with per-sandbox snapshots, live progress, file browse/edit, and personal and workspace env vars.
- **Cross-session long-term memory**: profile / preference / fact / task / interest, auto-extracted with user confirmation, plus `search_memory`.
- **Parsing and sources**: in-process anydoc office parser; GitLab and Tencent IMA data sources; XMind parsing.
- **Ecosystem**: official DeepSeek Harness plugin `@wxg-prc-cpg/dsh-weknora`; LiteLLM; Exa and Metaso web search.
- **Chat**: chat artifacts, question outline and timestamps; context compaction and provider prompt-cache markers.
- **Security**: OIDC JWKS verification, optional complex passwords, document auto-tagging, and broad sandbox/security hardening.
<details>
<summary><b>Earlier releases (v0.2.0 – v0.7.2)</b></summary>
<br/>
- **v0.7.2** — Product documentation site; knowledge base folder tree; chunk editing with revision history; wiki page revisions; directly loadable file URLs (`resource_urls=public`); Feishu Drive data source; batch tagging; MCP Server 1.1 (29 tools); AWS S3 default credential chain.
- **v0.7.1** — Yunzhijia IM; Volcengine rerank; Zhipu AI web search; platform-scoped API keys; per-KB activity audit; FAQ filtering, tagging and export; Langfuse OTLP tracing; one-click Markdown export.
- **v0.7.0** — Scoped API keys and principal model; task-queue dashboard and worker-pool governance; multiple storage instances per workspace; temporary chat attachments; `@Skill / @MCP` mentions; mid-conversation MCP OAuth; QQBot and Lark IM; Redis TLS; `weknora` CLI v0.10.
- **v0.6.3** — Website embed widget & Integrations Center (secure-mode token exchange + rate limits); chat experience overhaul (citation popovers, RAG pipeline progress, streaming markdown); document multi-tag & batch reparse; Wiki folders & hierarchy navigation; RSS data source; MCP OAuth2; EPUB / MHTML parsing; agent model-readiness checks; model test debugger; session source filter; workspace deletion UI.
- **v0.6.2** — Per-upload process configuration with upload-confirm dialog; document reparse with `process_config`; `weknora` CLI v0.9 (bundled Agent Skills, `session stop`, auth/profile harmonization); KB marquee multi-select; HNSW index for 1024-dim pgvector embeddings; chat resources store refactor; Langfuse-only tracing (Jaeger removed).
- **v0.6.1** — Document parsing trace timeline (Langfuse-style span tree with stage-by-stage progress + stop-parse); OpenSearch vector store driver; declarative built-in models via YAML; system admin & consolidated platform settings + audit log; new-user onboarding guide; settings UI redesign; `weknora` CLI v0.7 / v0.8 (agent-first wire contract, NDJSON, `--dry-run`); OpenDataLoader + PaddleOCR-VL parsers; MCP server multi-transport (stdio / SSE / HTTP); per-model thinking-mode config; Tencent LKEAP rerank + native Gemini embeddings + MiniMax-M3.
- **v0.6.0** — Workspace RBAC (4-tier role matrix `Owner` / `Admin` / `Contributor` / `Viewer` + per-KB ownership + per-workspace audit log), workspace member management & multi-workspace UX, self-service workspaces; `weknora` CLI v0.4 GA with `mcp serve`; KB retrieval fan-out across vector stores; AES-256-GCM credential encryption + docreader gRPC TLS + Token; Zhipu embedder + Huawei OBS; server-side user preferences; Go 1.26.0. See [Tenants & auth](https://weknora.weixin.qq.com/docs/03-features/01-tenant-auth).
- **v0.5.2** — Wiki ingest scales to 40k-document KBs (task queue + DLQ); MCP human-in-the-loop tool approval; Anthropic / Apache Doris / Tencent VectorDB / KS3 / SearXNG backends; adaptive 3-tier chunking with live preview; global ⌘K command palette; Yuque connector + WeChat Mini Program; `weknora` CLI preview.
- **v0.5.1** — Knowledge-base batch management; workspace-wide IM channels overview; session search + user-scoped pinning; unified Model / Web Search / MCP settings cards; per-agent LLM timeout; desktop workspace switching.
- **v0.5.0** — Wiki Mode GA — agents auto-generate structured, interlinked Markdown wiki pages with a knowledge graph; wiki browser + visual graph in the UI.
- **v0.4.0** — WeKnora Cloud (hosted LLM + parsing); Chrome Extension; ClawHub Skill; WeChat IM; attachment processing; Azure OpenAI / Alibaba OSS; Notion connector; Baidu + Ollama web search; VectorStore management.
- **v0.3.6** — ASR (audio); Feishu data-source auto-sync; OIDC; IM quote-reply context + thread-based sessions; document summarization; Tavily search; parallel tool calling; agent @mention scope restriction.
- **v0.3.5** — Telegram / DingTalk / Mattermost IM; IM slash commands + QA queue; suggested questions; VLM auto-describe MCP tool images; Novita AI; channel tracking.
- **v0.3.4** — WeCom / Feishu / Slack IM; multimodal image support; NVIDIA model API; Weaviate; AWS S3; AES-256-GCM API-key encryption; built-in MCP service; hybrid-search optimization; `final_answer` tool.
- **v0.3.3** — Parent-child chunking; KB pinning; fallback response; passage cleaning for rerank; storage auto-creation; Milvus.
- **v0.3.2** — Knowledge Search entry; per-source parser & storage engine config; image rendering in local storage; document preview; Volcengine TOS; Mermaid rendering; batch session management; memory graph preview.
- **v0.3.0** — Shared Space; Agent Skills + sandboxed execution; custom agents; Data Analyst agent; thinking mode; Bing / Google web search; API Key auth; Helm chart; Korean i18n; Qdrant.
- **v0.2.0** — Agent Mode (ReACT); multi-type knowledge bases (FAQ + document); conversation strategy config; DuckDuckGo web search; MCP tool integration; new UI with agent mode switching; MQ async task management.
Full history: [`CHANGELOG.md`](./CHANGELOG.md).
</details>
## Product Tour
### Quick Q&A and smart reasoning
**Two ways to ask.** Quick Q&A answers from the knowledge base with RAG and cites the sources it used. In smart reasoning the agent plans multi-step work, searching, reading documents and calling tools and skills, and shows each step in the conversation. [Docs →](https://weknora.weixin.qq.com/docs/03-features/18-chat-experience)
<a href="./docs/images/readme/spotlight-qa-light.webp">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/spotlight-qa-dark.webp">
<img src="./docs/images/readme/spotlight-qa-light.webp" alt="Quick Q&A and smart reasoning" width="100%">
</picture>
</a>
### Local browser
**Operate the browser on your computer.** Through Tencent's open-source BrowserSkill extension, the agent opens pages and fills in forms in your own Chrome or Edge, and hands over to you for logins and CAPTCHAs. [Docs →](https://weknora.weixin.qq.com/docs/05-clients/09-local-browser)
<a href="./docs/images/readme/spotlight-browser-light.webp">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/spotlight-browser-dark.webp">
<img src="./docs/images/readme/spotlight-browser-light.webp" alt="Local browser" width="100%">
</picture>
</a>
### Skills and sandbox
**Run skills and produce files.** Docker, E2B and Cube backends are supported. Turns in the same session share one workspace, and generated files can be previewed and downloaded. Open the graphical desktop or interactive terminal beside the chat to follow each step and take over when needed. [Docs →](https://weknora.weixin.qq.com/docs/03-features/22-skills-sandbox)
<a href="./docs/images/readme/spotlight-sandbox-light.webp">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/spotlight-sandbox-dark.webp">
<img src="./docs/images/readme/spotlight-sandbox-light.webp" alt="Skills and sandbox" width="100%">
</picture>
</a>
### Toolbox: MCP services and skills
**Tools the agent can use.** Connect external MCP services and choose, tool by tool, which are enabled and which calls need approval. Install skills from ClawHub, SkillHub, Git or ZIP, manage them per workspace, and reuse them across sandboxes. [Docs →](https://weknora.weixin.qq.com/docs/03-features/22-skills-sandbox)
<a href="./docs/images/readme/spotlight-toolbox-light.webp">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/spotlight-toolbox-dark.webp">
<img src="./docs/images/readme/spotlight-toolbox-light.webp" alt="Toolbox: MCP services and skills" width="100%">
</picture>
</a>
### Automatic wiki
**Documents organized into a browsable wiki.** With Wiki enabled, WeKnora extracts people, products and concepts from knowledge-base documents into pages with source citations, organized by directory. The knowledge graph shows how pages relate; pages can be edited directly and every change can be rolled back. [Docs →](https://weknora.weixin.qq.com/docs/03-features/14-wiki)
<a href="./docs/images/readme/spotlight-wiki-light.webp">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/spotlight-wiki-dark.webp">
<img src="./docs/images/readme/spotlight-wiki-light.webp" alt="Automatic wiki" width="100%">
</picture>
</a>
### Observability
**Tracing and runtime monitoring.** Langfuse traces the reasoning, tool calls and token usage of each agent step. The document parsing timeline shows progress stage by stage, and the task-queue dashboard lists queued and failed tasks. [Docs →](https://weknora.weixin.qq.com/docs/03-features/16-observability)
<a href="./docs/images/readme/spotlight-observability-light.webp">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/spotlight-observability-dark.webp">
<img src="./docs/images/readme/spotlight-observability-light.webp" alt="Observability" width="100%">
</picture>
</a>
## Architecture
<a href="./docs/images/readme/architecture-en-light.svg">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/architecture-en-dark.svg">
<img src="./docs/images/readme/architecture-en-light.svg" alt="WeKnora architecture: clients and channels connect to the WeKnora app, where RAG Q&A, agent reasoning and auto wiki share one knowledge pipeline; the app calls runtime services and stores data in PostgreSQL, Redis and optional stores" width="100%">
</picture>
</a>
A modular pipeline from document parsing, vectorization and retrieval to LLM inference, in which every component can be replaced or extended. It runs locally or on a private cloud, and the Web UI needs no setup to get started. More: [Architecture overview](https://weknora.weixin.qq.com/docs/02-architecture/01-overview) · [RAG pipeline](https://weknora.weixin.qq.com/docs/02-architecture/04-rag-pipeline) · [Extension points](https://weknora.weixin.qq.com/docs/06-development/03-extension-points).
## Features
| Area | Highlights |
|------|------------|
| [Q&A and agent](https://weknora.weixin.qq.com/docs/03-features/07-agent) | Quick Q&A answers from knowledge bases with citations; smart reasoning runs a ReAct agent over knowledge bases, web search, MCP tools, skills and the local browser. Steer, fork or rewind a running conversation, and keep [long-term memory](https://weknora.weixin.qq.com/docs/03-features/23-memory) across sessions |
| [Wiki](https://weknora.weixin.qq.com/docs/03-features/14-wiki) | Agent-generated, interlinked wiki pages with a knowledge graph; in-browser editing, revision diff and rollback |
| [Skills and sandbox](https://weknora.weixin.qq.com/docs/03-features/22-skills-sandbox) | Skill catalog installed from ClawHub / SkillHub / Git / ZIP; session-persistent Docker / E2B / Cube sandboxes with network policy; terminal and graphical desktop beside the chat |
| [Knowledge bases](https://weknora.weixin.qq.com/docs/03-features/02-knowledge-base) | FAQ, document and wiki bases; folder tree; chunk editing with revisions; per-upload parsing, chunking and multimodal settings; auto-tagging |
| [Retrieval](https://weknora.weixin.qq.com/docs/03-features/05-retrieval-engines) | Keyword + vector hybrid search, rerank, parent-child chunking and GraphRAG ([Neo4j](https://weknora.weixin.qq.com/docs/03-features/09-knowledge-graph)); end-to-end evaluation with recall and BLEU / ROUGE |
| [Access and security](https://weknora.weixin.qq.com/docs/03-features/01-tenant-auth) | Workspace RBAC with four roles and an audit log; scoped API keys; OIDC; AES-256-GCM credential encryption; SSRF-safe outbound requests with a whitelist-only mode |
| [Operations](https://weknora.weixin.qq.com/docs/03-features/16-observability) | Langfuse tracing for agent steps, tokens and pipelines; document parsing timeline; task-queue dashboard with worker pools; automatic migrations on upgrade |
### Supported backends
| Component | Options |
|-----------|---------|
| [LLMs](https://weknora.weixin.qq.com/docs/03-features/06-models) | 29 built-in vendors, including OpenAI / Azure OpenAI / Anthropic / DeepSeek / Qwen / Zhipu / Hunyuan / Doubao / Gemini / MiniMax / NVIDIA / SiliconFlow / OpenRouter / LiteLLM / Ollama |
| Embeddings | Ollama / BGE / GTE / Zhipu / OpenAI-compatible APIs |
| Vector databases | PostgreSQL (pgvector + ParadeDB) / Elasticsearch / OpenSearch / Milvus / Weaviate / Qdrant / Apache Doris / Tencent VectorDB |
| [Object storage](https://weknora.weixin.qq.com/docs/03-features/19-storage-backends) | Local / Tencent Cloud COS / MinIO / AWS S3 / Volcengine TOS / Alibaba Cloud OSS / Kingsoft Cloud KS3 / Huawei Cloud OBS |
| [Document formats](https://weknora.weixin.qq.com/docs/03-features/03-document-parsing) | PDF / Word / PPT / Excel / CSV / TXT / Markdown / HTML / EPUB / MHTML / JSON / XMind / images |
| [Data sources](https://weknora.weixin.qq.com/docs/03-features/10-datasource) | Feishu wiki / Feishu Drive / Lark / Confluence / GitLab / Tencent IMA / Notion / Yuque / DingTalk Docs / Seafile / RSS |
| [IM channels](https://weknora.weixin.qq.com/docs/03-features/12-im-integration) | WeCom / Feishu / Lark / QQBot / Slack / Telegram / DingTalk / Mattermost / WeChat / Yunzhijia |
| [Web search](https://weknora.weixin.qq.com/docs/03-features/11-web-search) | DuckDuckGo / Bing / Google / Tavily / Baidu / Ollama / SearXNG / Keenable / Zhipu AI / Exa / Metaso / Bocha / Serply |
| Deployment | Docker Compose / Kubernetes (Helm) / Lite single binary / desktop app; offline and private-cloud installs; UI in Chinese, English, Japanese, Korean and Russian |
## Clients and Integrations
| | Client | What it does |
|:-:|--------|--------------|
| <img src="./docs/images/readme/icons/terminal.svg" width="22" height="22" alt=""> | [**CLI `weknora`**](./cli/README.md) | Agent-first command line for the full API, with a curated MCP tool surface and bundled Agent Skills |
| <img src="./docs/images/readme/icons/plug.svg" width="22" height="22" alt=""> | [**Built-in MCP Server**](https://weknora.weixin.qq.com/docs/03-features/08-mcp) | Publishes knowledge bases to Cursor, Claude and other MCP clients over Streamable HTTP; the Python [`mcp-server/`](./mcp-server/MCP_CONFIG.md) is deprecated |
| <img src="./website-docs/homepage/public/docs/_home/brands/browserskill.png" width="22" height="22" alt=""> | [**Local Browser (BrowserSkill)**](https://weknora.weixin.qq.com/docs/05-clients/09-local-browser) | Lets agents operate the user's own Chrome / Edge |
| <img src="./website-docs/homepage/public/docs/_home/brands/chrome.svg" width="22" height="22" alt=""> | [**Chrome Extension**](https://chromewebstore.google.com/detail/jpemjbopikggjlmikmclgbmkhhopjdgd) | Select text, images, or entire pages in the browser and save them as knowledge entries with one click, without copy-paste or file upload |
| <img src="./docs/images/readme/icons/phone.svg" width="22" height="22" alt=""> | [**WeChat Mini Program**](./miniprogram/README.md) | Lightweight mobile client: configure API access, select knowledge bases, import URLs, and ask knowledge chat from WeChat |
| <img src="./docs/images/readme/icons/skills.svg" width="22" height="22" alt=""> | [**ClawHub Skill**](https://clawhub.ai/lyingbug/weknora) | A WeKnora skill on ClawHub for document import, hybrid search and knowledge management via the REST API |
| <img src="./website-docs/homepage/public/docs/_home/brands/deepseek-color.svg" width="22" height="22" alt=""> | [**DeepSeek Harness plugin**](https://www.npmjs.com/package/@wxg-prc-cpg/dsh-weknora) | Gives `dsh` coding agents four read-only tools: search, read document, ask and list knowledge bases |
| <img src="./docs/images/readme/icons/code.svg" width="22" height="22" alt=""> | [**Website Embed Widget**](https://weknora.weixin.qq.com/docs/03-features/13-embed-channel) | Publishes agents on external sites |
| <img src="./docs/images/readme/icons/braces.svg" width="22" height="22" alt=""> | [**Go SDK**](https://weknora.weixin.qq.com/docs/05-clients/03-go-sdk) | CRUD for knowledge bases, documents and sessions, plus SSE streaming Q&A |
| <img src="./website-docs/homepage/public/docs/_home/brands/wechat-dialog.png" width="22" height="22" alt=""> | [**WeChat Dialog Open Platform**](https://chatbot.weixin.qq.com) | Hosted Q&A built on WeKnora: upload knowledge and publish a Q&A service in WeChat without writing code |
### Command-Line Interface
`weknora` is the official CLI for driving the API from a terminal or an AI agent. It is **agent-first**: every command emits a stable JSON envelope by default (with typed error codes mapped to exit codes), and `--format text` renders for humans. It also serves a curated MCP tool surface (`weknora mcp serve`) and ships bundled Agent Skills.
```bash
weknora profile add prod --host https://kb.example.com --use
weknora auth login
weknora kb list
weknora link --kb my-knowledge-base # bind the current directory
weknora doc upload notes.md
weknora chat "summarise the design doc"
```
For headless / CI use, set `WEKNORA_API_KEY` + `WEKNORA_HOST` and skip `auth login`; no credentials are written to disk. See [`cli/README.md`](./cli/README.md) for install + 5-minute quickstart and [`cli/AGENTS.md`](./cli/AGENTS.md) for the operational contract AI agents rely on.
## Documentation
The full product documentation lives at **[weknora.weixin.qq.com/docs](https://weknora.weixin.qq.com/docs/)** (in Chinese), organized as Getting Started → Architecture → Features → API → Clients → Development and covering ~360 API endpoints and ~150 environment variables.
| Start here | |
|------------|---|
| [Introduction](https://weknora.weixin.qq.com/docs/01-getting-started/01-introduction) | Capabilities overview |
| [Installation](https://weknora.weixin.qq.com/docs/01-getting-started/02-installation) | Docker Compose, Helm, Lite and desktop |
| [Configuration](https://weknora.weixin.qq.com/docs/01-getting-started/04-configuration) | Environment variables and models |
| [Troubleshooting FAQ](https://weknora.weixin.qq.com/docs/01-getting-started/05-troubleshooting) | Common problems and fixes |
| [API reference](https://weknora.weixin.qq.com/docs/04-api/01-api-overview) | REST API overview |
| [Release notes](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3) | What changed in each release |
## Development
If you need to frequently modify code, you don't need to rebuild Docker images every time. Use fast development mode:
```bash
make dev-start # Start infrastructure
make dev-app # Start backend (new terminal)
make dev-frontend # Start frontend (new terminal)
```
- Frontend modifications auto hot-reload (no restart needed)
- Backend modifications quick restart (5-10 seconds, supports Air hot-reload)
- No need to rebuild Docker images
- Supports IDE breakpoint debugging
See the [Development guide](https://weknora.weixin.qq.com/docs/06-development/01-dev-guide) for details.
The documentation site and product homepage are built from [`website-docs/`](./website-docs/README.md). With Node.js 24, run `cd website-docs && npm run setup && npm run build && npm run preview` to preview both together; the unified static output serves the homepage at `/` and documentation at `/docs/`. See the directory's README for Nginx and Docker deployment.
## Contributing
Welcome to submit [Issues](https://github.com/Tencent/WeKnora/issues) or Pull Requests.
- **Process:** Fork → Create branch → Commit changes → Open PR
- **Standards:** Format code with `gofmt`, follow [Conventional Commits](https://www.conventionalcommits.org/) (`feat:` / `fix:` / `docs:` / `test:` / `refactor:`)
<details>
<summary><b>Validating your change</b></summary>
<br/>
For a focused PR, validate the changed scope first:
```bash
git fetch origin main
git diff --check origin/main...HEAD
golangci-lint run --new-from-rev=origin/main ./...
go test ./path/to/changed/package -count=1
```
Run `gofmt` on changed Go files before committing. For frontend changes, run the relevant tests from `frontend/` and use `npm run type-check` when the change affects TypeScript or Vue components.
The full maintainer gate remains:
```bash
make fmt
make lint
make test
```
`make fmt` formats the entire Go repository, so run it only with a clean worktree and review the resulting diff. Some full-suite tests require local infrastructure or service configuration. If a full check fails for an unrelated baseline or environment reason, include the exact command and failure in the PR while still providing passing targeted tests for your change.
</details>
### Contributors
Thanks to everyone who has contributed:
[![Contributors](https://contrib.rocks/image?repo=Tencent/WeKnora)](https://github.com/Tencent/WeKnora/graphs/contributors)
## License
This project is licensed under the [MIT License](./LICENSE). You are free to use, modify, and distribute the code with proper attribution.
+441
View File
@@ -0,0 +1,441 @@
<p align="center">
<a href="https://weknora.weixin.qq.com">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/hero-cn-dark.svg">
<img src="./docs/images/readme/hero-cn-light.svg" alt="WeKnora:帮你找到答案,并将知识付诸实践。腾讯开源的企业级知识管理框架,汇集团队资料,用于知识问答、任务执行和 Wiki 整理。" width="100%">
</picture>
</a>
</p>
<p align="center">
<a href="https://weknora.weixin.qq.com"><img alt="官方网站" src="https://img.shields.io/badge/官网-weknora.weixin.qq.com-b8863b?style=flat-square&labelColor=101f38"></a>
<a href="https://weknora.weixin.qq.com/docs/"><img alt="产品文档" src="https://img.shields.io/badge/文档-阅读-b8863b?style=flat-square&labelColor=101f38"></a>
<a href="./CHANGELOG.md"><img alt="版本" src="https://img.shields.io/badge/release-v0.8.3-b8863b?style=flat-square&labelColor=101f38"></a>
<a href="./LICENSE"><img alt="许可证" src="https://img.shields.io/badge/license-MIT-b8863b?style=flat-square&labelColor=101f38"></a>
<a href="https://github.com/Tencent/WeKnora/stargazers"><img alt="Stars" src="https://img.shields.io/github/stars/Tencent/WeKnora?style=flat-square&labelColor=101f38&color=b8863b"></a>
<br/>
<a href="https://chatbot.weixin.qq.com"><img alt="微信对话开放平台" src="https://img.shields.io/badge/微信对话-开放平台-07c160?style=flat-square&labelColor=101f38&logo=wechat&logoColor=white"></a>
<a href="https://chromewebstore.google.com/detail/jpemjbopikggjlmikmclgbmkhhopjdgd"><img alt="Chrome 插件" src="https://img.shields.io/badge/Chrome-插件-4285f4?style=flat-square&labelColor=101f38&logo=googlechrome&logoColor=white"></a>
<a href="https://clawhub.ai/lyingbug/weknora"><img alt="ClawHub Skill" src="https://img.shields.io/badge/ClawHub-skill-ff6b35?style=flat-square&labelColor=101f38"></a>
<a href="https://www.npmjs.com/package/@wxg-prc-cpg/dsh-weknora"><img alt="npm @wxg-prc-cpg/dsh-weknora" src="https://img.shields.io/npm/v/@wxg-prc-cpg/dsh-weknora?style=flat-square&label=dsh-weknora&labelColor=101f38&color=cb3837&logo=npm&logoColor=white"></a>
</p>
<p align="center">
<a href="./README.md">English</a> · <b>简体中文</b> · <a href="./README_JA.md">日本語</a> · <a href="./README_KO.md">한국어</a>
</p>
<p align="center">
<a href="#项目介绍">项目介绍</a> ·
<a href="#快速开始">快速开始</a> ·
<a href="#最新更新">最新更新</a> ·
<a href="#功能概览">功能概览</a> ·
<a href="#客户端与生态">客户端与生态</a> ·
<a href="#文档">文档</a> ·
<a href="#开发指南">开发指南</a>
</p>
<p align="center">
<a href="https://trendshift.io/repositories/15289"><img src="https://trendshift.io/api/badge/repositories/15289" alt="Tencent/WeKnora | Trendshift" width="220" height="48"/></a>
</p>
## 项目介绍
**[WeKnora(维娜拉)](https://weknora.weixin.qq.com)** 是一款开源的、基于大语言模型(LLM)的知识管理框架,面向企业级文档理解、语义检索与智能推理场景。它把团队分散的文档汇集起来,用于检索、推理,并随资料更新持续维护。
https://github.com/user-attachments/assets/5722b10d-d04d-49ed-a6cc-635a8c77d91f
<p align="center"><sub>1 分 52 秒 · 1080p · 无旁白,英文画面文字</sub></p>
查询资料用 RAG,处理多步任务用 Agent,整理知识用 Wiki。三种能力共享同一知识库。
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/capabilities-cn-dark.svg">
<img src="./docs/images/readme/capabilities-cn-light.svg" alt="01 RAG:回答有据可查,混合检索、多模态解析、原文引用。02 Agent:用知识和工具完成任务,多步推理、技能与沙箱、本机浏览器、MCP 工具、长期记忆。03 Wiki:把文档整理成 Wiki,自动组织、知识图谱、版本回滚。" width="100%">
</picture>
**Agent 的工具箱。** 技能可从 ClawHub / SkillHub / Git / ZIP 安装,在会话级持久的 Docker / E2B / Cube 沙箱中运行,对话旁可打开交互式终端与图形桌面。借助 BrowserSkill 扩展,Agent 可以操作用户自己的 Chrome / Edge;外部 MCP 服务(支持 OAuth)可以接入,并按工具逐个启用。
除此之外:
- **记忆与知识整理**:跨会话长期记忆保存用户确认过的个人信息、偏好与事实;文件夹上传保留原始目录结构;检索分块可以编辑、比对与回滚。
- **数据源与格式**:飞书知识库 / 飞书云盘 / Confluence / GitLab / 腾讯 IMA / Notion / 语雀 / 钉钉文档 / Seafile / RSS 自动同步,更多数据源持续接入中;覆盖 PDF、Word、图片、Excel、XMind 等十余种格式,Office 文档由 anydoc 在 Go 进程内解析。
- **渠道与集成**:企业微信、飞书、Slack、Telegram 等 IM 频道内直接问答;网站嵌入 Widget 把智能体发布到外部站点;内置 MCP Server 供 Cursor、Claude 等 AI 工具连接;权限范围 API Key 与 Principal 模型用于程序化集成。
- **模型**:内置 29 家模型厂商与自动生成的模型目录,兼容 OpenAI、DeepSeek、Qwen(阿里云)、智谱、混元、Gemini、MiniMax、NVIDIA、LiteLLM、Ollama 等。
- **权限与运维**:多空间 RBAC(四级角色、资源归属、空间审计日志)、每空间多实例存储后端、运行时任务队列面板与 Worker 池治理,并通过 Langfuse 追踪 Agent 步骤、Token 用量与任务流水线。
- **部署**:大模型、向量数据库、存储后端均可替换,支持本地与私有云部署,数据留在你自己的环境中。
## 快速开始
<table>
<tr>
<td width="33%" valign="top">
<img src="./website-docs/homepage/public/docs/_home/brands/wechat-dialog.png" width="28" height="28" alt=""><br/>
<sub>在线使用</sub><br/>
<b>微信对话开放平台</b><br/>
在线管理知识库,将问答服务接入公众号、小程序等微信场景。<br/><br/>
<a href="https://chatbot.weixin.qq.com/login">进入平台 →</a>
</td>
<td width="33%" valign="top">
<img src="./website-docs/homepage/public/docs/_home/brands/tencent-cloud.ico" width="28" height="28" alt=""><br/>
<sub>云端部署</sub><br/>
<b>腾讯云轻量应用服务器</b><br/>
通过应用模板部署 WeKnora,在自己的云服务器上运行。<br/><br/>
<a href="https://mc.tencent.com/s69nKCVz">前往腾讯云部署 →</a>
</td>
<td width="33%" valign="top">
<img src="./docs/images/readme/icons/server.svg" width="28" height="28" alt=""><br/>
<sub>自行部署</sub><br/>
<b>部署到自己的环境</b><br/>
使用 Docker 或 Kubernetes 部署,自行配置模型、存储和网络。<br/><br/>
<a href="#使用-docker-compose-部署">使用 Docker Compose 部署 ↓</a>
</td>
</tr>
</table>
### 使用 Docker Compose 部署
需要 [Docker](https://www.docker.com/)、[Docker Compose](https://docs.docker.com/compose/) 与 [Git](https://git-scm.com/)。
```bash
git clone https://github.com/Tencent/WeKnora.git
cd WeKnora
cp .env.example .env # 按需编辑 .env,详见文件内注释
docker compose pull # 拉取最新镜像
docker compose up -d # 启动核心服务
```
启动成功后访问 **[http://localhost](http://localhost)**,按新手引导完成配置即可使用。带样例数据的完整上手流程见[快速上手](https://weknora.weixin.qq.com/docs/01-getting-started/03-quickstart)。
> [!TIP]
> 如需使用本地 Ollama 模型,请先运行 `ollama serve > /dev/null 2>&1 &`。Ollama 向量模型名、`OLLAMA_BASE_URL` 与内存说明见[配置文档](https://weknora.weixin.qq.com/docs/01-getting-started/04-configuration)。
| 服务 | 地址 |
|------|------|
| Web UI | `http://localhost` |
| 后端 API | `http://localhost:8080` |
| 链路追踪 (Langfuse) | `http://localhost:3000` |
### 可选服务
按需添加 `--profile` 启动额外组件,多个 profile 可叠加使用:
| Profile | 说明 |
|---------|------|
| _(默认)_ | 核心服务 |
| `full` | 全部功能 |
| `neo4j` | 知识图谱 (Neo4j) |
| `minio` | 对象存储 (MinIO) |
| `langfuse` | 链路追踪 (Langfuse) |
```bash
docker compose --profile neo4j --profile minio pull
docker compose --profile neo4j --profile minio up -d
docker compose down # 停止服务
```
### 版本升级
若已有部署并下载了更新的 release:
```bash
# 在 .env 中将 WEKNORA_VERSION 设为目标版本(如 0.8.3),或保持 latest
docker compose pull # 拉取与 WEKNORA_VERSION 匹配的镜像
docker compose up -d # 用新镜像重建容器
```
> [!NOTE]
> 仅执行 `docker compose up -d` 会复用本地缓存镜像,可能导致 Web UI 显示版本与下载的 release 不一致。升级前请先阅读[升级须知](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#upgrade-notes)。
### 其他部署方式
| 方式 | 适用场景 |
|------|----------|
| **Docker Compose** | 上面的标准部署,功能完整,多服务 |
| **Kubernetes (Helm)** | 生产集群;Chart 位于 [`helm/`](./helm) |
| **Lite 单二进制** | 本机或低资源环境,零外部依赖(SQLite + 内存队列);与标准版的差异见 [Lite 与标准版区别](./docs/LITE.md) |
| **桌面应用** | 带图形界面的 Lite 运行时,免登录启动,macOS 上提供本机沙箱;尚未提供安装包,需自行构建 |
全部部署形态、硬件要求与常见拓扑见[安装部署](https://weknora.weixin.qq.com/docs/01-getting-started/02-installation)。
> [!WARNING]
> WeKnora 已提供登录鉴权,但在生产环境部署时,我们强烈建议:
> - 将 WeKnora 服务部署在内网 / 私有网络环境中,而非公网环境;
> - 避免将服务直接暴露在公网上,以防止重要信息泄露风险;
> - 为部署环境配置适当的防火墙规则和访问控制;
> - 定期更新到最新版本以获取安全补丁和改进。
## 最新更新
### v0.8.3 <sub>· 2026-10-14 · [版本说明](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3)</sub>
- **[画廊](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#images)**:集中浏览文档图片,按来源、描述、OCR 与图片属性筛选,查看原图和出处。
- **[多模态 Embedding](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#multimodal-embedding)**:支持将文字与图片编码到同一向量空间的多模态向量模型,例如腾讯 WeMM-Embedding、Qwen3-VL-Embedding 等;可按需开启图片向量检索,并搭配支持图片输入的重排模型。
- **[Wiki 图谱](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#wiki-graph)**:重新组织分组布局与主题说明,支持聚焦分组、切换分组和返回全图。
- **[原文引用](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#conversation)**:从回答直接定位原始文档中的引用片段。
- **[对话与工具](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#tools)**:无需沙箱即可按需读取附件,未读回答标记、@ 全局搜索、Docker 终端、Lite 本机技能与 MCP 兼容性更新。
- **[管理与集成](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#administration)**:平台用户管理、仅限邀请注册、管理员模型目录、WeMM 向量、TEI/Pinecone/Cohere 重排、Seafile 数据源与繁体中文。
- **[稳定性](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#other-changes)**:集中修复检索、解析、数据源、Wiki、OAuth 和 CLI。注册模式、空工具列表、数据库迁移与向量重建要求见[升级须知](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#upgrade-notes)。
### v0.8.2 <sub>· 2026-09-24 · [版本说明](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2)</sub>
智能体可以操作你电脑上的浏览器,知识库可以通过 MCP 接入其他 AI 工具,进行中的对话可以补充要求、分叉或回滚。
- **[本地浏览器(BrowserSkill)](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#local-browser)**:智能体通过开源 BrowserSkill 扩展操作用户自己的 Chrome / Edge,支持实时任务预览、暂停 / 继续,登录和验证码交给用户处理。
- **[内置 MCP Server](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#mcp-server)**:按空间发布 `/mcp/<endpoint_id>` 端点,Streamable HTTP,每个端点独立令牌、知识库范围、限流与工具分组;Python 版 `mcp-server/` 已弃用。
- **[对话控制](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#conversation-control)**:运行中追加要求、从任意历史问题分叉、原地回滚并还原沙箱检查点、按会话选择思考强度;生成的文件统一收在新增的产物库中。
- **[沙箱](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#sandbox)**:沙箱交互终端与图形桌面;macOS Lite 宿主机沙箱与项目文件夹;侧边栏工具箱集中管理技能、MCP 服务与浏览器连接。
- **[模型接入](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#models)**:重构的模型目录(27 家内置厂商,自动补全上下文窗口、最大输出、思考档位与视觉能力);Agent 检索工具合并为 `search_knowledge` / `read_document` / `list_documents`。
- **[知识库与平台](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#knowledge)**:Confluence 与钉钉文档数据源;博查与 Serply 网络搜索;日语界面;IM 频道级回复语言;仅白名单出站模式。
> [!IMPORTANT]
> **不兼容变更:** 钉钉频道仅支持 Stream 模式,沙箱命令默认以 `root` 执行。详见[升级须知](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#upgrade-notes)。
### v0.8.0 <sub>· [版本说明](https://weknora.weixin.qq.com/docs/07-releases/v0.8.0)</sub>
- **技能沙箱运行时**:会话级常驻 Docker / E2B / Cube 后端,按空间配置网络策略;移除 Local 宿主机进程后端;Docker 需显式开启。
- **空间技能目录**:从 ClawHub / SkillHub / git / zip 安装,按沙箱快照、实时进度、文件浏览/编辑、个人与空间环境变量。
- **跨会话长期记忆**:profile / preference / fact / task / interest,自动抽取需确认,`search_memory`。
- **解析与数据源**:进程内 anydoc Office 解析;GitLab 与腾讯 IMA 数据源;XMind 解析。
- **生态**:官方 DeepSeek Harness 插件 `@wxg-prc-cpg/dsh-weknora`;LiteLLM;Exa 与 Metaso 网络搜索。
- **对话**:对话产物、问题大纲与时间戳;上下文压缩与供应商 Prompt Cache 标记。
- **安全**:OIDC JWKS 验签、可选复杂密码、文档自动打标签,以及大范围沙箱/安全加固。
<details>
<summary><b>更早版本(v0.2.0 – v0.7.2)</b></summary>
<br/>
- **v0.7.2** —— 产品文档站;知识库文件夹树;分块编辑与版本历史;Wiki 页面版本历史;可直接加载的文件链接(`resource_urls=public`);飞书云盘数据源;批量打标签;MCP Server 1.1(29 个工具);AWS S3 默认凭据链。
- **v0.7.1** —— 云之家 IM;火山引擎重排序;智谱 AI 网络搜索;平台级 API Key;知识库活动审计;FAQ 筛选、打标签与导出;Langfuse OTLP 追踪;一键导出 Markdown。
- **v0.7.0** —— 权限范围 API Key 与 Principal 模型;任务队列面板与 Worker 池治理;每空间多实例存储;对话临时附件;`@Skill / @MCP` 提及;会话内 MCP OAuth;QQBot 与 Lark IM;Redis TLS;`weknora` CLI v0.10。
- **v0.6.3** —— 网站嵌入 Widget 与发布集成中心(安全模式 Token 交换 + 限流);对话体验全面革新(引用浮层、RAG 流水线进度、流式 Markdown);文档多标签与批量重新解析;Wiki 文件夹与层级导航;RSS 数据源;MCP OAuth2;EPUB / MHTML 解析;Agent 模型就绪校验;模型调试器;会话来源筛选;工作区删除 UI。
- **v0.6.2** —— 按批次解析配置(`process_config`)+ 上传确认对话框;文档重新解析(reparse)支持覆盖配置;`weknora` CLI v0.9(内置 Agent Skills、`session stop`、auth/profile 统一);知识库框选多选;pgvector 1024 维 HNSW 索引;对话资源 Store 重构;仅保留 Langfuse 追踪(移除 Jaeger)。
- **v0.6.1** —— 文档解析追踪时间线(Langfuse 风格 Span 树,逐阶段进度展示 + 解析中止);OpenSearch 向量库驱动;YAML 声明式内置模型配置;系统管理员与统一平台设置 + 审计日志;新用户引导;设置页 UI 重构;`weknora` CLI v0.7 / v0.8(Agent 优先线协议、NDJSON、`--dry-run`);OpenDataLoader 与 PaddleOCR-VL 解析引擎;MCP Server 多传输(stdio / SSE / HTTP);按模型的思考模式配置;腾讯云 LKEAP 重排 + 原生 Gemini Embedding + MiniMax-M3。
- **v0.6.0** —— 空间 RBAC(四级角色矩阵 `Owner` / `Admin` / `Contributor` / `Viewer` + 按 KB 归属 + 每空间审计日志)、空间成员管理与多工作区 UX、自助创建工作区;`weknora` CLI v0.4 正式版 + `mcp serve`;KB 检索跨向量库扇出;MCP / 数据源凭据 AES-256-GCM 加密 + docreader gRPC TLS + Token;新增智谱 Embedding 与华为云 OBS;服务端用户偏好;Go 1.26.0。详见[多租户与认证](https://weknora.weixin.qq.com/docs/03-features/01-tenant-auth)。
- **v0.5.2** —— Wiki 入库支撑万级文档知识库(任务队列 + 死信队列);MCP 工具人机审批;Anthropic / Apache Doris / 腾讯云 VectorDB / 金山云 KS3 / SearXNG 后端;自适应三层分块 + 实时调试面板;全局 ⌘K 命令面板;语雀连接器 + 微信小程序;`weknora` CLI 早期版本。
- **v0.5.1** —— 知识库批量管理;空间级 IM 频道总览;会话搜索 + 用户级置顶;模型 / 网页搜索 / MCP 统一卡片化设置;按 Agent LLM 调用超时;桌面端空间切换。
- **v0.5.0** —— Wiki 模式正式版 —— Agent 从原始文档自治生成结构化、相互链接的 Markdown Wiki 页面及知识图谱;Wiki 浏览器 + 可视化图谱。
- **v0.4.0** —— WeKnora Cloud(托管模型 + 解析);Chrome 插件;ClawHub Skill;微信 IM;附件处理;Azure OpenAI / 阿里云 OSS;Notion 连接器;百度 + Ollama 网页搜索;VectorStore 管理。
- **v0.3.6** —— ASR 语音;飞书数据源自动同步;OIDC;IM 引用回复 + 线程会话;文档自动摘要;Tavily 搜索;并行工具调用;Agent @提及范围限制。
- **v0.3.5** —— Telegram / 钉钉 / Mattermost IM;IM 斜杠命令 + QA 队列;推荐问题;VLM 自动描述 MCP 返回图片;Novita AI;来源频道标记。
- **v0.3.4** —— 企业微信 / 飞书 / Slack IM;多模态图片;NVIDIA 模型 API;Weaviate;AWS S3;AES-256-GCM API Key 加密;内置 MCP 服务;混合检索优化;`final_answer` 工具。
- **v0.3.3** —— 父子分块;知识库置顶;兜底回复;Rerank 段落清洗;存储桶自动创建;Milvus。
- **v0.3.2** —— 知识搜索入口;按来源配置解析与存储引擎;本地存储图片渲染;文档预览;火山引擎 TOS;Mermaid 渲染;对话批量管理;记忆图谱预览。
- **v0.3.0** —— 共享空间;Agent Skills + 沙盒执行;自定义 Agent;数据分析 Agent;思考模式;Bing / Google 搜索;API Key 认证;Helm Chart;韩语 i18n;Qdrant。
- **v0.2.0** —— Agent 模式(ReACT);多类型知识库(FAQ + 文档);对话策略配置;DuckDuckGo 网页搜索;MCP 工具集成;全新 UI + Agent 模式切换;MQ 异步任务管理。
完整变更记录见 [`CHANGELOG.md`](./CHANGELOG.md)。
</details>
## 功能展示
### 快速问答与智能推理
**两种提问方式。** 快速问答基于知识库做 RAG 检索作答,并标注引用来源;智能推理由智能体规划多步任务,检索、阅读文档、调用工具与技能,每一步都在对话中展示。 [文档 →](https://weknora.weixin.qq.com/docs/03-features/18-chat-experience)
<a href="./docs/images/readme/spotlight-qa-light.webp">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/spotlight-qa-dark.webp">
<img src="./docs/images/readme/spotlight-qa-light.webp" alt="快速问答与智能推理" width="100%">
</picture>
</a>
### 本机浏览器
**操作你电脑上的浏览器。** 借助腾讯开源的 BrowserSkill 扩展,智能体直接在你的 Chrome 或 Edge 中打开网页、填写表单;遇到登录或验证码时交给你。 [文档 →](https://weknora.weixin.qq.com/docs/05-clients/09-local-browser)
<a href="./docs/images/readme/spotlight-browser-light.webp">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/spotlight-browser-dark.webp">
<img src="./docs/images/readme/spotlight-browser-light.webp" alt="本机浏览器" width="100%">
</picture>
</a>
### 技能与沙箱
**运行技能,生成文件。** 支持 Docker、E2B、Cube。同一会话的多轮任务共用一个工作区,生成的文件可预览和下载;还可以在对话旁打开图形桌面或交互终端,查看智能体的每一步操作,必要时亲自接手。 [文档 →](https://weknora.weixin.qq.com/docs/03-features/22-skills-sandbox)
<a href="./docs/images/readme/spotlight-sandbox-light.webp">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/spotlight-sandbox-dark.webp">
<img src="./docs/images/readme/spotlight-sandbox-light.webp" alt="技能与沙箱" width="100%">
</picture>
</a>
### 工具箱:MCP 服务与技能
**智能体可用的工具。** 接入外部 MCP 服务,逐个选择启用哪些工具、哪些调用需要审批;从 ClawHub、SkillHub、Git 或 ZIP 安装技能,在空间内统一管理,供各个沙箱复用。 [文档 →](https://weknora.weixin.qq.com/docs/03-features/22-skills-sandbox)
<a href="./docs/images/readme/spotlight-toolbox-light.webp">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/spotlight-toolbox-dark.webp">
<img src="./docs/images/readme/spotlight-toolbox-light.webp" alt="工具箱:MCP 服务与技能" width="100%">
</picture>
</a>
### 自动 Wiki
**把文档整理成可浏览的 Wiki。** 开启 Wiki 后,从知识库文档中提取人物、产品和概念,生成带来源引用的页面,按目录浏览;在知识图谱中查看页面之间的关系,页面可直接编辑,改动可回溯。 [文档 →](https://weknora.weixin.qq.com/docs/03-features/14-wiki)
<a href="./docs/images/readme/spotlight-wiki-light.webp">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/spotlight-wiki-dark.webp">
<img src="./docs/images/readme/spotlight-wiki-light.webp" alt="自动 Wiki" width="100%">
</picture>
</a>
### 可观测性
**追踪与运行监控。** Langfuse 追踪智能体每一步的推理、工具调用与 Token 用量;文档解析时间线逐阶段展示进度;任务队列面板列出排队与失败的任务。 [文档 →](https://weknora.weixin.qq.com/docs/03-features/16-observability)
<a href="./docs/images/readme/spotlight-observability-light.webp">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/spotlight-observability-dark.webp">
<img src="./docs/images/readme/spotlight-observability-light.webp" alt="可观测性" width="100%">
</picture>
</a>
## 架构设计
<a href="./docs/images/readme/architecture-cn-light.svg">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/architecture-cn-dark.svg">
<img src="./docs/images/readme/architecture-cn-light.svg" alt="WeKnora 架构:客户端与渠道接入 WeKnora 主服务,RAG 问答、Agent 推理与自动 Wiki 共享同一条知识处理流水线;主服务调用运行时服务,数据存放在 PostgreSQL、Redis 及可选存储中" width="100%">
</picture>
</a>
从文档解析、向量化、检索到大模型推理,各环节模块化解耦,组件可替换、可扩展。支持本地与私有云部署,Web UI 开箱即用。延伸阅读:[架构总览](https://weknora.weixin.qq.com/docs/02-architecture/01-overview) · [RAG 流水线](https://weknora.weixin.qq.com/docs/02-architecture/04-rag-pipeline) · [扩展点](https://weknora.weixin.qq.com/docs/06-development/03-extension-points)。
## 功能概览
| 领域 | 要点 |
|------|------|
| [问答与 Agent](https://weknora.weixin.qq.com/docs/03-features/07-agent) | 快速问答基于知识库作答并附来源引用;智能推理由 ReAct Agent 编排知识库、网络搜索、MCP 工具、技能与本机浏览器。进行中的对话可以补充要求、分叉或回滚,并支持跨会话的[长期记忆](https://weknora.weixin.qq.com/docs/03-features/23-memory) |
| [Wiki](https://weknora.weixin.qq.com/docs/03-features/14-wiki) | Agent 生成相互链接的 Wiki 页面与知识图谱;支持浏览器内编辑、版本 diff 与回滚 |
| [技能与沙箱](https://weknora.weixin.qq.com/docs/03-features/22-skills-sandbox) | 技能目录支持从 ClawHub / SkillHub / Git / ZIP 安装;会话级持久的 Docker / E2B / Cube 沙箱,按配置设置网络策略;对话旁提供交互式终端与图形桌面 |
| [知识库](https://weknora.weixin.qq.com/docs/03-features/02-knowledge-base) | FAQ、文档、Wiki 三类知识库;文件夹树;分块编辑与版本历史;按批次设置解析、分块与多模态;自动打标签 |
| [检索](https://weknora.weixin.qq.com/docs/03-features/05-retrieval-engines) | 关键词 + 向量混合检索、重排序、父子分块与 GraphRAG([Neo4j](https://weknora.weixin.qq.com/docs/03-features/09-knowledge-graph));端到端评测召回命中率与 BLEU / ROUGE |
| [权限与安全](https://weknora.weixin.qq.com/docs/03-features/01-tenant-auth) | 空间 RBAC 四级角色与审计日志;权限范围 API Key;OIDC;凭据 AES-256-GCM 加密;防 SSRF 的出站请求与仅白名单出站模式 |
| [运维](https://weknora.weixin.qq.com/docs/03-features/16-observability) | Langfuse 追踪 Agent 步骤、Token 用量与任务流水线;文档解析时间线;带 Worker 池的任务队列面板;版本升级自动迁移数据库 |
### 支持的组件
| 组件 | 可选项 |
|------|--------|
| [模型厂商](https://weknora.weixin.qq.com/docs/03-features/06-models) | 内置 29 家,包括 OpenAI / Azure OpenAI / Anthropic / DeepSeek / Qwen(阿里云)/ 智谱 / 混元 / 豆包(火山引擎)/ Gemini / MiniMax / NVIDIA / SiliconFlow / OpenRouter / LiteLLM / Ollama |
| Embedding | Ollama / BGE / GTE / 智谱 / OpenAI 兼容接口 |
| 向量数据库 | PostgreSQL (pgvector + ParadeDB) / Elasticsearch / OpenSearch / Milvus / Weaviate / Qdrant / Apache Doris / 腾讯云 VectorDB |
| [对象存储](https://weknora.weixin.qq.com/docs/03-features/19-storage-backends) | 本地 / 腾讯云 COS / MinIO / AWS S3 / 火山引擎 TOS / 阿里云 OSS / 金山云 KS3 / 华为云 OBS |
| [文档格式](https://weknora.weixin.qq.com/docs/03-features/03-document-parsing) | PDF / Word / PPT / Excel / CSV / TXT / Markdown / HTML / EPUB / MHTML / JSON / XMind / 图片 |
| [数据源](https://weknora.weixin.qq.com/docs/03-features/10-datasource) | 飞书知识库 / 飞书云盘 / Lark / Confluence / GitLab / 腾讯 IMA / Notion / 语雀 / 钉钉文档 / Seafile / RSS |
| [IM 渠道](https://weknora.weixin.qq.com/docs/03-features/12-im-integration) | 企业微信 / 飞书 / Lark / QQBot / Slack / Telegram / 钉钉 / Mattermost / 微信 / 云之家 |
| [网络搜索](https://weknora.weixin.qq.com/docs/03-features/11-web-search) | DuckDuckGo / Bing / Google / Tavily / Baidu / Ollama / SearXNG / Keenable / 智谱 AI / Exa / Metaso / 博查 / Serply |
| 部署 | Docker Compose / Kubernetes (Helm) / Lite 单二进制 / 桌面版;支持离线与私有云部署;界面支持中文、英文、日文、韩文、俄文 |
## 客户端与生态
| | 客户端 | 用途 |
|:-:|--------|------|
| <img src="./docs/images/readme/icons/terminal.svg" width="22" height="22" alt=""> | [**命令行 `weknora`**](./cli/README.md) | Agent 优先的命令行,覆盖完整 API,附带精选 MCP 工具面与内置 Agent Skills |
| <img src="./docs/images/readme/icons/plug.svg" width="22" height="22" alt=""> | [**内置 MCP Server**](https://weknora.weixin.qq.com/docs/03-features/08-mcp) | 通过 Streamable HTTP 把知识库开放给 Cursor、Claude 等 MCP 客户端;[`mcp-server/`](./mcp-server/MCP_CONFIG.md) 下的 Python 服务已弃用 |
| <img src="./website-docs/homepage/public/docs/_home/brands/browserskill.png" width="22" height="22" alt=""> | [**本地浏览器(BrowserSkill)**](https://weknora.weixin.qq.com/docs/05-clients/09-local-browser) | 让智能体操作用户自己的 Chrome / Edge |
| <img src="./website-docs/homepage/public/docs/_home/brands/chrome.svg" width="22" height="22" alt=""> | [**Chrome 插件**](https://chromewebstore.google.com/detail/jpemjbopikggjlmikmclgbmkhhopjdgd) | 在浏览器中选中文本、图片或整个页面,一键保存为知识条目,无需复制粘贴或手动上传文件 |
| <img src="./docs/images/readme/icons/phone.svg" width="22" height="22" alt=""> | [**微信小程序**](./miniprogram/README.md) | 轻量移动端:配置 WeKnora API、选择知识库、导入 URL,并在微信内向知识库提问 |
| <img src="./docs/images/readme/icons/skills.svg" width="22" height="22" alt=""> | [**ClawHub Skill**](https://clawhub.ai/lyingbug/weknora) | 发布在 ClawHub 上的 WeKnora 技能,通过 REST API 导入文档、混合检索与管理知识条目 |
| <img src="./website-docs/homepage/public/docs/_home/brands/deepseek-color.svg" width="22" height="22" alt=""> | [**DeepSeek Harness 插件**](https://www.npmjs.com/package/@wxg-prc-cpg/dsh-weknora) | 为 `dsh` 编码 Agent 提供四个只读工具:检索、读取文档、提问、列出知识库 |
| <img src="./docs/images/readme/icons/code.svg" width="22" height="22" alt=""> | [**网站嵌入 Widget**](https://weknora.weixin.qq.com/docs/03-features/13-embed-channel) | 将智能体发布到外部站点 |
| <img src="./docs/images/readme/icons/braces.svg" width="22" height="22" alt=""> | [**Go SDK**](https://weknora.weixin.qq.com/docs/05-clients/03-go-sdk) | 知识库、文档、会话等资源的 CRUD 与 SSE 流式问答 |
| <img src="./website-docs/homepage/public/docs/_home/brands/wechat-dialog.png" width="22" height="22" alt=""> | [**微信对话开放平台**](https://chatbot.weixin.qq.com) | 基于 WeKnora 的托管问答平台,上传知识即可在微信内发布问答服务,无需写代码 |
### 命令行工具
`weknora` 是官方命令行工具,可在终端或 AI Agent 中驱动 API。它**以 Agent 为先**:每条命令默认输出稳定的 JSON 信封(带类型化错误码并映射到退出码),`--format text` 则面向人类阅读。它还提供精选的 MCP 工具面(`weknora mcp serve`),并内置 Agent Skills。
```bash
weknora profile add prod --host https://kb.example.com --use
weknora auth login
weknora kb list
weknora link --kb my-knowledge-base # 绑定当前目录
weknora doc upload notes.md
weknora chat "总结一下设计文档"
```
在无界面 / CI 场景下,设置 `WEKNORA_API_KEY` 与 `WEKNORA_HOST` 即可跳过 `auth login`,不会有凭据写入磁盘。安装与 5 分钟上手见 [`cli/README.md`](./cli/README.md),AI Agent 依赖的操作约定见 [`cli/AGENTS.md`](./cli/AGENTS.md)。
## 文档
完整产品文档见 **[weknora.weixin.qq.com/docs](https://weknora.weixin.qq.com/docs/)**,按「入门 → 架构 → 功能 → API → 客户端 → 开发」六个板块组织,覆盖约 360 个 API 端点、约 150 个环境变量与 9 大扩展点。
| 从这里开始 | |
|------------|---|
| [产品介绍](https://weknora.weixin.qq.com/docs/01-getting-started/01-introduction) | 能力总览 |
| [安装部署](https://weknora.weixin.qq.com/docs/01-getting-started/02-installation) | Docker Compose、Helm、Lite 与桌面端 |
| [配置说明](https://weknora.weixin.qq.com/docs/01-getting-started/04-configuration) | 环境变量与模型配置 |
| [常见问题排查](https://weknora.weixin.qq.com/docs/01-getting-started/05-troubleshooting) | 常见问题与解决办法 |
| [API 文档](https://weknora.weixin.qq.com/docs/04-api/01-api-overview) | REST API 总览 |
| [版本说明](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3) | 各版本变更详解 |
## 开发指南
频繁修改代码时不需要每次重新构建 Docker 镜像,使用快速开发模式即可:
```bash
make dev-start # 启动基础设施
make dev-app # 启动后端(新终端)
make dev-frontend # 启动前端(新终端)
```
- 前端修改自动热重载(无需重启)
- 后端修改快速重启(5-10 秒,支持 Air 热重载)
- 无需重新构建 Docker 镜像
- 支持 IDE 断点调试
详细说明见[开发环境快速入门](https://weknora.weixin.qq.com/docs/06-development/01-dev-guide)。
文档站与产品主页的源码位于 [`website-docs/`](./website-docs/README.md)。使用 Node.js 24 运行 `cd website-docs && npm run setup && npm run build && npm run preview` 即可同时预览两者;统一的静态产物在 `/` 提供主页、在 `/docs/` 提供文档。Nginx 与 Docker 部署方式见该目录的 README。
## 贡献指南
欢迎通过 [Issue](https://github.com/Tencent/WeKnora/issues) 反馈问题或提交 Pull Request。
- **流程:** Fork → 新建分支 → 提交更改 → 创建 PR
- **规范:** 使用 `gofmt` 格式化代码,遵循 [Conventional Commits](https://www.conventionalcommits.org/) 提交(`feat:` / `fix:` / `docs:` / `test:` / `refactor:`)
<details>
<summary><b>验证方式</b></summary>
<br/>
对于范围集中的 PR,优先验证本次改动涉及的文件和包:
```bash
git fetch origin main
git diff --check origin/main...HEAD
golangci-lint run --new-from-rev=origin/main ./...
go test ./path/to/changed/package -count=1
```
提交前请对改动过的 Go 文件运行 `gofmt`。对于前端改动,请在 `frontend/` 目录运行相关测试;如果改动涉及 TypeScript 或 Vue 组件,还应运行 `npm run type-check`。
维护者使用的全仓验证命令仍然是:
```bash
make fmt
make lint
make test
```
`make fmt` 会格式化整个 Go 仓库,因此请仅在工作区干净时运行,并检查产生的 diff。部分全量测试依赖本地基础设施或服务配置。如果全仓检查因无关的基线问题或环境依赖失败,请在 PR 中写明具体命令和错误,同时提供本次改动范围内通过的定向测试。
</details>
### 贡献者
感谢所有贡献者:
[![Contributors](https://contrib.rocks/image?repo=Tencent/WeKnora)](https://github.com/Tencent/WeKnora/graphs/contributors)
## 许可证
本项目基于 [MIT](./LICENSE) 协议发布。你可以自由使用、修改和分发本项目代码,但需保留原始版权声明。
+441
View File
@@ -0,0 +1,441 @@
<p align="center">
<a href="https://weknora.weixin.qq.com">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/hero-ja-dark.svg">
<img src="./docs/images/readme/hero-ja-light.svg" alt="WeKnora:答えを見つけ、知識を実践に活かす。Tencent が公開するオープンソースのエンタープライズ向けナレッジ管理フレームワーク。チームの資料を集約し、Q&A・タスク実行・Wiki 整理に活用します。" width="100%">
</picture>
</a>
</p>
<p align="center">
<a href="https://weknora.weixin.qq.com"><img alt="公式サイト" src="https://img.shields.io/badge/website-weknora.weixin.qq.com-b8863b?style=flat-square&labelColor=101f38"></a>
<a href="https://weknora.weixin.qq.com/docs/"><img alt="ドキュメント" src="https://img.shields.io/badge/docs-中国語-b8863b?style=flat-square&labelColor=101f38"></a>
<a href="./CHANGELOG.md"><img alt="リリース" src="https://img.shields.io/badge/release-v0.8.3-b8863b?style=flat-square&labelColor=101f38"></a>
<a href="./LICENSE"><img alt="ライセンス" src="https://img.shields.io/badge/license-MIT-b8863b?style=flat-square&labelColor=101f38"></a>
<a href="https://github.com/Tencent/WeKnora/stargazers"><img alt="Stars" src="https://img.shields.io/github/stars/Tencent/WeKnora?style=flat-square&labelColor=101f38&color=b8863b"></a>
<br/>
<a href="https://chatbot.weixin.qq.com"><img alt="WeChat 対話オープンプラットフォーム" src="https://img.shields.io/badge/WeChat_Dialog-Open_Platform-07c160?style=flat-square&labelColor=101f38&logo=wechat&logoColor=white"></a>
<a href="https://chromewebstore.google.com/detail/jpemjbopikggjlmikmclgbmkhhopjdgd"><img alt="Chrome 拡張機能" src="https://img.shields.io/badge/Chrome-extension-4285f4?style=flat-square&labelColor=101f38&logo=googlechrome&logoColor=white"></a>
<a href="https://clawhub.ai/lyingbug/weknora"><img alt="ClawHub Skill" src="https://img.shields.io/badge/ClawHub-skill-ff6b35?style=flat-square&labelColor=101f38"></a>
<a href="https://www.npmjs.com/package/@wxg-prc-cpg/dsh-weknora"><img alt="npm @wxg-prc-cpg/dsh-weknora" src="https://img.shields.io/npm/v/@wxg-prc-cpg/dsh-weknora?style=flat-square&label=dsh-weknora&labelColor=101f38&color=cb3837&logo=npm&logoColor=white"></a>
</p>
<p align="center">
<a href="./README.md">English</a> · <a href="./README_CN.md">简体中文</a> · <b>日本語</b> · <a href="./README_KO.md">한국어</a>
</p>
<p align="center">
<a href="#プロジェクト紹介">プロジェクト紹介</a> ·
<a href="#クイックスタート">クイックスタート</a> ·
<a href="#最新アップデート">最新アップデート</a> ·
<a href="#機能概要">機能概要</a> ·
<a href="#クライアントとエコシステム">クライアント</a> ·
<a href="#ドキュメント">ドキュメント</a> ·
<a href="#開発ガイド">開発ガイド</a>
</p>
<p align="center">
<a href="https://trendshift.io/repositories/15289"><img src="https://trendshift.io/api/badge/repositories/15289" alt="Tencent/WeKnora | Trendshift" width="220" height="48"/></a>
</p>
## プロジェクト紹介
**[WeKnora(ウィーノラ)](https://weknora.weixin.qq.com)** は、大規模言語モデル(LLM)をベースとしたオープンソースのナレッジフレームワークで、エンタープライズ向けの文書理解、セマンティック検索、推論に対応します。チームに散在する文書を集約し、検索・推論に使えるようにし、資料の更新に合わせて維持します。
https://github.com/user-attachments/assets/5722b10d-d04d-49ed-a6cc-635a8c77d91f
<p align="center"><sub>1 分 52 秒 · 1080p · ナレーションなし・英語の画面テキスト</sub></p>
資料の検索には RAG、マルチステップのタスクには Agent、ナレッジの整理には Wiki。3 つの機能は同じナレッジベースを共有します。
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/capabilities-ja-dark.svg">
<img src="./docs/images/readme/capabilities-ja-light.svg" alt="01 RAG:根拠のある回答。ハイブリッド検索、マルチモーダル解析、原文引用。02 Agent:知識とツールでタスクを完了。マルチステップ推論、サンドボックス、ローカルブラウザ、MCP ツール、長期メモリ。03 Wiki:ドキュメントを Wiki に整理。自動整理、ナレッジグラフ、ロールバック。" width="100%">
</picture>
**Agent のツールボックス。** ClawHub / SkillHub / Git / ZIP からインストールしたスキルは、セッション単位で永続する Docker / E2B / Cube サンドボックスで動作し、チャットの横でインタラクティブターミナルとグラフィカルデスクトップを開けます。BrowserSkill 拡張機能を通じて Agent はユーザー自身の Chrome / Edge を操作でき、外部 MCP サービス(OAuth 対応)を接続してツールごとに有効化できます。
そのほか:
- **メモリとナレッジ整理**:クロスセッション長期メモリが、ユーザーが確認したプロフィール・好み・事実を保持します。フォルダーアップロードは元のディレクトリ構造を保ち、検索チャンクは編集・差分比較・ロールバックできます。
- **データソースとフォーマット**:Feishu ナレッジベース / Feishu クラウドドライブ / Confluence / GitLab / Tencent IMA / Notion / Yuque / DingTalk Docs / Seafile / RSS の自動同期(順次拡充中)。PDF、Word、画像、Excel、XMind など 10 以上のフォーマットに対応し、Office 文書は anydoc でプロセス内解析します。
- **チャネルと連携**:WeChat Work、Feishu、Slack、Telegram などの IM で直接 Q&A、ウェブサイト埋め込み Widget で外部サイトにエージェントを公開、組み込み MCP Server で Cursor や Claude などの AI ツールと接続、スコープ付き API キーと Principal モデルでプログラム連携。
- **モデル**:29 の組み込みベンダーと自動生成のモデルカタログ。OpenAI、DeepSeek、Qwen(Alibaba Cloud)、Zhipu、Hunyuan、Gemini、MiniMax、NVIDIA、LiteLLM、Ollama などに対応。
- **権限と運用**:マルチワークスペース RBAC(4 階層ロール、リソース所有権、ワークスペース監査ログ)、ワークスペースごとの複数ストレージインスタンス、ランタイムタスクキューダッシュボードと Worker プール統治、Langfuse による Agent ステップ・トークン消費・パイプラインのトレーシング。
- **デプロイ**:LLM、ベクトルデータベース、ストレージバックエンドはすべて差し替え可能。ローカルまたはプライベートクラウドにデプロイし、データを自社環境に置けます。
## クイックスタート
<table>
<tr>
<td width="33%" valign="top">
<img src="./website-docs/homepage/public/docs/_home/brands/wechat-dialog.png" width="28" height="28" alt=""><br/>
<sub>オンライン</sub><br/>
<b>WeChat 対話オープンプラットフォーム</b><br/>
ナレッジベースをオンラインで管理し、Q&A を公式アカウントやミニプログラムなどの WeChat シナリオに接続します。<br/><br/>
<a href="https://chatbot.weixin.qq.com/login">プラットフォームを開く →</a>
</td>
<td width="33%" valign="top">
<img src="./website-docs/homepage/public/docs/_home/brands/tencent-cloud.ico" width="28" height="28" alt=""><br/>
<sub>クラウド</sub><br/>
<b>Tencent Cloud Lighthouse</b><br/>
アプリケーションテンプレートから WeKnora をデプロイし、自分のクラウドサーバーで運用します。<br/><br/>
<a href="https://mc.tencent.com/s69nKCVz">Tencent Cloud でデプロイ →</a>
</td>
<td width="33%" valign="top">
<img src="./docs/images/readme/icons/server.svg" width="28" height="28" alt=""><br/>
<sub>セルフホスト</sub><br/>
<b>自分の環境にデプロイ</b><br/>
Docker または Kubernetes でデプロイし、モデル・ストレージ・ネットワークを自分で設定します。<br/><br/>
<a href="#docker-compose-でデプロイ">Docker Compose でデプロイ ↓</a>
</td>
</tr>
</table>
### Docker Compose でデプロイ
[Docker](https://www.docker.com/)、[Docker Compose](https://docs.docker.com/compose/)、[Git](https://git-scm.com/) が必要です。
```bash
git clone https://github.com/Tencent/WeKnora.git
cd WeKnora
cp .env.example .env # 必要に応じて .env を編集(詳細はファイル内のコメント参照)
docker compose pull # 最新イメージを取得
docker compose up -d # コアサービスを起動
```
起動後、**[http://localhost](http://localhost)** にアクセスし、オンボーディングガイドに沿って設定してください。サンプルデータ付きの手順は[クイックスタート](https://weknora.weixin.qq.com/docs/01-getting-started/03-quickstart)(中国語)を参照してください。
> [!TIP]
> ローカル Ollama モデルを使用する場合は、先に `ollama serve > /dev/null 2>&1 &` を実行してください。Ollama の埋め込みモデル名、`OLLAMA_BASE_URL`、メモリの注意は[設定ドキュメント](https://weknora.weixin.qq.com/docs/01-getting-started/04-configuration)を参照してください。
| サービス | URL |
|---------|-----|
| Web UI | `http://localhost` |
| バックエンド API | `http://localhost:8080` |
| Langfuse トレーシング | `http://localhost:3000` |
### オプションサービス
`--profile` フラグで追加コンポーネントを有効化します。複数の profile を組み合わせ可能です。
| Profile | 説明 |
|---------|------|
| _(デフォルト)_ | コアサービス |
| `full` | 全機能 |
| `neo4j` | ナレッジグラフ (Neo4j) |
| `minio` | オブジェクトストレージ (MinIO) |
| `langfuse` | トレーシング (Langfuse) |
```bash
docker compose --profile neo4j --profile minio pull
docker compose --profile neo4j --profile minio up -d
docker compose down # サービスを停止
```
### アップグレード
既存のデプロイがあり、新しい release をダウンロードした場合:
```bash
# .env の WEKNORA_VERSION を対象バージョン(例: 0.8.3)に設定、または latest のまま
docker compose pull # WEKNORA_VERSION に一致するイメージを取得
docker compose up -d # 新しいイメージでコンテナを再作成
```
> [!NOTE]
> `docker compose up -d` のみではローカルキャッシュのイメージが再利用され、Web UI の表示バージョンがダウンロードした release と一致しない場合があります。アップグレードする前に[アップグレードの注意事項](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#upgrade-notes)を確認してください。
### その他のデプロイ方法
| 方法 | 用途 |
|------|------|
| **Docker Compose** | 上記の標準デプロイ。全機能、複数サービス構成 |
| **Kubernetes (Helm)** | 本番クラスター。Chart は [`helm/`](./helm) にあります |
| **Lite シングルバイナリ** | ローカルや低リソース環境向け、外部依存なし(SQLite + インメモリキュー)。標準版との違いは [Lite と標準版の違い](./docs/LITE.md)(中国語) |
| **デスクトップアプリ** | GUI 付きの Lite ランタイム。ログイン不要で起動し、macOS ではホストサンドボックスを提供。インストーラーは未公開のため、ソースからビルドしてください |
すべてのデプロイ形態、ハードウェア要件、構成例は[インストールガイド](https://weknora.weixin.qq.com/docs/01-getting-started/02-installation)を参照してください。
> [!WARNING]
> WeKnora にはログイン認証がありますが、本番環境でのデプロイでは以下を強く推奨します:
> - WeKnora サービスはパブリックインターネットではなく、内部 / プライベートネットワーク環境にデプロイする
> - 情報漏洩を防ぐため、サービスを直接パブリックネットワークに公開しない
> - デプロイ環境に適切なファイアウォールルールとアクセス制御を設定する
> - セキュリティパッチと改善のため、定期的に最新バージョンに更新する
## 最新アップデート
### v0.8.3 <sub>· 2026-10-14 · [リリースノート](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3)</sub>
- **[画像ギャラリー](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#images)**:文書内の画像を一覧表示し、出典・説明・OCR・画像属性で絞り込み。
- **[マルチモーダル Embedding](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#multimodal-embedding)**:テキストと画像を同じベクトル空間で扱うモデルに対応。Tencent WeMM-Embedding や Qwen3-VL-Embedding などを利用でき、画像ベクトル検索と対応モデルによる画像リランキングを任意で有効化。
- **[Wiki グラフ](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#wiki-graph)**:グループ配置とテーマ説明を改善。グループへのフォーカス、切り替え、全体表示への復帰に対応。
- **[原文引用](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#conversation)**:回答から原文の引用箇所へ直接移動。
- **[会話とツール](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#tools)**:サンドボックス不要の添付ファイルのオンデマンド読み取り、未読返信、@ 検索、Docker ターミナル、Lite ローカルスキル、MCP 互換性の改善。
- **[管理と連携](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#administration)**:ユーザー管理、招待による登録、管理者モデルカタログ、WeMM、TEI/Pinecone/Cohere、Seafile、繁体字中国語。
- **[安定性](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#other-changes)**:検索、解析、同期、Wiki、OAuth、CLI を修正。登録モード、空のツール一覧、DB 移行と再インデックスについては[アップグレード案内](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#upgrade-notes)を確認してください。
### v0.8.2 <sub>· 2026-09-24 · [リリースノート](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2)</sub>
エージェントがあなたのコンピューターのブラウザを操作できるようになり、ナレッジベースを MCP で他の AI ツールに公開でき、実行中の会話に要件を追加したり分岐・巻き戻ししたりできます。
- **[ローカルブラウザ(BrowserSkill)](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#local-browser)**:オープンソースの BrowserSkill 拡張機能を通じて、エージェントがユーザー自身の Chrome / Edge を操作します。ライブのタスクプレビュー、一時停止 / 再開に対応し、ログインや CAPTCHA はユーザーに引き継ぎます。
- **[組み込み MCP Server](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#mcp-server)**:ワークスペース単位の `/mcp/<endpoint_id>` エンドポイント(Streamable HTTP)。エンドポイントごとにトークン・ナレッジベース範囲・レート制限・ツールグループを設定します。Python 版 `mcp-server/` は非推奨です。
- **[会話コントロール](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#conversation-control)**:実行中のターンへの要件追加、過去の任意の質問からの分岐、サンドボックスのチェックポイントと連動したその場での巻き戻し、セッション単位の推論強度。生成ファイルは新しい成果物ライブラリにまとまります。
- **[サンドボックス](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#sandbox)**:インタラクティブターミナルとグラフィカルデスクトップ、macOS の Lite ホストサンドボックスとプロジェクトフォルダー、スキル・MCP サービス・ブラウザ接続をまとめたサイドバーのツールボックス。
- **[モデル](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#models)**:再構築されたモデルカタログ(27 の組み込みベンダー、コンテキストウィンドウ・最大出力・推論レベル・ビジョン対応を自動補完)。Agent の検索ツールを `search_knowledge` / `read_document` / `list_documents` に統合。
- **[ナレッジとプラットフォーム](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#knowledge)**:Confluence と DingTalk Docs データソース、Bocha と Serply の Web 検索、日本語 UI、IM チャネル単位の返信言語、ホワイトリスト限定の外部通信モード。
> [!IMPORTANT]
> **互換性のない変更:** DingTalk チャネルは Stream モードのみ、サンドボックスのコマンドは既定で `root` で実行されます。[アップグレードの注意事項](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#upgrade-notes)を参照してください。
### v0.8.0 <sub>· [リリースノート](https://weknora.weixin.qq.com/docs/07-releases/v0.8.0)</sub>
- **スキルサンドボックス実行環境**:セッション永続の Docker / E2B / Cube バックエンド、テナント単位のネットワークポリシー。Local ホストプロセスバックエンドを削除し、Docker はオプトイン。
- **テナントスキルカタログ**:ClawHub / SkillHub / git / zip からインストール、サンドボックス単位のスナップショット、ライブ進捗、ファイル閲覧 / 編集、個人・ワークスペース環境変数。
- **クロスセッション長期メモリ**:profile / preference / fact / task / interest、確認付き自動抽出、`search_memory`。
- **解析とデータソース**:プロセス内 anydoc Office パーサー、GitLab と Tencent IMA データソース、XMind 解析。
- **エコシステム**:公式 DeepSeek Harness プラグイン `@wxg-prc-cpg/dsh-weknora`、LiteLLM、Exa と Metaso の Web 検索。
- **チャット**:チャット成果物、質問アウトライン、タイムスタンプ、コンテキスト圧縮とプロバイダー Prompt Cache マーカー。
- **セキュリティ**:OIDC JWKS 検証、任意の複雑パスワード、ドキュメント自動タグ付け、広範なサンドボックス / セキュリティ強化。
<details>
<summary><b>以前のバージョン(v0.2.0 – v0.7.2)</b></summary>
<br/>
- **v0.7.2** — 製品ドキュメントサイト、ナレッジベースのフォルダーツリー、チャンク編集とバージョン履歴、Wiki ページのバージョン履歴、直接読み込めるファイル URL(`resource_urls=public`)、Feishu クラウドドライブのデータソース、一括タグ付け、MCP Server 1.1(29 ツール)、AWS S3 のデフォルト資格情報チェーン。
- **v0.7.1** — Yunzhijia IM、Volcengine リランク、Zhipu AI Web 検索、プラットフォームスコープの API キー、KB 単位のアクティビティ監査、FAQ のフィルター・タグ付け・エクスポート、Langfuse OTLP トレーシング、ワンクリック Markdown エクスポート。
- **v0.7.0** — スコープ付き API キーと Principal モデル、タスクキューダッシュボードと Worker プール統治、ワークスペースごとの複数ストレージインスタンス、会話の一時添付、`@Skill / @MCP` メンション、会話中の MCP OAuth、QQBot と Lark IM、Redis TLS、`weknora` CLI v0.10。
- **v0.6.3** — ウェブサイト埋め込み Widget と統合センター(セキュアモード Token 交換 + レート制限);チャット体験の全面刷新(引用ポップオーバー、RAG パイプライン進捗、ストリーミング Markdown);ドキュメント複数タグと一括 reparse;Wiki フォルダーと階層ナビゲーション;RSS データソース;MCP OAuth2;EPUB / MHTML 解析;Agent モデル準備状態チェック;モデルデバッガー;セッションソースフィルター;ワークスペース削除 UI。
- **v0.6.2** — アップロード単位の解析設定(`process_config`)+ アップロード確認ダイアログ;reparse 時の設定上書き;`weknora` CLI v0.9(同梱 Agent Skills、`session stop`、auth/profile 統合);KB マーキー複数選択;pgvector 1024 次元 HNSW インデックス;チャットリソース Store 刷新;Langfuse のみのトレーシング(Jaeger 削除)。
- **v0.6.1** — ドキュメント解析トレースタイムライン(Langfuse 風の Span ツリー、ステージごとの進捗表示 + 解析中止);OpenSearch ベクター DB ドライバー;YAML 宣言型ビルトインモデル設定;システム管理者と統合プラットフォーム設定 + 監査ログ;新規ユーザーオンボーディングガイド;設定 UI 刷新;`weknora` CLI v0.7 / v0.8(Agent ファースト ワイヤープロトコル、NDJSON、`--dry-run`);OpenDataLoader と PaddleOCR-VL 解析エンジン;MCP サーバーのマルチトランスポート(stdio / SSE / HTTP);モデル単位の思考モード設定;Tencent LKEAP リランク + ネイティブ Gemini Embedding + MiniMax-M3。
- **v0.6.0** — テナント RBAC(4 階層ロールマトリクス `Owner` / `Admin` / `Contributor` / `Viewer` + KB 単位の所有 + テナントごとの監査ログ)、テナントメンバー管理とマルチワークスペース UX、セルフサービスでのワークスペース作成;`weknora` CLI v0.4 GA + `mcp serve`;KB 検索の複数ベクター DB ファンアウト;MCP / データソース資格情報の AES-256-GCM 暗号化 + docreader gRPC TLS + Token;Zhipu Embedder と華為雲 OBS の追加;サーバーサイドユーザー設定;Go 1.26.0。詳細は[テナントと認証](https://weknora.weixin.qq.com/docs/03-features/01-tenant-auth)(中国語)を参照。
- **v0.5.2** — Wiki インジェストが万件規模 KB に対応(タスクキュー + DLQ);MCP 工具人機審批;Anthropic / Apache Doris / Tencent VectorDB / 金山雲 KS3 / SearXNG バックエンド;適応型 3 段階チャンキング + ライブプレビュー;グローバル ⌘K コマンドパレット;Yuque コネクタ + WeChat ミニプログラム;`weknora` CLI プレビュー版。
- **v0.5.1** — KB 一括管理;テナント全体の IM チャネル概観;セッション検索 + ユーザー単位ピン留め;モデル / Web 検索 / MCP 統一カード設定;Agent ごとの LLM タイムアウト;デスクトップ版テナント切替。
- **v0.5.0** — Wiki モード GA — Agent が原文書から構造化・相互リンクされた Markdown Wiki ページとナレッジグラフを自動生成、Wiki ブラウザと可視化グラフを UI に搭載。
- **v0.4.0** — WeKnora Cloud(ホスティング LLM + 解析);Chrome 拡張機能;ClawHub Skill;WeChat IM;添付ファイル処理;Azure OpenAI / Alibaba OSS;Notion コネクタ;Baidu + Ollama Web 検索;VectorStore 管理。
- **v0.3.6** — ASR(音声);Feishu データソース自動同期;OIDC;IM 引用返信 + スレッドベースセッション;ドキュメント自動要約;Tavily 検索;並列ツール呼び出し;Agent @メンション範囲制限。
- **v0.3.5** — Telegram / DingTalk / Mattermost IM;IM スラッシュコマンド + QA キュー;推奨質問;VLM による MCP ツール画像自動説明;Novita AI;チャネルトラッキング。
- **v0.3.4** — 企業 WeChat / Feishu / Slack IM;マルチモーダル画像;NVIDIA モデル API;Weaviate;AWS S3;AES-256-GCM API キー暗号化;組み込み MCP サービス;ハイブリッド検索最適化;`final_answer` ツール。
- **v0.3.3** — 親子チャンキング;KB ピン留め;フォールバック応答;Rerank パッセージクリーニング;ストレージバケット自動作成;Milvus。
- **v0.3.2** — ナレッジ検索エントリ;ソース別パーサー / ストレージエンジン設定;ローカルストレージ画像レンダリング;ドキュメントプレビュー;Volcengine TOS;Mermaid レンダリング;対話バッチ管理;メモリグラフプレビュー。
- **v0.3.0** — 共有スペース;Agent Skills + サンドボックス実行;カスタム Agent;データ分析 Agent;思考モード;Bing / Google 検索;API Key 認証;Helm Chart;韓国語 i18n;Qdrant。
- **v0.2.0** — Agent モード(ReACT);複数タイプのナレッジベース(FAQ + ドキュメント);対話戦略設定;DuckDuckGo Web 検索;MCP ツール統合;新 UI + Agent モード切替;MQ 非同期タスク管理。
完全な変更履歴は [`CHANGELOG.md`](./CHANGELOG.md) を参照してください。
</details>
## 機能デモ
### クイック Q&A とスマート推論
**2 つの質問方法。** クイック Q&A はナレッジベースを RAG で検索して回答し、参照した出典を示します。スマート推論ではエージェントがマルチステップの作業を計画し、検索、文書の読み込み、ツールやスキルの呼び出しを行い、各ステップを会話内に表示します。 [ドキュメント →](https://weknora.weixin.qq.com/docs/03-features/18-chat-experience)
<a href="./docs/images/readme/spotlight-qa-light.webp">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/spotlight-qa-dark.webp">
<img src="./docs/images/readme/spotlight-qa-light.webp" alt="クイック Q&A とスマート推論" width="100%">
</picture>
</a>
### ローカルブラウザ
**コンピューターのブラウザを操作。** Tencent がオープンソースで公開する BrowserSkill 拡張機能を通じて、エージェントがあなたの Chrome や Edge でページを開き、フォームに入力します。ログインや CAPTCHA ではあなたに引き継ぎます。 [ドキュメント →](https://weknora.weixin.qq.com/docs/05-clients/09-local-browser)
<a href="./docs/images/readme/spotlight-browser-light.webp">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/spotlight-browser-dark.webp">
<img src="./docs/images/readme/spotlight-browser-light.webp" alt="ローカルブラウザ" width="100%">
</picture>
</a>
### スキルとサンドボックス
**スキルを実行し、ファイルを生成。** Docker、E2B、Cube に対応。同じセッションの複数ターンは 1 つのワークスペースを共有し、生成ファイルはプレビューとダウンロードができます。会話の横でグラフィカルデスクトップやインタラクティブターミナルを開き、エージェントの各ステップを確認し、必要に応じて操作を引き継げます。 [ドキュメント →](https://weknora.weixin.qq.com/docs/03-features/22-skills-sandbox)
<a href="./docs/images/readme/spotlight-sandbox-light.webp">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/spotlight-sandbox-dark.webp">
<img src="./docs/images/readme/spotlight-sandbox-light.webp" alt="スキルとサンドボックス" width="100%">
</picture>
</a>
### ツールボックス:MCP サービスとスキル
**エージェントが使えるツール。** 外部の MCP サービスを接続し、有効にするツールと承認が必要な呼び出しをツールごとに選べます。スキルは ClawHub、SkillHub、Git、ZIP からインストールしてワークスペースで管理し、各サンドボックスで再利用できます。 [ドキュメント →](https://weknora.weixin.qq.com/docs/03-features/22-skills-sandbox)
<a href="./docs/images/readme/spotlight-toolbox-light.webp">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/spotlight-toolbox-dark.webp">
<img src="./docs/images/readme/spotlight-toolbox-light.webp" alt="ツールボックス:MCP サービスとスキル" width="100%">
</picture>
</a>
### 自動 Wiki
**ドキュメントを閲覧できる Wiki に。** Wiki を有効にすると、ナレッジベースの文書から人物・製品・概念を抽出し、出典付きのページを生成してディレクトリ別に閲覧できます。ナレッジグラフでページ間の関係を確認でき、ページは直接編集でき、変更はさかのぼれます。 [ドキュメント →](https://weknora.weixin.qq.com/docs/03-features/14-wiki)
<a href="./docs/images/readme/spotlight-wiki-light.webp">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/spotlight-wiki-dark.webp">
<img src="./docs/images/readme/spotlight-wiki-light.webp" alt="自動 Wiki" width="100%">
</picture>
</a>
### 可観測性
**トレーシングとランタイム監視。** Langfuse がエージェントの各ステップの推論、ツール呼び出し、トークン使用量を追跡します。文書解析タイムラインはステージごとの進捗を表示し、タスクキューダッシュボードは待機中と失敗したタスクを一覧します。 [ドキュメント →](https://weknora.weixin.qq.com/docs/03-features/16-observability)
<a href="./docs/images/readme/spotlight-observability-light.webp">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/spotlight-observability-dark.webp">
<img src="./docs/images/readme/spotlight-observability-light.webp" alt="可観測性" width="100%">
</picture>
</a>
## アーキテクチャ設計
<a href="./docs/images/readme/architecture-ja-light.svg">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/architecture-ja-dark.svg">
<img src="./docs/images/readme/architecture-ja-light.svg" alt="WeKnora アーキテクチャ:クライアントとチャネルが WeKnora アプリに接続し、RAG Q&A・Agent 推論・自動 Wiki が同じナレッジ処理パイプラインを共有。アプリはランタイムサービスを呼び出し、PostgreSQL・Redis と任意のストレージにデータを保存" width="100%">
</picture>
</a>
文書解析・ベクトル化・検索から大規模モデル推論まで、各工程をモジュール化し、コンポーネントは差し替え・拡張できます。ローカルとプライベートクラウドへのデプロイに対応し、Web UI はすぐに使い始められます。詳しくは:[アーキテクチャ概要](https://weknora.weixin.qq.com/docs/02-architecture/01-overview) · [RAG パイプライン](https://weknora.weixin.qq.com/docs/02-architecture/04-rag-pipeline) · [拡張ポイント](https://weknora.weixin.qq.com/docs/06-development/03-extension-points)(中国語)。
## 機能概要
| 領域 | 主な機能 |
|------|----------|
| [Q&A と Agent](https://weknora.weixin.qq.com/docs/03-features/07-agent) | クイック Q&A はナレッジベースから出典付きで回答し、スマート推論では ReAct エージェントがナレッジベース、Web 検索、MCP ツール、スキル、ローカルブラウザを組み合わせます。実行中の会話への要件追加・分岐・巻き戻しと、セッションをまたぐ[長期メモリ](https://weknora.weixin.qq.com/docs/03-features/23-memory)に対応 |
| [Wiki](https://weknora.weixin.qq.com/docs/03-features/14-wiki) | エージェントが相互リンクされた Wiki ページとナレッジグラフを生成。ブラウザ内編集、バージョン差分とロールバック |
| [スキルとサンドボックス](https://weknora.weixin.qq.com/docs/03-features/22-skills-sandbox) | ClawHub / SkillHub / Git / ZIP からインストールするスキルカタログ。セッション単位で永続する Docker / E2B / Cube サンドボックスと設定単位のネットワークポリシー。チャットの横にインタラクティブターミナルとグラフィカルデスクトップ |
| [ナレッジベース](https://weknora.weixin.qq.com/docs/03-features/02-knowledge-base) | FAQ・ドキュメント・Wiki の 3 種類。フォルダーツリー、チャンク編集とバージョン履歴、アップロード単位の解析・チャンキング・マルチモーダル設定、自動タグ付け |
| [検索](https://weknora.weixin.qq.com/docs/03-features/05-retrieval-engines) | キーワード + ベクトルのハイブリッド検索、リランク、親子チャンキング、GraphRAG([Neo4j](https://weknora.weixin.qq.com/docs/03-features/09-knowledge-graph))。リコール的中率と BLEU / ROUGE によるエンドツーエンド評価 |
| [権限とセキュリティ](https://weknora.weixin.qq.com/docs/03-features/01-tenant-auth) | 4 階層ロールと監査ログを備えたワークスペース RBAC、スコープ付き API キー、OIDC、AES-256-GCM による資格情報の暗号化、SSRF 対策済みの外部通信とホワイトリスト限定モード |
| [運用](https://weknora.weixin.qq.com/docs/03-features/16-observability) | Langfuse による Agent ステップ・トークン消費・パイプラインのトレーシング、ドキュメント解析タイムライン、Worker プール付きのタスクキューダッシュボード、バージョンアップ時の自動 DB マイグレーション |
### 対応バックエンド
| コンポーネント | 選択肢 |
|----------------|--------|
| [大規模モデル](https://weknora.weixin.qq.com/docs/03-features/06-models) | 29 の組み込みベンダー。OpenAI / Azure OpenAI / Anthropic / DeepSeek / Qwen(Alibaba Cloud)/ Zhipu / Hunyuan / Doubao(Volcengine)/ Gemini / MiniMax / NVIDIA / SiliconFlow / OpenRouter / LiteLLM / Ollama など |
| Embedding | Ollama / BGE / GTE / Zhipu / OpenAI 互換 API |
| ベクトル DB | PostgreSQL (pgvector) / Elasticsearch / OpenSearch / Milvus / Weaviate / Qdrant / Apache Doris / Tencent VectorDB |
| [オブジェクトストレージ](https://weknora.weixin.qq.com/docs/03-features/19-storage-backends) | ローカル / Tencent Cloud COS / MinIO / AWS S3 / 火山引擎 TOS / Alibaba Cloud OSS / 金山雲 KS3 / 華為雲 OBS |
| [文書フォーマット](https://weknora.weixin.qq.com/docs/03-features/03-document-parsing) | PDF / Word / PPT / Excel / CSV / TXT / Markdown / HTML / EPUB / MHTML / JSON / XMind / 画像 |
| [データソース](https://weknora.weixin.qq.com/docs/03-features/10-datasource) | Feishu ナレッジベース / Feishu クラウドドライブ / Lark / Confluence / GitLab / Tencent IMA / Notion / Yuque / DingTalk Docs / Seafile / RSS |
| [IM 統合](https://weknora.weixin.qq.com/docs/03-features/12-im-integration) | WeChat Work / Feishu / Lark / QQBot / Slack / Telegram / DingTalk / Mattermost / WeChat / Yunzhijia |
| [Web 検索](https://weknora.weixin.qq.com/docs/03-features/11-web-search) | DuckDuckGo / Bing / Google / Tavily / Baidu / Ollama / SearXNG / Keenable / Zhipu AI / Exa / Metaso / Bocha / Serply |
| デプロイ | Docker Compose / Kubernetes (Helm) / Lite シングルバイナリ / デスクトップアプリ。オフライン・プライベートクラウドに対応。UI は中国語 / 英語 / 日本語 / 韓国語 / ロシア語 |
## クライアントとエコシステム
| | クライアント | 用途 |
|:-:|------------|------|
| <img src="./docs/images/readme/icons/terminal.svg" width="22" height="22" alt=""> | [**CLI `weknora`**](./cli/README.md) | Agent ファーストのコマンドライン。API 全体を扱え、厳選した MCP ツールと同梱の Agent Skills を提供 |
| <img src="./docs/images/readme/icons/plug.svg" width="22" height="22" alt=""> | [**組み込み MCP Server**](https://weknora.weixin.qq.com/docs/03-features/08-mcp) | Streamable HTTP でナレッジベースを Cursor、Claude などの MCP クライアントに公開。[`mcp-server/`](./mcp-server/MCP_CONFIG.md) の Python サーバーは非推奨 |
| <img src="./website-docs/homepage/public/docs/_home/brands/browserskill.png" width="22" height="22" alt=""> | [**ローカルブラウザ(BrowserSkill)**](https://weknora.weixin.qq.com/docs/05-clients/09-local-browser) | エージェントがユーザー自身の Chrome / Edge を操作 |
| <img src="./website-docs/homepage/public/docs/_home/brands/chrome.svg" width="22" height="22" alt=""> | [**Chrome 拡張機能**](https://chromewebstore.google.com/detail/jpemjbopikggjlmikmclgbmkhhopjdgd) | テキスト、画像、ページ全体を選択してワンクリックでナレッジエントリとして保存。コピペやファイルアップロードは不要 |
| <img src="./docs/images/readme/icons/phone.svg" width="22" height="22" alt=""> | [**WeChat ミニプログラム**](./miniprogram/README.md) | 軽量なモバイルクライアント。API の設定、ナレッジベースの選択、URL のインポート、WeChat からのナレッジ Q&A |
| <img src="./docs/images/readme/icons/skills.svg" width="22" height="22" alt=""> | [**ClawHub Skill**](https://clawhub.ai/lyingbug/weknora) | ClawHub で公開された WeKnora スキル。REST API でドキュメントのインポート、ハイブリッド検索、ナレッジ管理 |
| <img src="./website-docs/homepage/public/docs/_home/brands/deepseek-color.svg" width="22" height="22" alt=""> | [**DeepSeek Harness プラグイン**](https://www.npmjs.com/package/@wxg-prc-cpg/dsh-weknora) | `dsh` のコーディングエージェントに 4 つの読み取り専用ツール(検索、ドキュメント読み取り、質問、ナレッジベース一覧)を提供 |
| <img src="./docs/images/readme/icons/code.svg" width="22" height="22" alt=""> | [**ウェブ埋め込み Widget**](https://weknora.weixin.qq.com/docs/03-features/13-embed-channel) | エージェントを外部サイトに公開 |
| <img src="./docs/images/readme/icons/braces.svg" width="22" height="22" alt=""> | [**Go SDK**](https://weknora.weixin.qq.com/docs/05-clients/03-go-sdk) | ナレッジベース・ドキュメント・セッションなどの CRUD と SSE ストリーミング Q&A |
| <img src="./website-docs/homepage/public/docs/_home/brands/wechat-dialog.png" width="22" height="22" alt=""> | [**WeChat 対話オープンプラットフォーム**](https://chatbot.weixin.qq.com) | WeKnora をベースにしたホスティング型 Q&A。ナレッジをアップロードするだけで WeChat 内に Q&A サービスを公開 |
### コマンドラインツール
`weknora` は、ターミナルや AI エージェントから API を操作するための公式 CLI です。**Agent ファースト**の設計で、すべてのコマンドは既定で安定した JSON エンベロープを出力し(型付きエラーコードは終了コードに対応)、`--format text` で人間向けに表示します。厳選した MCP ツール(`weknora mcp serve`)も提供し、Agent Skills を同梱しています。
```bash
weknora profile add prod --host https://kb.example.com --use
weknora auth login
weknora kb list
weknora link --kb my-knowledge-base # 現在のディレクトリを紐づけ
weknora doc upload notes.md
weknora chat "設計ドキュメントを要約して"
```
ヘッドレス / CI 環境では `WEKNORA_API_KEY` と `WEKNORA_HOST` を設定すれば `auth login` は不要で、資格情報はディスクに書き込まれません。インストールと 5 分間のクイックスタートは [`cli/README.md`](./cli/README.md)、AI エージェントが依存する運用上の約束は [`cli/AGENTS.md`](./cli/AGENTS.md) を参照してください。
## ドキュメント
製品ドキュメントは **[weknora.weixin.qq.com/docs](https://weknora.weixin.qq.com/docs/)**(中国語)にあります。「入門 → アーキテクチャ → 機能 → API → クライアント → 開発」の 6 セクションで構成され、約 360 の API エンドポイント、約 150 の環境変数、9 つの拡張ポイントを網羅しています。
| ここから | |
|---------|---|
| [製品紹介](https://weknora.weixin.qq.com/docs/01-getting-started/01-introduction) | 機能の概要 |
| [インストール](https://weknora.weixin.qq.com/docs/01-getting-started/02-installation) | Docker Compose、Helm、Lite、デスクトップ |
| [設定](https://weknora.weixin.qq.com/docs/01-getting-started/04-configuration) | 環境変数とモデル設定 |
| [トラブルシューティング](https://weknora.weixin.qq.com/docs/01-getting-started/05-troubleshooting) | よくある問題と解決方法 |
| [API ドキュメント](https://weknora.weixin.qq.com/docs/04-api/01-api-overview) | REST API の概要 |
| [リリースノート](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3) | 各バージョンの変更点 |
## 開発ガイド
コードを頻繁に変更する場合、Docker イメージを毎回再構築する必要はありません。高速開発モードを使用してください:
```bash
make dev-start # インフラストラクチャを起動
make dev-app # バックエンドを起動(新しいターミナル)
make dev-frontend # フロントエンドを起動(新しいターミナル)
```
- フロントエンドの変更は自動ホットリロード(再起動不要)
- バックエンドの変更は高速再起動(5-10 秒、Air ホットリロード対応)
- Docker イメージの再構築が不要
- IDE のブレークポイントデバッグに対応
詳細は[開発環境クイックスタート](https://weknora.weixin.qq.com/docs/06-development/01-dev-guide)(中国語)を参照してください。
ドキュメントサイトと製品ホームページのソースは [`website-docs/`](./website-docs/README.md) にあります。Node.js 24 で `cd website-docs && npm run setup && npm run build && npm run preview` を実行すると両方をプレビューできます。統合された静的出力は `/` でホームページ、`/docs/` でドキュメントを配信します。Nginx と Docker でのデプロイ方法は同ディレクトリの README を参照してください。
## 貢献ガイド
[Issue](https://github.com/Tencent/WeKnora/issues) や Pull Request の提出を歓迎します。
- **フロー:** Fork → ブランチ作成 → 変更をコミット → PR を作成
- **規約:** `gofmt` でコードをフォーマットし、[Conventional Commits](https://www.conventionalcommits.org/) に従う(`feat:` / `fix:` / `docs:` / `test:` / `refactor:`)
<details>
<summary><b>変更の検証</b></summary>
<br/>
範囲を絞った PR では、まず変更した範囲を検証してください:
```bash
git fetch origin main
git diff --check origin/main...HEAD
golangci-lint run --new-from-rev=origin/main ./...
go test ./path/to/changed/package -count=1
```
コミット前に、変更した Go ファイルに `gofmt` を実行してください。フロントエンドの変更では `frontend/` で関連するテストを実行し、TypeScript や Vue コンポーネントに影響する場合は `npm run type-check` も実行してください。
メンテナーが使うリポジトリ全体の検証コマンドは次のとおりです:
```bash
make fmt
make lint
make test
```
`make fmt` はリポジトリ全体の Go コードをフォーマットするため、ワークツリーがクリーンな状態でのみ実行し、生じた差分を確認してください。一部の全体テストはローカルのインフラやサービス設定を必要とします。無関係なベースラインや環境の理由で全体チェックが失敗した場合は、実行したコマンドとエラーを PR に記載し、変更範囲の対象テストが通ることを示してください。
</details>
### コントリビューター
すべてのコントリビューターに感謝します:
[![Contributors](https://contrib.rocks/image?repo=Tencent/WeKnora)](https://github.com/Tencent/WeKnora/graphs/contributors)
## ライセンス
このプロジェクトは [MIT](./LICENSE) ライセンスの下で公開されています。このプロジェクトのコードを自由に使用、変更、配布できますが、元の著作権表示を保持する必要があります。
+451
View File
@@ -0,0 +1,451 @@
<p align="center">
<a href="https://weknora.weixin.qq.com">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/hero-ko-dark.svg">
<img src="./docs/images/readme/hero-ko-light.svg" alt="WeKnora: 답을 찾고, 지식을 실천으로. Tencent가 오픈소스로 공개한 엔터프라이즈 지식 관리 프레임워크입니다. 팀 자료를 모아 Q&A, 작업 실행, Wiki 정리에 활용합니다." width="100%">
</picture>
</a>
</p>
<p align="center">
<a href="https://weknora.weixin.qq.com"><img alt="공식 웹사이트" src="https://img.shields.io/badge/website-weknora.weixin.qq.com-b8863b?style=flat-square&labelColor=101f38"></a>
<a href="https://weknora.weixin.qq.com/docs/"><img alt="문서" src="https://img.shields.io/badge/docs-중국어-b8863b?style=flat-square&labelColor=101f38"></a>
<a href="./CHANGELOG.md"><img alt="릴리스" src="https://img.shields.io/badge/release-v0.8.3-b8863b?style=flat-square&labelColor=101f38"></a>
<a href="./LICENSE"><img alt="라이선스" src="https://img.shields.io/badge/license-MIT-b8863b?style=flat-square&labelColor=101f38"></a>
<a href="https://github.com/Tencent/WeKnora/stargazers"><img alt="Stars" src="https://img.shields.io/github/stars/Tencent/WeKnora?style=flat-square&labelColor=101f38&color=b8863b"></a>
<br/>
<a href="https://chatbot.weixin.qq.com"><img alt="WeChat 대화 오픈 플랫폼" src="https://img.shields.io/badge/WeChat_Dialog-Open_Platform-07c160?style=flat-square&labelColor=101f38&logo=wechat&logoColor=white"></a>
<a href="https://chromewebstore.google.com/detail/jpemjbopikggjlmikmclgbmkhhopjdgd"><img alt="Chrome 확장 프로그램" src="https://img.shields.io/badge/Chrome-extension-4285f4?style=flat-square&labelColor=101f38&logo=googlechrome&logoColor=white"></a>
<a href="https://clawhub.ai/lyingbug/weknora"><img alt="ClawHub Skill" src="https://img.shields.io/badge/ClawHub-skill-ff6b35?style=flat-square&labelColor=101f38"></a>
<a href="https://www.npmjs.com/package/@wxg-prc-cpg/dsh-weknora"><img alt="npm @wxg-prc-cpg/dsh-weknora" src="https://img.shields.io/npm/v/@wxg-prc-cpg/dsh-weknora?style=flat-square&label=dsh-weknora&labelColor=101f38&color=cb3837&logo=npm&logoColor=white"></a>
</p>
<p align="center">
<a href="./README.md">English</a> · <a href="./README_CN.md">简体中文</a> · <a href="./README_JA.md">日本語</a> · <b>한국어</b>
</p>
<p align="center">
<a href="#개요">개요</a> ·
<a href="#시작하기">시작하기</a> ·
<a href="#최신-업데이트">최신 업데이트</a> ·
<a href="#기능-개요">기능 개요</a> ·
<a href="#클라이언트와-생태계">클라이언트</a> ·
<a href="#문서">문서</a> ·
<a href="#개발자-가이드">개발자 가이드</a>
</p>
<p align="center">
<a href="https://trendshift.io/repositories/15289"><img src="https://trendshift.io/api/badge/repositories/15289" alt="Tencent/WeKnora | Trendshift" width="220" height="48"/></a>
</p>
## 개요
[**WeKnora**](https://weknora.weixin.qq.com)는 엔터프라이즈 문서 이해, 시맨틱 검색, 추론을 위한 오픈소스 LLM 기반 지식 프레임워크입니다. 팀에 흩어진 문서를 한데 모아 검색하고 추론에 활용할 수 있게 하며, 자료가 바뀌면 함께 갱신합니다.
https://github.com/user-attachments/assets/5722b10d-d04d-49ed-a6cc-635a8c77d91f
<p align="center"><sub>1분 52초 · 1080p · 내레이션 없음, 영어 화면 텍스트</sub></p>
자료 조회는 RAG, 다단계 작업은 Agent, 지식 정리는 Wiki로 합니다. 세 기능은 같은 지식베이스를 공유합니다.
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/capabilities-ko-dark.svg">
<img src="./docs/images/readme/capabilities-ko-light.svg" alt="01 RAG: 근거 있는 답변. 하이브리드 검색, 멀티모달 파싱, 원문 인용. 02 Agent: 지식과 도구로 작업 완료. 다단계 추론, 스킬과 샌드박스, 로컬 브라우저, MCP 도구, 장기 메모리. 03 Wiki: 문서를 Wiki로 정리. 자동 정리, 지식 그래프, 버전 롤백." width="100%">
</picture>
**Agent 도구 상자.** ClawHub / SkillHub / Git / ZIP에서 설치한 스킬은 세션 단위로 유지되는 Docker / E2B / Cube 샌드박스에서 실행되며, 채팅 옆에서 대화형 터미널과 그래픽 데스크톱을 열 수 있습니다. BrowserSkill 확장 프로그램으로 Agent가 사용자의 Chrome / Edge를 직접 조작하고, 외부 MCP 서비스(OAuth 지원)를 연결해 도구별로 활성화할 수 있습니다.
그 밖에:
- **메모리와 지식 정리**: 크로스 세션 장기 메모리가 사용자가 확인한 프로필, 선호, 사실을 보관합니다. 폴더 업로드는 원래 디렉터리 구조를 유지하고, 검색 청크는 편집·비교·롤백할 수 있습니다.
- **데이터 소스와 포맷**: Feishu 지식베이스 / Feishu 클라우드 드라이브 / Confluence / GitLab / Tencent IMA / Notion / Yuque / DingTalk Docs / Seafile / RSS 자동 동기화(지속 확장 중). PDF, Word, 이미지, Excel, XMind 등 10가지 이상의 포맷을 지원하며, Office 문서는 anydoc으로 프로세스 내 파싱합니다.
- **채널과 연동**: WeChat Work, Feishu, Slack, Telegram 등 IM에서 바로 Q&A, 웹사이트 임베드 Widget으로 외부 사이트에 에이전트 게시, 내장 MCP Server로 Cursor·Claude 등 AI 도구와 연결, 범위 지정 API 키와 Principal 모델로 프로그램 연동.
- **모델**: 29개 내장 벤더와 자동 생성 모델 카탈로그. OpenAI, DeepSeek, Qwen(Alibaba Cloud), Zhipu, Hunyuan, Gemini, MiniMax, NVIDIA, LiteLLM, Ollama 등을 지원합니다.
- **권한과 운영**: 멀티 워크스페이스 RBAC(4단계 역할, 리소스 소유권, 워크스페이스 감사 로그), 워크스페이스별 다중 스토리지 인스턴스, 런타임 작업 큐 대시보드와 Worker 풀 거버넌스, Langfuse를 통한 Agent 단계·토큰 사용량·파이프라인 추적.
- **배포**: LLM, 벡터 데이터베이스, 스토리지 백엔드를 모두 교체할 수 있습니다. 로컬이나 프라이빗 클라우드에 배포해 데이터를 자체 환경에 둘 수 있습니다.
### 적용 시나리오
| 시나리오 | 적용 사례 | 핵심 가치 |
|---------|----------|----------|
| **기업 지식 관리** | 내부 문서 검색, 규정 Q&A, 운영 매뉴얼 조회 | 지식 탐색 효율 향상, 교육 비용 절감 |
| **학술 연구 분석** | 논문 검색, 연구 리포트 분석, 학술 자료 정리 | 문헌 조사 가속, 연구 의사결정 지원 |
| **제품 기술 지원** | 제품 매뉴얼 Q&A, 기술 문서 검색, 트러블슈팅 | 고객 지원 품질 향상, 지원 부담 감소 |
| **법무/컴플라이언스 검토** | 계약 조항 검색, 규제 정책 조회, 사례 분석 | 컴플라이언스 효율 향상, 법적 리스크 감소 |
| **의료 지식 지원** | 의학 문헌 검색, 진료 가이드라인 조회, 증례 분석 | 임상 의사결정 지원, 진단 품질 향상 |
## 시작하기
<table>
<tr>
<td width="33%" valign="top">
<img src="./website-docs/homepage/public/docs/_home/brands/wechat-dialog.png" width="28" height="28" alt=""><br/>
<sub>온라인</sub><br/>
<b>WeChat 대화 오픈 플랫폼</b><br/>
지식베이스를 온라인으로 관리하고, Q&A 서비스를 공식계정·미니프로그램 등 WeChat 시나리오에 연결합니다.<br/><br/>
<a href="https://chatbot.weixin.qq.com/login">플랫폼 열기 →</a>
</td>
<td width="33%" valign="top">
<img src="./website-docs/homepage/public/docs/_home/brands/tencent-cloud.ico" width="28" height="28" alt=""><br/>
<sub>클라우드</sub><br/>
<b>Tencent Cloud Lighthouse</b><br/>
애플리케이션 템플릿으로 WeKnora를 배포하고 자신의 클라우드 서버에서 운영합니다.<br/><br/>
<a href="https://mc.tencent.com/s69nKCVz">Tencent Cloud에 배포 →</a>
</td>
<td width="33%" valign="top">
<img src="./docs/images/readme/icons/server.svg" width="28" height="28" alt=""><br/>
<sub>셀프 호스팅</sub><br/>
<b>자체 환경에 배포</b><br/>
Docker 또는 Kubernetes로 배포하고 모델, 스토리지, 네트워크를 직접 구성합니다.<br/><br/>
<a href="#docker-compose로-배포">Docker Compose로 배포 ↓</a>
</td>
</tr>
</table>
### Docker Compose로 배포
[Docker](https://www.docker.com/), [Docker Compose](https://docs.docker.com/compose/), [Git](https://git-scm.com/)이 필요합니다.
```bash
git clone https://github.com/Tencent/WeKnora.git
cd WeKnora
cp .env.example .env # 필요에 따라 .env 편집 (파일 내 주석 참고)
docker compose pull # 최신 이미지 가져오기
docker compose up -d # 코어 서비스 시작
```
시작 후 **[http://localhost](http://localhost)** 에 접속해 온보딩 가이드에 따라 설정하세요. 샘플 데이터를 사용하는 전체 과정은 [빠른 시작](https://weknora.weixin.qq.com/docs/01-getting-started/03-quickstart)(중국어)을 참고하세요.
> [!TIP]
> 로컬 Ollama 모델을 사용하려면 먼저 `ollama serve > /dev/null 2>&1 &` 를 실행하세요. Ollama 임베딩 모델 이름, `OLLAMA_BASE_URL`, RAM 안내는 [설정 문서](https://weknora.weixin.qq.com/docs/01-getting-started/04-configuration)를 참고하세요.
| 서비스 | URL |
|--------|-----|
| Web UI | `http://localhost` |
| 백엔드 API | `http://localhost:8080` |
| Langfuse 트레이싱 | `http://localhost:3000` |
### 선택 서비스
`--profile` 플래그로 추가 컴포넌트를 활성화합니다. 여러 profile을 조합할 수 있습니다.
| Profile | 설명 |
|---------|------|
| _(기본)_ | 코어 서비스 |
| `full` | 전체 기능 |
| `neo4j` | 지식 그래프 (Neo4j) |
| `minio` | 오브젝트 스토리지 (MinIO) |
| `langfuse` | 트레이싱 (Langfuse) |
```bash
docker compose --profile neo4j --profile minio pull
docker compose --profile neo4j --profile minio up -d
docker compose down # 서비스 중지
```
### 업그레이드
기존 배포가 있고 새 release를 다운로드한 경우:
```bash
# .env에서 WEKNORA_VERSION을 대상 버전(예: 0.8.3)으로 설정하거나 latest 유지
docker compose pull # WEKNORA_VERSION에 맞는 이미지 가져오기
docker compose up -d # 새 이미지로 컨테이너 재생성
```
> [!NOTE]
> `docker compose up -d`만 실행하면 로컬 캐시 이미지가 재사용되어 Web UI 버전이 다운로드한 release와 일치하지 않을 수 있습니다. 업그레이드하기 전에 [업그레이드 안내](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#upgrade-notes)를 확인하세요.
### 기타 배포 방식
| 방식 | 용도 |
|------|------|
| **Docker Compose** | 위의 표준 배포. 전체 기능, 다중 서비스 구성 |
| **Kubernetes (Helm)** | 운영 클러스터. Chart는 [`helm/`](./helm)에 있습니다 |
| **Lite 단일 바이너리** | 로컬 또는 저사양 환경, 외부 의존성 없음(SQLite + 인메모리 큐). 표준판과의 차이는 [Lite와 표준판 비교](./docs/LITE.md)(중국어) |
| **데스크톱 앱** | GUI가 있는 Lite 런타임. 로그인 없이 시작하며 macOS에서는 호스트 샌드박스를 제공. 설치 파일이 아직 없으므로 소스에서 빌드하세요 |
모든 배포 형태, 하드웨어 요구 사항, 배포 토폴로지는 [설치 가이드](https://weknora.weixin.qq.com/docs/01-getting-started/02-installation)를 참고하세요.
> [!WARNING]
> WeKnora는 로그인 인증을 제공하지만, 운영 환경 배포 시 아래 사항을 강력히 권장합니다.
> - WeKnora 서비스를 공용 인터넷이 아닌 내부 / 사설 네트워크 환경에 배포
> - 정보 유출 방지를 위해 서비스를 공용 네트워크에 직접 노출하지 않기
> - 배포 환경에 적절한 방화벽 규칙 및 접근 제어 구성
> - 보안 패치와 개선 사항 적용을 위해 최신 버전으로 정기 업데이트
## 최신 업데이트
### v0.8.3 <sub>· 2026-10-14 · [릴리스 노트](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3)</sub>
- **[이미지 갤러리](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#images)**: 문서 이미지를 모아 보고 출처, 설명, OCR 및 이미지 속성으로 필터링.
- **[멀티모달 Embedding](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#multimodal-embedding)**: 텍스트와 이미지를 같은 벡터 공간으로 인코딩하는 모델 지원. Tencent WeMM-Embedding, Qwen3-VL-Embedding 등을 사용할 수 있으며 이미지 벡터 검색과 호환 모델의 이미지 리랭킹을 선택적으로 활성화.
- **[Wiki 그래프](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#wiki-graph)**: 그룹 배치와 주제 설명을 개선하고 그룹 집중 보기, 그룹 전환 및 전체 그래프 복귀를 지원.
- **[원문 인용](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#conversation)**: 답변에서 원문의 인용 부분으로 바로 이동.
- **[대화와 도구](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#tools)**: 샌드박스 없이 첨부 파일을 필요할 때 읽기, 읽지 않은 답변 표시, @ 검색, Docker 터미널, Lite 로컬 스킬과 MCP 호환성 개선.
- **[관리와 연동](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#administration)**: 플랫폼 사용자 관리, 초대 등록 모드, 관리자 모델 카탈로그, WeMM, TEI/Pinecone/Cohere, Seafile과 번체 중국어.
- **[안정성](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#other-changes)**: 검색, 파싱, 동기화, Wiki, OAuth와 CLI 수정. 등록 모드, 빈 도구 목록, DB 마이그레이션과 재색인은 [업그레이드 안내](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3#upgrade-notes)를 확인하세요.
### v0.8.2 <sub>· 2026-09-24 · [릴리스 노트](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2)</sub>
에이전트가 사용자 컴퓨터의 브라우저를 조작할 수 있고, 지식베이스를 MCP로 다른 AI 도구에 공개할 수 있으며, 진행 중인 대화에 요구 사항을 추가하거나 분기·되감기할 수 있습니다.
- **[로컬 브라우저(BrowserSkill)](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#local-browser)**: 오픈소스 BrowserSkill 확장 프로그램을 통해 에이전트가 사용자 자신의 Chrome / Edge를 조작합니다. 실시간 작업 미리보기, 일시정지 / 재개를 지원하며 로그인과 CAPTCHA는 사용자에게 인계합니다.
- **[내장 MCP Server](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#mcp-server)**: 워크스페이스별 `/mcp/<endpoint_id>` 엔드포인트(Streamable HTTP). 엔드포인트마다 별도 토큰·지식베이스 범위·요청 제한·도구 그룹을 둡니다. Python 버전 `mcp-server/`는 지원 중단되었습니다.
- **[대화 제어](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#conversation-control)**: 실행 중인 턴에 요구 사항 추가, 이전 질문에서 대화 분기, 샌드박스 체크포인트와 함께 제자리 되감기, 세션별 추론 강도. 생성된 파일은 새 산출물 라이브러리에 모입니다.
- **[샌드박스](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#sandbox)**: 대화형 터미널과 그래픽 데스크톱, macOS Lite 호스트 샌드박스와 프로젝트 폴더, 스킬·MCP 서비스·브라우저 연결을 모은 사이드바 도구 상자.
- **[모델](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#models)**: 재구축된 모델 카탈로그(27개 내장 벤더, 컨텍스트 윈도우·최대 출력·추론 단계·비전 지원 자동 채움). Agent 검색 도구를 `search_knowledge` / `read_document` / `list_documents`로 통합.
- **[지식과 플랫폼](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#knowledge)**: Confluence 및 DingTalk Docs 데이터 소스, Bocha 및 Serply 웹 검색, 일본어 UI, IM 채널별 응답 언어, 화이트리스트 전용 외부 통신 모드.
> [!IMPORTANT]
> **호환성 변경:** DingTalk 채널은 Stream 모드만 지원하며, 샌드박스 명령은 기본적으로 `root`로 실행됩니다. [업그레이드 안내](https://weknora.weixin.qq.com/docs/07-releases/v0.8.2#upgrade-notes)를 참고하세요.
### v0.8.0 <sub>· [릴리스 노트](https://weknora.weixin.qq.com/docs/07-releases/v0.8.0)</sub>
- **스킬 샌드박스 런타임**: 세션 지속 Docker / E2B / Cube 백엔드, 테넌트별 네트워크 정책. Local 호스트 프로세스 백엔드를 제거했고 Docker는 옵트인입니다.
- **테넌트 스킬 카탈로그**: ClawHub / SkillHub / git / zip에서 설치, 샌드박스별 스냅샷, 실시간 진행 상황, 파일 탐색 / 편집, 개인·워크스페이스 환경 변수.
- **크로스 세션 장기 메모리**: profile / preference / fact / task / interest, 확인 기반 자동 추출, `search_memory`.
- **파싱과 데이터 소스**: 프로세스 내 anydoc Office 파서, GitLab 및 Tencent IMA 데이터 소스, XMind 파싱.
- **생태계**: 공식 DeepSeek Harness 플러그인 `@wxg-prc-cpg/dsh-weknora`, LiteLLM, Exa 및 Metaso 웹 검색.
- **채팅**: 채팅 산출물, 질문 개요, 타임스탬프, 컨텍스트 압축과 프로바이더 Prompt Cache 마커.
- **보안**: OIDC JWKS 검증, 선택적 복잡 비밀번호, 문서 자동 태깅, 광범위한 샌드박스 / 보안 강화.
<details>
<summary><b>이전 버전(v0.2.0 – v0.7.2)</b></summary>
<br/>
- **v0.7.2** — 제품 문서 사이트, 지식베이스 폴더 트리, 청크 편집 및 버전 이력, Wiki 페이지 버전 이력, 바로 로드 가능한 파일 URL(`resource_urls=public`), Feishu 클라우드 드라이브 데이터 소스, 일괄 태깅, MCP Server 1.1(도구 29개), AWS S3 기본 자격 증명 체인.
- **v0.7.1** — Yunzhijia IM, Volcengine 리랭크, Zhipu AI 웹 검색, 플랫폼 범위 API 키, KB 단위 활동 감사, FAQ 필터·태깅·내보내기, Langfuse OTLP 추적, 원클릭 Markdown 내보내기.
- **v0.7.0** — 범위 지정 API 키와 Principal 모델, 작업 큐 대시보드와 Worker 풀 거버넌스, 워크스페이스당 여러 스토리지 인스턴스, 대화 임시 첨부, `@Skill / @MCP` 멘션, 대화 중 MCP OAuth, QQBot과 Lark IM, Redis TLS, `weknora` CLI v0.10.
- **v0.6.3** — 웹사이트 임베드 Widget 및 통합 센터(보안 모드 Token 교환 + 속도 제한); 채팅 경험 전면 개편(인용 팝오버, RAG 파이프라인 진행, 스트리밍 Markdown); 문서 다중 태그 및 일괄 reparse; Wiki 폴더 및 계층 탐색; RSS 데이터 소스; MCP OAuth2; EPUB / MHTML 파싱; Agent 모델 준비 상태 검사; 모델 디버거; 세션 소스 필터; 워크스페이스 삭제 UI.
- **v0.6.2** — 업로드 단위 파싱 설정(`process_config`) + 업로드 확인 대화상자; reparse 시 설정 덮어쓰기; `weknora` CLI v0.9(번들 Agent Skills, `session stop`, auth/profile 통합); KB 마키 선택 다중 선택; pgvector 1024차원 HNSW 인덱스; 채팅 리소스 Store 리팩터; Langfuse 단일 추적(Jaeger 제거).
- **v0.6.1** — 문서 파싱 추적 타임라인(Langfuse 스타일 Span 트리, 단계별 진행 표시 + 파싱 중단); OpenSearch 벡터 저장소 드라이버; YAML 선언형 내장 모델 구성; 시스템 관리자와 통합 플랫폼 설정 + 감사 로그; 신규 사용자 온보딩 가이드; 설정 UI 리디자인; `weknora` CLI v0.7 / v0.8(Agent 우선 와이어 프로토콜, NDJSON, `--dry-run`); OpenDataLoader 및 PaddleOCR-VL 파싱 엔진; MCP 서버 멀티 트랜스포트(stdio / SSE / HTTP); 모델별 사고 모드 설정; Tencent LKEAP 리랭크 + 네이티브 Gemini 임베딩 + MiniMax-M3.
- **v0.6.0** — 테넌트 RBAC(4단계 역할 매트릭스 `Owner` / `Admin` / `Contributor` / `Viewer` + KB 단위 소유 + 테넌트별 감사 로그), 테넌트 멤버 관리와 멀티 워크스페이스 UX, 셀프 서비스 워크스페이스 생성; `weknora` CLI v0.4 GA + `mcp serve`; 여러 벡터 저장소에 걸친 KB 검색 팬아웃; MCP / 데이터 소스 자격 증명 AES-256-GCM 암호화 + docreader gRPC TLS + Token; Zhipu 임베더와 화웨이 클라우드 OBS 추가; 서버 사이드 사용자 환경설정; Go 1.26.0. 자세한 내용은 [테넌트와 인증](https://weknora.weixin.qq.com/docs/03-features/01-tenant-auth)(중국어) 참고.
- **v0.5.2** — Wiki 인제스트가 만 건 규모 KB 지원(작업 큐 + DLQ); MCP 휴먼인더루프 도구 승인; Anthropic / Apache Doris / Tencent VectorDB / Kingsoft Cloud KS3 / SearXNG 백엔드; 적응형 3단계 청킹 + 라이브 미리보기; 글로벌 ⌘K 명령 팔레트; Yuque 커넥터 + WeChat 미니프로그램; `weknora` CLI 프리뷰.
- **v0.5.1** — 지식베이스 일괄 관리; 테넌트 전체 IM 채널 개요; 세션 검색 + 사용자 단위 핀; 모델 / 웹 검색 / MCP 통일 카드 설정; Agent별 LLM 타임아웃; 데스크탑 테넌트 전환.
- **v0.5.0** — Wiki 모드 GA — Agent가 원본 문서에서 구조화·상호 연결된 Markdown Wiki 페이지와 지식 그래프 자동 생성, Wiki 브라우저 및 시각화 그래프를 UI에 탑재.
- **v0.4.0** — WeKnora Cloud(호스팅 LLM + 파싱); Chrome 확장 프로그램; ClawHub Skill; WeChat IM; 첨부 처리; Azure OpenAI / Alibaba OSS; Notion 커넥터; Baidu + Ollama 웹 검색; VectorStore 관리.
- **v0.3.6** — ASR(음성); Feishu 데이터 소스 자동 동기화; OIDC; IM 인용 회신 + 스레드 기반 세션; 문서 자동 요약; Tavily 검색; 병렬 도구 호출; Agent @멘션 범위 제한.
- **v0.3.5** — Telegram / DingTalk / Mattermost IM; IM 슬래시 커맨드 + QA 큐; 추천 질문; VLM에 의한 MCP 도구 이미지 자동 설명; Novita AI; 채널 추적.
- **v0.3.4** — 기업 WeChat / Feishu / Slack IM; 멀티모달 이미지; NVIDIA 모델 API; Weaviate; AWS S3; AES-256-GCM API 키 암호화; 내장 MCP 서비스; 하이브리드 검색 최적화; `final_answer` 도구.
- **v0.3.3** — 부모-자식 청킹; KB 핀; 폴백 응답; Rerank 패시지 클리닝; 스토리지 버킷 자동 생성; Milvus.
- **v0.3.2** — 지식 검색 진입점; 소스별 파서 / 스토리지 엔진 설정; 로컬 스토리지 이미지 렌더링; 문서 미리보기; Volcengine TOS; Mermaid 렌더링; 대화 일괄 관리; 메모리 그래프 미리보기.
- **v0.3.0** — 공유 스페이스; Agent Skills + 샌드박스 실행; 커스텀 Agent; 데이터 분석 Agent; 사고 모드; Bing / Google 검색; API Key 인증; Helm Chart; 한국어 i18n; Qdrant.
- **v0.2.0** — Agent 모드(ReACT); 다중 타입 지식베이스(FAQ + 문서); 대화 전략 설정; DuckDuckGo 웹 검색; MCP 도구 통합; 새 UI + Agent 모드 전환; MQ 비동기 작업 관리.
전체 변경 이력은 [`CHANGELOG.md`](./CHANGELOG.md)를 참고하세요.
</details>
## 기능 데모
### 빠른 Q&A와 스마트 추론
**두 가지 질문 방식.** 빠른 Q&A는 지식베이스를 RAG로 검색해 답하고 참고한 출처를 표시합니다. 스마트 추론에서는 에이전트가 다단계 작업을 계획해 검색, 문서 읽기, 도구와 스킬 호출을 수행하며 각 단계를 대화에 보여 줍니다. [문서 →](https://weknora.weixin.qq.com/docs/03-features/18-chat-experience)
<a href="./docs/images/readme/spotlight-qa-light.webp">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/spotlight-qa-dark.webp">
<img src="./docs/images/readme/spotlight-qa-light.webp" alt="빠른 Q&A와 스마트 추론" width="100%">
</picture>
</a>
### 로컬 브라우저
**사용자 컴퓨터의 브라우저 조작.** Tencent가 오픈소스로 공개한 BrowserSkill 확장 프로그램으로 에이전트가 사용자의 Chrome이나 Edge에서 페이지를 열고 양식을 입력합니다. 로그인이나 CAPTCHA는 사용자에게 넘깁니다. [문서 →](https://weknora.weixin.qq.com/docs/05-clients/09-local-browser)
<a href="./docs/images/readme/spotlight-browser-light.webp">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/spotlight-browser-dark.webp">
<img src="./docs/images/readme/spotlight-browser-light.webp" alt="로컬 브라우저" width="100%">
</picture>
</a>
### 스킬과 샌드박스
**스킬을 실행하고 파일을 생성.** Docker, E2B, Cube를 지원합니다. 같은 세션의 여러 턴이 하나의 작업 공간을 공유하며, 생성된 파일은 미리 보고 내려받을 수 있습니다. 대화 옆에서 그래픽 데스크톱이나 대화형 터미널을 열어 에이전트의 각 단계를 확인하고, 필요하면 직접 이어받을 수 있습니다. [문서 →](https://weknora.weixin.qq.com/docs/03-features/22-skills-sandbox)
<a href="./docs/images/readme/spotlight-sandbox-light.webp">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/spotlight-sandbox-dark.webp">
<img src="./docs/images/readme/spotlight-sandbox-light.webp" alt="스킬과 샌드박스" width="100%">
</picture>
</a>
### 도구 상자: MCP 서비스와 스킬
**에이전트가 쓰는 도구.** 외부 MCP 서비스를 연결하고, 켤 도구와 승인이 필요한 호출을 도구별로 고를 수 있습니다. 스킬은 ClawHub, SkillHub, Git, ZIP에서 설치해 워크스페이스에서 관리하고 여러 샌드박스에서 재사용합니다. [문서 →](https://weknora.weixin.qq.com/docs/03-features/22-skills-sandbox)
<a href="./docs/images/readme/spotlight-toolbox-light.webp">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/spotlight-toolbox-dark.webp">
<img src="./docs/images/readme/spotlight-toolbox-light.webp" alt="도구 상자: MCP 서비스와 스킬" width="100%">
</picture>
</a>
### 자동 Wiki
**문서를 탐색 가능한 Wiki로.** Wiki를 켜면 지식베이스 문서에서 인물, 제품, 개념을 추출해 출처가 달린 페이지를 만들고 디렉터리별로 탐색할 수 있습니다. 지식 그래프에서 페이지 간 관계를 보고, 페이지를 직접 편집하며 변경 내역을 되돌릴 수 있습니다. [문서 →](https://weknora.weixin.qq.com/docs/03-features/14-wiki)
<a href="./docs/images/readme/spotlight-wiki-light.webp">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/spotlight-wiki-dark.webp">
<img src="./docs/images/readme/spotlight-wiki-light.webp" alt="자동 Wiki" width="100%">
</picture>
</a>
### 관측 가능성
**추적과 런타임 모니터링.** Langfuse가 에이전트 각 단계의 추론, 도구 호출, 토큰 사용량을 추적합니다. 문서 파싱 타임라인은 단계별 진행 상황을 보여 주고, 작업 큐 대시보드는 대기 중이거나 실패한 작업을 나열합니다. [문서 →](https://weknora.weixin.qq.com/docs/03-features/16-observability)
<a href="./docs/images/readme/spotlight-observability-light.webp">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/spotlight-observability-dark.webp">
<img src="./docs/images/readme/spotlight-observability-light.webp" alt="관측 가능성" width="100%">
</picture>
</a>
## 아키텍처
<a href="./docs/images/readme/architecture-ko-light.svg">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="./docs/images/readme/architecture-ko-dark.svg">
<img src="./docs/images/readme/architecture-ko-light.svg" alt="WeKnora 아키텍처: 클라이언트와 채널이 WeKnora 앱에 연결되고, RAG Q&A·Agent 추론·자동 Wiki가 같은 지식 처리 파이프라인을 공유. 앱은 런타임 서비스를 호출하고 PostgreSQL·Redis와 선택적 스토리지에 데이터를 저장" width="100%">
</picture>
</a>
문서 파싱, 벡터화, 검색부터 LLM 추론까지 각 단계를 모듈화하여 구성 요소를 교체·확장할 수 있습니다. 로컬과 프라이빗 클라우드 배포를 지원하며 Web UI로 바로 시작할 수 있습니다. 자세히 보기: [아키텍처 개요](https://weknora.weixin.qq.com/docs/02-architecture/01-overview) · [RAG 파이프라인](https://weknora.weixin.qq.com/docs/02-architecture/04-rag-pipeline) · [확장 지점](https://weknora.weixin.qq.com/docs/06-development/03-extension-points)(중국어).
## 기능 개요
| 영역 | 주요 기능 |
|------|-----------|
| [Q&A와 Agent](https://weknora.weixin.qq.com/docs/03-features/07-agent) | 빠른 Q&A는 지식베이스에서 출처와 함께 답하고, 스마트 추론에서는 ReAct 에이전트가 지식베이스, 웹 검색, MCP 도구, 스킬, 로컬 브라우저를 조합합니다. 실행 중인 대화에 요구 사항 추가·분기·되감기, 세션을 넘는 [장기 메모리](https://weknora.weixin.qq.com/docs/03-features/23-memory) 지원 |
| [Wiki](https://weknora.weixin.qq.com/docs/03-features/14-wiki) | 에이전트가 상호 연결된 Wiki 페이지와 지식 그래프를 생성. 브라우저 내 편집, 버전 diff 및 롤백 |
| [스킬과 샌드박스](https://weknora.weixin.qq.com/docs/03-features/22-skills-sandbox) | ClawHub / SkillHub / Git / ZIP에서 설치하는 스킬 카탈로그. 세션 단위로 유지되는 Docker / E2B / Cube 샌드박스와 설정 단위 네트워크 정책. 채팅 옆 대화형 터미널과 그래픽 데스크톱 |
| [지식베이스](https://weknora.weixin.qq.com/docs/03-features/02-knowledge-base) | FAQ·문서·Wiki 세 가지 유형. 폴더 트리, 청크 편집 및 버전 이력, 업로드 단위 파싱·청킹·멀티모달 설정, 자동 태깅 |
| [검색](https://weknora.weixin.qq.com/docs/03-features/05-retrieval-engines) | 키워드 + 벡터 하이브리드 검색, 리랭크, 부모-자식 청킹, GraphRAG([Neo4j](https://weknora.weixin.qq.com/docs/03-features/09-knowledge-graph)). 리콜 적중률과 BLEU / ROUGE 기반 엔드투엔드 평가 |
| [권한과 보안](https://weknora.weixin.qq.com/docs/03-features/01-tenant-auth) | 4단계 역할과 감사 로그를 갖춘 워크스페이스 RBAC, 범위 지정 API 키, OIDC, AES-256-GCM 자격 증명 암호화, SSRF 방지 아웃바운드 요청과 화이트리스트 전용 모드 |
| [운영](https://weknora.weixin.qq.com/docs/03-features/16-observability) | Langfuse로 Agent 단계·토큰 사용량·파이프라인 추적, 문서 파싱 타임라인, Worker 풀을 갖춘 작업 큐 대시보드, 버전 업그레이드 시 자동 DB 마이그레이션 |
### 지원 백엔드
| 구성 요소 | 선택지 |
|-----------|--------|
| [LLM](https://weknora.weixin.qq.com/docs/03-features/06-models) | 29개 내장 벤더. OpenAI / Azure OpenAI / Anthropic / DeepSeek / Qwen (Alibaba Cloud) / Zhipu / Hunyuan / Doubao (Volcengine) / Gemini / MiniMax / NVIDIA / SiliconFlow / OpenRouter / LiteLLM / Ollama 등 |
| Embedding | Ollama / BGE / GTE / Zhipu / OpenAI 호환 API |
| 벡터 DB | PostgreSQL (pgvector) / Elasticsearch / OpenSearch / Milvus / Weaviate / Qdrant / Apache Doris / Tencent VectorDB |
| [오브젝트 스토리지](https://weknora.weixin.qq.com/docs/03-features/19-storage-backends) | 로컬 / Tencent Cloud COS / MinIO / AWS S3 / Volcengine TOS / Alibaba Cloud OSS / Kingsoft Cloud KS3 / Huawei Cloud OBS |
| [문서 포맷](https://weknora.weixin.qq.com/docs/03-features/03-document-parsing) | PDF / Word / PPT / Excel / CSV / TXT / Markdown / HTML / EPUB / MHTML / JSON / XMind / 이미지 |
| [데이터 소스](https://weknora.weixin.qq.com/docs/03-features/10-datasource) | Feishu 지식베이스 / Feishu 클라우드 드라이브 / Lark / Confluence / GitLab / Tencent IMA / Notion / Yuque / DingTalk Docs / Seafile / RSS |
| [IM 통합](https://weknora.weixin.qq.com/docs/03-features/12-im-integration) | WeChat Work / Feishu / Lark / QQBot / Slack / Telegram / DingTalk / Mattermost / WeChat / Yunzhijia |
| [웹 검색](https://weknora.weixin.qq.com/docs/03-features/11-web-search) | DuckDuckGo / Bing / Google / Tavily / Baidu / Ollama / SearXNG / Keenable / Zhipu AI / Exa / Metaso / Bocha / Serply |
| 배포 | Docker Compose / Kubernetes (Helm) / Lite 단일 바이너리 / 데스크톱 앱. 오프라인·프라이빗 클라우드 배포 지원. UI는 중국어 / 영어 / 일본어 / 한국어 / 러시아어 지원 |
## 클라이언트와 생태계
| | 클라이언트 | 용도 |
|:-:|----------|------|
| <img src="./docs/images/readme/icons/terminal.svg" width="22" height="22" alt=""> | [**CLI `weknora`**](./cli/README.md) | Agent 우선 명령줄 도구. 전체 API를 다루며 엄선한 MCP 도구와 내장 Agent Skills 제공 |
| <img src="./docs/images/readme/icons/plug.svg" width="22" height="22" alt=""> | [**내장 MCP Server**](https://weknora.weixin.qq.com/docs/03-features/08-mcp) | Streamable HTTP로 지식베이스를 Cursor, Claude 등 MCP 클라이언트에 공개. [`mcp-server/`](./mcp-server/MCP_CONFIG.md)의 Python 서버는 지원 중단 |
| <img src="./website-docs/homepage/public/docs/_home/brands/browserskill.png" width="22" height="22" alt=""> | [**로컬 브라우저(BrowserSkill)**](https://weknora.weixin.qq.com/docs/05-clients/09-local-browser) | 에이전트가 사용자 자신의 Chrome / Edge를 조작 |
| <img src="./website-docs/homepage/public/docs/_home/brands/chrome.svg" width="22" height="22" alt=""> | [**Chrome 확장 프로그램**](https://chromewebstore.google.com/detail/jpemjbopikggjlmikmclgbmkhhopjdgd) | 텍스트, 이미지 또는 전체 페이지를 선택해 원클릭으로 지식 항목으로 저장. 복사/붙여넣기나 파일 업로드 불필요 |
| <img src="./docs/images/readme/icons/phone.svg" width="22" height="22" alt=""> | [**WeChat 미니 프로그램**](./miniprogram/README.md) | 경량 모바일 클라이언트. API 설정, 지식베이스 선택, URL 임포트, WeChat에서 지식 Q&A |
| <img src="./docs/images/readme/icons/skills.svg" width="22" height="22" alt=""> | [**ClawHub Skill**](https://clawhub.ai/lyingbug/weknora) | ClawHub에 게시된 WeKnora 스킬. REST API로 문서 임포트, 하이브리드 검색, 지식 관리 |
| <img src="./website-docs/homepage/public/docs/_home/brands/deepseek-color.svg" width="22" height="22" alt=""> | [**DeepSeek Harness 플러그인**](https://www.npmjs.com/package/@wxg-prc-cpg/dsh-weknora) | `dsh` 코딩 에이전트에 읽기 전용 도구 4개(검색, 문서 읽기, 질문, 지식베이스 목록) 제공 |
| <img src="./docs/images/readme/icons/code.svg" width="22" height="22" alt=""> | [**웹사이트 임베드 Widget**](https://weknora.weixin.qq.com/docs/03-features/13-embed-channel) | 에이전트를 외부 사이트에 게시 |
| <img src="./docs/images/readme/icons/braces.svg" width="22" height="22" alt=""> | [**Go SDK**](https://weknora.weixin.qq.com/docs/05-clients/03-go-sdk) | 지식베이스·문서·세션 등의 CRUD와 SSE 스트리밍 Q&A |
| <img src="./website-docs/homepage/public/docs/_home/brands/wechat-dialog.png" width="22" height="22" alt=""> | [**WeChat 대화 오픈 플랫폼**](https://chatbot.weixin.qq.com) | WeKnora 기반 호스팅 Q&A. 지식을 업로드하면 코드 없이 WeChat에 Q&A 서비스 게시 |
### 명령줄 도구
`weknora`는 터미널이나 AI 에이전트에서 API를 다루기 위한 공식 CLI입니다. **Agent 우선**으로 설계되어 모든 명령이 기본적으로 안정적인 JSON 엔벨로프를 출력하고(타입이 지정된 오류 코드는 종료 코드에 매핑), `--format text`로 사람이 읽기 좋은 형태로 표시합니다. 엄선한 MCP 도구(`weknora mcp serve`)를 제공하며 Agent Skills를 내장하고 있습니다.
```bash
weknora profile add prod --host https://kb.example.com --use
weknora auth login
weknora kb list
weknora link --kb my-knowledge-base # 현재 디렉터리 연결
weknora doc upload notes.md
weknora chat "설계 문서를 요약해 줘"
```
헤드리스 / CI 환경에서는 `WEKNORA_API_KEY`와 `WEKNORA_HOST`를 설정하면 `auth login` 없이 사용할 수 있으며, 자격 증명이 디스크에 기록되지 않습니다. 설치와 5분 빠른 시작은 [`cli/README.md`](./cli/README.md), AI 에이전트가 의존하는 운영 규약은 [`cli/AGENTS.md`](./cli/AGENTS.md)를 참고하세요.
## 문서
제품 문서는 **[weknora.weixin.qq.com/docs](https://weknora.weixin.qq.com/docs/)**(중국어)에 있습니다. 「입문 → 아키텍처 → 기능 → API → 클라이언트 → 개발」 6개 섹션으로 구성되며, 약 360개 API 엔드포인트, 약 150개 환경 변수, 9개 확장 지점을 다룹니다.
| 여기서 시작 | |
|------------|---|
| [제품 소개](https://weknora.weixin.qq.com/docs/01-getting-started/01-introduction) | 기능 개요 |
| [설치](https://weknora.weixin.qq.com/docs/01-getting-started/02-installation) | Docker Compose, Helm, Lite, 데스크톱 |
| [설정](https://weknora.weixin.qq.com/docs/01-getting-started/04-configuration) | 환경 변수와 모델 설정 |
| [문제 해결 FAQ](https://weknora.weixin.qq.com/docs/01-getting-started/05-troubleshooting) | 자주 발생하는 문제와 해결 방법 |
| [API 문서](https://weknora.weixin.qq.com/docs/04-api/01-api-overview) | REST API 개요 |
| [릴리스 노트](https://weknora.weixin.qq.com/docs/07-releases/v0.8.3) | 버전별 변경 사항 |
## 개발자 가이드
코드를 자주 수정한다면 매번 Docker 이미지를 다시 빌드할 필요가 없습니다. 고속 개발 모드를 사용하세요.
```bash
make dev-start # 인프라 시작
make dev-app # 백엔드 시작 (새 터미널)
make dev-frontend # 프론트엔드 시작 (새 터미널)
```
- 프론트엔드 변경 자동 핫리로드(재시작 불필요)
- 백엔드 변경 빠른 재시작(5~10초, Air 핫리로드 지원)
- Docker 이미지 재빌드 불필요
- IDE 브레이크포인트 디버깅 지원
자세한 내용은 [개발 환경 빠른 시작](https://weknora.weixin.qq.com/docs/06-development/01-dev-guide)(중국어)을 참고하세요.
문서 사이트와 제품 홈페이지의 소스는 [`website-docs/`](./website-docs/README.md)에 있습니다. Node.js 24에서 `cd website-docs && npm run setup && npm run build && npm run preview`를 실행하면 둘 다 미리 볼 수 있습니다. 통합 정적 출력은 `/`에서 홈페이지를, `/docs/`에서 문서를 제공합니다. Nginx와 Docker 배포 방법은 해당 디렉터리의 README를 참고하세요.
## 기여하기
[Issue](https://github.com/Tencent/WeKnora/issues) 또는 Pull Request를 환영합니다.
- **절차:** Fork → 브랜치 생성 → 변경사항 커밋 → PR 생성
- **규칙:** `gofmt`로 코드 포맷팅, [Conventional Commits](https://www.conventionalcommits.org/) 준수 (`feat:` / `fix:` / `docs:` / `test:` / `refactor:`)
<details>
<summary><b>변경 사항 검증</b></summary>
<br/>
범위가 좁은 PR은 먼저 변경한 범위를 검증하세요.
```bash
git fetch origin main
git diff --check origin/main...HEAD
golangci-lint run --new-from-rev=origin/main ./...
go test ./path/to/changed/package -count=1
```
커밋 전에 변경한 Go 파일에 `gofmt`를 실행하세요. 프론트엔드 변경은 `frontend/`에서 관련 테스트를 실행하고, TypeScript나 Vue 컴포넌트에 영향이 있다면 `npm run type-check`도 실행하세요.
메인테이너가 사용하는 저장소 전체 검증 명령은 다음과 같습니다.
```bash
make fmt
make lint
make test
```
`make fmt`는 저장소 전체의 Go 코드를 포맷하므로 작업 트리가 깨끗할 때만 실행하고 생긴 diff를 확인하세요. 일부 전체 테스트는 로컬 인프라나 서비스 설정이 필요합니다. 관련 없는 기준선이나 환경 문제로 전체 검사가 실패하면, 실행한 명령과 오류를 PR에 적고 변경 범위의 대상 테스트가 통과함을 보여 주세요.
</details>
### 기여자
모든 기여자 여러분께 감사드립니다.
[![Contributors](https://contrib.rocks/image?repo=Tencent/WeKnora)](https://github.com/Tencent/WeKnora/graphs/contributors)
## 라이선스
이 프로젝트는 [MIT License](./LICENSE)로 배포됩니다. 적절한 저작권 고지를 유지하는 조건으로 코드를 자유롭게 사용, 수정, 배포할 수 있습니다.
+46
View File
@@ -0,0 +1,46 @@
# Security Policy
## Reporting a Vulnerability
The WeKnora team takes security vulnerabilities seriously.
We appreciate your efforts to responsibly disclose any security issues you discover.
⚠️ **Please do NOT report security vulnerabilities through public GitHub issues.**
### Preferred reporting method
We recommend reporting security vulnerabilities using GitHub’s private vulnerability reporting feature:
1. Go to the **Security** tab of this repository
2. Click **“Report a vulnerability”**
3. Fill in the details and submit the report
This allows us to discuss, investigate, and fix the issue privately.
### Alternative contact
If you are unable to use GitHub’s Security Advisory feature, you may contact the maintainers through the repository owners.
> Please avoid sharing sensitive information publicly.
### What to include in your report
To help us understand and resolve the issue quickly, please include:
- A clear description of the vulnerability
- Steps to reproduce (proof-of-concept if available)
- The affected version(s)
- Potential impact and severity
- Any suggested mitigations or fixes (if known)
### Response timeline
We aim to:
- Acknowledge receipt of your report within **48 hours**
- Provide a status update as the investigation progresses
### Coordinated disclosure
We kindly ask reporters to follow responsible disclosure practices and allow us reasonable time to address the issue before any public disclosure.
Thank you for helping keep **WeKnora** and its users secure.
+143
View File
@@ -0,0 +1,143 @@
# Third-party notices and corresponding source
This file supplements the third-party notices in `LICENSE`. The MIT license
for WeKnora's own code does not replace the licenses of third-party components.
Keep this file, `LICENSE`, and the `licenses/` directory with redistributed
backend and desktop packages. `scripts/copy-licenses.sh` adds checksum-verified
source archives at packaging time; they are not stored in this Git repository.
Container distributions include the complete bundle in `/app`;
macOS applications include them in `Contents/Resources`.
Windows installers place them next to the installed executable.
## Go MySQL Driver
- Component: `github.com/go-sql-driver/mysql`, version `v1.10.0`.
- Used in backend and desktop binaries, including the Doris MySQL protocol driver.
- License: Mozilla Public License 2.0, reproduced in
[`licenses/go-sql-driver-mysql-MPL-2.0.txt`](licenses/go-sql-driver-mysql-MPL-2.0.txt).
- Copyright: The Go-MySQL-Driver Authors; the original per-file notices and
`AUTHORS` are preserved in the accompanying source archive.
- Modifications by WeKnora: none. Dialer configuration is in separate WeKnora files.
- Corresponding source, available under MPL-2.0, is included in binary releases
as `licenses/sources/mysql-v1.10.0.zip`. Source repository users can obtain it from the
[Go module proxy](https://proxy.golang.org/github.com/go-sql-driver/mysql/@v/v1.10.0.zip)
and [upstream repository](https://github.com/go-sql-driver/mysql/tree/v1.10.0).
## go-m1cpu
- Component: `github.com/shoenig/go-m1cpu`, version `v0.1.6`.
- Used by the macOS backend/desktop dependency chain through gopsutil. It is
absent from Linux backend build dependencies. Its source is included in all
notice bundles for consistent packaging; this does not imply Linux linkage.
- License: Mozilla Public License 2.0, reproduced in
[`licenses/go-m1cpu-MPL-2.0.txt`](licenses/go-m1cpu-MPL-2.0.txt).
- Attribution: the go-m1cpu project and its contributors. The complete original
source and notices are preserved in the accompanying archive.
- Modifications by WeKnora: none.
- Corresponding source, available under MPL-2.0, is included in binary releases
as `licenses/sources/go-m1cpu-v0.1.6.zip`. Source repository users can obtain it from the
[Go module proxy](https://proxy.golang.org/github.com/shoenig/go-m1cpu/@v/v0.1.6.zip)
and [upstream repository](https://github.com/shoenig/go-m1cpu/tree/v0.1.6).
## OpenCC dictionary data
- Files: `internal/textconv/data/TSPhrases.txt` and `TSCharacters.txt`, copied
unchanged from `github.com/longbridgeapp/opencc` version `v0.3.13`.
- Attribution: the OpenCC and longbridge/opencc contributors.
- License: Apache-2.0, reproduced in
[`licenses/OpenCC-Apache-2.0.txt`](licenses/OpenCC-Apache-2.0.txt).
- Source: [versioned dictionary directory](https://github.com/longbridgeapp/opencc/tree/v0.3.13/dictionary)
and the two text files distributed with WeKnora's source.
- Only dictionary data is retained. WeKnora uses its own standard-library lookup
implementation; the upstream Go converter, `liuzl/da`, and GPL-licensed
`cedar-go` code are not included.
## Build-only component
The Windows installer template in `cmd/desktop/build/windows/installer/project.nsi`
is based on Wails v2.12.0's MIT-licensed default template, with local changes to
install this notice/source bundle. Its license and copyright are reproduced in
[`licenses/Wails-MIT.txt`](licenses/Wails-MIT.txt).
`cbindgen` 0.29.4 (MPL-2.0) generates the AnyDoc C ABI header during the Rust
build. Its code/tool executable is not copied into the runtime image or release
packages by the current build recipes. Generating the header does not copy the
tool's implementation into the product. If distributing build environments or
the tool itself, retain its license and provide its corresponding source too.
## Maintaining this bundle
When upgrading either MPL module, update the version, license, and SHA-256 pin in
`licenses/sources/modules.tsv` together. Archives are unmodified Go module proxy
ZIPs, including their original copyright notices. Verify them with
`go mod download -json` and the module's `go.sum` entry before updating.
`scripts/check-license-bundle.sh` checks the pins and notices without downloading
dependencies. `scripts/copy-licenses.sh DESTINATION` obtains the pinned archives
through Go's configured `GOPROXY` and module cache, verifies their SHA-256 hashes,
and includes them in the destination bundle. Offline packaging requires those
module archives to be present in the Go module cache beforehand. To verify a
packaged source directory, run `scripts/check-license-bundle.sh PATH/TO/licenses/sources`.
## Docreader OCR page-preprocessing components (Python)
The docreader service straightens and crops photographed pages before OCR. That
capability adds the following Python components to the docreader image. They are
redistributed inside the container image, so their notices travel here rather
than in `licenses/sources/modules.tsv`, which records Go modules only
(`scripts/check-license-bundle.sh` verifies that manifest against `go.mod`).
### RapidOCR
- Component: `rapidocr`, version `3.10.0` (Python package, docreader service).
- Used in the docreader service to detect text lines and score their
recognition, which is what the page-cropping pipeline keys off.
- License: Apache License 2.0, reproduced in
[`licenses/rapidocr-Apache-2.0.txt`](licenses/rapidocr-Apache-2.0.txt).
- Copyright: The RapidOCR Authors.
- Model artifacts: RapidOCR redistributes OCR model weights whose copyright is
held separately by Baidu and/or the applicable PaddleOCR rights holders. They
are distributed under Apache-2.0 as well, and their provenance and
redistribution terms are recorded in
[`licenses/rapidocr-MODEL_LICENSES.md`](licenses/rapidocr-MODEL_LICENSES.md).
- Modifications by WeKnora: none. The integration calls the published API and
adds no changes to the component.
- Corresponding source: [PyPI](https://pypi.org/project/rapidocr/3.10.0/) and
[upstream repository](https://github.com/RapidAI/RapidOCR).
### ONNX Runtime
- Component: `onnxruntime`, version `1.23.2` (Python package, docreader service).
- Used as the inference engine RapidOCR runs its models on.
- License: MIT License, reproduced in
[`licenses/onnxruntime-MIT.txt`](licenses/onnxruntime-MIT.txt).
- Copyright: Microsoft Corporation.
- Modifications by WeKnora: none.
- Corresponding source: [PyPI](https://pypi.org/project/onnxruntime/1.23.2/) and
[upstream repository](https://github.com/microsoft/onnxruntime).
### OpenCV (headless)
- Component: `opencv-python-headless`, version `5.0.0.93` (Python package,
docreader service).
- Used for geometric image operations: rotation with canvas expansion, line
intersection, homography and warping.
- License: Apache License 2.0, reproduced in
[`licenses/opencv-python-headless-Apache-2.0.txt`](licenses/opencv-python-headless-Apache-2.0.txt);
bundled third-party components are listed in
[`licenses/opencv-python-headless-THIRD-PARTY.txt`](licenses/opencv-python-headless-THIRD-PARTY.txt).
- Copyright: The OpenCV Foundation and contributors (see the notice file for
the per-component attributions it carries).
- Modifications by WeKnora: none.
- Corresponding source: [PyPI](https://pypi.org/project/opencv-python-headless/5.0.0.93/)
and [upstream repository](https://github.com/opencv/opencv-python).
### NumPy
- Component: `numpy`, version `2.3.4` (Python package, docreader service).
- Used for array manipulation throughout the page-preprocessing pipeline.
- License: BSD 3-Clause License, reproduced in
[`licenses/numpy-BSD-3-Clause.txt`](licenses/numpy-BSD-3-Clause.txt).
- Copyright: The NumPy Developers.
- Modifications by WeKnora: none.
- Corresponding source: [PyPI](https://pypi.org/project/numpy/2.3.4/) and
[upstream repository](https://github.com/numpy/numpy).
+1
View File
@@ -0,0 +1 @@
0.8.3
+4
View File
@@ -0,0 +1,4 @@
bin/
coverage.out
ROADMAP.md
ROADMAP.html
+622
View File
@@ -0,0 +1,622 @@
# AGENTS.md
This is the WeKnora CLI (`weknora`), a command-line client for the WeKnora RAG server. The module path is `github.com/Tencent/WeKnora/cli`.
The wire contract for AI agents *consuming* `weknora` output (JSON shape, exit codes, error format) is documented below and in [README.md](README.md). Read this file if you're integrating with the CLI binary — build / test / architecture details follow the wire contract sections.
## Wire contract for AI agents
This CLI's primary consumers include AI agents (Claude Code, Cursor, Gemini CLI,
etc.). Output format is the agent-facing API. **Every error message and every
JSON field you write becomes part of an agent's decision-making input.**
### Stdout (success path)
All `--format json` (default) commands emit a symmetric envelope. Optional
fields are `omitempty` — they only appear when populated:
```json
// list (kb list, doc list, ...) — data is an array, meta carries count
{
"ok": true,
"data": [ {"id": "kb_abc", "name": "prod"} ],
"meta": {"count": 1},
"profile": "prod"
}
// single resource (kb view, doc view, ...) — data is an object
{
"ok": true,
"data": {"id": "kb_abc", "name": "prod", "description": "..."},
"profile": "prod"
}
// mutation success with no payload (some delete / edit paths)
{"ok": true, "profile": "prod"}
```
`data` is omitted on mutation-only success (no payload). `meta` carries list
counters (`count`, `has_more`) and batch successes/failures, and is omitted
when empty. `meta.next_cursor`, `meta.total_count`, and `meta.request_id` are
reserved — not currently populated; planned for v0.8 when the SDK exposes
pagination cursors and response headers. `_notice` is reserved — open-map
infrastructure is in place for deprecation / version_skew / security notices;
the field is omitted until a producer is wired in v0.8. `profile` echoes the
resolved profile name and is omitted when no profile is configured.
### Stderr (error path)
Errors emit an error envelope on stderr (`--format json`) or prose
`code: message\nhint: ...\nretry: ...` (`--format text`):
```json
{
"ok": false,
"error": {
"type": "auth.unauthenticated",
"message": "fetch current user: HTTP error 401",
"hint": "run `weknora auth login`",
"retry_argv": ["weknora", "auth", "login"],
"retry_after_seconds": 0,
"risk": {"level": "destructive", "action": "noun.verb"},
"detail": {}
},
"_notice": {}
}
```
`type` is the typed code (see [Error code reference](#error-code-reference)
below). `hint` is prose; `retry_argv` is the suggested next argv as a JSON
string array. For non-destructive errors agents may execute it; on exit-10
(`input.confirmation_required`) it is informational only — the human must
approve the destructive write explicitly. See "Exit-10 anti-patterns" for
details.
`retry_after_seconds` mirrors HTTP `Retry-After`. `risk` tags high-risk writes.
`detail` carries structured per-error context (e.g. `unknown_subcommand`'s
`available[]` list).
### NDJSON event stream (chat / session ask)
`--format json` and `--format ndjson` both produce one JSON event per line —
no envelope wrapping. The CLI injects exactly one event (`init`) at the head;
all subsequent events pass through verbatim from the SDK:
```
{"type":"init","session_id":"...","kb_id":"...","profile":"...","agent_id":"..."}
{"type":"thinking","content":"..."}
{"type":"answer","content":"Hello"}
{"type":"tool_call","name":"...","input":{}}
{"type":"complete","done":true}
```
For prose rendering, pass `--format text`.
### `_notice` evolution policy
`_notice` is an open map. New keys are **additive non-breaking**; agents MUST
ignore unknown keys. v0.7 reserves three keys: `deprecation` / `version_skew` /
`security`. New keys follow snake_case convention. The `_notice` field is
currently always empty — producer wiring is planned for v0.8 when the SDK
exposes version metadata. The wire infrastructure is in place so adding a
producer in v0.8 will not change the envelope shape.
### CLI vs server SDK contract boundary
CLI 1.0 contract covers:
- ✅ Envelope wire shape (success + error)
- ✅ CLI-injected events (`init` only)
- ✅ NDJSON line shape (bare `{type:...,...}`)
- ✅ Passthrough discipline (CLI doesn't rename SDK events)
CLI 1.0 contract does NOT cover:
- ❌ Specific SDK event names (`answer` / `tool_call` / `complete` / ...)
- ❌ SDK event field shapes (server's own version contract)
The CLI contract and the server's wire contract are versioned independently:
agents pin against the CLI surface, while server-side event shape evolves on
its own track.
### The one rule
Every error message you write will be parsed by an AI to decide its next action.
Make errors structured, actionable, and specific.
### Environment variables
| Variable | Purpose |
|---|---|
| `WEKNORA_PROFILE` | Active profile name. Equivalent to the global `--profile <name>` flag; overridden by `--profile`. Useful in CI scripts that cannot pass global flags. |
| `WEKNORA_FORMAT` | Default `--format` value (`text \| json \| ndjson`). Overridden by explicit `--format`. Invalid values ignored silently. |
| `WEKNORA_KB_ID` | Default KB ID for commands that accept `--kb`. Overridden by `--kb`. |
| `WEKNORA_LOG_LEVEL` | SDK debug log level (`error \| warn \| info \| debug`). Overridden by `--log-level`. |
| `WEKNORA_AGENT_HELP` | Set to `1` to emit structured JSON agent-help (machine-readable) instead of human help text when `--help` is invoked. |
> **Note for agents — machine-readable version and help:** The `--version` flag
> and `--help` flag on the root command bypass `--format json` and always emit
> prose (cobra built-in paths). For machine-readable output use the `version`
> subcommand (`weknora version --format json`) or `WEKNORA_AGENT_HELP=1
> weknora <cmd> --help`. Planned fix for v0.8.
## Design decisions worth flagging
Five design decisions readers may want context on: where WeKnora picks an
opinionated default, what the trade-off is, and what mainstream practice it
is or isn't aligned with.
### 1. Channel split: success → stdout, error → stderr
| | |
|---|---|
| **WeKnora** | success envelope → stdout; error envelope → stderr |
| **Rationale** | `weknora ... --format json \| jq '.data[]'` must not mix error objects into the data stream. Channel split lets pipeline consumers suppress errors with `2>/dev/null` and still get clean JSON on stdout. |
### 2. `weknora api DELETE` triggers exit-10 confirmation
| | |
|---|---|
| **WeKnora** | DELETE triggers exit-10 (`input.confirmation_required`); user bypasses with `-y/--yes` |
| **Rationale** | DELETE is irreversible. Most raw-API CLI commands rely on restricted credentials for safety, but self-hosted deployments may not have restricted-credential infrastructure available. Defensive default because agents are common consumers. |
### 3. `retry_argv` distinct from `hint`
| | |
|---|---|
| **WeKnora** | two separate fields: `retry_argv` (suggested next argv as a string array, directly executable for non-destructive errors; informational only on exit-10) + `hint` (prose) |
| **Rationale** | Agents don't regex-extract argv from prose — known fragility. Trade-off: one extra envelope field. On exit-10, the user must approve the destructive write; agents surface `retry_argv` for human review, not auto-execution. |
### 4. NDJSON event stream has no envelope wrapping
| | |
|---|---|
| **WeKnora** | streaming commands (`chat`, `session ask`) emit bare `{type:...}` per line; no envelope |
| **Rationale** | This matches established practice across NDJSON-emitting CLIs and webhook protocols. A streaming envelope requires unwrap before dispatch — net burden with no benefit. |
### 5. No `schema_version` field in payload
| | |
|---|---|
| **Mainstream** | some APIs (Anthropic / OpenAI) embed a `version` field in payload |
| **WeKnora** | version identity via CLI binary semver + CHANGELOG `### BREAKING` + skill `tested_against` + CI parity tests |
| **Rationale** | Mainstream CLIs don't embed version in payload. Agents have complete version awareness via `weknora --version` and skill version binding. |
## Pre-1.0 breaking policy
CLI is in `v0.x` pre-release. Breaking changes ship together in concentrated
batches (v0.5 / v0.6 / v0.7) rather than scattered across patch releases.
After 1.0, any breaking change requires a 2-version deprecation period.
`CHANGELOG.md` `### BREAKING` section is authoritative.
For agents: pin the CLI version in your skill's `tested_against` field; bump
`tested_against` only after manually validating against the new CLI.
## Build, Test, and Lint
```bash
go build -o weknora . # build (from cli/)
go test -count=1 ./... # unit + contract tests
go test -run TestFoo ./internal/format/ # single test
go test ./acceptance/contract/ -args -update # refresh wire goldens
go test -tags acceptance_e2e ./acceptance/e2e/... # live-server e2e (gated by env)
go vet ./...
```
Both `go test -count=1 ./...` and `go vet ./...` must pass before committing.
## Architecture
Entry point: `cmd/main.go` → `cmd.Execute()` → `cmd.NewRootCmd(cmdutil.New())`.
Key packages:
- `cmd/<name>/` — cobra command implementations, one subdir per top-level command
- `internal/cmdutil/` — `Factory`, `FormatOptions`, typed `Error`, exit-code mapping, destructive-write confirm, KB id-or-name resolve
- `internal/format/` — bare JSON emitter (`WriteJSON` / `WriteJSONFiltered`)
- `internal/iostreams/` — global IO singleton + TTY detection + `SetForTest` swap
- `internal/secrets/` — `Store` interface; `KeyringStore` primary, `FileStore` 0600 fallback, `MemStore` for tests
- `internal/prompt/` — `TTYPrompter` (password no-echo) + `AgentPrompter` (non-TTY no-prompt sentinel)
- `internal/sse/` — `Accumulator` for chat / session ask SSE streams
- `internal/mcp/` — curated 10-tool stdio MCP server (wired by `cmd/mcp/serve.go`); see [MCP tool surface](#mcp-tool-surface) for the curation rationale and inventory
- `client/` (parent module) — generated SDK
## Command Structure
A command `weknora foo bar` lives in `cmd/foo/bar.go` with `bar_test.go`.
### Canonical Examples
- **Command + tests**: `cmd/kb/list.go` and `list_test.go`
- **Destructive write + confirm protocol**: `cmd/kb/delete.go`
- **SSE streaming command**: `cmd/chat/chat.go`
- **Factory wiring**: `internal/cmdutil/factory.go`
### The Options + Narrow Service Pattern
Every command follows this structure (see `cmd/kb/list.go`):
1. `Options` struct with flag-bound fields
2. `Service` interface declaring only the SDK methods this command calls. `*sdk.Client` satisfies it implicitly via duck typing.
3. `NewCmd<Verb>(f *cmdutil.Factory) *cobra.Command` constructor — flag registration + `cmdutil.AddFormatFlag`
4. Separate `run<Verb>(ctx, opts, fopts, svc, args...)` with the business logic — the test injection point
Key rules:
- Each command owns its own `Service` interface; do NOT share interfaces across `cmd/*` packages. Per-file dependency graph is the goal.
- Lazy-init `f.Client()` / `f.Secrets()` / `f.Prompter()` inside `RunE`, not the constructor (else `--help` forces auth).
- Required flags: `_ = cmd.MarkFlagRequired("name")` — cobra returns the error only on registration-time typo.
- New subtrees register in `cmd/root.go NewRootCmd`. Verb subtrees register their leaves in the subtree's own `NewCmd`.
### Command Examples and Help Text
Use a Go raw string with `weknora` as the example prefix. Keep one-line `Short` ≤ 70 chars; `Long` may run multi-paragraph; `Example` always includes `weknora` so copy-paste works:
```go
Example: ` weknora kb view <id>
weknora kb view kb_abc --format json
weknora kb view kb_abc --format json --jq '{id, name}'`,
```
### JSON Output
Add `--format` / `--jq` via `cmdutil.AddFormatFlag(cmd, fieldNames...)`. In `RunE`:
```go
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil { return err }
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
// ...
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, result)
}
```
`Emit` is the single source for the bare-JSON contract — it honors `--format json|ndjson` and `--jq <expr>` filtering. Never call `format.WriteJSON*` directly from a command. See `cmd/kb/list.go`.
### Destructive Writes
Commands that delete / empty / overwrite call `cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), what, id)` before mutation. In non-TTY OR JSON-output mode without `-y`, it returns `CodeInputConfirmationRequired` → exit 10. See `internal/cmdutil/confirm.go`.
## Testing
### Narrow Service Fakes
Each command's `runX(ctx, opts, fopts, svc, ...)` takes its interface, not `*sdk.Client`. Tests inject plain-struct fakes:
```go
type fakeBarSvc struct {
gotID string
resp *sdk.Bar
err error
}
func (f *fakeBarSvc) GetBar(_ context.Context, id string) (*sdk.Bar, error) {
f.gotID = id
return f.resp, f.err
}
```
No mocking library; the narrow-interface design makes fakes 5 lines each.
### IOStreams in Tests
```go
out, errBuf := iostreams.SetForTest(t) // bytes.Buffer sinks, non-TTY
ios, _ := iostreams.SetForTestWithTTY(t) // simulate terminal
```
### Confirm Prompts
Use `testutil.ConfirmPrompter{Answer: bool, Err: error}` from `internal/testutil/`. Single source for the prompt double — do NOT re-define `confirmPrompter` per package.
### Assertions
Use `testify`. Prefer `require` (not `assert`) for error checks so the test halts immediately, and `assert` for value comparisons:
```go
require.NoError(t, err)
require.ErrorAs(t, err, &typed)
assert.Equal(t, "expected", actual)
```
### Acceptance: Wire-Shape Goldens
`acceptance/contract/wire_test.go` drives the in-process cobra tree against `httptest.Server` fixtures and compares stdout to `acceptance/testdata/wire/<case>.json`. Error-path cases also assert stderr contains the typed code substring (e.g. `auth.unauthenticated`). Update goldens with `go test ./acceptance/contract/ -args -update`.
### Table-Driven Tests
Use for flag validation, error classification, parser edge cases. See `internal/cmdutil/exit_test.go` and `cmd/kb/list_test.go`.
```go
tests := []struct{ name string; ...}{
{name: "descriptive case", ...},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { /* arrange, act, assert */ })
}
```
## Code Style
- Add godoc to every exported function, type, and constant. Explain *why*, not *what* — the name already says *what*.
- Don't comment to restate the code. Delete comments that narrate the next line.
- Don't reference task numbers, commit SHAs, or version tags in inline comments — they belong in CHANGELOG or git log.
- Never paste em-dashes (—) into Go source; use ASCII `-` or rewrite. (Markdown docs may use em-dashes.)
- Don't add a helper for a single caller — inline.
## Error Handling
Typed error helpers in `internal/cmdutil/errors.go`:
- `cmdutil.NewError(code, msg)` — fresh typed error
- `cmdutil.WrapHTTP(err, format, args...)` — wrap an SDK error + classify from HTTP status (404 → `resource.not_found`, 401 → `auth.unauthenticated`, …). Use at every SDK call site.
- `cmdutil.Wrapf(code, err, format, args...)` — explicit wrap with a chosen code
- `cmdutil.NewFlagError(err)` — flag / argument problem → exit 2
- `cmdutil.SilentError` — exit 1 without printing (when output already emitted)
- `cmd.MarkFlagsMutuallyExclusive("a", "b")` — cobra-level mutex
Errors print to STDERR via `cmdutil.PrintError(w, err)` as `code: msg\nhint: ...`. STDOUT stays bare JSON or empty on failure, so `--json | jq` pipelines never have to filter error shapes.
User-facing exit-code mapping lives in [README.md "Exit codes"](README.md#exit-codes). When adding a new `ErrorCode` constant, also append to `AllCodes()` so the acceptance contract picks it up.
## Error code reference
> **Audience:** AI agents and scripted callers parsing `weknora` stderr.
> Code authors writing new error sites — see [`## Error Handling`](#error-handling) above.
When `weknora` exits non-zero, stderr carries a structured triplet:
```
<code>: <message>
hint: <actionable next step>
```
Agents parse the first colon to extract the typed code. The exit code class (see [`README.md` "Exit codes"](README.md#exit-codes)) controls retry / surface decisions; the typed code disambiguates within a class.
<!-- ERROR_REFERENCE_START -->
<!-- DO NOT EDIT manually below this marker. Add new codes to
internal/cmdutil/errors.go + register in AllCodes() + add a row here.
The CI scan in errors_doc_test.go enforces parity. -->
| Code | Exit | Retryable | Default hint |
|---|---|---|---|
| `auth.unauthenticated` | 3 | no (run `auth login`) | run `weknora auth login` |
| `auth.token_expired` | 3 | yes (after refresh) | your session expired; run `weknora auth login` to re-authenticate |
| `auth.bad_credential` | 3 | no (re-login) | run `weknora auth login` |
| `auth.forbidden` | 3 | no | active profile lacks permission for this resource |
| `auth.cross_tenant_blocked` | 3 | no | verify tenant context with `weknora auth status` |
| `auth.tenant_mismatch` | 3 | no | verify tenant context with `weknora auth status` |
| `input.invalid_argument` | 5 | no | see `weknora <command> --help` for valid usage |
| `input.missing_flag` | 5 | no | see `weknora <command> --help` for valid usage |
| `input.confirmation_required` | 10 | **NO automatic retry** | high-risk write - re-run with `-y/--yes` after the user explicitly approves |
| `input.unknown_subcommand` | 5 | no | invocation reached a command path with no matching subcommand. Detail includes `available` list; retry with `<path> --help`. |
| `resource.not_found` | 4 | no | verify the resource ID and try again |
| `resource.already_exists` | 1 | no | use a different name or fetch the existing resource |
| `resource.locked` | 1 | maybe (transient lock) | (no canonical hint; check resource state) |
| `server.error` | 7 | yes (with backoff for 5xx) | (no canonical hint) |
| `server.timeout` | 7 | yes (with backoff) | request timed out; retry, or run `weknora doctor` to check connectivity |
| `server.rate_limited` | 6 | yes (back off, then retry) | rate-limited; retry after a few seconds |
| `server.session_create_failed` | 1 | yes (with backoff) | could not create a chat session; pass `--session` to reuse an existing session |
| `server.incompatible_version` | 7 | no (upgrade required) | run `weknora doctor` to see version skew details |
| `network.error` | 7 | yes (with backoff) | check base URL reachability with `weknora doctor` |
| `operation.timeout` | 124 | yes (raise `--timeout`) | wait timed out; raise `--timeout` or check the underlying job |
| `operation.failed` | 1 | no (target reached terminal failure) | one or more targets reached a terminal failure (e.g. doc parse_status=failed) |
| `operation.cancelled` | 1 (main overrides to 130) | no | command interrupted by SIGINT / SIGTERM. The typed code maps to exit 1, but `main` raises the exit to 130 when the root context was signal-cancelled so the user-visible exit follows Unix signal convention. |
| `local.config_corrupt` | 1 | no (manual fix) | remove `~/.config/weknora/config.yaml` and re-run `weknora auth login` |
| `local.profile_not_found` | 1 | no | (no canonical hint; check `weknora profile list`) |
| `local.file_io` | 1 | no | check file permissions under `$XDG_CONFIG_HOME/weknora/` |
| `local.kb_id_required` | 1 | no | run `weknora link` to bind this directory to a knowledge base, or pass `--kb` |
| `local.kb_not_found` | 1 | no | list available with `weknora kb list` |
| `local.keychain_denied` | 1 | no (system-level) | verify keyring access; falls back to file storage |
| `local.project_link_corrupt` | 1 | no | remove `.weknora/project.yaml` and run `weknora link` again |
| `local.sse_stream_aborted` | 1 | yes (rerun chat / session ask) | the streaming answer was cut off mid-flight; retry, or pass `--format json` to buffer the full response |
| `local.unimplemented` | 1 | no | (planned in a future release) |
| `local.upload_file_not_found` | 1 | no | verify the path is correct and readable |
| `local.user_aborted` | 1 | no (user said no) | no action taken; pass `-y/--yes` to skip the confirmation prompt |
| `internal.error` | 1 | no | catch-all for an untyped error that reached the top (a bug or unmapped dependency error); a recurring one is a classification gap worth reporting |
<!-- ERROR_REFERENCE_END -->
### AI agent decision shortcuts
For common retry patterns, AI agents can hardcode:
- `network.*` → retry with exponential backoff
- `auth.token_expired` → run `weknora auth refresh`, then retry once
- `server.rate_limited` → back off (Retry-After if present) then retry
- `operation.timeout` → raise `--timeout` and retry, or surface to user
- `input.confirmation_required` → **NEVER** auto-pass `-y` without explicit user authorization
- `*.invalid_argument` / `*.missing_flag` → surface to user (don't retry)
## Exit-10 anti-patterns
Exit code 10 (`input.confirmation_required`) marks a destructive write where the
CLI refused to proceed without explicit user approval. The retry envelope includes
`retry_argv` showing the exact argv that would proceed. AI agents must NEVER
auto-retry this exit code — every exit 10 is a user-in-the-loop decision.
**Don't do these:**
1. **Auto-add `-y/--yes` and retry.** The flag exists for the user, not the agent.
Surface the exit-10 envelope to the user verbatim and wait for explicit go-ahead.
2. **Execute `retry_argv`.** The argv is *informational* --
showing what *would* execute. Running it without user input collapses two steps
the user is supposed to see.
3. **Wrap the call in a retry-with-backoff loop.** Exit 10 is not transient. It's
a "this needs human approval" signal, not a transient transport error.
4. **Treat exit 10 as a generic error and fall back to a less-destructive verb.**
The user asked for the destructive verb. If they want something else they'll
say so. Don't substitute.
5. **Auto-add `-y` because the *previous* exit-10 was approved.** Each invocation
stands on its own. The user's prior approval doesn't extend to similar calls.
6. **Skip the prompt by switching to `--format json`.** JSON mode still emits
`input.confirmation_required` (just in envelope form). It's the same gate.
## Stream recovery
The `weknora session resume <session-id> --message <msg-id>` command resumes an SSE event stream for an existing assistant message. Use cases: network-blip recovery, long-running agent invocation polling, completed-stream inspection.
### Server semantics: replay-from-0, not cursor-resume
The server **replays all stored events from the start** of the assistant message, then **tails new events**. This is NOT a cursor-from-disconnect resume. Agents reconnecting mid-stream will receive ALL previously-emitted events again.
### Agent contract
1. **Dedupe by message_id** (or maintain a per-message event hash set). Naively processing all received events causes duplicate side effects (re-running tool calls, re-rendering answers).
2. **Capture message_id from the init event** of the original `chat` or `session ask` invocation — the CLI injects `{"event":"init", "session_id":"...", "message_id":"..."}` as the first NDJSON line.
3. **Handle `local.sse_stream_aborted` typed error**: server-side buffer expired (TTL exceeded) or process restarted (memory mode). The message is no longer recoverable; restart the original query.
### Server-side buffer TTL
| Mode | TTL |
|---|---|
| `STREAM_MANAGER_TYPE=redis` | **1 hour** (server-side; not configurable from the CLI) |
| `STREAM_MANAGER_TYPE=memory` (default) | **Process lifetime** (server restart = data loss; no explicit cleanup logic) |
After TTL, `weknora session resume` returns the typed error `local.sse_stream_aborted`, which maps to exit code 1 per the Error code reference.
## Dry-run contract
The `--dry-run` flag is available on every mutation cobra command (`kb create/edit/delete`, `agent create/edit/delete`, `doc create/upload/fetch/delete`, `chunk delete`, `session delete`, `auth refresh/logout`, `link/unlink`, `profile add/remove`) and on `weknora api` (POST/PUT/PATCH/DELETE only; GET rejected with FlagError exit 2).
### Envelope shape on dry-run
Success envelope (exit 0) with `data` field omitted (omitempty) and `meta.dry_run=true`:
```json
{"ok":true,"meta":{"dry_run":true,"plan":{"action":"kb.create","args":{"name":"foo","description":"bar"}}},"profile":"prod"}
```
`api` command additionally includes `method` / `path` / `body` in plan:
```json
{"ok":true,"meta":{"dry_run":true,"plan":{"action":"api.post","method":"POST","path":"/api/v1/knowledge-bases","body":{"name":"foo"}}}}
```
### Side effects suppressed
The dry-run path is **offline** — no SDK calls, no Factory.Client() init, no ResolveKB network query, no writes (keyring / `.weknora/project.yaml` / files). Works without active profile or network access.
### Interactions
| Combination | Behavior |
|---|---|
| `--dry-run` (destructive cmd, no `-y`) | NO exit-10; emits plan + exit 0 (preview implies no execution, so the confirmation gate is irrelevant) |
| `--dry-run` + `-y` | Equivalent to single `--dry-run`; `-y` is no-op (dry-run early-exits before ConfirmDestructive) |
| `--dry-run` + `api -X GET` (or default GET) | FlagError exit 2: "--dry-run requires explicit -X POST/PUT/PATCH/DELETE; default GET is read-only with no side effect to preview" |
| `--dry-run` + `--jq <expr>` | jq applied to envelope output normally |
| `--dry-run` + `kb edit my-kb` | plan.args contains user raw input (NOT ResolveKB-resolved); agent verifies kb name correctness |
| `--dry-run` + fetch-then-update (`kb edit / agent edit`) | plan.args contains user-explicit fields ONLY; agent infers server-side fetch-then-update preserves unmentioned fields |
| `--dry-run` + body containing secrets (`--input` payload) | **plan.body echoes the full body to stdout** so the agent can verify what would be sent; avoid piping secret-bearing bodies through dry-run for inspection |
### Streaming commands explicitly excluded
`session ask` and `chat` do NOT support `--dry-run` (streaming and dry-run have a semantic mismatch). For prompt-formation preview, use:
```bash
echo '{"query":"...","kb":"..."}' | weknora api -X POST /api/v1/sessions/<id>/agent-qa --input - --dry-run
```
## Risk metadata
Agents see the same `risk.action` string (in the form `noun.verb`) on three independent surfaces:
1. **Error envelope** — `envelope.error.risk.action` on an exit-10 confirmation-required error, so the agent can decide whether to escalate to the user. 11 unique values: `kb.delete`, `kb.edit`, `agent.delete`, `agent.edit`, `doc.delete`, `doc.delete_all`, `session.delete`, `chunk.delete`, `profile.remove`, `auth.logout`, `api.delete`.
2. **Help text** — a `Risk: <action> (destructive)` line prepended to the top of `--help` output on the 9 destructive cobra commands. `weknora api` is intentionally excluded: it is a generic HTTP passthrough whose risk depends on the method, so a static Risk: line would mislead for non-DELETE methods.
3. **MCP tool annotations** — `Tool.Annotations.destructiveHint` / `readOnlyHint` / `idempotentHint` / `openWorldHint` on every tool returned by `weknora mcp serve`.
The three surfaces do not auto-sync: each is wired separately so agents that only consume one surface still get the signal, but contributors adding a new destructive command must touch all three.
## MCP Tool Surface
WeKnora's MCP server exposes a curated read-only tool surface. Many MCP servers in the wild ship write / mutation operations on by default and rely on credential-scope or sandbox restrictions for safety. WeKnora opts for curation instead: the server side doesn't yet enforce per-token scope, so an agent holding a user's token has full write access. Until server-side scope ships, the CLI keeps mutation tools out of the MCP surface as a belt-and-braces second line of defense. When server scope arrives this stance can loosen.
The curated 10 tools (`cli/internal/mcp/tools.go`):
| Tool | Purpose |
| --- | --- |
| `kb_list` | list knowledge bases |
| `kb_view` | fetch a knowledge base by id |
| `doc_list` | list documents in a kb (paginated, status-filterable) |
| `doc_view` | fetch a document by id |
| `doc_download` | download raw bytes (1 MiB cap, base64 for binary) |
| `chunk_list` | list chunks of a document for RAG retrieval debug |
| `search_chunks` | hybrid (vector + keyword) retrieval |
| `chat` | stream a RAG answer; auto-creates a session if absent |
| `agent_list` | list custom agents |
| `session_ask` | run a query through a custom agent |
Adding a tool is a deliberate API expansion — the AI-agent-callable surface is the reason this CLI ships an MCP server, not its CLI command list, so the registration list in `registerTools` is maintained by hand.
## Command surface design SOP
Before specifying any CLI command, do this in order:
1. `grep -A 50 "type Foo struct" client/foo.go` — dump SDK request/response schemas.
2. List every field with type and source line.
3. For each field, decide: hot-path flag / config-file only / hidden / never-expose.
4. Cross-check pagination signatures: an SDK `(ctx, id, page, pageSize)` shape demands `--limit` + `--all-pages` + `--page-size` on the CLI side.
5. ONLY THEN consult mainstream CLI conventions to choose flag names, positionals, mutex, and confirm semantics.
6. Decide which fields are "top use case" (flag) / "advanced" (`--config-file` or escape hatch via `weknora api`). Don't try to flag-cover every SDK field — mature CLIs that curate ship a tighter surface; CLIs that 1:1 mirror their API pay the UX cost.
Rationale: earlier drafts produced three categories of schema errors — fields that didn't exist on the underlying SDK, wrong field counts in user-facing docs, and missing pagination flags — that all stemmed from "design from convention, not from SDK." The fix is canonical: the SDK schema is the ground truth; convention decides names and shapes around that ground truth.
## CRUD command flag conventions
CRUD commands follow the **hard-required-flags** pattern: every required input is a flag or positional, and a missing one yields an immediate `input.invalid_argument` exit. The contrast is **TTY-prompts-fill**, where missing input opens an interactive prompt; that pattern is reserved for `auth login` (the one command where a human must be at the terminal).
Required-input idioms in this codebase:
- Positional required: `cobra.ExactArgs(N)` or `cobra.MinimumNArgs(1)`
- Flag required: `cmd.MarkFlagRequired("flag")`
- Custom required (e.g., `agent edit` needs at-least-one-edit-flag): RunE-level validation that returns `input.invalid_argument`
- Mutex: `cmd.MarkFlagsMutuallyExclusive("a", "b")`
Reasons hard-required-flags is the v0.5+ default:
- Admin / debug commands have no natural human-interactive prompt to lean on.
- Agent-friendly: MCP callers do not stall waiting for stdin prompts.
- Consistent with every existing non-auth WeKnora command.
- **Agent help blob**: Commands MAY call
`cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{...})` to expose a stable
JSON used_for / required_flags / examples / output / warnings shape.
Activated by `WEKNORA_AGENT_HELP=1` at `--help` time. Warnings are
always rendered in human help (stderr, not env-gated). Applied to
`chat`, `kb list`, `session ask`, and all destructive commands.
Extending to another command requires touching only that command's `NewCmd`.
## Status / check verb pair pattern
When a resource has both a cheap "is it alive?" probe and a deeper
"verify its dependencies / aggregate state" probe, expose them as two
verbs so the verb itself communicates cost:
- `status <id>` — single HTTP, returns reachable + cheap fields.
- `check <id>` — 1 + N HTTP, adds derived state that needs follow-up
calls (e.g., aggregating `failed_count` via doc-list page-walk,
probing every KB in an agent's scope).
Current pairs: `kb status` / `kb check`, `agent status` / `agent check`.
The deep verb's `Long` help text must enumerate the extra HTTP calls so
cost is predictable.
## Long-poll wait commands
`doc wait <doc-id> [<doc-id>...]` is the model for any future
`wait` command:
- Always wait-all on multi-target (no fail-fast flag); compose in shell
(`wait id1 && wait id2`) when fail-fast is needed.
- Exponential backoff with jitter (initial `--interval`, cap 15s).
- Concurrency capped (5 in flight); large fan-out via `xargs -P`.
- Exit-code priority: failed (1) > timeout (124) > completed (0). The
failed bucket is `operation.failed`, not `server.error` — a target's
own terminal failure is not a transient transport issue.
- Validate `--format` / `--jq` before polling so an invalid flag does
not cost the caller a multi-minute poll.
+575
View File
@@ -0,0 +1,575 @@
# Changelog — `weknora` CLI
All notable changes to the `weknora` CLI (the binary under `cli/` in this
repository) will be documented in this file.
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
and the CLI follows [Semantic Versioning](https://semver.org/) independently
of the WeKnora server / frontend release cadence.
CLI history before v0.3 is recorded in the project root
[CHANGELOG.md](../CHANGELOG.md) under the release that introduced the CLI.
## [Unreleased]
### Breaking
- `chat` and `session ask` now distinguish JSON from NDJSON: the default
`--format json` buffers a bounded answer-event projection into one
`{ok:true,data:{events:[...]}}` envelope; use `--format ndjson` for the
complete raw event stream.
- JSON, text, and MCP chat/session output hide reasoning, tools, lifecycle
frames, and references by default. `--reference` adds bounded `kb_id` /
`chunk_id` / `parent_chunk_id` indexes; `--verbose` adds execution events.
- `session continue-stream` renamed to `session resume`.
- `kb init` renamed to `kb config set`.
- Error envelope: `retry_command` (a shell string) replaced by `retry_argv`
(a directly-executable argv array — no shell-splitting or quoting).
### Added
- `chat` / `session ask --reference` includes indexed citations, while
`--verbose` includes reasoning, tools, and lifecycle events. MCP `chat` /
`session_ask` expose the same controls through `reference` / `verbose` inputs.
- Buffered chat/session errors include the auto-created `session_id` in
`error.detail` so interrupted sessions remain recoverable.
- `error.exit_code` embeds the process exit code in the JSON error envelope,
disambiguating the two `input.invalid_argument` cases (parse error → 2,
typed-value error → 5).
- `kb status` / `kb check` / `kb create` report `retrieval_ready` (whether an
embedding model is bound); `kb create` hints the fix when it is false.
- `model create` / `model update` / `model delete` (`update` rotates key /
base-url in place, preserving the id).
- Stateless env-credential auth: `WEKNORA_API_KEY` / `WEKNORA_TOKEN` +
`WEKNORA_HOST`, a zero-disk path for headless / agent use. `auth logout` now
keeps the profile registered (use `profile remove` to delete it entirely).
- `meta.total_count` on paginated list / search output (full result size before
client-side `--limit` truncation).
### Changed
- JSON, text, and MCP now share one event projector and filtering policy.
- Projected references contain lookup indexes only; fetch full
passages with `chunk view <chunk_id>` or `chunk view <parent_chunk_id>`.
- NDJSON remains an unmodified SDK event trace, including reasoning and full
reference payloads.
### Fixed
- Streaming SDK calls are no longer cut off by the client's default 30-second
timeout (explicit `WithTimeout` values remain honored), and SSE data lines
up to 4 MiB are accepted.
- Terminal `response_type=error, done=true` frames now end SDK stream calls
even when the server leaves the HTTP connection open.
- Agent accumulation now waits for `response_type=complete` instead of treating
per-event `done:true` markers as completion of the whole run.
- Reference `knowledge_base_id`, `parent_chunk_id`, and `sub_chunk_id` fields
now survive SDK unmarshal.
- E2E chat step parses the bounded JSON envelope; MCP stream errors include
`session_id` in `error.detail`; terminal SSE errors classify as
`server.error` instead of `network.error` or `local.sse_stream_aborted`.
## [0.9.0] - 2026-06-10
### v0.9 — auth/profile model harmonization + flag cleanup
#### Added
- `weknora session stop <session-id>` command to abort an in-flight agent run.
- `profile add --use`: switch to the newly-added profile immediately (instead of only auto-selecting the first profile added).
- `-L` shorthand on `session view` (alias for `--limit`).
- `doc download --format json` now emits a success envelope (was bare).
- `SetAgentHelp` coverage extended across create / list / search commands.
#### Changed
- `auth login` now authenticates the **active profile** (resolved from config / global `--profile`) instead of creating a profile. Re-login MERGES credential refs into the existing record — host and an existing user are preserved, never clobbered.
#### Breaking
- **`--kb` now accepts a knowledge-base name *or* id** on `doc delete --all` and `search chunks` / `search docs`; it stays required (no silent project-link fallback on these commands).
- **`agent create --kb` renamed to `--attach-kb`** to disambiguate from the global `--kb` scope flag.
- **MCP tool `agent_invoke` renamed to `session_ask`** (clean rename — external MCP clients must update cached tool schemas).
- **`auth login` drops `--host` and `--name`.** It authenticates the active profile; create it first with `weknora profile add <name> --host <h> --use`. Target a non-active profile with the global `weknora --profile <name> auth login`.
- **`auth logout` and `auth refresh` drop `--name`.** They act on the active profile; target another with the global `--profile <name>`.
#### Removed
- Dead MCP error codes `mcp.readonly_mode`, `mcp.tool_not_allowed`, and `mcp.schema_unknown_command` (never emitted by the current tool surface).
---
### v0.8 — Agent safety nets + MCP annotations
#### Added
- `--dry-run` flag on every mutation cobra command (`kb create/edit/delete`, `agent create/edit/delete`, `doc create/upload/fetch/delete`, `chunk delete`, `session delete`, `auth refresh/logout`, `link/unlink`, `profile add/remove`) and on `weknora api` (POST/PUT/PATCH/DELETE only; GET returns FlagError exit 2).
- envelope `meta.dry_run: true` + `meta.plan: {action, args | method+path+body}` open-map fields (omitempty in non-dry-run envelopes).
- `weknora session continue-stream <session-id> --message <msg-id>` command for SSE event stream replay/recovery.
- MCP `Tool.Annotations` on all 10 MCP serve tools (`destructiveHint` / `readOnlyHint` / `idempotentHint` / `openWorldHint` + `Title`) per MCP spec 2025-06-18.
- `cli/internal/cmdutil/risk.go`: `SetRisk(cmd, action)` helper + `RiskDestructive` const + `GetRisk(cmd)` reader.
- Help output "Risk: <action> (<level>)" line at top of 9 destructive commands' `--help` (via modified `SetAgentHelp` wrapper).
- `cli/AGENTS.md` sections: Stream recovery / Dry-run contract / Risk metadata.
- `cli/README.md` sections: Dry-run preview / Resuming streams.
#### Changed
- `SetAgentHelp` wrapper in `cli/internal/cmdutil/agenthelp.go` now prepends "Risk:" line in default (non-JSON) help branch when `cmd.Annotations["risk.action"]` is set. WEKNORA_AGENT_HELP=1 JSON path unchanged.
- 9 destructive commands' `SetAgentHelp` Warnings standardized: line 1 is a verbatim exit-10 / `-y` reminder; line 2 carries per-command destructive context.
- `cli/cmd/api/api.go` now has `SetAgentHelp` with runtime exit-10 note for `-X DELETE/PUT/PATCH`.
- `cli/cmd/doc/delete.go` Warnings adds a 3rd line describing `--all` blast radius.
- Bumped `github.com/modelcontextprotocol/go-sdk` v1.6.0 → v1.6.1 (patch; opt-in `MCPGODEBUG` env var).
#### Breaking
*(none — v0.8 is fully additive on top of v0.7 envelope shape, NDJSON vocab, and typed code contracts; existing consumers continue to work and the new fields are optional via `omitempty`)*
---
### v0.7 — Agent-first wire contract + command-surface cleanup
#### BREAKING (v0.6 → v0.7)
- **All JSON output now wrapped in symmetric envelope.**
- Success on stdout: `{ok:true, data?:<T>, meta?, _notice?, profile?}` (`data`
omitted on mutation-only success).
- Error on stderr (json mode): `{ok:false, error:{type, message, hint?,
retry_command?, retry_after_seconds?, risk?, detail?}, _notice?}`.
- `meta.count` / `meta.has_more` surface list totals and server-side
pagination state. `meta.next_cursor` / `meta.total_count` /
`meta.request_id` are reserved — populated when the SDK exposes them
(planned for v0.8).
- Migration: replace `jq '.[]'` with `jq '.data[]'`; `.id` → `.data.id`;
list-count consumers read `.meta.count`.
- **`--format` default flips to `json` regardless of TTY.**
- v0.6: smart default (text on TTY, json on pipe).
- v0.7: always json; TTY only affects indent (compact in pipe). Enum
`text | json | ndjson` unchanged.
- Migration: humans on a TTY pass `--format text` (or set
`WEKNORA_FORMAT=text` env) for the prior auto-text behavior.
- **`chat` / `session ask` default to NDJSON event-stream (SDK passthrough).**
- v0.6: TTY rendered a live SSE animation; `--format json` produced a buffered
object; NDJSON was opt-in.
- v0.7: `--format json` and `--format ndjson` both emit one JSON event per line
(no envelope wrapping). CLI injects exactly one `init` event at stream head;
all subsequent events pass through verbatim from the SDK (`answer` /
`tool_call` / `tool_result` / `references` / `thinking` / `reflection` /
`error` / `complete` for chat; agent vocab is a subset).
- For prose rendering: `--format text`.
- **`weknora context` command group renamed to `weknora profile`.**
- Subcommands `context list/add/remove/use` → `profile list/add/remove/use`.
- Global flag `--context` → `--profile`.
- On-disk config `~/.config/weknora/config.yaml` keys `current_context:` /
`contexts:` → `current_profile:` / `profiles:` (no backwards-compat
alias; delete the file or rename the keys by hand to migrate).
- Binding file `.weknora/project.yaml` field `context:` → `profile:`
(re-run `weknora link` to regenerate).
- `profile use` JSON fields `current_context` / `previous_context` →
`current_profile` / `previous_profile`.
- `weknora link` JSON field `context` → `profile`.
- Rationale: `context` collided with LLM "context window" / RAG "context" /
Go `context.Context`. Mainstream multi-credential CLIs (AWS, Stripe,
OpenAI, Anthropic) settle on `profile` as the term of art.
- **`weknora agent invoke` removed; use `weknora session ask --agent <id>`.**
- Server route is `POST /sessions/{session_id}/agent-qa` — session-anchored.
- `weknora agent` keeps CRUD only (list / view / create / edit / delete /
status / check).
- Migration: `weknora agent invoke ag_x "Q"` →
`weknora session ask --agent ag_x "Q"` (auto-creates session if none given).
- **`weknora doc upload` split into three commands.**
- `weknora doc upload <file>` — local file only.
- `weknora doc fetch <url>` — server-side remote fetch (was `upload --from-url`).
- `weknora doc create --text "..."` — direct text knowledge.
- URL-only flags (`--title`, `--file-type`, `--tag-id`) moved to `doc fetch`.
- Rationale: `upload --from-url` mixed semantics ("send out" vs "pull in");
the three-verb split matches the server's three endpoints and gives each
one a single unambiguous shape.
- **`weknora kb empty` removed; use `weknora doc delete --all --kb=<id>`.**
- Atomic server `ClearKnowledgeBaseContents` (no list-then-delete race).
- Same exit-10 `-y/--yes` guard as `kb delete`.
- Migration: `weknora kb empty kb_x -y` →
`weknora doc delete --all --kb=kb_x -y`.
- **`weknora api -d/--data` flag removed; use `--input <file>` or `--input -`
(stdin).**
- `weknora api` now accepts any non-empty HTTP method (whitelist removed)
so the escape hatch can hit endpoints the CLI doesn't natively model.
- Migration: `weknora api -d '{"foo":1}' /endpoint` →
`echo '{"foo":1}' | weknora api --input - /endpoint`.
- **Batch operations envelope shape — per-item `ok` pattern.**
- `weknora doc delete id1,id2,id3` and similar multi-id mutations now emit:
`{ok, data:[{id, ok, result?|error?}, ...], meta:{count, successes, failures}}`.
- Top-level `ok` = AND-aggregate of per-item `ok` (false on partial failure).
- All-fail stays in batch shape (not error envelope) — agents can iterate
detail per id.
- jq pattern: `jq '.data[] | select(.ok == false) | .id'`.
- **MCP server tool errors now return `StructuredContent`.**
- `CallToolResult{IsError: true, Content:[text-fallback],
StructuredContent:{type, message, hint?, retry_command?, risk?, detail?}}`.
- Shape mirrors stderr `envelope.error` sub-object — one parser handles both.
- **Unknown subcommand emits typed envelope.**
- `input.unknown_subcommand` with `detail.{unknown, command_path, available[]}`
+ `retry_command: "<parent> --help"`. Replaces v0.6's free-form
`"unknown command \"x\" for \"weknora\""` prose.
- **`weknora chat` requires the query as a single quoted argument.**
- v0.6: `MinimumNArgs(1)` silently joined `weknora chat hello world` into
`"hello world"`.
- v0.7: `ExactArgs(1)` rejects multi-arg with exit 2; matches
`weknora session ask`. Quote the query: `weknora chat "hello world"`.
#### Added
- **`WEKNORA_PROFILE` env var** selects the active profile for a single
invocation (equivalent to `--profile <name>` global flag). Overridden by
explicit `--profile`. Useful for CI scripts that cannot pass global flags.
- **`WEKNORA_FORMAT` env var** sets the default `--format`. Values:
`text | json | ndjson`. Overridden by explicit `--format`. Invalid values
ignored.
- **`error.retry_command`** — directly-executable retry argv, distinct from
prose `hint`. Agents read `retry_command` without regex-parsing `hint`.
- **`error.retry_after_seconds`** — `server.rate_limited` / `server.timeout`
surface server `Retry-After` header verbatim. CLI-direct (`weknora api`)
parses HTTP `Retry-After` headers; SDK-mediated paths will gain coverage
as the SDK exposes typed transport errors.
- **`error.risk.{level, action}`** — destructive writes carry
`{level:"destructive", action:"<noun.verb>"}` (e.g. `doc.delete_all`,
`kb.delete`). Reserved levels `"read"` / `"write"` not yet emitted.
- **`_notice` envelope channel reserved** — open-map infrastructure in place
for deprecation / version_skew / security notices. Producer wiring planned
for v0.8 when the SDK exposes version metadata. Additive non-breaking;
unknown keys must be ignored.
- **`meta.count` / `meta.has_more`** on list commands. `meta.next_cursor` /
`meta.total_count` / `meta.request_id` reserved — populated when the SDK
exposes them (planned for v0.8).
- **`weknora doc fetch <url>`** — new command (see split above).
- **`weknora doc create --text "..."`** — new command (see split above).
- **`weknora session ask --agent <id> "..."`** — new command (replaces
`agent invoke`).
- **`weknora doc delete --all --kb=<id>`** — new mode of `doc delete`
(replaces `kb empty`).
- **NDJSON `init` event** at stream head for `chat` / `session ask` —
carries `session_id` + optional `kb_id` / `agent_id` / `model` / `profile`.
`request_id` field is reserved (not currently populated; planned for v0.8
when the SDK exposes response headers).
- **`AgentHelp.Warnings`** — destructive commands (`kb delete`, `doc delete`,
`agent delete`, `session delete`, `chunk delete`, `profile remove`,
`kb edit`, `agent edit`, `auth logout`) render an "AI agents:" warnings
block in `--help` to set explicit expectations around `-y/--yes`.
#### Changed
- `AGENTS.md` adds `## Wire contract for AI agents`, `## Deliberate deviations
+ mainstream alignments`, `## Pre-1.0 breaking policy`, `## Exit-10
anti-patterns` sections.
- `README.md` adds `### Agent quick start` under `## Wire contract`.
- `chunk` command group help: disambiguation prose vs `search chunks` removed
in favour of plain verb descriptions.
#### Deprecated (will remove in v0.8+)
- *(none — pre-release breaking release; no deprecation alias period.)*
---
### v0.6 — agent runtime hardening: --format, doc wait, --log-level, status, multi-id delete, paginate
#### BREAKING (v0.5 → v0.6)
- **`--json` flag removed** → use **`--format json`** (with optional
`--jq '<expr>'` for projection / filtering). The v0.5 `--json=fields,...`
per-field projection drops entirely; rewrite as
`--format json --jq '.[] | {id, name}'` (jq is the canonical projection
mechanism going forward).
- **`--no-stream` flag removed** on `chat` / `agent invoke` → use
**`--format json`** to buffer the full answer before printing. The bare
text-accumulate use case (TTY but no streaming) is dropped.
- **`WEKNORA_SDK_DEBUG=1` env removed** → use **`WEKNORA_LOG_LEVEL=debug`**.
- **`kb create --name <name>` flag removed** → use positional
**`kb create <name>`** (consistent with `agent create <name>`).
#### Added
- **`--format text|json|ndjson`** flag selecting the stdout serialization.
Registered per-command (only commands that honor `--format` register it;
others reject it with `unknown flag` / exit 2). Output mode auto-resolved
to `text` on a TTY and `json` when stdout was piped (v0.7 promoted the
flag to a persistent global and made the default always `json`).
- **`--jq '<expr>'`** flag pairs with `--format json|ndjson` to filter or
project the JSON output via a jq expression.
- **`weknora doc wait <id> [<id>...]`** — block until every document reaches a
terminal `parse_status`. Always wait-all — use shell composition
(`wait id1 && wait id2`) for fail-fast.
- `--timeout DURATION` (default 10m; exit 124 on hit)
- `--interval DURATION` (default 2s; exponential backoff to 15s + jitter)
- Multi-id concurrent (max 5 parallel); exit code priority 1 > 124 > 0
- **`--log-level error|warn|info|debug`** persistent flag + `WEKNORA_LOG_LEVEL`
env. Wires into the SDK's debug logger via the additive
`client.SetDebugLevel(level string)` function.
- **`kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3>`** —
sets the new KB's `storage_provider_config.provider` at creation time
(server only accepts it on create, not update). Required on self-hosted
deployments where the server-side default doesn't pre-populate a
provider — without it, subsequent `doc upload` returns `kb not found`.
- **`weknora kb status <id>`** — fast health snapshot (1 HTTP). Returns
reachable / counts / is_processing.
- **`weknora kb check <id>`** — deep verification: status fields + `failed_count`
aggregated via doc list page-walk (1 + N HTTP). The verb split between
`status` (read state cheaply) and `check` (actively verify) communicates
cost to the caller.
- **`weknora agent status <id>`** — fast health snapshot (1 HTTP):
reachable / model_id.
- **`weknora agent check <id>`** — deep verification: status fields +
`kb_scope_all_reachable` from probing each KB in scope (1 + N HTTP). Same
status/check verb split as kb status/check.
- **`weknora doc delete <doc-id> [<doc-id>...]`** — positional multi-id.
Default keep-going on failure. Single `-y/--yes` confirms the entire
batch; non-TTY without `-y` still exits 10.
- **`weknora session delete <session-id> [<session-id>...]`** — positional
multi-id with the same keep-going semantics as `doc delete`.
- **`weknora chunk delete <chunk-id> [<chunk-id>...] --doc <doc-id>`** — positional
multi-id, all chunks share the same `--doc` parent (server route requires it).
- **`weknora api <path> --paginate`** — follows weknora's offset-based
pagination (`?page=N&page_size=M`) and merges all pages into a single
`{data, total}` JSON response.
- **MCP `chat` and `agent_invoke` tools** output schemas extended with
`thinking` / `tool_calls` / `assistant_message_id`. Tool descriptions
callout "server-side accumulated, NOT streaming" (MCP tools/call has
no standard partial-response).
- **`SetAgentHelp` pattern** — `cmdutil.SetAgentHelp(cmd, AgentHelp{...})`
exposes a stable JSON used_for / required_flags / examples / output
shape, activated by `WEKNORA_AGENT_HELP=1` at `--help` time. Applied
to `chat` and `kb list` as proof-of-pattern; extending to another
command requires touching only that command's `NewCmd`.
- **`cli/AGENTS.md`** gains an "Error code reference" section (35 typed
codes + exit codes + retryable / hint), with `<!-- ERROR_REFERENCE_START -->`
markers and CI parity test (`errors_doc_test.go`) — every new typed
code in `AllCodes()` must be documented or CI fails.
- New `operation.*` typed error namespace for CLI-level wait/poll outcomes:
- `operation.timeout` → exit 124 (distinct from `server.timeout` → exit 7;
matches the convention from GNU `timeout(1)`). Used by `doc wait` and
any future CLI-level wait/poll surfaces.
- `operation.failed` → exit 1. Emitted when one or more wait targets
reach a terminal failure (`doc wait` finds `parse_status=failed`) or
when multi-id `delete` rolls up partial failures. Distinct from
`server.error` because the failure is the target's own terminal state,
not a transient transport issue — `server.error`'s "retry with backoff"
hint would be misleading.
- `operation.cancelled` → exit 1, raised to **130** by `main.go` when the
root context was signal-cancelled. Surfaced by chat / agent invoke /
doc wait on Ctrl-C or SIGTERM. Carries a hint pointing at the signal,
not at `-y/--yes` (which would have been the misleading
`local.user_aborted` hint).
- **Signal-aware root context** — `main.go` wires `signal.NotifyContext` for
SIGINT and SIGTERM so long-running commands observe `ctx.Done()` and run
their cancellation cleanup (re-emit auto-created session id, return
`operation.cancelled`); the process exits 130 whenever the context was
signal-cancelled, matching Unix signal convention.
- **MCP tool input renames for consistency**: `doc_view` and `doc_download`
now accept `doc_id` (was `knowledge_id`) so every MCP tool that
references a document uses the same parameter name as `chunk_list` and
the CLI's `<doc-id>` positional.
- `WriteNDJSON` helper in `internal/format/` (per http://ndjson.org:
arrays split per-line, single records emit one line).
#### Changed
- `cli/README.md` "Exit codes" subsection extended with `124`
(`operation.timeout`); rows for `1` and `130` now name `operation.failed`
and `operation.cancelled` alongside the existing groupings.
- `cli/README.md` gains a "Status / check verb pair" subtable under "Health
check" and a `doc wait` paragraph with full exit-code list (0/1/124/130).
- `cli/AGENTS.md` gains design SOPs for **Status / check verb pair pattern**
and **Long-poll wait commands**, plus a note on the SetAgentHelp pattern
and current coverage (chat / kb list).
- **Multi-id delete partial-failure exit code**: `doc delete` /
`session delete` / `chunk delete` (multi-id mode) now exit `1`
(`operation.failed`) when some targets fail, rather than exit `7`
(`server.error`). The retry-with-backoff hint for server.* would have
misled callers when the actual cause is a target's terminal state.
- **`doc upload` with no path / no `--from-url`** now exits `2`
(`FlagError`, matching cobra's `MinimumNArgs` convention for commands
that need a positional), rather than `5` (`input.invalid_argument`).
- **`--log-level` invalid value** exits `2` (`FlagError`) for consistency
with `--format` invalid-value behaviour. Env values still fall through
silently (env is best-effort).
- **Multi-id delete stdout contract**: pre-flight failures (e.g. missing
`-y` confirmation) no longer emit the empty `{ok, failed}` envelope to
stdout — stdout stays empty per the wire contract in README.md, the
typed error goes to stderr only.
- **Positional id help strings now namespaced** for clarity in both human
help and agent `--help` parsing: `<id>` → `<kb-id>` / `<doc-id>` /
`<session-id>` on kb / doc / session subtrees. `agent` and `chunk`
subtrees were already namespaced. Pure help-text change — argument
parsing is unchanged.
- `chat "<text>"` Use string now shows quotes — matches `agent invoke` and
`search chunks` quoting hint for queries that contain spaces.
#### SDK additions (strictly additive)
- `client.SetDebugLevel(level string)` — programmatic control over the SDK's
internal slog debug logger.
### v0.5 — agent CRUD, chunk subtree, MCP chunk_list, audit-driven cleanup
#### Added
- `weknora agent create <name> --model <id>` / `agent edit <id>` /
`agent delete <id>` — hybrid surface (hot-path flags for the common
fields + `--config-file` YAML/JSON for the long tail +
`--generate-skeleton` template emit). `--from <agent-id>` copies
from an existing agent.
- `weknora chunk list --doc <doc-id>` / `chunk view <chunk-id>` /
`chunk delete <chunk-id> --doc <doc-id>` — new subtree for RAG retrieval
debug. Paginated with v0.4 `--limit` / `--page-size` / `--all-pages` canon.
- `weknora mcp serve` adds `chunk_list` as the 10th curated tool.
- `weknora agent view <id>` human output now renders all 34 AgentConfig
fields (previously 7), grouped into 10 presentation sections.
- `--all-pages` / `--page-size` on `search docs` and `search sessions`
(catching up with `session list` / `doc list` canon from v0.3+v0.4).
- `weknora doc list` gains `--keyword` / `--file-type` / `--source` /
`--tag-id` / `--start-time` / `--end-time` (RFC3339) — matches the
SDK's `KnowledgeListFilter` surface. Time flags reject malformed
input with `input.invalid_argument`.
- MCP `doc_list` tool gains the same 6 filter fields (`keyword`,
`file_type`, `source`, `tag_id`, `start_time`, `end_time`) so agents
have parity with the CLI.
- `weknora session view --full` (with `--limit`, default 50, bounds
1..1000) loads chat history via `LoadMessages` and renders messages
inline after session metadata. JSON mode projects messages into a
`messages` array. `--limit` without `--full` errors with
`input.invalid_argument`.
- `weknora kb view` human render now includes `TYPE`, `PINNED` (badge,
only when set), `TEMPORARY` (badge), `PROCESSING` (with doc count,
only when active), `SUMMARY MODEL`, and `CREATED`. Nested config
structs stay JSON-only.
- `weknora doc view` human render expands to include `TITLE` (when
distinct from filename), `DESC`, `SOURCE`, `CHANNEL`, `TAG`,
`STORAGE` (human-readable bytes), `SUMMARY`, `ENABLED`, and `HASH`
(12-char prefix). All omit-empty.
- `weknora doc upload` gains `--enable-multimodel` (tri-state:
unset/true/false), repeatable `--metadata key=value`, and
`--channel` flags. `--enable-multimodel` and `--channel` apply to
file / `--recursive` / `--from-url`; `--metadata` is file /
`--recursive` only (the URL-ingest request carries no metadata
field server-side, so passing it with `--from-url` is rejected
up-front as `input.invalid_argument`). URL mode additionally
accepts `--title`, `--file-type`, and `--tag-id`. Threads through
to the SDK's `CreateKnowledgeFromFile` / `CreateKnowledgeFromURL`
signatures (previously hardcoded to nil/"api" and dropped URL
extras).
#### Fixed
- MCP `search_chunks` tool: `limit` arg now correctly threads into
`SearchParams.MatchCount`. Previously the server's default cap won,
silently capping below the requested limit.
- `search sessions` human time format: now renders a relative
duration ("2 hours ago") matching `session list`, instead of raw
RFC3339.
- `doc upload` (file path): re-uploading a file already ingested into
the KB now surfaces as `resource.already_exists` (exit 1) instead of
the misleading `network.error` ("check base URL reachability"). The
SDK returns its `ErrDuplicateFile` sentinel with no `HTTP error <n>:`
prefix because the duplicate is detected via file-hash short-circuit,
not by HTTP status; the previous fall-through to `WrapHTTP` therefore
misclassified it. The `--from-url` branch already handled the
symmetric `ErrDuplicateURL` correctly.
#### Breaking changes
- `weknora search docs` now applies the keyword filter server-side via
`ListKnowledgeWithFilter` (was: page through every doc and
substring-match client-side). Smaller wire payload on large KBs.
**The match is now case-sensitive** (server uses `LIKE %keyword%`),
whereas the previous client-side path lowered both sides. Callers
that relied on case-insensitive matching (e.g. `search docs Q3`
finding `q3 retro`) must lower-case the query themselves, or fall
back to `weknora api` with a custom filter.
#### Changed
- `cli/AGENTS.md` MCP curation rationale rewritten: curated read-only
is a deliberate product call gated on the absence of server-side
per-token scope. When server-side scope ships, mutation tools can
land in the MCP surface.
- `cli/AGENTS.md` adds "Command surface design SOP" and "CRUD command
flag canon" sections for future contributors. The design-SOP
section includes a step reminding contributors to decide
flag-vs-escape-hatch per field rather than trying to flag-mirror
every SDK capability.
- `cli/README.md` now documents the `weknora api` raw HTTP passthrough
as the canonical escape hatch for deep KB config, per-request `chat`
/ `agent invoke` overrides, and operations without a CLI verb.
### v0.4 — output contract hardening and mainstream alignment
#### Breaking changes
- Dropped the JSON envelope. `stdout` now emits bare typed data
(`{...}` or `[...]`); errors are written to `stderr` as `code: msg`
with an actionable `hint:` line. Pipelines using `--json | jq` no
longer have to filter out an envelope wrapper.
- Dropped `--dry-run`. Destructive writes still require `-y/--yes`;
non-TTY callers that omit `-y` exit with code 10 and
`input.confirmation_required` so an agent must surface the prompt
to a human before retrying.
- Dropped the per-command AI footer that rendered when AI-coding-agent
env detection fired. The same machine-readable guidance now lives in
the standard `--help` (visible to all callers) and in `mcp serve`'s
tool descriptions.
#### Added
- `weknora mcp serve` — curated read-only stdio MCP server exposing 9
tools (`kb_list`, `kb_view`, `doc_list`, `doc_view`, `doc_download`,
`search_chunks`, `chat`, `agent_list`, `agent_invoke`). Destructive
verbs are intentionally excluded.
- `weknora agent list` / `agent view` / `agent invoke` — manage and
call WeKnora's server-side Custom Agent resources.
- `weknora auth token` — print the active credential to `stdout` for
scripting (raw secret by default; `--json` emits `{token, mode, context}`).
- `weknora doc upload --from-url` — ingest a remote URL.
- `--json=fields,...` field projection and `--jq <expr>` filtering on
every command that emits JSON.
- `--limit` and `--all-pages` on list / search commands for bounded
output and explicit pagination control.
- Per-resource filter flags: `kb list --pinned`, `doc list --status`,
`session list --since`.
#### Changed
- Go toolchain bumped from 1.24 to 1.26.
- `auth login --with-token` validates the supplied key against
`/auth/me` before persisting, and prints an advisory if the keyring
is unavailable and credentials fall back to a 0600 file under
`$XDG_CONFIG_HOME/weknora/secrets/`.
- AGENTS.md rewritten as a developer guide (~170 lines, 6 H2 sections).
### v0.3 — extended management surface and a `session` subtree
#### Added
- `context add` / `context list` / `context remove` — first-class CRUD over
connection targets (previously implicit via `auth login --name`).
Removing the *current* context requires explicit `-y` (exit-10 protocol)
because subsequent commands have no default target.
- `auth refresh` — exchanges the stored refresh token for a new access +
refresh pair (OAuth refresh-token grant). Transparent 401 → refresh →
retry is also wired into the SDK transport with singleflight de-dup, so
most callers never need to invoke this explicitly.
- `kb edit` — partial-update edit with only-sent-fields semantics
(`*string` options so unset fields stay unset in the PUT body).
- `kb pin` / `kb unpin` — idempotent pin/unpin toggle; no-op when already
in the target state (emits `_meta.warnings`, no server call).
- `kb empty` — bulk-delete documents while preserving the KB record and
its config. High-risk-write; exit-10 confirmation in non-TTY / `--json`
paths.
- `doc view <id>` — show one document's metadata (title, file name,
type, size, parse status, embedding model, processed-at, error
message). Counterpart to `kb view` and `session view`.
- `doc download` — stream a knowledge file to disk (`-O FILE` /
`-O -` for stdout) with `--clobber` controlling overwrite. Rejects
server-supplied path-like filenames; partial writes on error are
cleaned up.
- `doc upload --recursive --glob '*.md'` — walk a directory and upload
every match. Per-file `OK` / `FAIL` progress lines on the human path;
aggregated `uploaded[]` / `failed[]` envelope on `--json`. Exit code
typed to the first failure's class on partial failure.
- `search chunks` / `search kb` / `search docs` / `search sessions` —
verb-noun subtree (gh `search code/repos/issues/…` shape). `search
chunks` is hybrid (vector + keyword) retrieval; the other three are
client-side substring filters useful for discovering identifiers.
All four take `--limit N` / `-L N` (1..1000) to cap returned rows.
- `session list` / `session view` / `session delete` — chat session
management.
- `api --input FILE` / `api --input -` — body source for raw HTTP
passthrough (file or stdin); mutually exclusive with `--data`.
- `unlink` — remove the cwd's `.weknora/project.yaml` so subsequent
commands stop auto-resolving `--kb` from it. Walks up from cwd so a
user in a subdirectory can unlink without cd-ing to the project root.
- Completion smoke test guards against cobra bumps silently breaking
bash / zsh / fish / powershell completion.
#### SDK additions (Go client at `client/`, strictly additive)
- `OpenKnowledgeFile(ctx, id) (filename, body io.ReadCloser, err)` — new
primitive returning the body as a stream plus the server-suggested
Content-Disposition filename. `DownloadKnowledgeFile` is now a thin
wrapper (signature unchanged, gained partial-file-on-error cleanup).
- `WithTransport(http.RoundTripper) ClientOption` — lets the CLI install
the 401-retry transport.
- `PathAuthLogin` / `PathAuthRefresh` constants — so HTTP middleware
doesn't re-hardcode the literals.
- `IsPinned bool` field on `KnowledgeBase` (server already returned it;
SDK just hadn't modeled it).
+47
View File
@@ -0,0 +1,47 @@
# Makefile for the WeKnora CLI (cli/ Go module).
#
# Usage:
# make build compile to ./bin/weknora with version metadata
# make test go test ./...
# make test-coverage same with coverage report
# make lint go vet (golangci-lint planned)
# make tidy go mod tidy
# make clean remove ./bin
BINARY := weknora
BUILD_DIR := bin
PKG := github.com/Tencent/WeKnora/cli
VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo dev)
COMMIT := $(shell git rev-parse --short HEAD 2>/dev/null || echo none)
DATE := $(shell date -u +%Y-%m-%dT%H:%M:%SZ)
LDFLAGS := -s -w \
-X $(PKG)/internal/build.Version=$(VERSION) \
-X $(PKG)/internal/build.Commit=$(COMMIT) \
-X $(PKG)/internal/build.Date=$(DATE)
.PHONY: build test test-coverage lint tidy clean help
build:
@mkdir -p $(BUILD_DIR)
go build -ldflags="$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY) .
test:
go test ./...
test-coverage:
go test -coverprofile=coverage.out ./...
go tool cover -func=coverage.out
lint:
go vet ./...
tidy:
go mod tidy
clean:
rm -rf $(BUILD_DIR) coverage.out
help:
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}'
+466
View File
@@ -0,0 +1,466 @@
# weknora — WeKnora CLI
A command-line interface for the WeKnora RAG knowledge-base server. Lets you
authenticate, manage knowledge bases and documents, run hybrid search, and
ask streaming RAG questions from your terminal or from an AI agent.
```bash
$ weknora --help
Command-line client for the WeKnora RAG server. Manage knowledge bases
and documents, run hybrid search, chat with grounded answers, or expose
a curated read-only MCP tool surface for AI agents.
Available Commands:
agent Manage custom agents (CRUD + status/check)
api Make a raw API request to the WeKnora server
auth Manage authentication credentials and profiles
chat Ask a streaming RAG question against a knowledge base
chunk Manage document chunks (RAG retrieval debug)
completion Generate the autocompletion script for the specified shell
config Inspect the CLI's resolved configuration
doc Manage documents in a knowledge base
doctor Run 4 self-checks: base URL, auth, server version, credential storage
exit-codes Exit code matrix and the agent action for each
help Help about any command
kb Manage knowledge bases
link Bind the current directory to a knowledge base
mcp Run weknora as a Model Context Protocol server
message Inspect and manage messages inside chat sessions
model Manage models (list / view / create / update / delete)
profile Manage CLI profiles (named connection targets)
schema Machine-readable contract for a command (or the whole surface)
search Search across chunks, knowledge bases, documents, or sessions
session Manage chat sessions
skills List and install the bundled Agent Skills
unlink Remove the directory's knowledge-base binding
version Show CLI build metadata
```
The wire contract for AI agents is documented [below](#wire-contract).
For contributing to the CLI source, see [AGENTS.md](AGENTS.md).
---
## Install
### From source
Requires Go 1.26+.
```bash
git clone https://github.com/Tencent/WeKnora.git
cd WeKnora/cli
go build -o weknora .
sudo mv weknora /usr/local/bin/ # or anywhere on $PATH
```
### Pre-built binaries
Building from source is the supported install method today. Pre-built binaries,
`go install`, and a Homebrew formula are planned to accompany a tagged release;
until then, use the from-source build above.
---
## 5-minute quickstart
```bash
# 1. Register your WeKnora server as a profile and make it active
weknora profile add prod --host https://kb.example.com --use
# 2. Authenticate the active profile (interactive password prompt)
weknora auth login
# 2b. Or pipe an API key from stdin (for CI / AI agents)
echo "sk-..." | weknora auth login --with-token
# 3. List knowledge bases
weknora kb list
# 4. Bind this directory to a knowledge base — subsequent commands auto-resolve --kb
weknora link --kb my-knowledge-base
# 5. Upload a document, then block until parsing finishes
weknora doc upload notes.md
weknora doc wait doc_abc # exit 0 completed, 1 failed, 124 --timeout, 130 ^C
weknora doc reparse doc_abc # re-trigger parsing if it failed, then wait again
# 6. Search
weknora search chunks "what is reciprocal rank fusion?"
# 7. Ask the LLM (streams to terminal)
weknora chat "summarise the design doc"
# 8. Manage custom agents and run them (see `weknora agent --help` / `weknora session --help`)
weknora model list # discover a model id for --model
weknora agent list
weknora session ask --agent ag_abc "what's our q4 retention plan?"
# 9. Inspect a document's chunks for RAG retrieval debug
weknora chunk list --doc doc_xyz
# 10. Inspect messages in a session / search across sessions
weknora message list --session sess_abc
weknora message search "retry policy" # cross-session Q&A retrieval
# 11. Resolve a pending tool approval (agent run blocked on approval event)
weknora session tool-approval resolve pend_xxx -y # approve (after user go-ahead)
weknora session resume sess_abc --message msg_xyz # resume the blocked stream
# 12. Health & verification verbs
weknora kb status kb_abc # fast snapshot: reachable / counts / processing flag (1 HTTP)
weknora kb check kb_abc # deep verify: also aggregates failed_count via doc list (1+N HTTP)
weknora agent status ag_abc # fast: reachable / model_id
weknora agent check ag_abc # deep: probes every KB in the agent's scope
```
---
### Agent quick start
For AI agents (any MCP-capable host) integrating WeKnora:
1. Install: build from source (see [Install](#install))
2. Authenticate. In a sandbox / CI, the **stateless** path needs no `auth login`
and writes nothing to disk — just set two env vars:
```bash
export WEKNORA_API_KEY="sk-…" # or WEKNORA_TOKEN for a bearer JWT
export WEKNORA_HOST="https://kb.example.com"
weknora kb list # already authenticated
```
Or, for a persisted local profile:
```bash
weknora profile add prod --host <server-url> --use
weknora auth login
```
3. Register MCP in the host's MCP config:
```json
{"mcpServers": {"weknora": {"command": "weknora", "args": ["mcp", "serve"]}}}
```
4. Read the [wire contract](AGENTS.md#wire-contract-for-ai-agents) before
parsing `--format json` output.
5. Read the [exit-10 anti-patterns](AGENTS.md#exit-10-anti-patterns) before
any destructive call.
**Bundled Agent Skills.** This CLI ships [Agent Skills](https://agentskills.io/specification)
under [`skills/`](skills/) that teach an agent to drive WeKnora without trial and error:
- [`weknora-shared`](skills/weknora-shared/SKILL.md) — **read first**: auth/profile
sequence, `--kb` resolution, the JSON-envelope + exit-code contract, the exit-10
protocol, `--dry-run`, and CLI-vs-MCP selection.
- [`weknora-rag-search`](skills/weknora-rag-search/SKILL.md) — when to use `chat`
vs `session ask` vs `search chunks`, plus retrieval gotchas.
Install them with the CLI (the skills are embedded in the binary, no checkout
needed):
```bash
weknora skills install # writes to ~/.claude/skills
weknora skills install --dir <agent-skills-dir> --force # other agents / overwrite
weknora skills list --format json # what would be installed
```
Existing files are left untouched without `--force`; `--dry-run` previews the
file list. Each skill's frontmatter records the CLI version it was
`tested_against`; a CI parity test (`internal/skillparity`) fails if a skill
ever references a command, flag, or MCP tool the CLI no longer has.
---
## Multi-profile
`profile.*` manages profile *records* (positional `<name>`); `auth.*` operates
on the *active* profile (override per-invocation with the global `--profile`
flag). Create a profile first, then authenticate it:
```bash
weknora profile add prod --host https://prod.example.com --use # add + switch
weknora auth login # authenticate active (prod)
weknora profile add staging --host https://staging.example.com # add (stays inactive)
echo "sk-..." | weknora --profile staging auth login --with-token # authenticate staging
weknora auth list
weknora profile use prod # switch back
```
Credentials are persisted to your OS keyring (Keychain on macOS, libsecret on
Linux, Wincred on Windows) when available, otherwise to a 0600-mode file
under `$XDG_CONFIG_HOME/weknora/secrets/`. The active profile lives in
`~/.config/weknora/config.yaml`.
To remove a profile's stored credentials:
```bash
weknora auth logout # active profile
weknora --profile staging auth logout # specific profile
weknora auth logout --all
```
---
## Wire contract
Designed to be AI-agent-first. Stable across minor releases; breaking
changes announced in the changelog and the corresponding
`weknora --version` bump. This section is the human overview; the complete,
authoritative contract (envelope field stability, error taxonomy, streaming,
confirmation and dry-run protocols) lives in **[AGENTS.md](AGENTS.md)**.
### Streams
- **stdout** is the data channel: bare JSON with `--format json`, or
human-formatted output. Never carries error text.
- **stderr** is logs, progress, warnings, and errors. A non-empty
stderr does **not** mean failure — read the exit code.
### JSON output
Every command supports `--format json`, wrapping the resource in the
symmetric envelope `{ok, data, meta?}` — `data` is an array for `list` /
`search`, a single object for `view` and write outcomes. `--jq` runs
against the whole envelope, so reach into list items with `.data[]`:
```bash
weknora kb list --format json # {"ok":true,"data":[{"id":"kb_x",…}],"meta":{"count":1,…}}
weknora kb view kb_x --format json # {"ok":true,"data":{"id":"kb_x","name":"Eng",…}}
weknora kb list --format json --jq '.data[] | {id, name}' # project listed fields out of each item
weknora kb list --format json --jq '.data[].id' # ids only
weknora kb list --format json --jq '.meta.count' # number returned
```
`--format ndjson` is also accepted for streaming list commands; each
element is emitted as its own JSON line. `--format json` is the default
regardless of TTY — running `weknora kb list | jq` works without an
explicit flag. Use `--format text` for human-readable output.
### Errors
On failure, stdout stays empty and the typed error goes to stderr in
this format:
```
<code.namespace>: <message>[: <wrapped cause>]
hint: <actionable next-step>
```
Example:
```
auth.unauthenticated: fetch current user: HTTP error 401: ...
hint: run `weknora auth login`
```
Under `--format json` the same failure is the typed error envelope on stderr
(`{ok:false, error:{type, exit_code, hint?, retry_argv?, …}}`) — see
[AGENTS.md §1.4](AGENTS.md) for the field-by-field contract and the full code
taxonomy.
### Exit codes
| Code | Meaning | Agent action |
|---|---|---|
| `0` | success | continue |
| `1` | typed `local.*` / `operation.failed` / unclassified | read stderr, decide retry/abort |
| `2` | flag / argument validation error | re-check `weknora <cmd> --help` |
| `3` | `auth.*` (token missing / expired / forbidden) | re-auth, then retry |
| `4` | `resource.not_found` | verify the resource id |
| `5` | `input.*` (other than `confirmation_required`) | adjust args, retry |
| `6` | `server.rate_limited` | back off, retry |
| `7` | `server.*` / `network.*` | transient — retry with backoff |
| `10` | **`input.confirmation_required`** (high-risk write) | ask the human, retry with `-y` only after explicit approval |
| `124` | `operation.timeout` (e.g. `doc wait --timeout` reached) | raise `--timeout` or check the underlying job |
| `130` | cancelled by signal — typed `operation.cancelled` errors exit 1; `main.go` promotes the process exit to 130 when the root context was signal-cancelled (SIGINT / SIGTERM) | stop, do not retry |
Run `weknora exit-codes` for the machine-readable matrix (JSON); `weknora help exit-codes` for the human-readable table.
**Exit 10** is the wire-level signal for "destructive write needs
explicit confirmation". Pass `-y/--yes` on `kb delete` /
`doc delete` (including `--all --kb=<id>`) / `session delete` /
`profile remove` (on the current profile) / `agent delete` /
`chunk delete` when running headless.
**Never auto-add `-y` without the user's explicit go-ahead** — exit 10
is the guard against unintended writes.
### Other AI-agent ergonomics
- For chat / session ask in AI-agent contexts, pass `--format json` for a
bounded answer-event envelope. Add `--reference` for indexed citations,
`--verbose` for reasoning/tools/lifecycle events, or `--format ndjson` for
the unmodified raw stream.
- `--format json` composes with the global `--profile <name>` for
single-shot profile overrides without disk writes.
- `weknora mcp serve` exposes a curated read-only tool surface over
stdio MCP for any MCP-compatible client.
- `weknora schema` enumerates every command with its `used_for`, and
`weknora schema <cmd path>` (e.g. `weknora schema doc update`) prints that
command's full contract — `used_for`, `required_flags`, `examples`,
`output`, `warnings`, `risk`, and local `flags` — as the standard envelope,
so an agent can discover the surface without scraping `--help` prose.
---
## Advanced operations not exposed as flags
WeKnora CLI exposes top use cases as polished commands; deep
configuration goes through the raw HTTP passthrough. CLI flag coverage
targets common workflows, not 1:1 API parity. Examples of deep
operations that intentionally go through `weknora api`:
- **Tuning a KB's nested config** — chunking strategy, summary model,
multimodal extraction defaults, FAQ thresholds, VLM model. Use
`weknora api PUT /api/v1/knowledge-bases/<id> --input -` with a JSON
body matching the server's `UpdateKnowledgeBaseRequest`. (Note: the
storage provider is set once at create time via
`kb create --storage-provider <name>` and is not updatable.)
- **Per-request `chat` parameters** — multi-KB scope, summary model
override, image attachments, web search toggle. Use `weknora api POST
/api/v1/knowledge-chat/<session-id> --input -`.
- **Per-request `session ask --agent` overrides** — same shape via
`weknora api POST /api/v1/agent-chat/<session-id> --input -`.
- **Operations without a CLI verb** — register / change-password /
OIDC flows, organization / sharing endpoints, tenant management.
`weknora api --help` documents the raw passthrough. Run
`weknora doctor` first to verify auth and base URL.
---
## Dry-run preview
Add `--dry-run` to any mutation command to preview the would-be action without executing it. Useful for verifying flag/arg parsing before committing to a destructive operation, or for agent-side action planning.
```bash
# Preview a kb create without actually creating
weknora kb create --name "test-kb" --description "for review" --dry-run
# Output (single line; pretty-printed here for readability):
# {
# "ok": true,
# "meta": {
# "dry_run": true,
# "plan": {
# "action": "kb.create",
# "args": {"name": "test-kb", "description": "for review"}
# }
# }
# }
# Exit code: 0
```
dry-run is **offline**: no network calls, no file IO, no credential touches. Works without an active profile.
For destructive commands, dry-run does NOT trigger the exit-10 confirmation flow:
```bash
weknora kb delete kb_xxxx --dry-run # exit 0, no prompt
weknora kb delete kb_xxxx # exit 10, prompts for -y
```
For the `api` command, dry-run requires explicit write method (POST/PUT/PATCH/DELETE); GET returns FlagError:
```bash
echo '{"name":"foo"}' | weknora api -X POST /api/v1/knowledge-bases --input - --dry-run # OK
weknora api /api/v1/knowledge-bases --dry-run # exit 2: requires explicit -X
```
---
## Resuming streams
The `weknora session resume` command resumes an SSE event stream for an existing assistant message. Useful for network-blip recovery or polling long-running agent invocations:
```bash
# Original streaming call captures session_id + message_id from init event:
weknora session ask "..." --agent ag_xxxx --format ndjson | tee /tmp/stream.ndjson
# {"type":"init","session_id":"sess_abc","message_id":"msg_xyz"}
# ... events flow ...
# [network blip]
# Resume the same stream:
weknora session resume sess_abc --message msg_xyz
# Server REPLAYS all stored events from the start, then tails new ones.
# Agent must dedupe (by message_id or event hash) to avoid double-processing.
```
### Tool-approval unlock chain
An agent run may pause the stream on a tool-approval event until a human approves or rejects the pending tool call. The unlock sequence:
```bash
# 1. Stream pauses with a tool-approval event carrying a pending_id.
# 2. Surface the pending tool call to the user; get explicit go-ahead.
weknora session tool-approval resolve pend_xxx -y # approve
# weknora session tool-approval resolve pend_xxx --reject --reason "..." -y # reject
# 3. Resume the stream — server replays + tails from where the run was blocked.
weknora session resume sess_abc --message msg_xyz
```
Pass `--modified-args '{"key":"value"}'` to replace tool arguments on approve (must be a non-empty JSON object). Never auto-pass `-y` — the approval is the exit-10 human-in-the-loop gate.
Server-side buffer TTL: 1 hour for redis mode; process lifetime for memory mode (default). After TTL, expect `local.sse_stream_aborted` typed error.
See `cli/AGENTS.md` "Stream recovery" section for the full agent contract.
---
## Health check
Run `weknora doctor` for a 4-status diagnostic (OK / warn / fail /
skip) covering base URL reachability, authentication, server-CLI
version skew, and credential storage backend. Add `--format json` for
machine-readable output, `--offline` to skip network checks.
For per-resource verification, the `status` / `check` verb pair gives
a fast vs deep choice:
| Verb | Cost | Use |
|---|---|---|
| `weknora kb status <kb-id>` | 1 HTTP | live counts / processing flag |
| `weknora kb check <kb-id>` | 1+N HTTP | adds `failed_count` via doc-list page-walk |
| `weknora agent status <agent-id>` | 1 HTTP | reachable / model_id |
| `weknora agent check <agent-id>` | 1+N HTTP | also probes every KB in the agent's scope |
`weknora doc wait <doc-id> [<doc-id>...]` blocks until each document
reaches a terminal `parse_status` (completed or failed). Exit codes:
0 (all completed), 1 (any failed), 124 (`--timeout` reached), 130
(Ctrl-C / SIGTERM). Multi-target is polled concurrently (max 5 in
flight; pipe through `xargs -P` for more).
---
## Development
```bash
# Run unit + contract tests
go test ./...
# Run the real-server e2e suite (requires WEKNORA_E2E_HOST + token env vars)
go test -tags acceptance_e2e ./acceptance/e2e/...
# Static analysis
go vet ./...
```
CI (`.github/workflows/cli.yml`) runs build + unit + contract tests on Linux /
macOS / Windows × Go 1.26, path-filtered to changes under `cli/`.
---
## Contributing / Reporting issues
- **Bugs and feature requests**: file an issue at
[github.com/Tencent/WeKnora/issues](https://github.com/Tencent/WeKnora/issues).
- **Security disclosures**: see the repository-level
[SECURITY.md](../SECURITY.md). Do not file public issues for
security findings.
- **Pull requests**: the developer guide for editing the CLI lives in
[AGENTS.md](AGENTS.md) (build / test / command-surface design SOP /
CRUD flag conventions). Run `go test ./... -race -count=1` and `go vet ./...`
before submitting.
---
## License
MIT — see the repository [LICENSE](../LICENSE).
+214
View File
@@ -0,0 +1,214 @@
// cli/acceptance/contract/errorcodes_test.go
package contract_test
import (
"go/ast"
"go/parser"
"go/token"
"os"
"path/filepath"
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
)
// TestAllReferencedCodesAreRegistered scans cli/cmd/ for every literal use of
// cmdutil.NewError(codeXxx, ...) and cmdutil.Wrapf(codeXxx, ...) and verifies
// that codeXxx is registered in cmdutil.AllCodes().
//
// ClassifyHTTPError is dynamic - callers don't pass a literal CodeXxx
// ident. Most SDK call sites go through cmdutil.WrapHTTP(err, ...) which
// the scanner skips entirely (it only inspects NewError / Wrapf selector
// names). A few sites still call ClassifyHTTPError directly to inspect
// or remap the code; those are call-expression args the scanner also
// skips. Either way, the codes those paths can yield are bridged via
// cmdutil.ClassifyHTTPErrorOutputs(), which enumerates every code the
// switch can return - added to the registered set so the AST scanner
// doesn't false-positive on them.
//
// Limitations:
// - Only literal cmdutil.CodeXxx idents are detected; codes assigned to
// a local variable then passed are NOT scanned (rare pattern).
// - cmdutil.WrapHTTP(...) and cmdutil.ClassifyHTTPError(...) call
// expressions are skipped - the ClassifyHTTPErrorOutputs bridge
// covers their dynamic codes.
func TestAllReferencedCodesAreRegistered(t *testing.T) {
registered := make(map[cmdutil.ErrorCode]struct{})
for _, c := range cmdutil.AllCodes() {
registered[c] = struct{}{}
}
// Bridge: ClassifyHTTPError returns these dynamically; treat them as
// "registered" for the purposes of the AST scan since callers pass the
// function call (not a literal ident) as arg0.
for _, c := range cmdutil.ClassifyHTTPErrorOutputs() {
registered[c] = struct{}{}
}
referenced := scanCmdDir(t, "../../cmd")
for code, locs := range referenced {
if _, ok := registered[code]; !ok {
for _, loc := range locs {
t.Errorf("%s: error code %q referenced but not registered in cmdutil.AllCodes()", loc, code)
}
}
}
}
// scanCmdDir walks cli/cmd/** for *.go files (excluding tests) and collects
// every literal cmdutil.CodeXxx ident passed as the first arg to
// cmdutil.NewError / cmdutil.Wrapf.
//
// Returns map keyed by ErrorCode value (the const's underlying string), with
// a slice of source positions for nicer error messages.
func scanCmdDir(t *testing.T, dir string) map[cmdutil.ErrorCode][]token.Position {
t.Helper()
out := make(map[cmdutil.ErrorCode][]token.Position)
fset := token.NewFileSet()
walkAndScan(t, fset, dir, out)
return out
}
func walkAndScan(t *testing.T, fset *token.FileSet, root string, out map[cmdutil.ErrorCode][]token.Position) {
t.Helper()
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
if filepath.Ext(path) != ".go" {
return nil
}
if strings.HasSuffix(path, "_test.go") {
return nil
}
f, err := parser.ParseFile(fset, path, nil, 0)
if err != nil {
t.Fatalf("parse %s: %v", path, err)
}
collectErrorCodes(fset, f, out)
return nil
})
if err != nil {
t.Fatalf("walk %s: %v", root, err)
}
}
func collectErrorCodes(fset *token.FileSet, f *ast.File, out map[cmdutil.ErrorCode][]token.Position) {
ast.Inspect(f, func(n ast.Node) bool {
call, ok := n.(*ast.CallExpr)
if !ok || len(call.Args) == 0 {
return true
}
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
return true
}
x, ok := sel.X.(*ast.Ident)
if !ok || x.Name != "cmdutil" {
return true
}
if sel.Sel.Name != "NewError" && sel.Sel.Name != "Wrapf" {
return true
}
// First arg should be cmdutil.CodeXxx (SelectorExpr ident).
// If it's a function call (e.g. cmdutil.ClassifyHTTPError(err)), skip
// - bridge handles those.
arg0Sel, ok := call.Args[0].(*ast.SelectorExpr)
if !ok {
return true
}
argX, ok := arg0Sel.X.(*ast.Ident)
if !ok || argX.Name != "cmdutil" {
return true
}
code, ok := identToErrorCode(arg0Sel.Sel.Name)
if !ok {
// Unknown ident name - record as bogus so the test fails with
// a clear "code referenced but not registered" message.
code = cmdutil.ErrorCode("UNKNOWN_REF:" + arg0Sel.Sel.Name)
}
pos := fset.Position(call.Pos())
out[code] = append(out[code], pos)
return true
})
}
// identToErrorCode maps an ident name like "CodeAuthUnauthenticated" to its
// underlying ErrorCode value via a simple switch. Avoids reflect.
// Keep in sync with cmdutil.AllCodes() - adding a new const here is the same
// bookkeeping as adding it to AllCodes().
func identToErrorCode(name string) (cmdutil.ErrorCode, bool) {
switch name {
case "CodeAuthUnauthenticated":
return cmdutil.CodeAuthUnauthenticated, true
case "CodeAuthTokenExpired":
return cmdutil.CodeAuthTokenExpired, true
case "CodeAuthBadCredential":
return cmdutil.CodeAuthBadCredential, true
case "CodeAuthForbidden":
return cmdutil.CodeAuthForbidden, true
case "CodeAuthCrossTenantBlocked":
return cmdutil.CodeAuthCrossTenantBlocked, true
case "CodeAuthTenantMismatch":
return cmdutil.CodeAuthTenantMismatch, true
case "CodeResourceNotFound":
return cmdutil.CodeResourceNotFound, true
case "CodeResourceAlreadyExists":
return cmdutil.CodeResourceAlreadyExists, true
case "CodeResourceLocked":
return cmdutil.CodeResourceLocked, true
case "CodeInputInvalidArgument":
return cmdutil.CodeInputInvalidArgument, true
case "CodeInputMissingFlag":
return cmdutil.CodeInputMissingFlag, true
case "CodeInputConfirmationRequired":
return cmdutil.CodeInputConfirmationRequired, true
case "CodeInputUnknownSubcommand":
return cmdutil.CodeInputUnknownSubcommand, true
case "CodeServerError":
return cmdutil.CodeServerError, true
case "CodeServerTimeout":
return cmdutil.CodeServerTimeout, true
case "CodeServerRateLimited":
return cmdutil.CodeServerRateLimited, true
case "CodeServerIncompatibleVersion":
return cmdutil.CodeServerIncompatibleVersion, true
case "CodeNetworkError":
return cmdutil.CodeNetworkError, true
case "CodeLocalConfigCorrupt":
return cmdutil.CodeLocalConfigCorrupt, true
case "CodeLocalKeychainDenied":
return cmdutil.CodeLocalKeychainDenied, true
case "CodeLocalFileIO":
return cmdutil.CodeLocalFileIO, true
case "CodeLocalProfileNotFound":
return cmdutil.CodeLocalProfileNotFound, true
case "CodeKBIDRequired":
return cmdutil.CodeKBIDRequired, true
case "CodeKBNotFound":
return cmdutil.CodeKBNotFound, true
case "CodeProjectLinkCorrupt":
return cmdutil.CodeProjectLinkCorrupt, true
case "CodeUserAborted":
return cmdutil.CodeUserAborted, true
case "CodeUploadFileNotFound":
return cmdutil.CodeUploadFileNotFound, true
case "CodeSSEStreamAborted":
return cmdutil.CodeSSEStreamAborted, true
case "CodeSessionCreateFailed":
return cmdutil.CodeSessionCreateFailed, true
case "CodeOperationTimeout":
return cmdutil.CodeOperationTimeout, true
case "CodeOperationFailed":
return cmdutil.CodeOperationFailed, true
case "CodeOperationCancelled":
return cmdutil.CodeOperationCancelled, true
case "CodeInternalError":
return cmdutil.CodeInternalError, true
}
return "", false
}
+118
View File
@@ -0,0 +1,118 @@
// cli/acceptance/contract/helpers_test.go
package contract_test
import (
"bytes"
"context"
"flag"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"github.com/Tencent/WeKnora/cli/cmd"
"github.com/Tencent/WeKnora/cli/cmd/doctor"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/secrets"
sdk "github.com/Tencent/WeKnora/client"
)
// TestMain pins the doctor credential-storage outcome for the whole suite.
// Otherwise the check probes the real OS keyring, which differs between
// macOS dev machines (Keychain present → ok) and Linux CI runners without
// libsecret (file fallback → warn), making golden outputs host-dependent.
// MemStore is neither *FileStore nor a real keyring, so the doctor's
// type-switch hits the StatusOK branch.
func TestMain(m *testing.M) {
restore := doctor.SetCredStoreFactoryForTest(func() (secrets.Store, error) {
return secrets.NewMemStore(), nil
})
defer restore()
os.Exit(m.Run())
}
// update is the standard Go test golden-update flag.
//
// go test -update ./acceptance/contract/...
var update = flag.Bool("update", false, "update golden files")
// newTestFactory builds a Factory whose Client returns mockClient.
// Caller must NOT use t.Parallel() - see iostreams.SetForTest contract.
//
// WEKNORA_BASE_URL is set when mockServer is non-nil. buildClient does not
// currently honor this env var (it reads from config.Host); commands that
// need the mock URL rely on the mockClient injection above. The env is set
// anyway for any direct net/http callers (e.g. doctor's HEAD /health).
func newTestFactory(t *testing.T, mockServer *httptest.Server, mockClient *sdk.Client) *cmdutil.Factory {
t.Helper()
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
if mockServer != nil {
t.Setenv("WEKNORA_BASE_URL", mockServer.URL)
}
f := cmdutil.New()
if mockClient != nil {
f.Client = func() (*sdk.Client, error) { return mockClient, nil }
}
return f
}
// runCmd executes the root command in-process and returns captured stdout/stderr.
// Replaces iostreams.IO singleton via SetForTest (auto-restored in t.Cleanup).
//
// Mirrors cmd.Execute(): wires the cobra Out / Err sinks to the same buffers
// it returns, and re-runs cmdutil.PrintError on stderr for failure cases so
// the contract assertion sees the typed `code: message\nhint: ...` line.
func runCmd(t *testing.T, f *cmdutil.Factory, args ...string) (stdout, stderr string, exitCode int) {
t.Helper()
out, errBuf := iostreams.SetForTest(t)
root := cmd.NewRootCmd(f) // exported in cli/cmd/root.go (Task 16)
root.SetArgs(args)
root.SetContext(context.Background())
root.SetOut(out)
root.SetErr(errBuf)
_, err := root.ExecuteC()
if err != nil {
err = cmd.MapCobraError(err)
cmdutil.PrintError(iostreams.IO.Err, err)
}
return out.String(), errBuf.String(), cmdutil.ExitCode(err)
}
// assertGolden compares got against the JSON golden file at path.
// With -update, writes got to path.
//
// CRLF normalization: Windows checkouts with the default core.autocrlf=true
// turn LF in tracked text files into CRLF on disk. The command output is
// always LF, so byte-equal would fail despite identical content.
// .gitattributes is the primary defense (forcing LF on testdata/**/*.json),
// but we also strip CR here so a misconfigured contributor checkout doesn't
// break the suite locally before they push.
func assertGolden(t *testing.T, got []byte, path string) {
t.Helper()
if *update {
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
t.Fatalf("mkdir testdata: %v", err)
}
if err := os.WriteFile(path, got, 0644); err != nil {
t.Fatalf("write golden: %v", err)
}
return
}
want, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read golden %s: %v (run with -update to create)", path, err)
}
want = stripCR(want)
got = stripCR(got)
if !bytes.Equal(want, got) {
t.Errorf("stdout mismatch for %s\nwant:\n%s\ngot:\n%s", path, want, got)
}
}
// stripCR removes CR bytes so CRLF golden files (from Windows autocrlf
// checkout) compare equal to LF runtime output.
func stripCR(b []byte) []byte {
return bytes.ReplaceAll(b, []byte{'\r'}, nil)
}
+372
View File
@@ -0,0 +1,372 @@
// cli/acceptance/contract/wire_test.go
//
// Wire contract test. Drives root cobra in-process for each scenario,
// captures stdout + stderr, and asserts:
//
// - stdout matches a JSON golden in cli/acceptance/testdata/wire/
// - on wantErr cases, stderr contains the expected typed error code
//
// Successful cases produce bare JSON on stdout (no envelope wrapper);
// failure cases produce empty stdout (or, for `doctor`, the data object
// the command writes before returning SilentError) and a `code: msg`
// line on stderr.
//
// Cases intentionally omitted (with reason):
// - doctor.success - non-offline path emits
// unstable timing
// ("reachable in 2ms").
// Unit tests in cli/cmd/doctor
// cover the all-pass shape;
// doctor.success_offline is
// the deterministic sibling
// kept here.
// - auth_login.success - requires stdin pipe
// (--with-token) + keyring-
// aware Secrets store; the
// helper does not yet expose
// a stdin hook.
// - auth_login.error_auth_unauthenticated - same setup as above.
//
// All cases use leaf-positioned --format json (e.g. `version --format json`). --format is a
// per-leaf flag, not a global persistent flag.
package contract_test
import (
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"time"
"github.com/Tencent/WeKnora/cli/internal/config"
sdk "github.com/Tencent/WeKnora/client"
)
// wireCase declares one row in the contract matrix. Optional fields:
//
// server - mock /api/v1/* endpoints; nil means no network.
// preConfig - seed config.yaml under the per-test XDG_CONFIG_HOME
// (set by newTestFactory); use for cases like
// `profile use` that read local state without an
// SDK round-trip.
// wantErr - non-zero exit expected.
// wantStderrSubstring - stderr must contain this substring (typically the
// typed error code, e.g. "auth.unauthenticated").
// Only meaningful when wantErr=true.
type wireCase struct {
name string
args []string
server http.HandlerFunc
preConfig func(t *testing.T)
wantErr bool
wantStderrSubstring string
}
// wireCases enumerates every contract scenario whose stdout is golden-pinned.
// Order is illustrative, not load-bearing.
var wireCases = []wireCase{
// 1. version.success - pure local; no client touched.
{
name: "version.success",
args: []string{"version", "--format", "json"},
},
// 2. doctor.success_offline - only credential_storage runs; the three
// network checks are skipped. Stable details + summary.
{
name: "doctor.success_offline",
args: []string{"doctor", "--offline", "--format", "json"},
server: doctorReachable, // ensures buildServices succeeds even if probed
},
// 3. doctor.error_network - base_url returns 500 → ping fail → cascade
// skip on auth_credential + server_version. credential_storage still
// runs (independent). Contract: any check=fail bumps summary.failed
// and RunE returns SilentError → exit 1 with the data object
// written by emit() as the only stdout content.
{
name: "doctor.error_network",
args: []string{"doctor", "--format", "json"},
server: alwaysServerError,
wantErr: true,
},
// 4-7. kb list / get - SDK paths /api/v1/knowledge-bases[/<id>]
{
name: "kb_list.success",
args: []string{"kb", "list", "--format", "json"},
server: kbListTwo,
},
{
name: "kb_list.success_empty",
args: []string{"kb", "list", "--format", "json"},
server: kbListEmpty,
},
{
name: "kb_list.error_auth_forbidden",
args: []string{"kb", "list", "--format", "json"},
server: always403,
wantErr: true,
wantStderrSubstring: "auth.forbidden",
},
{
name: "kb_view.success",
args: []string{"kb", "view", "kb1", "--format", "json"},
server: kbGetOne,
},
{
name: "kb_view.error_resource_not_found",
args: []string{"kb", "view", "missing", "--format", "json"},
server: always404,
wantErr: true,
wantStderrSubstring: "resource.not_found",
},
// 8. profile use - pure local I/O against config.yaml.
{
name: "profile_use.success",
args: []string{"profile", "use", "production", "--format", "json"},
preConfig: func(t *testing.T) {
cfg := &config.Config{
CurrentProfile: "staging",
Profiles: map[string]config.Profile{
"staging": {Host: "https://staging.example.com"},
"production": {Host: "https://prod.example.com"},
},
}
if err := config.Save(cfg); err != nil {
t.Fatalf("seed config: %v", err)
}
},
},
// (profile_use.error_local_context_not_found dropped - see file header.)
// 9-10. auth status - SDK /api/v1/auth/me, plus config inspection.
{
name: "auth_status.success",
args: []string{"auth", "status", "--format", "json"},
server: whoamiOK,
},
{
name: "auth_status.error_auth_unauthenticated",
args: []string{"auth", "status", "--format", "json"},
server: always401,
wantErr: true,
wantStderrSubstring: "auth.unauthenticated",
},
// 11-13. search chunks - verb-noun shape, positional query, --kb required.
// --kb accepts either a kb_<id> (passed through) or a name (resolved via
// list); UUID-format detection happens client-side so callers can use
// either form interchangeably.
{
name: "search.success",
args: []string{"search", "chunks", "query", "--kb=11111111-1111-4111-8111-111111111111", "--limit=3", "--format", "json"},
server: searchTwoResults,
},
{
name: "search.error_resource_not_found",
args: []string{"search", "chunks", "query", "--kb=eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee", "--format", "json"},
server: always404,
wantErr: true,
wantStderrSubstring: "resource.not_found",
},
{
// --no-vector + --no-keyword is the input.invalid case; the KB UUID
// is just there to satisfy MarkFlagRequired so validation runs deep
// enough to hit the mutex-channel check.
name: "search.error_input_invalid",
args: []string{"search", "chunks", "query", "--kb=11111111-1111-4111-8111-111111111111", "--no-vector", "--no-keyword", "--format", "json"},
wantErr: true,
wantStderrSubstring: "input.invalid_argument",
},
}
// TestWireGolden is the matrix-runner. Cases are sequential (the
// iostreams singleton swap inside helpers.runCmd is package-global;
// t.Parallel is contractually forbidden - see helpers_test.go).
func TestWireGolden(t *testing.T) {
for _, tc := range wireCases {
t.Run(tc.name, func(t *testing.T) {
var ts *httptest.Server
var mockClient *sdk.Client
if tc.server != nil {
ts = httptest.NewServer(tc.server)
defer ts.Close()
mockClient = sdk.NewClient(ts.URL)
}
f := newTestFactory(t, ts, mockClient)
if tc.preConfig != nil {
tc.preConfig(t)
}
stdout, stderr, exit := runCmd(t, f, tc.args...)
if tc.wantErr && exit == 0 {
t.Errorf("expected non-zero exit, got 0; stdout=%q stderr=%q", stdout, stderr)
}
if !tc.wantErr && exit != 0 {
t.Errorf("unexpected non-zero exit %d; stdout=%q stderr=%q", exit, stdout, stderr)
}
if tc.wantStderrSubstring != "" && !strings.Contains(stderr, tc.wantStderrSubstring) {
t.Errorf("stderr missing %q; got %q", tc.wantStderrSubstring, stderr)
}
path := filepath.Join("..", "testdata", "wire", tc.name+".json")
assertGolden(t, []byte(stdout), path)
})
}
}
// ---------------------------------------------------------------------------
// HTTP fixtures
//
// Handlers are intentionally permissive on path matching (HasSuffix) so they
// work whether the SDK adds the /api/v1 prefix or not. The SDK pins the
// /api/v1 prefix today; the suffix match keeps the fixtures resilient to
// future route renames as long as the leaf path stays stable.
// fixedTime is the deterministic timestamp embedded in KnowledgeBase fixtures.
// time.Time marshals to RFC3339; using a fixed value keeps the golden stable.
var fixedTime = time.Date(2025, 1, 1, 12, 0, 0, 0, time.UTC)
func whoamiOK(w http.ResponseWriter, r *http.Request) {
if !strings.HasSuffix(r.URL.Path, "/auth/me") {
w.WriteHeader(http.StatusNotFound)
return
}
resp := sdk.CurrentUserResponse{Success: true}
resp.Data.User = &sdk.AuthUser{ID: "usr_abc", Email: "user@example.com", TenantID: 42}
resp.Data.Tenant = &sdk.AuthTenant{ID: 42, Name: "Acme"}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
}
func always401(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte(`{"error":"unauthenticated"}`))
}
func always403(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte(`{"error":"forbidden"}`))
}
func always404(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"error":"not found"}`))
}
func alwaysServerError(w http.ResponseWriter, _ *http.Request) {
// 5xx triggers PingBaseURL failure path and SDK transport error.
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(`internal error`))
}
// doctorReachable serves /health 200 (so PingBaseURL would succeed if it
// were called). doctor.success_offline still skips ping, so this handler
// is a no-op for that case but keeps buildServices on a happy path.
func doctorReachable(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}
func kbListTwo(w http.ResponseWriter, r *http.Request) {
if !strings.HasSuffix(r.URL.Path, "/knowledge-bases") {
w.WriteHeader(http.StatusNotFound)
return
}
resp := sdk.KnowledgeBaseListResponse{
Success: true,
Data: []sdk.KnowledgeBase{
{
ID: "kb1",
Name: "Onboarding Docs",
TenantID: 42,
EmbeddingModelID: "text-embedding-3",
CreatedAt: fixedTime,
UpdatedAt: fixedTime,
KnowledgeCount: 5,
ChunkCount: 128,
},
{
ID: "kb2",
Name: "API Reference",
TenantID: 42,
EmbeddingModelID: "text-embedding-3",
CreatedAt: fixedTime,
UpdatedAt: fixedTime,
KnowledgeCount: 12,
ChunkCount: 340,
},
},
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
}
func kbListEmpty(w http.ResponseWriter, r *http.Request) {
if !strings.HasSuffix(r.URL.Path, "/knowledge-bases") {
w.WriteHeader(http.StatusNotFound)
return
}
resp := sdk.KnowledgeBaseListResponse{Success: true, Data: []sdk.KnowledgeBase{}}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
}
func kbGetOne(w http.ResponseWriter, r *http.Request) {
if !strings.HasSuffix(r.URL.Path, "/knowledge-bases/kb1") {
w.WriteHeader(http.StatusNotFound)
return
}
resp := sdk.KnowledgeBaseResponse{
Success: true,
Data: sdk.KnowledgeBase{
ID: "kb1",
Name: "Onboarding Docs",
Description: "Internal onboarding handbook",
TenantID: 42,
EmbeddingModelID: "text-embedding-3",
CreatedAt: fixedTime,
UpdatedAt: fixedTime,
KnowledgeCount: 5,
ChunkCount: 128,
},
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
}
func searchTwoResults(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.URL.Path, "/knowledge-bases/11111111-1111-4111-8111-111111111111/hybrid-search") {
w.WriteHeader(http.StatusNotFound)
return
}
resp := sdk.HybridSearchResponse{
Success: true,
Data: []*sdk.SearchResult{
{
ID: "chunk-1",
Content: "first chunk content",
KnowledgeID: "doc-1",
ChunkIndex: 0,
KnowledgeTitle: "Doc 1",
Score: 0.92,
MatchType: sdk.MatchTypeVector,
},
{
ID: "chunk-2",
Content: "second chunk content",
KnowledgeID: "doc-2",
ChunkIndex: 1,
KnowledgeTitle: "Doc 2",
Score: 0.81,
MatchType: sdk.MatchTypeKeyword,
},
},
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
}
+11
View File
@@ -0,0 +1,11 @@
// cli/acceptance/doc.go
//
// Package acceptance is the cli/ subtree top-level home for cross-cutting
// contract / integration tests. Lives outside cli/internal/ so a future
// reviewer immediately sees "this is the contract surface - change with care".
//
// Sub-packages:
//
// contract/ - envelope JSON shape golden + error.code registry consistency
// e2e/ - real WeKnora server blackbox tests (testscript-style)
package acceptance
+279
View File
@@ -0,0 +1,279 @@
//go:build acceptance_e2e
// Package e2e_test drives the WeKnora CLI binary against a real running
// server to validate the RAG closing loop end-to-end.
//
// Build tag isolation: //go:build acceptance_e2e excludes this file from
// the default `go test ./...` so the e2e suite only runs when explicitly
// requested. To run:
//
// cd cli
// WEKNORA_E2E_HOST=https://kb.example.com \
// WEKNORA_E2E_TOKEN=eyJhbGc... \
// go test -tags=acceptance_e2e -v ./acceptance/e2e/...
//
// Optional WEKNORA_E2E_KB_NAME_PREFIX customizes the throwaway KB name (default
// "cli-e2e-"). Cleanup runs even on test failure via t.Cleanup so the server
// doesn't accumulate test debris.
package e2e_test
import (
"bytes"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
)
// TestRAGFullLoop walks the demo MVP path: link a profile, create a KB,
// upload a doc, wait for indexing, search it, then chat against it. Each
// step parses the CLI's bare JSON to extract IDs for the next step -
// validating both functional behavior and wire-contract stability.
func TestRAGFullLoop(t *testing.T) {
host := mustEnv(t, "WEKNORA_E2E_HOST")
token := mustEnv(t, "WEKNORA_E2E_TOKEN")
prefix := envOr("WEKNORA_E2E_KB_NAME_PREFIX", "cli-e2e-")
bin := buildBinary(t)
xdg := t.TempDir()
// Inject host + token as WEKNORA_HOST / WEKNORA_TOKEN env vars. The
// CLI's env-credential path (buildClientFromEnv) takes precedence
// over profile config, so this bypasses the secrets-store dance
// entirely — no keychain access, no file:// ref plumbing. This is
// the most robust path for CI and local e2e alike.
env := append(os.Environ(),
"XDG_CONFIG_HOME="+xdg,
"XDG_CACHE_HOME="+filepath.Join(xdg, "cache"),
"WEKNORA_HOST="+host,
"WEKNORA_TOKEN="+token,
// SDK debug off - explicit so the CI run isn't noisy.
"WEKNORA_LOG_LEVEL=error",
)
// 1. kb create → KnowledgeBase object (envelope-wrapped: {ok, data})
// The CLI now requires explicit model binding so uploaded docs are
// immediately searchable. Use the server's builtin model IDs (they
// exist on every deployment that configures builtin_models.yaml).
embeddingModel := envOr("WEKNORA_E2E_EMBEDDING_MODEL", "Qwen/Qwen3-Embedding-8B")
chatModel := envOr("WEKNORA_E2E_CHAT_MODEL", "deepseek-ai/DeepSeek-V3.2")
kbName := prefix + fmt.Sprintf("%d", time.Now().UnixNano())
var created struct {
OK bool `json:"ok"`
Data struct {
ID string `json:"id"`
Name string `json:"name"`
} `json:"data"`
}
runJSONInto(t, bin, env, &created, "kb", "create", kbName,
"--embedding-model", embeddingModel,
"--chat-model", chatModel,
"--format", "json")
if created.Data.ID == "" {
t.Fatalf("kb create returned no id")
}
t.Logf("created KB: %s (%s)", created.Data.ID, kbName)
t.Cleanup(func() {
// Best-effort cleanup; a 404 means the KB was already gone.
out, err := run(bin, env, "kb", "delete", created.Data.ID, "-y", "--format", "json")
if err != nil {
t.Logf("cleanup kb delete: %v\n%s", err, out)
}
})
// 2. doc upload → Knowledge object (envelope-wrapped: {ok, data})
docPath := writeSampleDoc(t)
var uploaded struct {
OK bool `json:"ok"`
Data struct {
ID string `json:"id"`
} `json:"data"`
}
runJSONInto(t, bin, env, &uploaded, "doc", "upload", docPath, "--kb", created.Data.ID, "--format", "json")
if uploaded.Data.ID == "" {
t.Fatalf("doc upload returned no id")
}
t.Logf("uploaded doc: %s", uploaded.Data.ID)
// 3. poll until indexing finishes (status changes from "pending" / "processing" to "ready" / similar)
waitDocReady(t, bin, env, created.Data.ID, uploaded.Data.ID, 90*time.Second)
// 4. search chunks → SearchResult list (envelope-wrapped: {ok, data})
var searchResp struct {
OK bool `json:"ok"`
Data []map[string]any `json:"data"`
}
runJSONInto(t, bin, env, &searchResp, "search", "chunks", "sample", "--kb", created.Data.ID, "--limit", "5", "--format", "json")
results := searchResp.Data
if len(results) == 0 {
t.Fatalf("search returned no results")
}
t.Logf("search returned %d results", len(results))
// 5. chat --format json → bounded answer-event envelope (--reference for citations)
var chatEnv struct {
OK bool `json:"ok"`
Data struct {
Events []struct {
ResponseType string `json:"response_type"`
Content string `json:"content"`
KnowledgeReferences []struct {
ChunkID string `json:"chunk_id"`
} `json:"knowledge_references"`
} `json:"events"`
SessionID string `json:"session_id"`
} `json:"data"`
}
runJSONInto(t, bin, env, &chatEnv, "chat", "summarize the document briefly", "--kb", created.Data.ID, "--format", "json", "--reference")
if !chatEnv.OK {
t.Fatal("chat ok=false")
}
var answer strings.Builder
refCount := 0
for _, ev := range chatEnv.Data.Events {
if ev.ResponseType == "answer" {
answer.WriteString(ev.Content)
}
refCount += len(ev.KnowledgeReferences)
}
if strings.TrimSpace(answer.String()) == "" {
t.Fatalf("chat returned empty answer")
}
t.Logf("chat answer (%d chars), %d reference indexes", len(answer.String()), refCount)
if refCount == 0 {
// Soft warning - some servers may not surface references for every
// question, but the demo flow is supposed to.
t.Logf("warning: chat returned 0 reference indexes (server may have a different config)")
}
}
func mustEnv(t *testing.T, key string) string {
t.Helper()
v := os.Getenv(key)
if v == "" {
t.Skipf("e2e: %s not set; skipping (set the env var or run `gh workflow run cli-e2e.yml`)", key)
}
return v
}
func envOr(key, fallback string) string {
if v := os.Getenv(key); v != "" {
return v
}
return fallback
}
// buildBinary compiles the CLI to a temp dir once per test run. Re-using a
// single binary across sub-cases avoids the multi-second linker cost on each
// step and matches gh acceptance/ build behavior.
func buildBinary(t *testing.T) string {
t.Helper()
dir := t.TempDir()
out := filepath.Join(dir, "weknora")
// Repo layout: this test sits at cli/acceptance/e2e/, so cli/ is two levels up.
cmd := exec.Command("go", "build", "-o", out, ".")
cmd.Dir = filepath.Join("..", "..")
cmd.Stdout = os.Stderr
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
t.Fatalf("build cli: %v", err)
}
return out
}
// writeSampleDoc emits a small bilingual doc that gives the embedder enough
// signal for retrieval but stays tiny so indexing finishes within the poll
// window.
func writeSampleDoc(t *testing.T) string {
t.Helper()
content := `WeKnora E2E Sample Document
This sample document is used by the WeKnora CLI acceptance test suite to
validate the end-to-end retrieval-augmented generation pipeline.
向量检索的核心思想是把文本通过 embedding 模型映射到高维向量空间,然后通过余弦相似度
等度量找出语义最接近的内容片段。WeKnora 支持 vector + keyword 的混合检索模式。
The hybrid search mode combines vector similarity (semantic) with keyword
matching (lexical) to balance recall and precision.
`
dir := t.TempDir()
p := filepath.Join(dir, "sample.txt")
if err := os.WriteFile(p, []byte(content), 0o600); err != nil {
t.Fatalf("write sample: %v", err)
}
return p
}
// waitDocReady polls `doc list` until the uploaded document's status indicates
// indexing is complete. WeKnora server uses a few status values across versions
// ("ready", "completed", "ok") - accept any non-pending/non-processing/non-failed
// state so we don't break on a server-side rename. Failed status fails the test
// fast.
func waitDocReady(t *testing.T, bin string, env []string, kbID, docID string, timeout time.Duration) {
t.Helper()
deadline := time.Now().Add(timeout)
tick := 2 * time.Second
type docItem struct {
ID string `json:"id"`
ParseStatus string `json:"parse_status"`
}
for time.Now().Before(deadline) {
// doc list is envelope-wrapped: {ok, data: [...]} (bare array)
var resp struct {
OK bool `json:"ok"`
Data []docItem `json:"data"`
}
runJSONInto(t, bin, env, &resp, "doc", "list", "--kb", kbID, "--page-size", "100", "--format", "json")
for _, d := range resp.Data {
if d.ID != docID {
continue
}
low := strings.ToLower(d.ParseStatus)
switch {
case low == "failed", low == "error":
t.Fatalf("doc %s indexing failed: status=%q", docID, d.ParseStatus)
case low == "pending", low == "processing", low == "finalizing", low == "":
// keep waiting
default:
t.Logf("doc %s ready (status=%q)", docID, d.ParseStatus)
return
}
}
time.Sleep(tick)
}
t.Fatalf("doc %s did not reach ready within %s", docID, timeout)
}
// run executes the CLI and returns combined stdout. Errors include stderr +
// exit code so failures are debuggable without re-running.
func run(bin string, env []string, args ...string) ([]byte, error) {
cmd := exec.Command(bin, args...)
cmd.Env = env
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return stdout.Bytes(), fmt.Errorf("%s %s: %v\nstderr:\n%s", filepath.Base(bin), strings.Join(args, " "), err, stderr.String())
}
return stdout.Bytes(), nil
}
// runJSONInto runs the CLI expecting bare JSON output and decodes stdout
// into out (a struct, slice, or map pointer). Test fails on non-zero exit
// or unparseable JSON.
func runJSONInto(t *testing.T, bin string, env []string, out any, args ...string) {
t.Helper()
stdout, err := run(bin, env, args...)
if err != nil {
t.Fatalf("%v", err)
}
if err := json.Unmarshal(stdout, out); err != nil {
t.Fatalf("parse JSON from %v: %v\nstdout:\n%s", args, err, string(stdout))
}
}
Whitespace-only changes.
+1
View File
@@ -0,0 +1 @@
{"ok":true,"data":{"profile":"","auth_source":"profile + keyring","user_id":"usr_abc","email":"user@example.com","tenant_id":42,"tenant_name":"Acme"}}
@@ -0,0 +1 @@
{"ok":true,"data":{"summary":{"all_passed":false,"passed":1,"failed":1,"skipped":2},"checks":[{"name":"base_url_reachable","status":"fail","details":"server returned 500","hint":"verify the host configured for the active profile (run `weknora profile list` / `weknora profile add <n> --host=...`) and network reachability"},{"name":"auth_credential","status":"skip","details":"prereq failed: base_url_reachable"},{"name":"server_version","status":"skip","details":"prereq failed: auth_credential"},{"name":"credential_storage","status":"ok","details":"keyring or file storage available"}]}}
@@ -0,0 +1 @@
{"ok":true,"data":{"summary":{"all_passed":false,"passed":1,"failed":0,"skipped":3},"checks":[{"name":"base_url_reachable","status":"skip","details":"offline mode"},{"name":"auth_credential","status":"skip","details":"offline mode"},{"name":"server_version","status":"skip","details":"offline mode"},{"name":"credential_storage","status":"ok","details":"keyring or file storage available"}]}}
Whitespace-only changes.
+1
View File
@@ -0,0 +1 @@
{"ok":true,"data":[{"id":"kb1","name":"Onboarding Docs","type":"","is_temporary":false,"is_pinned":false,"description":"","tenant_id":42,"chunking_config":{"chunk_size":0,"chunk_overlap":0,"separators":null},"image_processing_config":{"model_id":""},"faq_config":null,"embedding_model_id":"text-embedding-3","summary_model_id":"","vlm_config":{"enabled":false,"model_id":""},"storage_provider_config":null,"storage_config":{"secret_id":"","secret_key":"","region":"","bucket_name":"","app_id":"","path_prefix":"","provider":""},"extract_config":null,"auto_tag_config":null,"created_at":"2025-01-01T12:00:00Z","updated_at":"2025-01-01T12:00:00Z","knowledge_count":5,"chunk_count":128,"is_processing":false,"processing_count":0},{"id":"kb2","name":"API Reference","type":"","is_temporary":false,"is_pinned":false,"description":"","tenant_id":42,"chunking_config":{"chunk_size":0,"chunk_overlap":0,"separators":null},"image_processing_config":{"model_id":""},"faq_config":null,"embedding_model_id":"text-embedding-3","summary_model_id":"","vlm_config":{"enabled":false,"model_id":""},"storage_provider_config":null,"storage_config":{"secret_id":"","secret_key":"","region":"","bucket_name":"","app_id":"","path_prefix":"","provider":""},"extract_config":null,"auto_tag_config":null,"created_at":"2025-01-01T12:00:00Z","updated_at":"2025-01-01T12:00:00Z","knowledge_count":12,"chunk_count":340,"is_processing":false,"processing_count":0}],"meta":{"count":2,"total_count":2}}
@@ -0,0 +1 @@
{"ok":true,"data":[],"meta":{"count":0,"total_count":0}}
Whitespace-only changes.
+1
View File
@@ -0,0 +1 @@
{"ok":true,"data":{"id":"kb1","name":"Onboarding Docs","type":"","is_temporary":false,"is_pinned":false,"description":"Internal onboarding handbook","tenant_id":42,"chunking_config":{"chunk_size":0,"chunk_overlap":0,"separators":null},"image_processing_config":{"model_id":""},"faq_config":null,"embedding_model_id":"text-embedding-3","summary_model_id":"","vlm_config":{"enabled":false,"model_id":""},"storage_provider_config":null,"storage_config":{"secret_id":"","secret_key":"","region":"","bucket_name":"","app_id":"","path_prefix":"","provider":""},"extract_config":null,"auto_tag_config":null,"created_at":"2025-01-01T12:00:00Z","updated_at":"2025-01-01T12:00:00Z","knowledge_count":5,"chunk_count":128,"is_processing":false,"processing_count":0}}
+1
View File
@@ -0,0 +1 @@
{"ok":true,"data":{"current_profile":"production","previous_profile":"staging"},"profile":"staging"}
Whitespace-only changes.
Whitespace-only changes.
+1
View File
@@ -0,0 +1 @@
{"ok":true,"data":[{"id":"chunk-1","content":"first chunk content","knowledge_id":"doc-1","chunk_index":0,"knowledge_title":"Doc 1","start_at":0,"end_at":0,"seq":0,"score":0.92,"match_type":0,"chunk_type":"","image_info":"","metadata":null,"knowledge_filename":"","knowledge_source":"","knowledge_channel":""},{"id":"chunk-2","content":"second chunk content","knowledge_id":"doc-2","chunk_index":1,"knowledge_title":"Doc 2","start_at":0,"end_at":0,"seq":0,"score":0.81,"match_type":1,"chunk_type":"","image_info":"","metadata":null,"knowledge_filename":"","knowledge_source":"","knowledge_channel":""}],"meta":{"count":2}}
+1
View File
@@ -0,0 +1 @@
{"ok":true,"data":{"commit":"none","date":"unknown","version":"dev"}}
+36
View File
@@ -0,0 +1,36 @@
// Package agentcmd holds the `weknora agent` command tree:
// list / view / create / update / delete / status / check. The directory is
// named `agent/` to match the cobra subcommand; the Go package is `agentcmd`
// to avoid colliding with cobra's *cobra.Command identifier.
//
// "agent" in this subtree refers to WeKnora's user-defined Custom
// Agents (server resource: GET/POST /agents/...) and handles CRUD
// operations only. Agent invocation has moved to `weknora session ask
// --agent <id>` (see cli/cmd/session/ask.go).
package agentcmd
import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
)
// NewCmd builds the `weknora agent` parent and registers leaves. Called
// from cli/cmd/root.go.
func NewCmd(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "agent",
Short: "Manage custom agents (CRUD + status/check)",
Long: `Custom Agents bundle a system prompt, model, tool allow-list, and KB
scope into an addressable resource. Create, update, list, view, check,
or delete agents. To invoke an agent, use: weknora session ask --agent <id>`,
}
cmd.AddCommand(NewCmdList(f))
cmd.AddCommand(NewCmdView(f))
cmd.AddCommand(NewCmdCreate(f))
cmd.AddCommand(NewCmdEdit(f))
cmd.AddCommand(NewCmdDelete(f))
cmd.AddCommand(NewCmdStatus(f))
cmd.AddCommand(NewCmdCheck(f))
return cmd
}
+134
View File
@@ -0,0 +1,134 @@
package agentcmd
import (
"context"
"fmt"
"io"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
// AgentCheckResult is the deep-verification response for `agent check <id>`.
// Superset of AgentStatusResult: status fields + KBScopeAllReachable from
// probing each KB in agent.Config.KnowledgeBases. Verb split with
// `agent status`: status reads existing state cheaply, check actively
// verifies dependencies.
type AgentCheckResult struct {
ID string `json:"id"`
Reachable bool `json:"reachable"`
ModelID string `json:"model_id,omitempty"`
KBScopeAllReachable *bool `json:"kb_scope_all_reachable,omitempty"` // pointer so we can distinguish "not applicable" (e.g. agent unreachable) from "false"
}
// AgentCheckService is the narrow SDK surface needed for agent check.
type AgentCheckService interface {
GetAgent(ctx context.Context, id string) (*sdk.Agent, error)
GetKnowledgeBase(ctx context.Context, id string) (*sdk.KnowledgeBase, error)
}
var agentCheckFields = []string{"id", "reachable", "model_id", "kb_scope_all_reachable"}
// NewCmdCheck builds `weknora agent check <id>`.
func NewCmdCheck(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "check <agent-id>",
Short: "Verify a custom agent end-to-end (status + kb_scope reachability)",
Long: `Active verification of a custom agent.
Performs 1 + N HTTP calls:
1 GET /agents/{id} — reachable + model_id
N GET /kb/{kb_id} for each id in agent.config.knowledge_bases
— sets kb_scope_all_reachable = true iff every probe succeeds
Use 'weknora agent status <id>' for a fast read-only health snapshot
(1 HTTP call, no KB probing). Use 'agent check' when you need to verify
the agent's downstream dependencies are all reachable.`,
Example: ` weknora agent check ag_abc
weknora agent check ag_abc --format json`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
cli, err := f.Client()
if err != nil {
return err
}
res, err := runAgentCheck(c.Context(), cli, args[0])
if err != nil {
return err
}
return emitAgentCheck(res, fopts, iostreams.IO.Out)
},
}
cmdutil.AddFormatFlag(cmd, agentCheckFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "verify a custom agent end-to-end: status plus kb_scope reachability",
RequiredFlags: []string{"<agent-id> (positional)"},
Examples: []string{"weknora agent check agent_abc"},
Output: "envelope.data is {id, reachable, ...} with kb_scope reachability folded in",
})
return cmd
}
// runAgentCheck is the testable core. Never errors for "agent not
// reachable" — Reachable=false carries that signal.
func runAgentCheck(ctx context.Context, svc AgentCheckService, id string) (*AgentCheckResult, error) {
a, err := svc.GetAgent(ctx, id)
if err != nil {
return &AgentCheckResult{ID: id, Reachable: false}, nil
}
res := &AgentCheckResult{ID: a.ID, Reachable: true}
if a.Config != nil {
res.ModelID = a.Config.ModelID
}
// Probe each KB in scope. Vacuously true when scope is empty or
// config is nil.
allOK := true
if a.Config != nil {
for _, kbID := range a.Config.KnowledgeBases {
if _, err := svc.GetKnowledgeBase(ctx, kbID); err != nil {
allOK = false
break
}
}
}
res.KBScopeAllReachable = &allOK
return res, nil
}
// emitAgentCheck renders res. Same dispatch as emitAgentStatus.
func emitAgentCheck(res *AgentCheckResult, fopts *cmdutil.FormatOptions, w io.Writer) error {
switch fopts.Mode {
case cmdutil.FormatJSON, cmdutil.FormatNDJSON:
return fopts.Emit(w, res, nil)
case cmdutil.FormatText, "":
return writeAgentCheckText(w, res)
default:
return fmt.Errorf("unsupported --format %q for agent check", fopts.Mode)
}
}
func writeAgentCheckText(w io.Writer, res *AgentCheckResult) error {
fmt.Fprintf(w, "ID: %s\n", res.ID)
fmt.Fprintf(w, "Reachable: %v\n", res.Reachable)
if !res.Reachable {
return nil
}
if res.ModelID != "" {
fmt.Fprintf(w, "Model: %s\n", res.ModelID)
}
if res.KBScopeAllReachable != nil {
fmt.Fprintf(w, "KB scope OK: %v\n", *res.KBScopeAllReachable)
}
return nil
}
// compile-time check: SDK client satisfies AgentCheckService.
var _ AgentCheckService = (*sdk.Client)(nil)
+154
View File
@@ -0,0 +1,154 @@
package agentcmd
import (
"bytes"
"context"
"encoding/json"
"fmt"
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
sdk "github.com/Tencent/WeKnora/client"
)
type fakeAgentCheckSvc struct {
agent *sdk.Agent
agentErr error
kbProbeOK map[string]bool // kb_id → reachable
kbErr error // applied for any KB id not in the map
}
func (f *fakeAgentCheckSvc) GetAgent(_ context.Context, id string) (*sdk.Agent, error) {
if f.agentErr != nil {
return nil, f.agentErr
}
return f.agent, nil
}
func (f *fakeAgentCheckSvc) GetKnowledgeBase(_ context.Context, id string) (*sdk.KnowledgeBase, error) {
if ok, found := f.kbProbeOK[id]; found {
if !ok {
return nil, fmt.Errorf("kb %s unreachable", id)
}
return &sdk.KnowledgeBase{ID: id}, nil
}
if f.kbErr != nil {
return nil, f.kbErr
}
return &sdk.KnowledgeBase{ID: id}, nil
}
func TestRunAgentCheck_AllReachable(t *testing.T) {
svc := &fakeAgentCheckSvc{
agent: &sdk.Agent{ID: "ag_x", Config: &sdk.AgentConfig{
ModelID: "m_x",
KnowledgeBases: []string{"kb_a", "kb_b"},
}},
kbProbeOK: map[string]bool{"kb_a": true, "kb_b": true},
}
res, err := runAgentCheck(context.Background(), svc, "ag_x")
if err != nil {
t.Fatalf("%v", err)
}
if !res.Reachable {
t.Error("Reachable=false, want true")
}
if res.ModelID != "m_x" {
t.Errorf("ModelID=%q, want m_x", res.ModelID)
}
if res.KBScopeAllReachable == nil || !*res.KBScopeAllReachable {
t.Errorf("KBScopeAllReachable should be true (pointer set), got %v", res.KBScopeAllReachable)
}
}
func TestRunAgentCheck_OneKBFails(t *testing.T) {
svc := &fakeAgentCheckSvc{
agent: &sdk.Agent{ID: "ag_x", Config: &sdk.AgentConfig{
ModelID: "m_x",
KnowledgeBases: []string{"kb_a", "kb_b"},
}},
kbProbeOK: map[string]bool{"kb_a": true, "kb_b": false},
}
res, _ := runAgentCheck(context.Background(), svc, "ag_x")
if res.KBScopeAllReachable == nil || *res.KBScopeAllReachable {
t.Errorf("KBScopeAllReachable should be false; got %v", res.KBScopeAllReachable)
}
}
func TestRunAgentCheck_Unreachable(t *testing.T) {
svc := &fakeAgentCheckSvc{agentErr: fmt.Errorf("404")}
res, err := runAgentCheck(context.Background(), svc, "ag_x")
if err != nil {
t.Fatalf("%v", err)
}
if res.Reachable {
t.Error("Reachable=true on 404; want false")
}
if res.ID != "ag_x" {
t.Errorf("ID=%q, want ag_x (echoed even on unreachable)", res.ID)
}
// KBScopeAllReachable should be nil when agent is unreachable
if res.KBScopeAllReachable != nil {
t.Errorf("KBScopeAllReachable should be nil when agent unreachable; got %v", res.KBScopeAllReachable)
}
}
func TestRunAgentCheck_NilConfig(t *testing.T) {
// Defensive: Agent.Config is a pointer; nil should not panic and
// KBScopeAllReachable should be vacuously true (no KBs to probe).
svc := &fakeAgentCheckSvc{agent: &sdk.Agent{ID: "ag_x", Config: nil}}
res, err := runAgentCheck(context.Background(), svc, "ag_x")
if err != nil {
t.Fatalf("%v", err)
}
if !res.Reachable {
t.Error("Reachable=false, want true on nil config")
}
if res.ModelID != "" {
t.Errorf("ModelID=%q, want empty (no config)", res.ModelID)
}
// Vacuously true: no KBs to probe
if res.KBScopeAllReachable == nil || !*res.KBScopeAllReachable {
t.Errorf("KBScopeAllReachable should be vacuously true for nil config; got %v", res.KBScopeAllReachable)
}
}
func TestEmitAgentCheck_JSON(t *testing.T) {
trueP := true
var buf bytes.Buffer
res := &AgentCheckResult{ID: "ag_x", Reachable: true, ModelID: "m_x", KBScopeAllReachable: &trueP}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
if err := emitAgentCheck(res, fopts, &buf); err != nil {
t.Fatalf("%v", err)
}
var env struct {
OK bool `json:"ok"`
Data AgentCheckResult `json:"data"`
}
if err := json.Unmarshal(buf.Bytes(), &env); err != nil {
t.Fatalf("%v", err)
}
got := env.Data
if got.ModelID != "m_x" {
t.Errorf("ModelID=%q, want m_x", got.ModelID)
}
if got.KBScopeAllReachable == nil || !*got.KBScopeAllReachable {
t.Errorf("KBScopeAllReachable should be true in JSON output; got %v", got.KBScopeAllReachable)
}
}
func TestEmitAgentCheck_Text(t *testing.T) {
trueP := true
var buf bytes.Buffer
res := &AgentCheckResult{ID: "ag_x", Reachable: true, ModelID: "m_x", KBScopeAllReachable: &trueP}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
if err := emitAgentCheck(res, fopts, &buf); err != nil {
t.Fatalf("%v", err)
}
for _, want := range []string{"ag_x", "m_x", "true"} {
if !strings.Contains(buf.String(), want) {
t.Errorf("output missing %q:\n%s", want, buf.String())
}
}
}
+384
View File
@@ -0,0 +1,384 @@
package agentcmd
import (
"context"
"fmt"
"io"
"path/filepath"
"strings"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
// CreateService is the narrow SDK surface this command depends on.
// *sdk.Client satisfies it via duck typing.
type CreateService interface {
CreateAgent(ctx context.Context, req *sdk.CreateAgentRequest) (*sdk.Agent, error)
CopyAgent(ctx context.Context, id string) (*sdk.Agent, error)
UpdateAgent(ctx context.Context, id string, req *sdk.UpdateAgentRequest) (*sdk.Agent, error)
}
// CreateOptions captures flag state. SystemPromptReader and ConfigFileBody
// are populated from --system-prompt-file and --config-file respectively
// (or stdin when the value is "-"). The embedded flags struct tracks "was
// set" bits so MergeAgentConfig can distinguish "user passed --foo zero"
// from "user did not pass --foo".
type CreateOptions struct {
Name string
Model string
Description string
SystemPrompt string
SystemPromptReader io.Reader
AgentMode string
KBs []string
KBSelectionMode string
RerankModel string
Temperature float64
From string
ConfigFileBody io.Reader
ConfigFileKind string // "yaml" or "json"
GenerateSkeleton bool
DryRun bool
flags createFlagSet // populated in PreRunE for *Set bits
}
// createFlagSet records which hot-path flags the user explicitly passed so
// MergeAgentConfig knows which fields to overlay onto the base config.
type createFlagSet struct {
agentModeSet bool
systemPromptSet bool
rerankModelSet bool
temperatureSet bool
kbSelectionModeSet bool
kbsSet bool
}
const agentCreateExample = ` weknora agent create "Support Bot" --model <model-id>
weknora agent create "Code Reviewer" --model <model-id> --system-prompt-file ./prompt.md --attach-kb kb_eng --attach-kb kb_arch
weknora agent create "From Template" --model <model-id> --from ag_existing
weknora agent create --generate-skeleton > my-agent.yaml
weknora agent create "Tuned" --model <model-id> --config-file ./my-agent.yaml`
const agentCreateLong = `Create a new custom agent.
--model is required (an agent without a model cannot invoke); discover a
valid model id with 'weknora model list'. The 7
optional hot-path flags cover the most frequently set AgentConfig fields;
for the remaining 27 use --config-file with a YAML or JSON document
matching the AgentConfig schema (run --generate-skeleton to get a
ready-to-edit template).
Precedence when both a config file and hot-path flags are supplied:
hot-path flag > config-file value > server default
--from <id> copies an existing agent (SDK CopyAgent) then applies any
hot-path overrides via UpdateAgent. --attach-kb on --from REPLACES the copied
agent's KB list (not merge) — matches surgical-flag semantics.
AI agents: writes a new resource server-side. Failure surfaces as a
typed code on stderr: input.invalid_argument (bad flags, bad file, or
bad model), resource.not_found (--from <missing>), auth.unauthenticated.`
// NewCmdCreate builds `weknora agent create <name> --model <id>`.
func NewCmdCreate(f *cmdutil.Factory) *cobra.Command {
opts := &CreateOptions{}
var systemPromptFile, configFile string
cmd := &cobra.Command{
Use: "create <name>",
Short: "Create a new custom agent",
Long: agentCreateLong,
Example: agentCreateExample,
// Allow 0 args for --generate-skeleton; PreRunE enforces the real
// arity rule once it knows whether skeleton mode is active.
Args: cobra.MaximumNArgs(1),
PreRunE: func(cmd *cobra.Command, args []string) error {
if opts.GenerateSkeleton {
return nil
}
if len(args) != 1 {
return cmdutil.NewFlagError(fmt.Errorf("accepts 1 arg, received %d", len(args)))
}
opts.Name = args[0]
if opts.Model == "" {
return cmdutil.NewFlagError(fmt.Errorf(`required flag(s) "model" not set`))
}
opts.flags.agentModeSet = cmd.Flags().Changed("agent-mode")
opts.flags.systemPromptSet = cmd.Flags().Changed("system-prompt") || cmd.Flags().Changed("system-prompt-file")
opts.flags.rerankModelSet = cmd.Flags().Changed("rerank-model")
opts.flags.temperatureSet = cmd.Flags().Changed("temperature")
opts.flags.kbSelectionModeSet = cmd.Flags().Changed("kb-selection-mode")
opts.flags.kbsSet = cmd.Flags().Changed("attach-kb")
// --temperature is bounded 0.0..2.0. Reject out-of-range
// early with a typed input.invalid_argument so users don't
// burn a roundtrip on a value the server would also reject.
if opts.flags.temperatureSet && (opts.Temperature < 0.0 || opts.Temperature > 2.0) {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
fmt.Sprintf("--temperature must be in 0.0..2.0, got %g", opts.Temperature))
}
// Reject an unknown --agent-mode / --kb-selection-mode up front
// (typed exit 5) rather than letting the server fail the create.
if err := validateAgentModeFlags(&opts.AgentMode, &opts.KBSelectionMode); err != nil {
return err
}
if systemPromptFile != "" {
r, err := cmdutil.OpenInput(systemPromptFile)
if err != nil {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("--system-prompt-file: %v", err))
}
opts.SystemPromptReader = r
}
if configFile != "" {
r, kind, err := openConfigFile(configFile)
if err != nil {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("--config-file: %v", err))
}
opts.ConfigFileBody = r
opts.ConfigFileKind = kind
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(cmd)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
planArgs := map[string]any{"name": opts.Name}
if configFile != "" {
planArgs["config"] = configFile
}
if handled, err := cmdutil.HandleDryRun(cmd, opts.DryRun, cmdutil.DryRunPlan{
Action: "agent.create",
Args: planArgs,
}); handled {
return err
}
cli, err := f.Client()
if err != nil {
return err
}
// Resolve --model / --rerank-model (id or name) and validate they
// exist, matching the id-or-name policy of `kb config set`. A bogus name
// fails fast here instead of creating an agent whose model never
// resolves at run time.
if opts.Model, err = cmdutil.ResolveModelRef(cmd.Context(), cli, opts.Model, "KnowledgeQA"); err != nil {
return err
}
if opts.RerankModel, err = cmdutil.ResolveModelRef(cmd.Context(), cli, opts.RerankModel, "Rerank"); err != nil {
return err
}
// Resolve --attach-kb values (id or name) to canonical ids,
// matching the --kb flag's id-or-name policy. Without this a raw
// name is stored verbatim as a kb_id, silently creating an agent
// whose KB reference never resolves at run time.
if len(opts.KBs) > 0 {
resolved := make([]string, 0, len(opts.KBs))
for _, raw := range opts.KBs {
id, rerr := cmdutil.ResolveKBFlag(cmd.Context(), cli, raw)
if rerr != nil {
return rerr
}
resolved = append(resolved, id)
}
opts.KBs = resolved
}
return runCreate(cmd.Context(), opts, fopts, cli)
},
}
// Required (enforced in PreRunE rather than cmd.MarkFlagRequired so
// --generate-skeleton can bypass it — cobra's MarkFlagRequired runs
// before PreRunE and would otherwise block the skeleton path).
cmd.Flags().StringVar(&opts.Model, "model", "", "LLM model id or name (required, except with --generate-skeleton)")
// Hot-path (8 flag names, 7 distinct config fields)
cmd.Flags().StringVar(&opts.Description, "description", "", "Agent description")
cmd.Flags().StringVar(&opts.SystemPrompt, "system-prompt", "", "System prompt text (mutex with --system-prompt-file)")
cmd.Flags().StringVar(&systemPromptFile, "system-prompt-file", "", "Read system prompt from FILE, or '-' for stdin")
cmd.MarkFlagsMutuallyExclusive("system-prompt", "system-prompt-file")
cmd.Flags().StringVar(&opts.AgentMode, "agent-mode", "", "Agent operating mode: "+strings.Join(agentModeValues, " | "))
cmd.Flags().StringSliceVar(&opts.KBs, "attach-kb", nil, "Attach a knowledge base id (repeatable); aligns with 'agent update --add-kb'")
cmd.Flags().StringVar(&opts.KBSelectionMode, "kb-selection-mode", "", "KB selection mode: "+strings.Join(kbSelectionModeValues, " | "))
cmd.Flags().StringVar(&opts.RerankModel, "rerank-model", "", "Rerank model id or name")
cmd.Flags().Float64Var(&opts.Temperature, "temperature", 0.0, "Generation temperature (0.0..2.0)")
// Power-user / utility
cmd.Flags().StringVar(&opts.From, "from", "", "Copy from existing agent id (then apply other flags)")
cmd.Flags().StringVar(&configFile, "config-file", "", "Full AgentConfig YAML or JSON (use '-' for stdin)")
cmd.Flags().BoolVar(&opts.GenerateSkeleton, "generate-skeleton", false, "Emit blank AgentConfig YAML to stdout and exit")
cmdutil.AddFormatFlag(cmd, agentViewFields...)
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "Create a new custom agent. --model is required and accepts a model id or name; --attach-kb (repeatable) accepts KB ids or names. Emits the created Agent object.",
RequiredFlags: []string{"<name> (positional)", "--model"},
Examples: []string{
`weknora agent create "Support Bot" --model gpt-4o`,
`weknora agent create "Support Bot" --model gpt-4o --attach-kb kb_eng --system-prompt "You are a support assistant."`,
`weknora agent create --generate-skeleton # print a blank config to fill in (no --model needed)`,
},
Output: "envelope.data is the created Agent object with id, name, config",
})
return cmd
}
func runCreate(ctx context.Context, opts *CreateOptions, fopts *cmdutil.FormatOptions, svc CreateService) error {
if opts.GenerateSkeleton {
return cmdutil.GenerateAgentSkeleton(iostreams.IO.Out)
}
// 1. Build base AgentConfig from --config-file (if any), else zero.
// (For --from, the copied agent's existing config becomes the base
// instead — set after CopyAgent below, before MergeAgentConfig.)
var base sdk.AgentConfig
if opts.ConfigFileBody != nil {
parsed, err := cmdutil.LoadAgentConfig(opts.ConfigFileBody, opts.ConfigFileKind)
if err != nil {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, err.Error())
}
base = *parsed
}
// 2. Resolve system prompt (file/stdin > flag string)
if opts.SystemPromptReader != nil {
body, err := io.ReadAll(opts.SystemPromptReader)
if err != nil {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("--system-prompt-file read: %v", err))
}
opts.SystemPrompt = strings.TrimSpace(string(body))
}
// 3. Either copy-then-update, or create from scratch. For --from we
// must seed `base` from the copied agent's existing config FIRST so
// MergeAgentConfig preserves source fields the user did not override
// (e.g. SystemPrompt, AgentMode, KB list). Without this seeding the
// surgical overrides would ship UpdateAgent with the other 33 fields
// zeroed, clobbering source state.
if opts.From != "" {
copied, err := svc.CopyAgent(ctx, opts.From)
if err != nil {
return cmdutil.WrapHTTP(err, "copy agent %s", opts.From)
}
if copied.Config != nil {
base = *copied.Config
}
// --attach-kb on --from REPLACES the copied KB list; when --attach-kb
// is not set, KnowledgeBasesSet stays false inside applyCreateOverrides
// and the copy's KB list passes through unchanged.
cfg := applyCreateOverrides(&base, opts)
// Apply overrides on top of copied state via UpdateAgent (no
// server-side template-parameters route, so we do two roundtrips).
updateReq := &sdk.UpdateAgentRequest{
Name: opts.Name,
Description: opts.Description,
Config: cfg,
}
updated, err := svc.UpdateAgent(ctx, copied.ID, updateReq)
if err != nil {
return cmdutil.WrapHTTP(err, "update copied agent %s", copied.ID)
}
return emitAgent(fopts, updated)
}
// 4. Plain create path: apply hot-path flag overrides onto base
// (zero-valued unless --config-file supplied content).
cfg := applyCreateOverrides(&base, opts)
req := &sdk.CreateAgentRequest{
Name: opts.Name,
Description: opts.Description,
Config: cfg,
}
created, err := svc.CreateAgent(ctx, req)
if err != nil {
return cmdutil.WrapHTTP(err, "create agent")
}
return emitAgent(fopts, created)
}
// agentModeValues / kbSelectionModeValues are the closed server enums for the
// --agent-mode / --kb-selection-mode flags, sourced from the SDK enumerators so
// the CLI can't drift from the server vocabulary.
var (
agentModeValues = cmdutil.EnumStrings(sdk.AllAgentModes())
kbSelectionModeValues = cmdutil.EnumStrings(sdk.AllKBSelectionModes())
)
// validateAgentModeFlags validates and canonicalises --agent-mode and
// --kb-selection-mode in place against the SDK enums. An empty value passes
// through (flag unset → no override). Rejecting a typo here gives a fast,
// typed input.invalid_argument instead of a confusing server-side failure.
// Shared by `agent create` and `agent update`.
func validateAgentModeFlags(agentMode, kbSelectionMode *string) error {
v, err := cmdutil.ValidateEnum("agent-mode", *agentMode, agentModeValues)
if err != nil {
return err
}
*agentMode = v
v, err = cmdutil.ValidateEnum("kb-selection-mode", *kbSelectionMode, kbSelectionModeValues)
if err != nil {
return err
}
*kbSelectionMode = v
return nil
}
// applyCreateOverrides merges hot-path flag overrides into the base config,
// then applies the "--attach-kb implies --kb-selection-mode=selected" fallback.
// Shared by the --from path (base=copied agent's config) and the plain
// create path (base=zero or --config-file). Keeping both paths on one
// helper prevents silent divergence when future flags are added.
func applyCreateOverrides(base *sdk.AgentConfig, opts *CreateOptions) *sdk.AgentConfig {
overrides := cmdutil.AgentConfigFlags{
AgentMode: opts.AgentMode, AgentModeSet: opts.flags.agentModeSet,
SystemPrompt: opts.SystemPrompt, SystemPromptSet: opts.flags.systemPromptSet,
ModelID: opts.Model, ModelIDSet: true, // --model is required
RerankModelID: opts.RerankModel, RerankModelIDSet: opts.flags.rerankModelSet,
Temperature: opts.Temperature, TemperatureSet: opts.flags.temperatureSet,
KBSelectionMode: opts.KBSelectionMode, KBSelectionModeSet: opts.flags.kbSelectionModeSet,
KnowledgeBases: opts.KBs, KnowledgeBasesSet: opts.flags.kbsSet,
}
cfg := cmdutil.MergeAgentConfig(base, overrides)
// --attach-kb without explicit --kb-selection-mode implies "selected".
if opts.flags.kbsSet && !opts.flags.kbSelectionModeSet && cfg.KBSelectionMode == "" {
cfg.KBSelectionMode = "selected"
}
return cfg
}
// openConfigFile returns a Reader, the detected kind ("yaml"/"json"), or
// an error. Format is inferred from file extension; "-" defaults to YAML.
func openConfigFile(path string) (io.Reader, string, error) {
r, err := cmdutil.OpenInput(path)
if err != nil {
return nil, "", err
}
kind := "yaml"
if strings.EqualFold(filepath.Ext(path), ".json") {
kind = "json"
}
return r, kind, nil
}
// emitAgent writes the Agent to stdout (bare SDK shape for --format json,
// text KV otherwise). Shared by create and edit; defined here for proximity
// to the create flow.
func emitAgent(fopts *cmdutil.FormatOptions, ag *sdk.Agent) error {
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, ag, nil)
}
renderAgent(iostreams.IO.Out, ag)
return nil
}
+297
View File
@@ -0,0 +1,297 @@
package agentcmd
import (
"bytes"
"context"
"encoding/json"
"fmt"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
// fakeCreateSvc records all three SDK methods this command may invoke.
type fakeCreateSvc struct {
createReq *sdk.CreateAgentRequest
createResp *sdk.Agent
createErr error
copySrcID string
copyResp *sdk.Agent
copyErr error
updateID string
updateReq *sdk.UpdateAgentRequest
updateResp *sdk.Agent
updateErr error
updateCalled bool
}
func (f *fakeCreateSvc) CreateAgent(_ context.Context, req *sdk.CreateAgentRequest) (*sdk.Agent, error) {
f.createReq = req
return f.createResp, f.createErr
}
func (f *fakeCreateSvc) CopyAgent(_ context.Context, id string) (*sdk.Agent, error) {
f.copySrcID = id
return f.copyResp, f.copyErr
}
func (f *fakeCreateSvc) UpdateAgent(_ context.Context, id string, req *sdk.UpdateAgentRequest) (*sdk.Agent, error) {
f.updateCalled = true
f.updateID = id
f.updateReq = req
return f.updateResp, f.updateErr
}
func TestCreate_HappyPath_MinimalRequired(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{createResp: &sdk.Agent{ID: "ag_new", Name: "Test"}}
opts := &CreateOptions{Name: "Test", Model: "model-x"}
err := runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc)
require.NoError(t, err)
require.NotNil(t, svc.createReq)
assert.Equal(t, "Test", svc.createReq.Name)
require.NotNil(t, svc.createReq.Config)
assert.Equal(t, "model-x", svc.createReq.Config.ModelID)
}
func TestCreate_MissingName_FlagError(t *testing.T) {
cmd := NewCmdCreate(nil)
cmd.SetArgs([]string{"--model", "model-x"})
cmd.SilenceUsage = true
cmd.SilenceErrors = true
err := cmd.Execute()
require.Error(t, err)
// PreRunE rejects "0 args" with our flag-error sentinel; the message
// always carries the canonical "accepts 1 arg" phrase.
assert.Contains(t, err.Error(), "accepts 1 arg")
}
func TestCreate_MissingModel_FlagError(t *testing.T) {
cmd := NewCmdCreate(nil)
cmd.SetArgs([]string{"Test"})
cmd.SilenceUsage = true
cmd.SilenceErrors = true
err := cmd.Execute()
require.Error(t, err)
assert.Contains(t, err.Error(), `required flag(s) "model" not set`)
}
func TestCreate_ConfigFile_FlagsOverrideFile(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{createResp: &sdk.Agent{ID: "ag_new"}}
opts := &CreateOptions{
Name: "Test",
Model: "model-x", // override file
ConfigFileBody: bytes.NewBufferString(`{"agent_mode":"smart-reasoning","model_id":"model-y","temperature":0.5}`),
ConfigFileKind: "json",
}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
require.NotNil(t, svc.createReq.Config)
assert.Equal(t, "smart-reasoning", svc.createReq.Config.AgentMode, "file value preserved when no flag override")
assert.Equal(t, "model-x", svc.createReq.Config.ModelID, "flag overrides file")
assert.InDelta(t, 0.5, svc.createReq.Config.Temperature, 0.001)
}
func TestCreate_From_CopiesThenUpdates(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{
copyResp: &sdk.Agent{ID: "ag_clone", Name: "Source", Config: &sdk.AgentConfig{ModelID: "model-y"}},
updateResp: &sdk.Agent{ID: "ag_clone", Name: "Renamed"},
}
opts := &CreateOptions{Name: "Renamed", Model: "model-x", From: "ag_source"}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
assert.Equal(t, "ag_source", svc.copySrcID)
require.True(t, svc.updateCalled, "must Update after Copy when overrides present")
assert.Equal(t, "ag_clone", svc.updateID)
assert.Equal(t, "Renamed", svc.updateReq.Name)
body, err := json.Marshal(svc.updateReq)
require.NoError(t, err)
var fields map[string]json.RawMessage
require.NoError(t, json.Unmarshal(body, &fields))
assert.NotContains(t, fields, "avatar", "overrides must preserve the copied avatar")
require.NotNil(t, svc.updateReq.Config)
assert.Equal(t, "model-x", svc.updateReq.Config.ModelID)
}
func TestCreate_GenerateSkeleton_NoAPICall(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeCreateSvc{}
opts := &CreateOptions{GenerateSkeleton: true}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
assert.Nil(t, svc.createReq, "must not call CreateAgent")
assert.Equal(t, "", svc.copySrcID, "must not call CopyAgent")
assert.Contains(t, out.String(), "agent_mode:", "skeleton emitted to stdout")
}
func TestCreate_RepeatedKB_ImpliesSelectedMode(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{createResp: &sdk.Agent{ID: "ag_new"}}
opts := &CreateOptions{
Name: "Test",
Model: "model-x",
KBs: []string{"kb_a", "kb_b"},
flags: createFlagSet{kbsSet: true},
}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
assert.Equal(t, []string{"kb_a", "kb_b"}, svc.createReq.Config.KnowledgeBases)
assert.Equal(t, "selected", svc.createReq.Config.KBSelectionMode, "passing --attach-kb implies selected mode")
}
func TestCreate_SystemPromptFile_ReaderRead(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{createResp: &sdk.Agent{ID: "ag_new"}}
opts := &CreateOptions{
Name: "Test",
Model: "model-x",
SystemPromptReader: strings.NewReader("You are a helpful assistant.\n"),
flags: createFlagSet{systemPromptSet: true},
}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
assert.Equal(t, "You are a helpful assistant.", svc.createReq.Config.SystemPrompt, "TrimSpace removes trailing newline")
}
func TestCreate_From_PreservesSourceFieldsNotOverridden(t *testing.T) {
// Regression: with --from X and only --temperature overridden, the
// other 33 AgentConfig fields must round-trip from the copied agent.
// Pre-fix, runCreate built `cfg` from a zero AgentConfig{} baseline,
// so UpdateAgent shipped temperature=0.9 plus every other field
// zeroed — clobbering source SystemPrompt / AgentMode / KBs.
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{
copyResp: &sdk.Agent{ID: "ag_clone", Config: &sdk.AgentConfig{
ModelID: "model-y",
SystemPrompt: "Source prompt",
AgentMode: "smart-reasoning",
Temperature: 0.5,
KnowledgeBases: []string{"kb_src_a", "kb_src_b"},
}},
updateResp: &sdk.Agent{ID: "ag_clone"},
}
// Only --temperature overridden; other fields should round-trip.
opts := &CreateOptions{
Name: "Renamed", Model: "model-y", From: "ag_source",
Temperature: 0.9,
flags: createFlagSet{temperatureSet: true},
}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
require.NotNil(t, svc.updateReq)
require.NotNil(t, svc.updateReq.Config)
assert.Equal(t, "Source prompt", svc.updateReq.Config.SystemPrompt, "source SystemPrompt must round-trip")
assert.Equal(t, "smart-reasoning", svc.updateReq.Config.AgentMode, "source AgentMode must round-trip")
assert.Equal(t, []string{"kb_src_a", "kb_src_b"}, svc.updateReq.Config.KnowledgeBases, "source KB list must round-trip when --attach-kb not passed")
assert.InDelta(t, 0.9, svc.updateReq.Config.Temperature, 0.001, "Temperature overridden")
}
func TestCreate_From_KBReplacesSourceList(t *testing.T) {
// --attach-kb on --from REPLACES the copied agent's KB list (instead of
// merging with it). The override semantic matches a from-scratch
// `agent create --attach-kb a --attach-kb b`: whatever was on the source agent is
// discarded for KBs the caller explicitly listed.
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{
copyResp: &sdk.Agent{ID: "ag_clone", Config: &sdk.AgentConfig{
ModelID: "model-y",
KnowledgeBases: []string{"kb_src_a", "kb_src_b"},
}},
updateResp: &sdk.Agent{ID: "ag_clone"},
}
opts := &CreateOptions{
Name: "X", Model: "model-y", From: "ag_source",
KBs: []string{"kb_new"},
flags: createFlagSet{kbsSet: true},
}
require.NoError(t, runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
require.NotNil(t, svc.updateReq.Config)
assert.Equal(t, []string{"kb_new"}, svc.updateReq.Config.KnowledgeBases, "--attach-kb replaces source KB list")
assert.Equal(t, "selected", svc.updateReq.Config.KBSelectionMode, "--attach-kb on --from implies selected mode")
}
func TestCreate_Temperature_Bounds(t *testing.T) {
for _, badT := range []float64{-0.1, 2.1, 100.0} {
t.Run(fmt.Sprintf("t=%g", badT), func(t *testing.T) {
cmd := NewCmdCreate(nil)
cmd.SetArgs([]string{"Test", "--model", "model-x", "--temperature", fmt.Sprintf("%f", badT)})
cmd.SilenceUsage = true
cmd.SilenceErrors = true
err := cmd.Execute()
require.Error(t, err, "expected error for --temperature %g", badT)
assert.Contains(t, err.Error(), "0.0..2.0")
})
}
}
// TestCreate_AgentModeValidation: an unknown --agent-mode / --kb-selection-mode
// is rejected up front (PreRunE) with a typed input.invalid_argument (exit 5),
// while a valid value passes the gate. The closed set is sourced from the SDK
// enumerators, so this also guards against CLI/SDK drift.
func TestCreate_AgentModeValidation(t *testing.T) {
cases := []struct {
name string
args []string
wantErr string // substring; "" means the mode gate must pass
}{
{"bad agent-mode", []string{"--agent-mode", "bogus"}, "agent-mode"},
{"bad kb-selection-mode", []string{"--kb-selection-mode", "every"}, "kb-selection-mode"},
{"valid agent-mode", []string{"--agent-mode", "smart-reasoning", "--dry-run"}, ""},
{"valid kb-selection-mode", []string{"--kb-selection-mode", "selected", "--dry-run"}, ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
_, _ = iostreams.SetForTest(t)
cmd := NewCmdCreate(nil)
cmd.SetArgs(append([]string{"Test", "--model", "model-x"}, tc.args...))
cmd.SilenceUsage, cmd.SilenceErrors = true, true
err := cmd.Execute()
if tc.wantErr == "" {
// Valid mode + --dry-run: must clear the mode gate. (--dry-run
// short-circuits before any client call, so nil factory is fine.)
require.NoError(t, err)
return
}
require.Error(t, err)
var ce *cmdutil.Error
require.ErrorAs(t, err, &ce)
assert.Equal(t, cmdutil.CodeInputInvalidArgument, ce.Code)
assert.Equal(t, 5, cmdutil.ExitCode(err))
assert.Contains(t, err.Error(), tc.wantErr)
})
}
}
func TestCreate_CopyAgent_NotFound(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeCreateSvc{copyErr: errBadHTTP404}
opts := &CreateOptions{Name: "X", Model: "model-x", From: "ag_missing"}
err := runCreate(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc)
require.Error(t, err)
assert.Contains(t, err.Error(), "resource.not_found")
}
// errBadHTTP404 simulates the SDK's "HTTP error 404: not found" format that
// ClassifyHTTPError parses. Defined here so create_test and edit_test/delete_test
// can share it via package scope without spinning up an HTTP server.
var errBadHTTP404 = &simpleErr{msg: "HTTP error 404: not found"}
type simpleErr struct{ msg string }
func (e *simpleErr) Error() string { return e.msg }
// ---------------------------------------------------------------------------
// --attach-kb (renamed from --kb)
// ---------------------------------------------------------------------------
// TestCreate_AttachKBFlagExists asserts that `--attach-kb` is a registered flag
// on `agent create` and that the old `--kb` flag no longer exists.
func TestCreate_AttachKBFlagExists(t *testing.T) {
cmd := NewCmdCreate(nil)
// --attach-kb must exist
f := cmd.Flags().Lookup("attach-kb")
require.NotNil(t, f, "--attach-kb flag must be registered on 'agent create'")
// bare --kb must NOT exist (renamed)
old := cmd.Flags().Lookup("kb")
assert.Nil(t, old, "old --kb flag must not exist on 'agent create' (renamed to --attach-kb)")
}
+121
View File
@@ -0,0 +1,121 @@
package agentcmd
import (
"context"
"fmt"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
)
// agentDeleteFields enumerates the JSON discovery fields for `agent delete`.
// Result payload is a tiny {id, deleted} object — mirrors `kb delete`.
var agentDeleteFields = []string{"id", "deleted"}
type DeleteOptions struct {
AgentID string
Yes bool // sourced from the global -y/--yes persistent flag
DryRun bool
}
// DeleteService is the narrow SDK surface this command depends on.
type DeleteService interface {
DeleteAgent(ctx context.Context, id string) error
}
// deleteResult is the typed payload emitted on success in JSON mode.
type deleteResult struct {
ID string `json:"id"`
Deleted bool `json:"deleted"`
}
// Delete is NOT idempotent on a missing id — it surfaces resource.not_found
// rather than silently exiting 0. Idempotent-already-true semantics are
// reserved for unlink-style local cleanups, not server-side resource removal.
const agentDeleteLong = `Permanently delete a custom agent.
Prompts for confirmation by default when stdout is a TTY and --format json is
not set. Pass -y/--yes (the global flag) to skip the prompt (required in
agent / CI / piped contexts).
Typed exit codes:
resource.not_found no agent with the given id (exit 4)
auth.forbidden caller lacks delete permission on the agent (exit 3)
input.confirmation_required destructive op without -y on a TTY (exit 10)
AI agents: This is a high-risk write. Without -y/--yes the CLI exits 10
and writes input.confirmation_required to stderr. NEVER auto-pass -y
without the user's explicit go-ahead — the exit-10 protocol exists
exactly to guard against unintended deletes.`
const agentDeleteExample = ` weknora agent delete ag_abc # interactive confirm
weknora agent delete ag_abc -y # no prompt
weknora agent delete ag_abc -y --format json # bare {id, deleted:true} JSON`
// NewCmdDelete builds `weknora agent delete <agent-id>`.
func NewCmdDelete(f *cmdutil.Factory) *cobra.Command {
opts := &DeleteOptions{}
cmd := &cobra.Command{
Use: "delete <agent-id>",
Short: "Delete a custom agent",
Long: agentDeleteLong,
Example: agentDeleteExample,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(cmd)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
opts.AgentID = args[0]
opts.Yes, _ = cmd.Flags().GetBool("yes")
if handled, err := cmdutil.HandleDryRun(cmd, opts.DryRun, cmdutil.DryRunPlan{
Action: "agent.delete",
Args: map[string]any{
"agent_id": opts.AgentID,
},
}); handled {
return err
}
cli, err := f.Client()
if err != nil {
return err
}
return runDelete(cmd.Context(), opts, fopts, cli, f.Prompter())
},
}
cmdutil.AddFormatFlag(cmd, agentDeleteFields...)
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
cmdutil.SetRisk(cmd, "agent.delete")
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "permanently delete a custom agent",
RequiredFlags: []string{"<agent-id> (positional)"},
Output: "envelope.data is {id, deleted:true}",
Examples: []string{
"weknora agent delete ag_abc -y",
"weknora agent delete ag_abc -y --format json",
},
Warnings: []string{
"Requires explicit user approval (exit 10 / input.confirmation_required); never auto-add -y.",
"agent delete is irreversible; loses the agent + its KB binding + custom skills.",
},
})
return cmd
}
func runDelete(ctx context.Context, opts *DeleteOptions, fopts *cmdutil.FormatOptions, svc DeleteService, p prompt.Prompter) error {
if err := cmdutil.ConfirmDestructive(p, opts.Yes, fopts.WantsJSON(), "delete", "agent", opts.AgentID, "agent.delete", []string{"weknora", "agent", "delete", opts.AgentID, "-y"}); err != nil {
return err
}
if err := svc.DeleteAgent(ctx, opts.AgentID); err != nil {
return cmdutil.WrapHTTP(err, "delete agent %s", opts.AgentID)
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, deleteResult{ID: opts.AgentID, Deleted: true}, nil)
}
fmt.Fprintf(iostreams.IO.Out, "✓ Deleted agent %s\n", opts.AgentID)
return nil
}
+107
View File
@@ -0,0 +1,107 @@
package agentcmd
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/testutil"
)
type fakeDeleteSvc struct {
gotID string
err error
}
func (f *fakeDeleteSvc) DeleteAgent(_ context.Context, id string) error {
f.gotID = id
return f.err
}
func TestDelete_NonTTY_NoYes_ExitTen(t *testing.T) {
_, _ = iostreams.SetForTest(t) // non-TTY
svc := &fakeDeleteSvc{}
err := runDelete(
context.Background(),
&DeleteOptions{AgentID: "ag_abc", Yes: false},
&cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, &testutil.ConfirmPrompter{},
)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeInputConfirmationRequired, typed.Code)
assert.Empty(t, svc.gotID, "must not call DeleteAgent without confirm")
assert.Equal(t, 10, cmdutil.ExitCode(err), "exit code 10 per destructive-write protocol")
}
func TestDelete_NonTTY_WithYes_Direct(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeDeleteSvc{}
require.NoError(t, runDelete(
context.Background(),
&DeleteOptions{AgentID: "ag_abc", Yes: true},
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{},
))
assert.Equal(t, "ag_abc", svc.gotID)
assert.Contains(t, out.String(), "ag_abc")
}
func TestDelete_404_PropagatesNotFound(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeDeleteSvc{err: errBadHTTP404}
err := runDelete(
context.Background(),
&DeleteOptions{AgentID: "ag_missing", Yes: true},
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, &testutil.ConfirmPrompter{},
)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeResourceNotFound, typed.Code)
}
func TestDelete_TTY_ConfirmYes(t *testing.T) {
_, _ = iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{Answer: true}
require.NoError(t, runDelete(
context.Background(),
&DeleteOptions{AgentID: "ag_abc"},
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p,
))
assert.True(t, p.Asked)
assert.Equal(t, "ag_abc", svc.gotID)
}
func TestDelete_TTY_ConfirmNo(t *testing.T) {
_, errBuf := iostreams.SetForTestWithTTY(t)
svc := &fakeDeleteSvc{}
p := &testutil.ConfirmPrompter{Answer: false}
err := runDelete(
context.Background(),
&DeleteOptions{AgentID: "ag_abc"},
&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, p,
)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeUserAborted, typed.Code)
assert.Empty(t, svc.gotID, "answer=no must not call DeleteAgent")
assert.Contains(t, errBuf.String(), "Aborted")
}
func TestDelete_JSON_BareObject(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeDeleteSvc{}
require.NoError(t, runDelete(
context.Background(),
&DeleteOptions{AgentID: "ag_abc", Yes: true},
&cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, &testutil.ConfirmPrompter{},
))
assert.Contains(t, out.String(), `"id":"ag_abc"`)
assert.Contains(t, out.String(), `"deleted":true`)
}
+453
View File
@@ -0,0 +1,453 @@
package agentcmd
import (
"context"
"fmt"
"io"
"sort"
"strings"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
// EditService is the narrow SDK surface this command depends on. The fetch
// half (GetAgent) is mandatory because UpdateAgent is a full PUT — without
// the pre-fetch baseline, any field not passed as a flag would silently
// clobber to the zero value.
type EditService interface {
GetAgent(ctx context.Context, id string) (*sdk.Agent, error)
UpdateAgent(ctx context.Context, id string, req *sdk.UpdateAgentRequest) (*sdk.Agent, error)
// ListModels backs --model / --rerank-model id-or-name resolution so a
// bogus name fails fast instead of clobbering config.model_id with an
// unresolvable string (which never resolves at run time).
ListModels(ctx context.Context) ([]sdk.Model, error)
}
// EditOptions captures the surgical flag state. Both string fields and
// reader-based file inputs are tracked alongside per-flag *Set bits in
// editFlagSet so empty strings are distinguishable from "unset".
type EditOptions struct {
AgentID string
Name string
Description string
Model string
SystemPrompt string
SystemPromptReader io.Reader
AgentMode string
RerankModel string
Temperature float64
AddKBs []string
RemoveKBs []string
KBSelectionMode string
ConfigFileBody io.Reader
ConfigFileKind string // "yaml" or "json"
DryRun bool
flags editFlagSet
}
// editFlagSet tracks which surgical flags the user passed. Empty-string
// values are valid (clear semantics) so cmd.Flags().Changed() is the only
// reliable signal of "user supplied this flag."
type editFlagSet struct {
nameSet bool
descriptionSet bool
modelSet bool
systemPromptSet bool
agentModeSet bool
rerankModelSet bool
temperatureSet bool
addKBsSet bool
removeKBsSet bool
kbSelectionModeSet bool
configFileSet bool
}
const agentEditLong = `Update a custom agent's fields surgically.
At least one update flag is required; flags you omit preserve the current
server-side value via fetch-then-update. Pass --description "" to clear
the description (empty string is a valid value, not "unset").
KB list operations are list-shaped: --add-kb and --remove-kb are
idempotent (re-adding an already-attached KB is silent success; removing
an unattached KB is silent success). Passing the same id to both flags
nets out to no-op and prints a stderr warning.
--config-file fully replaces the AgentConfig baseline (the same shape
GenerateAgentSkeleton emits). Surgical flags then apply on top of that
replaced baseline. To partially update one or two fields without
touching the rest, use surgical flags alone — that path L-2 fetches
current state and only mutates what's set. Precedence within a single
invocation:
surgical flag > config-file value > zero value
AI agents: this is a high-risk write. Without -y/--yes the CLI exits 10
with input.confirmation_required. Surface the prompt to the user and only
retry with -y after explicit approval. Other failure codes: resource.not_found
(agent id or KB id), auth.forbidden, input.invalid_argument (no flags, bad file).`
const agentEditExample = ` weknora agent update ag_abc --name "Renamed" -y
weknora agent update ag_abc --description "" -y # clear description
weknora agent update ag_abc --add-kb kb_new --remove-kb kb_old -y
weknora agent update ag_abc --system-prompt-file ./prompt.md -y
weknora agent update ag_abc --config-file ./tuned.yaml --temperature 0.9 -y`
// NewCmdEdit builds `weknora agent update <agent-id>`.
func NewCmdEdit(f *cmdutil.Factory) *cobra.Command {
opts := &EditOptions{}
var systemPromptFile, configFile string
cmd := &cobra.Command{
Use: "update <agent-id>",
Short: "Update a custom agent's configuration",
Long: agentEditLong,
Example: agentEditExample,
Args: cobra.ExactArgs(1),
PreRunE: func(cmd *cobra.Command, args []string) error {
opts.AgentID = args[0]
opts.flags.nameSet = cmd.Flags().Changed("name")
opts.flags.descriptionSet = cmd.Flags().Changed("description")
opts.flags.modelSet = cmd.Flags().Changed("model")
opts.flags.systemPromptSet = cmd.Flags().Changed("system-prompt") || cmd.Flags().Changed("system-prompt-file")
opts.flags.agentModeSet = cmd.Flags().Changed("agent-mode")
opts.flags.rerankModelSet = cmd.Flags().Changed("rerank-model")
opts.flags.temperatureSet = cmd.Flags().Changed("temperature")
opts.flags.addKBsSet = cmd.Flags().Changed("add-kb")
opts.flags.removeKBsSet = cmd.Flags().Changed("remove-kb")
opts.flags.kbSelectionModeSet = cmd.Flags().Changed("kb-selection-mode")
opts.flags.configFileSet = cmd.Flags().Changed("config-file")
// --temperature is bounded 0.0..2.0. Reject out-of-range
// early with a typed input.invalid_argument.
if opts.flags.temperatureSet && (opts.Temperature < 0.0 || opts.Temperature > 2.0) {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
fmt.Sprintf("--temperature must be in 0.0..2.0, got %g", opts.Temperature))
}
// Reject an unknown --agent-mode / --kb-selection-mode up front
// (typed exit 5) rather than letting the server fail the update.
if err := validateAgentModeFlags(&opts.AgentMode, &opts.KBSelectionMode); err != nil {
return err
}
if systemPromptFile != "" {
r, err := cmdutil.OpenInput(systemPromptFile)
if err != nil {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("--system-prompt-file: %v", err))
}
opts.SystemPromptReader = r
}
if configFile != "" {
r, kind, err := openConfigFile(configFile)
if err != nil {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("--config-file: %v", err))
}
opts.ConfigFileBody = r
opts.ConfigFileKind = kind
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(cmd)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
// Validate "at least one update flag" before the dry-run gate so
// --dry-run rejects identically to the live path. Same typed
// Error as runEdit (kept there for direct-call callers).
if !editHasAnyFlag(opts) {
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: "agent update requires at least one flag",
Hint: "pass at least one update flag (e.g., --name, --add-kb, --description) or --config-file",
}
}
if opts.DryRun {
planArgs := map[string]any{"agent_id": opts.AgentID}
if opts.flags.nameSet {
planArgs["name"] = opts.Name
}
if opts.flags.descriptionSet {
planArgs["description"] = opts.Description
}
if opts.flags.modelSet {
planArgs["model"] = opts.Model
}
if opts.flags.agentModeSet {
planArgs["agent_mode"] = opts.AgentMode
}
if opts.flags.rerankModelSet {
planArgs["rerank_model"] = opts.RerankModel
}
if opts.flags.temperatureSet {
planArgs["temperature"] = opts.Temperature
}
if opts.flags.addKBsSet {
planArgs["add_kb"] = opts.AddKBs
}
if opts.flags.removeKBsSet {
planArgs["remove_kb"] = opts.RemoveKBs
}
if opts.flags.kbSelectionModeSet {
planArgs["kb_selection_mode"] = opts.KBSelectionMode
}
if opts.flags.configFileSet {
planArgs["config_file"] = configFile
}
if opts.flags.systemPromptSet {
if systemPromptFile != "" {
planArgs["system_prompt_file"] = systemPromptFile
} else {
planArgs["system_prompt"] = opts.SystemPrompt
}
}
if handled, err := cmdutil.HandleDryRun(cmd, true, cmdutil.DryRunPlan{
Action: "agent.update",
Args: planArgs,
}); handled {
return err
}
}
yes, _ := cmd.Flags().GetBool("yes")
// Build the retry command from the flags the user actually passed.
// Include list-shaped and file-path flags so exit-10 retry_argv reproduces
// the original update (BuildRetryArgv expands StringSlice as repeats).
retryCmd := cmdutil.BuildRetryArgv(cmd, []string{"weknora", "agent", "update", opts.AgentID},
"name", "description", "model", "system-prompt", "system-prompt-file",
"agent-mode", "rerank-model", "temperature", "add-kb", "remove-kb",
"kb-selection-mode", "config-file", "format")
if err := cmdutil.ConfirmWrite(f.Prompter(), yes, fopts.WantsJSON(), "update", "agent", opts.AgentID, "agent.update", retryCmd); err != nil {
return err
}
cli, err := f.Client()
if err != nil {
return err
}
// Resolve --add-kb values (id or name) to canonical ids, matching
// the --kb id-or-name policy and agent create --attach-kb. Avoids
// silently attaching an unresolvable name as a kb_id.
if len(opts.AddKBs) > 0 {
resolved := make([]string, 0, len(opts.AddKBs))
for _, raw := range opts.AddKBs {
id, rerr := cmdutil.ResolveKBFlag(cmd.Context(), cli, raw)
if rerr != nil {
return rerr
}
resolved = append(resolved, id)
}
opts.AddKBs = resolved
}
return runEdit(cmd.Context(), opts, fopts, cli)
},
}
// Surgical flags
cmd.Flags().StringVar(&opts.Name, "name", "", "New agent name")
cmd.Flags().StringVar(&opts.Description, "description", "", `New description (use "" to clear)`)
cmd.Flags().StringVar(&opts.Model, "model", "", "LLM model id")
cmd.Flags().StringVar(&opts.SystemPrompt, "system-prompt", "", "System prompt text (mutex with --system-prompt-file)")
cmd.Flags().StringVar(&systemPromptFile, "system-prompt-file", "", "Read system prompt from FILE, or '-' for stdin")
cmd.MarkFlagsMutuallyExclusive("system-prompt", "system-prompt-file")
cmd.Flags().StringVar(&opts.AgentMode, "agent-mode", "", "Agent operating mode: "+strings.Join(agentModeValues, " | "))
cmd.Flags().StringVar(&opts.RerankModel, "rerank-model", "", "Rerank model id")
cmd.Flags().Float64Var(&opts.Temperature, "temperature", 0.0, "Generation temperature (0.0..2.0)")
cmd.Flags().StringSliceVar(&opts.AddKBs, "add-kb", nil, "Attach knowledge base id (repeatable, idempotent)")
cmd.Flags().StringSliceVar(&opts.RemoveKBs, "remove-kb", nil, "Detach knowledge base id (repeatable, idempotent)")
cmd.Flags().StringVar(&opts.KBSelectionMode, "kb-selection-mode", "", "KB selection mode: "+strings.Join(kbSelectionModeValues, " | "))
// Full-replace
cmd.Flags().StringVar(&configFile, "config-file", "", "Full AgentConfig YAML or JSON (REPLACES current config baseline; surgical flags then apply on top)")
cmdutil.AddFormatFlag(cmd, agentViewFields...)
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
cmdutil.SetWriteRisk(cmd, "agent.update")
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "surgically update a custom agent's configuration",
RequiredFlags: []string{"<agent-id> (positional)", "at least one update flag (--name, --add-kb, etc.)"},
Examples: []string{
"weknora agent update ag_abc --name \"Renamed\"",
"weknora agent update ag_abc --add-kb kb_new --remove-kb kb_old",
"weknora agent update ag_abc --config-file ./tuned.yaml",
},
Output: "envelope.data is the updated Agent object (id, name, config) after the update is applied",
Warnings: []string{
"Requires explicit user approval (exit 10 / input.confirmation_required); never auto-add -y.",
"agent update overwrites config; fetch-then-update protects unmentioned fields, but bad input still saved.",
},
})
return cmd
}
// editHasAnyFlag reports whether opts carries at least one surgical update
// signal. Required-flag validation lives in runEdit (not PreRunE) so unit
// tests can invoke runEdit with a hand-built EditOptions directly.
func editHasAnyFlag(opts *EditOptions) bool {
fl := opts.flags
return fl.nameSet || fl.descriptionSet || fl.modelSet || fl.systemPromptSet ||
fl.agentModeSet || fl.rerankModelSet || fl.temperatureSet ||
fl.addKBsSet || fl.removeKBsSet || fl.kbSelectionModeSet || fl.configFileSet
}
func runEdit(ctx context.Context, opts *EditOptions, fopts *cmdutil.FormatOptions, svc EditService) error {
if !editHasAnyFlag(opts) {
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: "agent update requires at least one flag",
Hint: "pass at least one update flag (e.g., --name, --add-kb, --description) or --config-file",
}
}
// Fetch-then-update so omitted fields round-trip unchanged through
// the full PUT body.
current, err := svc.GetAgent(ctx, opts.AgentID)
if err != nil {
return cmdutil.WrapHTTP(err, "fetch agent %s", opts.AgentID)
}
// Build base config: server state, then overlay --config-file (if any).
base := sdk.AgentConfig{}
if current.Config != nil {
base = *current.Config
}
if opts.ConfigFileBody != nil {
parsed, err := cmdutil.LoadAgentConfig(opts.ConfigFileBody, opts.ConfigFileKind)
if err != nil {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, err.Error())
}
base = *parsed
}
// Resolve --system-prompt-file before flag overlay.
if opts.SystemPromptReader != nil {
body, err := io.ReadAll(opts.SystemPromptReader)
if err != nil {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("--system-prompt-file read: %v", err))
}
opts.SystemPrompt = strings.TrimSpace(string(body))
}
// Resolve --model / --rerank-model (id or name) and validate they exist,
// mirroring agent create. Without this a bogus name is stored verbatim as
// config.model_id and the agent silently never resolves at run time.
if opts.flags.modelSet {
if opts.Model, err = cmdutil.ResolveModelRef(ctx, svc, opts.Model, "KnowledgeQA"); err != nil {
return err
}
}
if opts.flags.rerankModelSet {
if opts.RerankModel, err = cmdutil.ResolveModelRef(ctx, svc, opts.RerankModel, "Rerank"); err != nil {
return err
}
}
// Compute KB list from current + add/remove with a stderr warning when
// the same id appears in both flags (net no-op, still idempotent).
kbs := computeKBList(base.KnowledgeBases, opts.AddKBs, opts.RemoveKBs)
overrides := cmdutil.AgentConfigFlags{
AgentMode: opts.AgentMode, AgentModeSet: opts.flags.agentModeSet,
SystemPrompt: opts.SystemPrompt, SystemPromptSet: opts.flags.systemPromptSet,
ModelID: opts.Model, ModelIDSet: opts.flags.modelSet,
RerankModelID: opts.RerankModel, RerankModelIDSet: opts.flags.rerankModelSet,
Temperature: opts.Temperature, TemperatureSet: opts.flags.temperatureSet,
KBSelectionMode: opts.KBSelectionMode, KBSelectionModeSet: opts.flags.kbSelectionModeSet,
// KB list is always replaced (its add/remove was already merged
// into kbs); we only signal "set" when the user actually touched
// the list so a plain --name edit doesn't churn the field.
KnowledgeBases: kbs,
KnowledgeBasesSet: opts.flags.addKBsSet || opts.flags.removeKBsSet,
}
cfg := cmdutil.MergeAgentConfig(&base, overrides)
// Build the full PUT body. Name/Description default to the current
// server values so the surgical-flag-only path preserves them.
req := &sdk.UpdateAgentRequest{
Name: current.Name,
Description: current.Description,
Config: cfg,
}
if opts.flags.nameSet {
req.Name = opts.Name
}
if opts.flags.descriptionSet {
req.Description = opts.Description
}
updated, err := svc.UpdateAgent(ctx, opts.AgentID, req)
if err != nil {
return cmdutil.WrapHTTP(err, "update agent %s", opts.AgentID)
}
return emitAgent(fopts, updated)
}
// computeKBList applies --add-kb / --remove-kb to current with idempotent
// semantics. Ids present in both add and remove cancel out and surface a
// stderr warning so users notice the conflict but don't see a hard error.
// Stderr is the right channel here (not stdout) because callers piping
// --format json | jq would otherwise see corrupted JSON.
func computeKBList(current, add, remove []string) []string {
// Detect ids in both add and remove; they net out to no-op and are
// excluded from both operations.
canceledSet := map[string]struct{}{}
addSeen := map[string]struct{}{}
for _, id := range add {
addSeen[id] = struct{}{}
}
for _, id := range remove {
if _, both := addSeen[id]; both {
canceledSet[id] = struct{}{}
}
}
if len(canceledSet) > 0 {
canceled := make([]string, 0, len(canceledSet))
for id := range canceledSet {
canceled = append(canceled, id)
}
// Sort for deterministic test output; map iteration is random.
sort.Strings(canceled)
fmt.Fprintf(iostreams.IO.Err, "warning: --add-kb and --remove-kb cancel out for: %s\n", strings.Join(canceled, ", "))
}
// Compute effective remove set (excluding canceled).
removeEff := map[string]struct{}{}
for _, id := range remove {
if _, c := canceledSet[id]; c {
continue
}
removeEff[id] = struct{}{}
}
// Filter removals out of the current list (idempotent: unattached id
// simply isn't in current).
out := make([]string, 0, len(current))
for _, id := range current {
if _, drop := removeEff[id]; drop {
continue
}
out = append(out, id)
}
// Append any add ids not already present (idempotent: already-attached
// id silently de-dupes).
present := map[string]struct{}{}
for _, id := range out {
present[id] = struct{}{}
}
for _, id := range add {
if _, c := canceledSet[id]; c {
continue
}
if _, dup := present[id]; dup {
continue
}
out = append(out, id)
present[id] = struct{}{}
}
return out
}
+46
View File
@@ -0,0 +1,46 @@
package agentcmd
import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
sdk "github.com/Tencent/WeKnora/client"
)
// agentDryRunFactory builds a Factory whose Client closure panics if invoked —
// dry-run must early-exit before any SDK call.
func agentDryRunFactory(t *testing.T) *cmdutil.Factory {
t.Helper()
return &cmdutil.Factory{
Client: func() (*sdk.Client, error) {
t.Fatal("dry-run path must not call Factory.Client(); SDK side effect leaked")
return nil, nil
},
Prompter: func() prompt.Prompter {
t.Fatal("dry-run path must not call Factory.Prompter(); confirm-prompt side effect leaked")
return nil
},
}
}
// TestAgentEdit_DryRun_RejectsNoFlag: --dry-run must reject the same
// "no update flag supplied" invocation the live path rejects. Before the
// fix the editHasAnyFlag check lived in runEdit() (live-only), reached only
// after HandleDryRun early-exited.
func TestAgentEdit_DryRun_RejectsNoFlag(t *testing.T) {
iostreams.SetForTest(t)
f := agentDryRunFactory(t)
root := withRootHarnessAgent(NewCmdEdit(f), "ag_abc", "--dry-run", "--format", "json")
err := root.Execute()
require.Error(t, err, "dry-run must reject identically to live path")
var typed *cmdutil.Error
require.True(t, errors.As(err, &typed), "expected *cmdutil.Error, got %T %v", err, err)
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)
}
+361
View File
@@ -0,0 +1,361 @@
package agentcmd
import (
"bytes"
"context"
"encoding/json"
"fmt"
"strings"
"testing"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
sdk "github.com/Tencent/WeKnora/client"
)
// fakeEditSvc scripts GetAgent (fetch baseline) + UpdateAgent (apply
// surgical overlays). updateCalls lets tests verify that no-flag invocations
// don't reach the wire.
type fakeEditSvc struct {
getResp *sdk.Agent
getErr error
updateReq *sdk.UpdateAgentRequest
updateID string
updateResp *sdk.Agent
updateErr error
updateCalls int
models []sdk.Model
modelsErr error
}
func (f *fakeEditSvc) GetAgent(_ context.Context, _ string) (*sdk.Agent, error) {
return f.getResp, f.getErr
}
func (f *fakeEditSvc) UpdateAgent(_ context.Context, id string, req *sdk.UpdateAgentRequest) (*sdk.Agent, error) {
f.updateReq = req
f.updateID = id
f.updateCalls++
return f.updateResp, f.updateErr
}
func (f *fakeEditSvc) ListModels(_ context.Context) ([]sdk.Model, error) {
return f.models, f.modelsErr
}
func TestEdit_ModelName_ResolvedToID(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeEditSvc{
getResp: &sdk.Agent{ID: "ag_abc", Name: "A", Config: &sdk.AgentConfig{ModelID: "old-id"}},
updateResp: &sdk.Agent{ID: "ag_abc"},
models: []sdk.Model{{ID: "m-real", Name: "good-llm", Type: "KnowledgeQA"}},
}
opts := &EditOptions{AgentID: "ag_abc", Model: "good-llm", flags: editFlagSet{modelSet: true}}
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
require.NotNil(t, svc.updateReq)
require.NotNil(t, svc.updateReq.Config)
assert.Equal(t, "m-real", svc.updateReq.Config.ModelID, "--model name must resolve to the model id")
}
func TestEdit_BogusModelName_RejectedNoWrite(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeEditSvc{
getResp: &sdk.Agent{ID: "ag_abc", Name: "A", Config: &sdk.AgentConfig{ModelID: "old-id"}},
updateResp: &sdk.Agent{ID: "ag_abc"},
models: []sdk.Model{{ID: "m-real", Name: "good-llm", Type: "KnowledgeQA"}},
}
opts := &EditOptions{AgentID: "ag_abc", Model: "totally-bogus-model-xyz", flags: editFlagSet{modelSet: true}}
err := runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc)
require.Error(t, err, "a --model name matching no model must fail")
var e *cmdutil.Error
require.ErrorAs(t, err, &e)
assert.Equal(t, cmdutil.CodeResourceNotFound, e.Code)
assert.Equal(t, 0, svc.updateCalls, "must not write an agent with an unresolvable model")
}
func TestEdit_FetchThenUpdate_PreservesUntouchedFields(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeEditSvc{
getResp: &sdk.Agent{
ID: "ag_abc", Name: "Original", Description: "Keep me", Avatar: "🤖",
Config: &sdk.AgentConfig{ModelID: "model-x", Temperature: 0.7, KnowledgeBases: []string{"kb_a"}},
},
updateResp: &sdk.Agent{ID: "ag_abc"},
}
// Only --description passed; everything else should round-trip.
opts := &EditOptions{
AgentID: "ag_abc",
Description: "Updated",
flags: editFlagSet{descriptionSet: true},
}
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
require.NotNil(t, svc.updateReq)
assert.Equal(t, "Original", svc.updateReq.Name, "Name must round-trip unchanged")
assert.Equal(t, "Updated", svc.updateReq.Description)
body, err := json.Marshal(svc.updateReq)
require.NoError(t, err)
var fields map[string]json.RawMessage
require.NoError(t, json.Unmarshal(body, &fields))
assert.NotContains(t, fields, "avatar", "an unrelated edit must not clear the avatar")
require.NotNil(t, svc.updateReq.Config)
assert.Equal(t, "model-x", svc.updateReq.Config.ModelID, "ModelID must round-trip")
assert.Equal(t, []string{"kb_a"}, svc.updateReq.Config.KnowledgeBases, "KBs must round-trip")
assert.InDelta(t, 0.7, svc.updateReq.Config.Temperature, 0.001)
}
func TestEdit_AddRemoveKB_SameID_NetNoOpWithWarning(t *testing.T) {
_, errBuf := iostreams.SetForTest(t)
svc := &fakeEditSvc{
getResp: &sdk.Agent{Config: &sdk.AgentConfig{KnowledgeBases: []string{"kb_a"}}},
updateResp: &sdk.Agent{},
}
opts := &EditOptions{
AgentID: "ag_abc",
AddKBs: []string{"kb_b"},
RemoveKBs: []string{"kb_b"},
flags: editFlagSet{addKBsSet: true, removeKBsSet: true},
}
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
assert.Equal(t, []string{"kb_a"}, svc.updateReq.Config.KnowledgeBases, "net no-op preserves original list")
assert.Contains(t, errBuf.String(), "cancel out", "warning emitted to stderr")
}
func TestEdit_NoFlags_InvalidArgument(t *testing.T) {
svc := &fakeEditSvc{}
err := runEdit(context.Background(), &EditOptions{AgentID: "ag_abc"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)
assert.Equal(t, 0, svc.updateCalls, "must not call UpdateAgent")
}
func TestEdit_AddKB_AlreadyAttached_Silent(t *testing.T) {
_, errBuf := iostreams.SetForTest(t)
svc := &fakeEditSvc{
getResp: &sdk.Agent{Config: &sdk.AgentConfig{KnowledgeBases: []string{"kb_a", "kb_b"}}},
updateResp: &sdk.Agent{},
}
opts := &EditOptions{
AgentID: "ag_abc",
AddKBs: []string{"kb_a"}, // already attached
flags: editFlagSet{addKBsSet: true},
}
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
assert.Equal(t, []string{"kb_a", "kb_b"}, svc.updateReq.Config.KnowledgeBases, "no duplicate")
assert.NotContains(t, errBuf.String(), "warning", "already-attached is silent success")
}
func TestEdit_RemoveKB_Unattached_Silent(t *testing.T) {
_, errBuf := iostreams.SetForTest(t)
svc := &fakeEditSvc{
getResp: &sdk.Agent{Config: &sdk.AgentConfig{KnowledgeBases: []string{"kb_a"}}},
updateResp: &sdk.Agent{},
}
opts := &EditOptions{
AgentID: "ag_abc",
RemoveKBs: []string{"kb_zzz"},
flags: editFlagSet{removeKBsSet: true},
}
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
assert.Equal(t, []string{"kb_a"}, svc.updateReq.Config.KnowledgeBases)
assert.NotContains(t, errBuf.String(), "warning")
}
func TestEdit_ClearDescription_EmptyString(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeEditSvc{
getResp: &sdk.Agent{Name: "X", Description: "old", Config: &sdk.AgentConfig{ModelID: "m"}},
updateResp: &sdk.Agent{},
}
opts := &EditOptions{
AgentID: "ag_abc",
Description: "",
flags: editFlagSet{descriptionSet: true},
}
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
assert.Equal(t, "", svc.updateReq.Description, "explicit empty must clear server-side")
assert.Equal(t, "X", svc.updateReq.Name, "Name round-trip unchanged")
}
func TestEdit_ConfigFile_OverridesByFlag(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeEditSvc{
getResp: &sdk.Agent{
Name: "X",
Config: &sdk.AgentConfig{ModelID: "old-model", Temperature: 0.1},
},
updateResp: &sdk.Agent{},
}
opts := &EditOptions{
AgentID: "ag_abc",
Temperature: 0.9,
ConfigFileBody: bytes.NewBufferString(`{"temperature":0.5,"model_id":"file-model"}`),
ConfigFileKind: "json",
flags: editFlagSet{temperatureSet: true, configFileSet: true},
}
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
require.NotNil(t, svc.updateReq.Config)
assert.Equal(t, "file-model", svc.updateReq.Config.ModelID, "file overrides current state")
assert.InDelta(t, 0.9, svc.updateReq.Config.Temperature, 0.001, "flag overrides file")
}
// TestEdit_ConfigFile_FullReplacesBaseline pins the documented behavior:
// --config-file fully replaces the AgentConfig baseline; current-server
// fields not mentioned in the file are zeroed. The Long help directs
// users to surgical flags when they want a partial update.
func TestEdit_ConfigFile_FullReplacesBaseline(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeEditSvc{
getResp: &sdk.Agent{
Name: "X",
Config: &sdk.AgentConfig{
SystemPrompt: "Existing prompt",
ModelID: "old-model",
Temperature: 0.1,
AgentMode: "smart-reasoning",
KnowledgeBases: []string{"kb_existing"},
},
},
updateResp: &sdk.Agent{},
}
opts := &EditOptions{
AgentID: "ag_abc",
ConfigFileBody: bytes.NewBufferString(`{"model_id":"file-only"}`),
ConfigFileKind: "json",
flags: editFlagSet{configFileSet: true},
}
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
require.NotNil(t, svc.updateReq.Config)
assert.Equal(t, "file-only", svc.updateReq.Config.ModelID, "file's model_id applied")
assert.Equal(t, "", svc.updateReq.Config.SystemPrompt, "file fully replaces baseline; unset fields are zeroed")
assert.InDelta(t, 0.0, svc.updateReq.Config.Temperature, 0.001, "unset fields zeroed")
assert.Equal(t, "", svc.updateReq.Config.AgentMode, "unset fields zeroed")
assert.Empty(t, svc.updateReq.Config.KnowledgeBases, "unset fields zeroed")
}
func TestEdit_NotFound(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeEditSvc{getErr: errBadHTTP404}
opts := &EditOptions{AgentID: "ag_missing", Name: "x", flags: editFlagSet{nameSet: true}}
err := runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc)
require.Error(t, err)
assert.Contains(t, err.Error(), "resource.not_found")
}
func TestEdit_AddKB_AppendsToExisting(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeEditSvc{
getResp: &sdk.Agent{Config: &sdk.AgentConfig{KnowledgeBases: []string{"kb_a"}}},
updateResp: &sdk.Agent{},
}
opts := &EditOptions{
AgentID: "ag_abc",
AddKBs: []string{"kb_b", "kb_c"},
flags: editFlagSet{addKBsSet: true},
}
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
assert.Equal(t, []string{"kb_a", "kb_b", "kb_c"}, svc.updateReq.Config.KnowledgeBases)
}
func TestEdit_Temperature_Bounds(t *testing.T) {
for _, badT := range []float64{-0.1, 2.1, 100.0} {
t.Run(fmt.Sprintf("t=%g", badT), func(t *testing.T) {
cmd := NewCmdEdit(nil)
cmd.SetArgs([]string{"ag_abc", "--temperature", fmt.Sprintf("%f", badT)})
cmd.SilenceUsage = true
cmd.SilenceErrors = true
err := cmd.Execute()
require.Error(t, err, "expected error for --temperature %g", badT)
assert.Contains(t, err.Error(), "0.0..2.0")
})
}
}
func TestEdit_SystemPromptFile(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeEditSvc{
getResp: &sdk.Agent{Config: &sdk.AgentConfig{ModelID: "m"}},
updateResp: &sdk.Agent{},
}
opts := &EditOptions{
AgentID: "ag_abc",
SystemPromptReader: strings.NewReader("new prompt\n"),
flags: editFlagSet{systemPromptSet: true},
}
require.NoError(t, runEdit(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc))
assert.Equal(t, "new prompt", svc.updateReq.Config.SystemPrompt)
}
// withRootHarnessAgent wraps `weknora agent update ...` under a synthetic root
// cmd that registers the global persistent flags (mirrors addGlobalFlags in
// cmd/root.go).
func withRootHarnessAgent(edit *cobra.Command, args ...string) *cobra.Command {
root := &cobra.Command{Use: "weknora"}
pf := root.PersistentFlags()
pf.BoolP("yes", "y", false, "")
pf.String("format", "", "Output format: text | json | ndjson")
pf.StringP("jq", "q", "", "")
ag := &cobra.Command{Use: "agent"}
ag.AddCommand(edit)
root.AddCommand(ag)
root.SetArgs(append([]string{"agent", "update"}, args...))
root.SetContext(context.Background())
root.SilenceErrors = true
root.SilenceUsage = true
return root
}
// TestAgentEdit_RequiresConfirmation asserts that without -y (non-TTY / JSON
// mode), agent update returns input.confirmation_required (exit 10).
func TestAgentEdit_RequiresConfirmation(t *testing.T) {
iostreams.SetForTest(t) // non-TTY
f := &cmdutil.Factory{
Client: func() (*sdk.Client, error) { return nil, nil },
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
}
root := withRootHarnessAgent(NewCmdEdit(f), "ag_abc", "--name", "Renamed", "--format", "json")
err := root.Execute()
require.Error(t, err)
var ce *cmdutil.Error
require.ErrorAs(t, err, &ce)
assert.Equal(t, cmdutil.CodeInputConfirmationRequired, ce.Code)
assert.Equal(t, 10, cmdutil.ExitCode(err), "exit code 10 per destructive-write protocol")
// retry argv must include -y and the agent id
assert.Contains(t, ce.RetryArgv, "-y")
assert.Contains(t, ce.RetryArgv, "ag_abc")
}
// TestAgentEdit_RetryArgvPreservesAddKB is a regression for #2597: exit-10
// retry_argv must keep --add-kb / --remove-kb / --config-file so re-running
// after human approval reproduces the original update.
func TestAgentEdit_RetryArgvPreservesAddKB(t *testing.T) {
iostreams.SetForTest(t) // non-TTY
f := &cmdutil.Factory{
Client: func() (*sdk.Client, error) { return nil, nil },
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
}
// Avoid --config-file / --system-prompt-file here: PreRunE opens paths and
// would fail before ConfirmWrite. Those flags still go through the same
// BuildRetryArgv scalar path covered in cmdutil tests.
root := withRootHarnessAgent(NewCmdEdit(f),
"ag_abc", "--add-kb", "kb_new", "--remove-kb", "kb_old", "--format", "json")
err := root.Execute()
require.Error(t, err)
var ce *cmdutil.Error
require.ErrorAs(t, err, &ce)
assert.Equal(t, cmdutil.CodeInputConfirmationRequired, ce.Code)
// pflag Visit is lexicographical among changed flags.
assert.Equal(t, []string{
"weknora", "agent", "update", "ag_abc",
"--add-kb", "kb_new",
"--format", "json",
"--remove-kb", "kb_old",
"-y",
}, ce.RetryArgv)
}
+145
View File
@@ -0,0 +1,145 @@
package agentcmd
import (
"context"
"fmt"
"sort"
"text/tabwriter"
"time"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/output"
"github.com/Tencent/WeKnora/cli/internal/text"
sdk "github.com/Tencent/WeKnora/client"
)
// agentListFields enumerates the fields surfaced for `--format json` discovery
// on `agent list`. Mirrors the json tags on sdk.Agent - nested Config is
// omitted because its sub-fields make filtering noisy (use `--jq` instead).
var agentListFields = []string{
"id", "name", "description", "avatar",
"is_builtin", "tenant_id", "created_by",
"created_at", "updated_at",
}
// ListService is the narrow SDK surface this command depends on.
type ListService interface {
ListAgents(ctx context.Context) ([]sdk.Agent, error)
}
// ListOptions captures `agent list` filter flag state.
type ListOptions struct {
// Limit caps the returned slice client-side. 0 = no cap, 1..10000 = explicit.
// The agent list SDK is unpaginated; --all-pages is intentionally not
// exposed because it would be a no-op.
Limit int
}
// NewCmdList builds `weknora agent list`.
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
opts := &ListOptions{}
cmd := &cobra.Command{
Use: "list",
Short: "List custom agents visible to the active tenant",
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
// Validate static input before building the client so a bad --limit
// returns input.invalid_argument (exit 5), not an auth error (exit 3).
if err := validateListOpts(opts); err != nil {
return err
}
cli, err := f.Client()
if err != nil {
return err
}
return runList(c.Context(), opts, fopts, cli)
},
}
cmd.Flags().IntVarP(&opts.Limit, "limit", "L", 30, "Maximum results to return — client-side cap; meta.has_more/total_count report the full size (1..10000)")
cmdutil.AddFormatFlag(cmd, agentListFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "List custom agents visible to the active tenant. The SDK returns all agents in one call (no server-side pagination); meta.count reflects the full tenant set, --limit caps client-side.",
Examples: []string{"weknora agent list --format json", "weknora agent list --limit 10 --format json"},
Output: "envelope.data is an array of Agent objects with id, name, is_builtin; meta.total_count is the full tenant set and meta.has_more=true means --limit truncated it (raise --limit to get the rest)",
})
return cmd
}
// validateListOpts checks --limit. Called from RunE before the client is built
// (so a bad value surfaces as exit 5, not an auth error) and at runList's top
// for direct callers; idempotent and nil-safe.
func validateListOpts(opts *ListOptions) error {
if opts == nil {
return nil
}
if opts.Limit < 1 || opts.Limit > 10000 {
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: fmt.Sprintf("--limit must be in 1..10000, got %d", opts.Limit),
}
}
return nil
}
func runList(ctx context.Context, opts *ListOptions, fopts *cmdutil.FormatOptions, svc ListService) error {
if opts == nil {
opts = &ListOptions{}
}
if err := validateListOpts(opts); err != nil {
return err
}
items, err := svc.ListAgents(ctx)
if err != nil {
return cmdutil.WrapHTTP(err, "list agents")
}
if items == nil {
items = []sdk.Agent{} // ensure JSON [] not null
}
// Default sort: updated_at desc - most recently-edited agents surface
// first. Mirrors kb list / doc list behavior.
sort.Slice(items, func(i, j int) bool {
return items[i].UpdatedAt.After(items[j].UpdatedAt)
})
// The agent list SDK is unpaginated — it returns every agent in one
// call — so the CLI holds the true total and can tell the caller
// whether the client-side --limit dropped any. total_count is the full
// count; has_more flags that --limit truncated it (raise --limit to get
// the rest — there is no server cursor to continue with).
total := len(items)
truncated := false
if opts.Limit > 0 && len(items) > opts.Limit {
items = items[:opts.Limit]
truncated = true
}
if fopts.WantsJSON() {
meta := &output.Meta{Count: output.IntPtr(len(items)), HasMore: truncated, TotalCount: output.IntPtr(total)}
return fopts.Emit(iostreams.IO.Out, items, meta)
}
if len(items) == 0 {
fmt.Fprintln(iostreams.IO.Out, "(no agents)")
return nil
}
tw := tabwriter.NewWriter(iostreams.IO.Out, 0, 0, 2, ' ', 0)
fmt.Fprintln(tw, "ID\tNAME\tBUILTIN\tUPDATED")
now := time.Now()
for _, a := range items {
name := text.Truncate(40, a.Name)
builtin := "-"
if a.IsBuiltin {
builtin = "yes"
}
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\n", a.ID, name, builtin, text.FuzzyAgo(now, a.UpdatedAt))
}
return tw.Flush()
}
+205
View File
@@ -0,0 +1,205 @@
package agentcmd
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"testing"
"time"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
type fakeListSvc struct {
items []sdk.Agent
err error
}
func (f *fakeListSvc) ListAgents(_ context.Context) ([]sdk.Agent, error) {
return f.items, f.err
}
func TestList_Empty_Text(t *testing.T) {
out, _ := iostreams.SetForTest(t)
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{}); err != nil {
t.Fatalf("runList: %v", err)
}
if !strings.Contains(out.String(), "(no agents)") {
t.Errorf("expected '(no agents)', got %q", out.String())
}
}
func TestList_Empty_JSON(t *testing.T) {
out, _ := iostreams.SetForTest(t)
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeListSvc{}); err != nil {
t.Fatalf("runList: %v", err)
}
var env struct {
OK bool `json:"ok"`
Data []sdk.Agent `json:"data"`
}
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
t.Fatalf("parse envelope: %v\n%s", err, out.String())
}
if !env.OK {
t.Error("envelope.ok=false")
}
if len(env.Data) != 0 {
t.Errorf("expected empty data, got %d items", len(env.Data))
}
}
func TestList_NonEmpty_Text_RendersColumns(t *testing.T) {
out, _ := iostreams.SetForTest(t)
now := time.Now()
items := []sdk.Agent{
{ID: "ag_a", Name: "Research", IsBuiltin: true, UpdatedAt: now.Add(-1 * time.Hour)},
{ID: "ag_b", Name: "Triage", UpdatedAt: now.Add(-3 * 24 * time.Hour)},
}
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: items}); err != nil {
t.Fatalf("runList: %v", err)
}
got := out.String()
for _, w := range []string{"ID", "NAME", "BUILTIN", "ag_a", "Research", "yes", "ag_b", "Triage"} {
if !strings.Contains(got, w) {
t.Errorf("output missing %q in:\n%s", w, got)
}
}
}
func TestList_NonEmpty_JSON_SortsByUpdatedAtDesc(t *testing.T) {
out, _ := iostreams.SetForTest(t)
now := time.Now()
items := []sdk.Agent{
{ID: "ag_old", Name: "old", UpdatedAt: now.Add(-7 * 24 * time.Hour)},
{ID: "ag_new", Name: "new", UpdatedAt: now},
{ID: "ag_mid", Name: "mid", UpdatedAt: now.Add(-1 * time.Hour)},
}
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeListSvc{items: items}); err != nil {
t.Fatalf("runList: %v", err)
}
var env struct {
OK bool `json:"ok"`
Data []sdk.Agent `json:"data"`
}
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
t.Fatalf("parse: %v", err)
}
got := env.Data
if len(got) != 3 {
t.Fatalf("len = %d, want 3", len(got))
}
wantOrder := []string{"ag_new", "ag_mid", "ag_old"}
for i, w := range wantOrder {
if got[i].ID != w {
t.Errorf("position %d: got %s, want %s (updated_at desc)", i, got[i].ID, w)
}
}
}
func TestList_JSON_JQProjection(t *testing.T) {
out, _ := iostreams.SetForTest(t)
items := []sdk.Agent{
{ID: "ag_x", Name: "Foo", Description: "long description"},
}
// --jq projects from the envelope; .data[] | ... extracts from the array inside envelope.
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, JQ: ".data[] | {id, name}"}
if err := runList(context.Background(), &ListOptions{Limit: 30}, fopts, &fakeListSvc{items: items}); err != nil {
t.Fatalf("runList: %v", err)
}
var got map[string]any
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
t.Fatalf("parse: %v", err)
}
if _, has := got["description"]; has {
t.Errorf("description should be filtered out: %+v", got)
}
}
// makeAgents returns N Agents with distinct IDs and descending UpdatedAt.
func makeAgents(n int) []sdk.Agent {
base := time.Now()
out := make([]sdk.Agent, n)
for i := 0; i < n; i++ {
out[i] = sdk.Agent{
ID: fmt.Sprintf("ag_%02d", i),
Name: fmt.Sprintf("name-%02d", i),
UpdatedAt: base.Add(-time.Duration(i) * time.Hour),
}
}
return out
}
func TestList_Limit_CapsResults(t *testing.T) {
out, _ := iostreams.SetForTest(t)
if err := runList(context.Background(), &ListOptions{Limit: 5}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeListSvc{items: makeAgents(20)}); err != nil {
t.Fatalf("runList: %v", err)
}
got := strings.Count(out.String(), `"id":"ag_`)
if got != 5 {
t.Errorf("--limit 5 must slice 20 down to 5; got %d", got)
}
}
// TestList_Truncation_SignalsHasMoreAndTotal pins that --limit truncation
// tells the agent it did not get everything (has_more + total_count).
// Regression: agent list silently dropped agents past --limit with no signal.
func TestList_Truncation_SignalsHasMoreAndTotal(t *testing.T) {
out, _ := iostreams.SetForTest(t)
if err := runList(context.Background(), &ListOptions{Limit: 5}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeListSvc{items: makeAgents(20)}); err != nil {
t.Fatalf("runList: %v", err)
}
if !strings.Contains(out.String(), `"has_more":true`) {
t.Errorf("truncated list must set has_more:true; got:\n%s", out.String())
}
if !strings.Contains(out.String(), `"total_count":20`) {
t.Errorf("truncated list must report total_count:20; got:\n%s", out.String())
}
}
func TestList_NoTruncation_OmitsHasMore(t *testing.T) {
out, _ := iostreams.SetForTest(t)
if err := runList(context.Background(), &ListOptions{Limit: 30}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeListSvc{items: makeAgents(3)}); err != nil {
t.Fatalf("runList: %v", err)
}
if strings.Contains(out.String(), `"has_more"`) {
t.Errorf("non-truncated list must omit has_more; got:\n%s", out.String())
}
if !strings.Contains(out.String(), `"total_count":3`) {
t.Errorf("list must report total_count:3; got:\n%s", out.String())
}
}
func TestList_Limit_Zero_Rejected(t *testing.T) {
_, _ = iostreams.SetForTest(t)
err := runList(context.Background(), &ListOptions{Limit: 0}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, &fakeListSvc{items: makeAgents(7)})
if err == nil {
t.Fatal("expected error for --limit 0")
}
var typed *cmdutil.Error
if !errors.As(err, &typed) {
t.Fatalf("expected *cmdutil.Error, got %T: %v", err, err)
}
if typed.Code != cmdutil.CodeInputInvalidArgument {
t.Errorf("expected CodeInputInvalidArgument, got %v", typed.Code)
}
}
func TestList_Limit_Negative_Rejected(t *testing.T) {
_, _ = iostreams.SetForTest(t)
err := runList(context.Background(), &ListOptions{Limit: -1}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &fakeListSvc{items: makeAgents(2)})
if err == nil {
t.Fatal("expected error for negative --limit")
}
var typed *cmdutil.Error
if !errors.As(err, &typed) {
t.Fatalf("expected *cmdutil.Error, got %T: %v", err, err)
}
if typed.Code != cmdutil.CodeInputInvalidArgument {
t.Errorf("expected CodeInputInvalidArgument, got %v", typed.Code)
}
}
+117
View File
@@ -0,0 +1,117 @@
package agentcmd
import (
"context"
"fmt"
"io"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
// AgentStatusResult is the shallow health snapshot for `agent status <id>`.
//
// One HTTP call: reachable + model_id. For downstream KB reachability
// verification use 'agent check <id>' (1 + N HTTP).
//
// model_reachable is intentionally OMITTED: the server has no per-agent
// test endpoint, so we cannot verify model reachability from the agent
// resource alone.
type AgentStatusResult struct {
ID string `json:"id"`
Reachable bool `json:"reachable"`
ModelID string `json:"model_id,omitempty"`
}
// AgentStatusService is the narrow SDK surface needed for agent status.
type AgentStatusService interface {
GetAgent(ctx context.Context, id string) (*sdk.Agent, error)
}
var agentStatusFields = []string{"id", "reachable", "model_id"}
func NewCmdStatus(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "status <agent-id>",
Short: "Show health status of a custom agent",
Long: `Shallow health snapshot for an agent (1 HTTP call).
Returns: reachable / model_id.
For downstream KB reachability verification use 'weknora agent check <id>'
(active verification, 1 + N HTTP). For full agent config / metadata use
'weknora agent view <id>'.`,
Example: ` weknora agent status ag_abc
weknora agent status ag_abc --format json`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
cli, err := f.Client()
if err != nil {
return err
}
res, err := runAgentStatus(c.Context(), cli, args[0])
if err != nil {
return err
}
return emitAgentStatus(res, fopts, iostreams.IO.Out)
},
}
cmdutil.AddFormatFlag(cmd, agentStatusFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "shallow health probe of a custom agent: reachability without kb_scope verification",
RequiredFlags: []string{"<agent-id> (positional)"},
Examples: []string{"weknora agent status agent_abc"},
Output: "envelope.data is {id, reachable, ...}; use `agent check` for deep kb_scope verification",
})
return cmd
}
// runAgentStatus is the testable core. Never errors for "agent not
// reachable" — Reachable=false carries that signal.
func runAgentStatus(ctx context.Context, svc AgentStatusService, id string) (*AgentStatusResult, error) {
a, err := svc.GetAgent(ctx, id)
if err != nil {
return &AgentStatusResult{ID: id, Reachable: false}, nil
}
res := &AgentStatusResult{ID: a.ID, Reachable: true}
if a.Config != nil {
res.ModelID = a.Config.ModelID
}
return res, nil
}
// emitAgentStatus renders res per --format. Mirrors emitStatus pattern from
// cli/cmd/kb/status.go (C3).
func emitAgentStatus(res *AgentStatusResult, fopts *cmdutil.FormatOptions, w io.Writer) error {
switch fopts.Mode {
case cmdutil.FormatJSON, cmdutil.FormatNDJSON:
return fopts.Emit(w, res, nil)
case cmdutil.FormatText, "":
return writeAgentStatusText(w, res)
default:
return fmt.Errorf("unsupported --format %q for agent status", fopts.Mode)
}
}
func writeAgentStatusText(w io.Writer, res *AgentStatusResult) error {
fmt.Fprintf(w, "ID: %s\n", res.ID)
fmt.Fprintf(w, "Reachable: %v\n", res.Reachable)
if !res.Reachable {
return nil
}
if res.ModelID != "" {
fmt.Fprintf(w, "Model: %s\n", res.ModelID)
}
return nil
}
// compile-time check: SDK client satisfies AgentStatusService.
var _ AgentStatusService = (*sdk.Client)(nil)
+108
View File
@@ -0,0 +1,108 @@
package agentcmd
import (
"bytes"
"context"
"encoding/json"
"fmt"
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
sdk "github.com/Tencent/WeKnora/client"
)
type fakeAgentStatusSvc struct {
agent *sdk.Agent
agentErr error
}
func (f *fakeAgentStatusSvc) GetAgent(_ context.Context, id string) (*sdk.Agent, error) {
if f.agentErr != nil {
return nil, f.agentErr
}
return f.agent, nil
}
func TestRunAgentStatus_ShallowFields(t *testing.T) {
svc := &fakeAgentStatusSvc{agent: &sdk.Agent{
ID: "ag_x",
Config: &sdk.AgentConfig{
ModelID: "m_x",
KnowledgeBases: []string{"kb_a", "kb_b"},
},
}}
res, err := runAgentStatus(context.Background(), svc, "ag_x")
if err != nil {
t.Fatalf("%v", err)
}
if !res.Reachable {
t.Error("Reachable=false, want true")
}
if res.ModelID != "m_x" {
t.Errorf("ModelID=%q, want m_x", res.ModelID)
}
}
func TestRunAgentStatus_Unreachable(t *testing.T) {
svc := &fakeAgentStatusSvc{agentErr: fmt.Errorf("404")}
res, err := runAgentStatus(context.Background(), svc, "ag_x")
if err != nil {
t.Fatalf("%v", err)
}
if res.Reachable {
t.Error("Reachable=true on 404; want false")
}
if res.ID != "ag_x" {
t.Errorf("ID=%q, want ag_x (echoed even on unreachable)", res.ID)
}
}
func TestRunAgentStatus_NilConfig(t *testing.T) {
// Defensive: Agent.Config is a pointer; nil should not panic
svc := &fakeAgentStatusSvc{agent: &sdk.Agent{ID: "ag_x", Config: nil}}
res, err := runAgentStatus(context.Background(), svc, "ag_x")
if err != nil {
t.Fatalf("%v", err)
}
if !res.Reachable {
t.Error("Reachable=false, want true on nil config")
}
if res.ModelID != "" {
t.Errorf("ModelID=%q, want empty (no config)", res.ModelID)
}
}
func TestEmitAgentStatus_JSON(t *testing.T) {
var buf bytes.Buffer
res := &AgentStatusResult{ID: "ag_x", Reachable: true, ModelID: "m_x"}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
if err := emitAgentStatus(res, fopts, &buf); err != nil {
t.Fatalf("%v", err)
}
var env struct {
OK bool `json:"ok"`
Data AgentStatusResult `json:"data"`
}
if err := json.Unmarshal(buf.Bytes(), &env); err != nil {
t.Fatalf("%v", err)
}
got := env.Data
if got.ModelID != "m_x" {
t.Errorf("ModelID=%q, want m_x", got.ModelID)
}
}
func TestEmitAgentStatus_Text(t *testing.T) {
var buf bytes.Buffer
res := &AgentStatusResult{ID: "ag_x", Reachable: true, ModelID: "m_x"}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
if err := emitAgentStatus(res, fopts, &buf); err != nil {
t.Fatalf("%v", err)
}
for _, want := range []string{"ag_x", "m_x", "true"} {
if !strings.Contains(buf.String(), want) {
t.Errorf("output missing %q:\n%s", want, buf.String())
}
}
}
+291
View File
@@ -0,0 +1,291 @@
package agentcmd
import (
"context"
"fmt"
"io"
"strings"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/text"
sdk "github.com/Tencent/WeKnora/client"
)
// promptPreviewWidth caps inline KV row prompt previews. Multi-line prompts
// collapse to one line via text.OneLine; the Templates section gets the
// full multi-line treatment instead.
const promptPreviewWidth = 80
// agentViewFields enumerates the top-level Agent keys surfaced in `--help`
// as a hint for `--jq` projection. Nested AgentConfig fields are reachable
// via `--jq '.config.system_prompt'` or by selecting `config` whole and
// post-processing.
var agentViewFields = []string{
"id", "name", "description", "avatar",
"is_builtin", "tenant_id", "created_by", "config",
"created_at", "updated_at",
}
// ViewService is the narrow SDK surface this command depends on.
type ViewService interface {
GetAgent(ctx context.Context, agentID string) (*sdk.Agent, error)
}
// NewCmdView builds `weknora agent view <agent-id>`.
func NewCmdView(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "view <agent-id>",
Short: "Show a custom agent's configuration",
Long: `Renders the agent's metadata and full AgentConfig as grouped KV
sections (Identity / LLM / KB attachment / Retrieval / Query rewrite /
Tools / FAQ / Web search / Multi-turn / Fallback / Templates). Zero-value
fields are omitted; sections with no set fields are suppressed entirely.
Pass --format json for the bare SDK Agent object (config nested, not flattened).
Use --jq to project specific fields or reach into nested config.`,
Example: ` weknora agent view ag_abc
weknora agent view ag_abc --format json --jq '{id, name, config}' # top-level projection
weknora agent view ag_abc --format json --jq '.config.system_prompt'`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
cli, err := f.Client()
if err != nil {
return err
}
return runView(c.Context(), fopts, cli, args[0])
},
}
cmdutil.AddFormatFlag(cmd, agentViewFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "fetch one custom agent's full configuration by id",
RequiredFlags: []string{"<agent-id> (positional)"},
Examples: []string{"weknora agent view agent_abc"},
Output: "envelope.data is the custom agent (id, name, description, is_builtin, and a nested config object holding model/kb_scope/...)",
})
return cmd
}
func runView(ctx context.Context, fopts *cmdutil.FormatOptions, svc ViewService, agentID string) error {
a, err := svc.GetAgent(ctx, agentID)
if err != nil {
return cmdutil.WrapHTTP(err, "fetch agent %s", agentID)
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, a, nil)
}
renderAgent(iostreams.IO.Out, a)
return nil
}
// renderAgent prints a single agent in human-readable form, grouped into
// 10 presentation sections. Zero-value fields are omitted; a section
// header prints only when at least one of its fields is set. Group
// labels and order are pinned by snapshot tests so future drift surfaces
// as test failure rather than silent divergence.
func renderAgent(w io.Writer, a *sdk.Agent) {
// Identity is always rendered — id/name/created_at/updated_at are
// never meaningfully empty for a fetched Agent.
fmt.Fprintln(w, "Identity:")
fmt.Fprintf(w, " ID: %s\n", a.ID)
fmt.Fprintf(w, " Name: %s\n", a.Name)
if a.Description != "" {
fmt.Fprintf(w, " Description: %s\n", a.Description)
}
if a.IsBuiltin {
fmt.Fprintln(w, " Builtin: yes")
}
if a.CreatedBy != "" {
fmt.Fprintf(w, " Created by: %s\n", a.CreatedBy)
}
if a.TenantID != 0 {
fmt.Fprintf(w, " Tenant ID: %d\n", a.TenantID)
}
fmt.Fprintf(w, " Created at: %s\n", a.CreatedAt.Format("2006-01-02 15:04:05"))
fmt.Fprintf(w, " Updated at: %s\n", a.UpdatedAt.Format("2006-01-02 15:04:05"))
if a.Config == nil {
return
}
c := a.Config
// Each group is rendered via a tiny helper: collect its set rows
// upfront, suppress the whole section if empty. Avoids the
// "header printed but no body" failure mode that plagues naive
// conditional rendering.
type row struct{ k, v string }
emit := func(label string, rows []row) {
if len(rows) == 0 {
return
}
fmt.Fprintln(w)
fmt.Fprintf(w, "%s:\n", label)
for _, r := range rows {
fmt.Fprintf(w, " %-32s %s\n", r.k+":", r.v)
}
}
// LLM
llm := []row{}
if c.ModelID != "" {
llm = append(llm, row{"Model ID", c.ModelID})
}
if c.RerankModelID != "" {
llm = append(llm, row{"Rerank model ID", c.RerankModelID})
}
if c.Temperature != 0 {
llm = append(llm, row{"Temperature", fmt.Sprintf("%g", c.Temperature)})
}
if c.MaxCompletionTokens != 0 {
llm = append(llm, row{"Max completion tokens", fmt.Sprintf("%d", c.MaxCompletionTokens)})
}
if c.MaxIterations < 0 {
llm = append(llm, row{"Max iterations", "unlimited"})
} else if c.MaxIterations != 0 {
llm = append(llm, row{"Max iterations", fmt.Sprintf("%d", c.MaxIterations)})
}
if c.AgentMode != "" {
llm = append(llm, row{"Mode", c.AgentMode})
}
emit("LLM", llm)
// KB attachment
kb := []row{}
if c.KBSelectionMode != "" {
kb = append(kb, row{"KB selection mode", c.KBSelectionMode})
}
if len(c.KnowledgeBases) > 0 {
kb = append(kb, row{"Knowledge bases", strings.Join(c.KnowledgeBases, ", ")})
}
emit("KB attachment", kb)
// Retrieval
retr := []row{}
if c.EmbeddingTopK != 0 {
retr = append(retr, row{"Embedding top K", fmt.Sprintf("%d", c.EmbeddingTopK)})
}
if c.KeywordThreshold != 0 {
retr = append(retr, row{"Keyword threshold", fmt.Sprintf("%g", c.KeywordThreshold)})
}
if c.VectorThreshold != 0 {
retr = append(retr, row{"Vector threshold", fmt.Sprintf("%g", c.VectorThreshold)})
}
if c.RerankTopK != 0 {
retr = append(retr, row{"Rerank top K", fmt.Sprintf("%d", c.RerankTopK)})
}
if c.RerankThreshold != 0 {
retr = append(retr, row{"Rerank threshold", fmt.Sprintf("%g", c.RerankThreshold)})
}
emit("Retrieval", retr)
// Query rewrite
qr := []row{}
if c.EnableQueryExpansion {
qr = append(qr, row{"Query expansion", "enabled"})
}
if c.EnableRewrite {
qr = append(qr, row{"Rewrite", "enabled"})
}
if c.QueryUnderstandModelID != "" {
qr = append(qr, row{"Query understand model ID", c.QueryUnderstandModelID})
}
if c.RewritePromptSystem != "" {
qr = append(qr, row{"Rewrite prompt (system)", text.OneLine(promptPreviewWidth, c.RewritePromptSystem)})
}
if c.RewritePromptUser != "" {
qr = append(qr, row{"Rewrite prompt (user)", text.OneLine(promptPreviewWidth, c.RewritePromptUser)})
}
emit("Query rewrite", qr)
// Tools
tools := []row{}
if len(c.AllowedTools) > 0 {
tools = append(tools, row{"Allowed tools", strings.Join(c.AllowedTools, ", ")})
}
if c.MCPSelectionMode != "" {
tools = append(tools, row{"MCP selection mode", c.MCPSelectionMode})
}
if len(c.MCPServices) > 0 {
tools = append(tools, row{"MCP services", strings.Join(c.MCPServices, ", ")})
}
if len(c.SupportedFileTypes) > 0 {
tools = append(tools, row{"Supported file types", strings.Join(c.SupportedFileTypes, ", ")})
}
emit("Tools", tools)
// FAQ
faq := []row{}
if c.FAQPriorityEnabled {
faq = append(faq, row{"FAQ priority", "enabled"})
}
if c.FAQDirectAnswerThreshold != 0 {
faq = append(faq, row{"FAQ direct-answer threshold", fmt.Sprintf("%g", c.FAQDirectAnswerThreshold)})
}
if c.FAQScoreBoost != 0 {
faq = append(faq, row{"FAQ score boost", fmt.Sprintf("%g", c.FAQScoreBoost)})
}
emit("FAQ", faq)
// Web search
web := []row{}
if c.WebSearchEnabled {
web = append(web, row{"Web search", "enabled"})
}
if c.WebSearchMaxResults != 0 {
web = append(web, row{"Web search max results", fmt.Sprintf("%d", c.WebSearchMaxResults)})
}
emit("Web search", web)
// Multi-turn
mt := []row{}
if c.MultiTurnEnabled {
mt = append(mt, row{"Multi-turn", "enabled"})
}
if c.HistoryTurns != 0 {
mt = append(mt, row{"History turns", fmt.Sprintf("%d", c.HistoryTurns)})
}
emit("Multi-turn", mt)
// Fallback
fb := []row{}
if c.FallbackStrategy != "" {
fb = append(fb, row{"Strategy", c.FallbackStrategy})
}
if c.FallbackResponse != "" {
fb = append(fb, row{"Response", c.FallbackResponse})
}
if c.FallbackPrompt != "" {
fb = append(fb, row{"Prompt", text.OneLine(promptPreviewWidth, c.FallbackPrompt)})
}
emit("Fallback", fb)
// Templates — system_prompt and context_template can be multi-line;
// render headed blocks rather than KV rows for readability.
if c.SystemPrompt != "" || c.ContextTemplate != "" {
fmt.Fprintln(w)
fmt.Fprintln(w, "Templates:")
if c.SystemPrompt != "" {
fmt.Fprintln(w, " System prompt:")
writeIndented(w, c.SystemPrompt, " ")
}
if c.ContextTemplate != "" {
fmt.Fprintln(w, " Context template:")
writeIndented(w, c.ContextTemplate, " ")
}
}
}
// writeIndented prints s with the given prefix on every line. Trailing
// newline always added so the next section starts on its own line.
func writeIndented(w io.Writer, s, prefix string) {
for _, line := range strings.Split(strings.TrimRight(s, "\n"), "\n") {
fmt.Fprintf(w, "%s%s\n", prefix, line)
}
}
+183
View File
@@ -0,0 +1,183 @@
package agentcmd
import (
"context"
"encoding/json"
"errors"
"slices"
"strings"
"testing"
"time"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
type fakeViewSvc struct {
resp *sdk.Agent
err error
}
func (f *fakeViewSvc) GetAgent(_ context.Context, _ string) (*sdk.Agent, error) {
return f.resp, f.err
}
func TestView_Text_RendersMetadataAndConfig(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeViewSvc{resp: &sdk.Agent{
ID: "ag_abc",
Name: "Research",
Description: "deep-dive helper",
IsBuiltin: true,
CreatedAt: time.Date(2026, 5, 1, 12, 0, 0, 0, time.UTC),
UpdatedAt: time.Date(2026, 5, 2, 13, 30, 0, 0, time.UTC),
Config: &sdk.AgentConfig{
AgentMode: "smart-reasoning",
ModelID: "model_42",
KBSelectionMode: "selected",
KnowledgeBases: []string{"kb_x", "kb_y"},
AllowedTools: []string{"knowledge_search", "web_search"},
WebSearchEnabled: true,
},
}}
if err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "ag_abc"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
for _, want := range []string{"ag_abc", "Research", "deep-dive helper", "Builtin:", "Identity", "LLM", "KB attachment", "Tools", "smart-reasoning", "model_42", "selected", "kb_x", "knowledge_search", "Web search"} {
if !strings.Contains(got, want) {
t.Errorf("missing %q in:\n%s", want, got)
}
}
}
// TestAgentViewFields_TopLevelOnly pins the contract that the field-hint
// list on `agent view` only lists top-level Agent keys (including `config`
// as a whole). Nested AgentConfig fields are reachable via --jq.
func TestAgentViewFields_TopLevelOnly(t *testing.T) {
for _, want := range []string{"id", "name", "config", "created_at"} {
if !slices.Contains(agentViewFields, want) {
t.Errorf("agentViewFields missing top-level key %q", want)
}
}
for _, dotted := range []string{"config.system_prompt", "config.model_id", "config.fallback_strategy"} {
if slices.Contains(agentViewFields, dotted) {
t.Errorf("agentViewFields must not list dotted nested key %q (the --jq projection path handles nesting directly)", dotted)
}
}
}
// TestRenderAgent_RendersAllGroupsWithOmitEmpty validates the grouped
// text rendering: present groups print, zero-value fields omit, and an
// entire section is suppressed when all of its fields are zero.
func TestRenderAgent_RendersAllGroupsWithOmitEmpty(t *testing.T) {
out, _ := iostreams.SetForTest(t)
ag := &sdk.Agent{
ID: "ag_abc",
Name: "Test",
Config: &sdk.AgentConfig{
AgentMode: "smart-reasoning",
SystemPrompt: "You help users.",
ModelID: "model-x",
Temperature: 0.7,
KBSelectionMode: "selected",
KnowledgeBases: []string{"kb_a"},
FAQPriorityEnabled: true,
WebSearchEnabled: false, // zero — omitted in text
FallbackStrategy: "fixed",
FallbackResponse: "I don't know.",
},
}
renderAgent(iostreams.IO.Out, ag)
body := out.String()
// Group labels appear:
for _, label := range []string{"Identity", "LLM", "KB attachment", "FAQ", "Fallback", "Templates"} {
if !strings.Contains(body, label) {
t.Errorf("missing group label %q in:\n%s", label, body)
}
}
// Set fields rendered:
for _, want := range []string{"smart-reasoning", "model-x", "You help users."} {
if !strings.Contains(body, want) {
t.Errorf("missing value %q in:\n%s", want, body)
}
}
// Zero-value fields omitted (web search disabled → max_results not shown):
if strings.Contains(body, "web_search_max_results") {
t.Errorf("zero-valued web_search_max_results leaked into:\n%s", body)
}
// Section with all zero values must be suppressed entirely (no Retrieval
// fields were set in this fixture).
if strings.Contains(body, "Retrieval") {
t.Errorf("Retrieval section rendered with all-zero fields in:\n%s", body)
}
// Multi-turn section is all-zero too — must be suppressed.
if strings.Contains(body, "Multi-turn") {
t.Errorf("Multi-turn section rendered with all-zero fields in:\n%s", body)
}
}
func TestView_Text_OmitsEmptyFields(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeViewSvc{resp: &sdk.Agent{
ID: "ag_min",
Name: "Minimal",
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}}
if err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "ag_min"); err != nil {
t.Fatalf("runView: %v", err)
}
got := out.String()
if strings.Contains(got, "Description:") {
t.Errorf("empty description should be omitted, got:\n%s", got)
}
if strings.Contains(got, "Builtin:") {
t.Errorf("non-builtin should not render Builtin: line, got:\n%s", got)
}
// With Config==nil none of the grouped config sections should appear.
for _, label := range []string{"LLM:", "KB attachment:", "Retrieval:", "Query rewrite:", "Tools:", "FAQ:", "Web search:", "Multi-turn:", "Fallback:", "Templates:"} {
if strings.Contains(got, label) {
t.Errorf("nil Config should not render %q, got:\n%s", label, got)
}
}
}
func TestView_JSON_BareObject(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeViewSvc{resp: &sdk.Agent{ID: "ag_json", Name: "JSONy"}}
if err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "ag_json"); err != nil {
t.Fatalf("runView: %v", err)
}
var env struct {
OK bool `json:"ok"`
Data sdk.Agent `json:"data"`
}
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
t.Fatalf("parse: %v", err)
}
got := env.Data
if got.ID != "ag_json" || got.Name != "JSONy" {
t.Errorf("envelope.data shape wrong: id=%s name=%s", got.ID, got.Name)
}
if !env.OK {
t.Errorf("envelope.ok must be true, got %q", out.String())
}
}
func TestView_404_MapsToResourceNotFound(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeViewSvc{err: errors.New("HTTP error 404: agent not found")}
err := runView(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, svc, "ag_missing")
if err == nil {
t.Fatal("expected error, got nil")
}
var typed *cmdutil.Error
if !errors.As(err, &typed) {
t.Fatalf("expected *cmdutil.Error, got %T", err)
}
if typed.Code != cmdutil.CodeResourceNotFound {
t.Errorf("expected resource.not_found, got %s", typed.Code)
}
}
+109
View File
@@ -0,0 +1,109 @@
package cmd
import (
"bytes"
"encoding/json"
"sort"
"testing"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
)
// TestEveryLeafCommandHasAgentHelp enforces the agent-first contract: every
// leaf (runnable, no subcommands) command must emit a structured AgentHelp JSON
// blob under WEKNORA_AGENT_HELP=1, so an agent never has to scrape human prose.
// Drift guard in the spirit of the K6/K7 skill-parity tests: a new leaf command
// added without SetAgentHelp fails CI here.
//
// Exemptions: cobra's generated `completion`/`help` subtrees carry no
// domain semantics worth a machine blob.
func TestEveryLeafCommandHasAgentHelp(t *testing.T) {
t.Setenv("WEKNORA_AGENT_HELP", "1")
root := NewRootCmd(cmdutil.New())
var missing []string
eachLeafCommand(root, func(c *cobra.Command) {
// Invoke the leaf's help func with the agent env set and require JSON.
var buf bytes.Buffer
c.SetOut(&buf)
c.Help()
var ah struct {
UsedFor string `json:"used_for"`
}
if err := json.Unmarshal(buf.Bytes(), &ah); err != nil || ah.UsedFor == "" {
missing = append(missing, c.CommandPath())
}
})
sort.Strings(missing)
if len(missing) > 0 {
t.Errorf("leaf commands missing agent-help JSON (register cmdutil.SetAgentHelp):\n %v\n(%d commands)",
missing, len(missing))
}
}
// renderAgentHelp runs a leaf's help under WEKNORA_AGENT_HELP=1 and decodes the
// machine blob (used_for / output / examples) an agent would read.
func renderAgentHelp(t *testing.T, c *cobra.Command) struct {
UsedFor string `json:"used_for"`
Output string `json:"output"`
Examples []string `json:"examples"`
} {
t.Helper()
var buf bytes.Buffer
c.SetOut(&buf)
c.Help()
var ah struct {
UsedFor string `json:"used_for"`
Output string `json:"output"`
Examples []string `json:"examples"`
}
if err := json.Unmarshal(buf.Bytes(), &ah); err != nil {
t.Fatalf("%s: agent-help is not JSON: %v", c.CommandPath(), err)
}
return ah
}
// TestEveryLeafCommandDeclaresOutput enforces that every leaf command tells an
// agent what its stdout carries. Even side-effect commands describe their
// envelope (e.g. deletes emit {id, deleted:true}); an empty Output is a contract
// gap, not a valid state. Sibling drift guard to the agent-help test above.
func TestEveryLeafCommandDeclaresOutput(t *testing.T) {
t.Setenv("WEKNORA_AGENT_HELP", "1")
root := NewRootCmd(cmdutil.New())
var missing []string
eachLeafCommand(root, func(c *cobra.Command) {
if renderAgentHelp(t, c).Output == "" {
missing = append(missing, c.CommandPath())
}
})
sort.Strings(missing)
if len(missing) > 0 {
t.Errorf("leaf commands missing agent-help Output (declare AgentHelp.Output):\n %v\n(%d commands)",
missing, len(missing))
}
}
// TestEveryLeafCommandHasExample enforces that every leaf ships at least one
// runnable example — agents learn invocation shape from examples, not prose.
func TestEveryLeafCommandHasExample(t *testing.T) {
t.Setenv("WEKNORA_AGENT_HELP", "1")
root := NewRootCmd(cmdutil.New())
var missing []string
eachLeafCommand(root, func(c *cobra.Command) {
if len(renderAgentHelp(t, c).Examples) == 0 {
missing = append(missing, c.CommandPath())
}
})
sort.Strings(missing)
if len(missing) > 0 {
t.Errorf("leaf commands missing agent-help Examples (declare AgentHelp.Examples):\n %v\n(%d commands)",
missing, len(missing))
}
}
+536
View File
@@ -0,0 +1,536 @@
// Package api implements the `weknora api` raw HTTP passthrough command.
//
// Shape: one positional (path) + `-X/--method` flag, default GET (auto-
// promoted to POST when a body is supplied via -d/--input). Text mode writes
// the raw response body to stdout; --format json places the parsed server
// response directly under envelope.data (no {status, headers, body} wrapper),
// so `--jq '.data...'` projects at the server's own depth. Reuses
// sdk.Client.Raw which already applies tenant + auth headers.
package api
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
// apiFields is intentionally a marker - api wraps arbitrary HTTP responses
// whose schema the CLI doesn't know, so field hints are meaningless here.
// The marker shows up in --help so users can tell.
var apiFields = []string{"<response-shape-varies>"}
type Options struct {
Method string
Input string // --input: file path, "-" for stdin
Data string // -d/--data: inline JSON body (mutually exclusive with --input)
Fields []string // -F/--field: key=value pairs assembled into a JSON object body (mutually exclusive with -d/--input)
Yes bool
DryRun bool
StdinReader io.Reader // overridden by tests; defaults to iostreams.IO.In
}
// Service is the narrow SDK surface this command depends on. The production
// implementation is *sdk.Client, whose Raw method already injects auth /
// tenant / request-id headers (see client.applyAuthHeaders). Tests substitute
// either a fake or a real client pointed at httptest.Server.
type Service interface {
Raw(ctx context.Context, method, path string, body any) (*http.Response, error)
}
// NewCmd returns the `weknora api` command.
func NewCmd(f *cmdutil.Factory) *cobra.Command {
opts := &Options{}
cmd := &cobra.Command{
Use: "api <path>",
Short: "Make a raw API request to the WeKnora server",
Long: `Raw HTTP API access. JSON body via -d/--data (inline) or --input <file>/- (stdin).
The default method is GET; supplying a body (-d or --input) auto-promotes it
to POST. Use -X/--method to override (any non-empty method is accepted:
DELETE / PUT / PATCH / HEAD / OPTIONS / TRACE / custom).
Auth, tenant, and request-id headers are applied automatically from the
active profile. In --format text the raw server response body is written
to stdout. In --format json (default) the parsed server response is placed directly
under envelope.data — drill in with --jq '.data...' at the server's own depth
(e.g. '.data.data[]' for a list endpoint). Only -X DELETE is confirmation-gated.
With --paginate, text mode writes the merged {data, total} JSON object with a
trailing newline and no envelope.
Examples:
weknora api /api/v1/knowledge-bases # GET
weknora api /api/v1/knowledge-bases -d '{"name":"foo"}' # POST (auto)
weknora api /api/v1/knowledge-bases -F name=foo -F enabled=true # POST, typed body
echo '{"name":"foo"}' | weknora api /api/v1/knowledge-bases --input - # POST via stdin
weknora api /api/v1/knowledge-bases/kb_xxx -X DELETE`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
opts.Yes, _ = c.Flags().GetBool("yes")
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
if opts.DryRun {
// --dry-run on the raw escape-hatch is only meaningful when a
// would-be mutation exists to preview. GET (default or explicit)
// is read-only with no side effect, so previewing it is a
// likely user error — signal it via FlagError exit 2 with the
// concrete repair. Use resolveMethod so --input auto-promotes
// GET → POST identically to the live path.
method := resolveMethod(opts)
if method == http.MethodGet {
return cmdutil.NewFlagError(fmt.Errorf(
"--dry-run requires explicit -X POST/PUT/PATCH/DELETE; default GET is read-only with no side effect to preview"))
}
var body any
if hasBody(opts) {
contents, err := resolveBody(opts)
if err != nil {
return err
}
// Surface the parsed body in the plan so agents can grep
// meta.plan.body for shape; resolveBody has already validated
// it as JSON.
var parsed any
if json.Unmarshal(contents, &parsed) == nil {
body = parsed
} else {
body = string(contents)
}
}
if handled, err := cmdutil.HandleDryRun(c, true, cmdutil.DryRunPlan{
Action: "api." + strings.ToLower(method),
Method: method,
Path: args[0],
Body: body,
}); handled {
return err
}
}
method := resolveMethod(opts)
// Escape-hatch DELETE through `weknora api` is just as destructive
// as `weknora kb delete` - exit-10 destructive protocol must apply
// (cli/README.md). PUT/PATCH mutate server state like a typed
// `kb/agent/doc update`, so they get the same exit-10 WRITE gate;
// without it the raw escape hatch bypassed the "an agent cannot
// silently mutate" guarantee. POST stays ungated to match typed
// `create` (also ungated). GET/HEAD are reads.
switch method {
case http.MethodDelete:
if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, fopts.WantsJSON(), "delete", "endpoint", args[0], "api.delete", []string{"weknora", "api", "-X", "DELETE", args[0], "-y"}); err != nil {
return err
}
case http.MethodPut, http.MethodPatch:
if err := cmdutil.ConfirmWrite(f.Prompter(), opts.Yes, fopts.WantsJSON(), "write", "endpoint", args[0], "api."+strings.ToLower(method), apiRetryArgv(opts, method, args[0])); err != nil {
return err
}
}
cli, err := f.Client()
if err != nil {
return err
}
paginate, _ := c.Flags().GetBool("paginate")
return runAPI(c.Context(), opts, fopts, cli, method, args[0], paginate)
},
}
cmd.Flags().StringVarP(&opts.Method, "method", "X", "", "HTTP method (default: GET, or POST when a body is supplied via -d/--input). Any non-empty method is accepted.")
cmd.Flags().StringVarP(&opts.Data, "data", "d", "", "Inline JSON request body (e.g. -d '{\"name\":\"x\"}'). Mutually exclusive with --input.")
cmd.Flags().StringVar(&opts.Input, "input", "", "Read JSON request body from file (use `-` for stdin). Mutually exclusive with -d/--data.")
cmd.Flags().StringArrayVarP(&opts.Fields, "field", "F", nil, "Add a key=value to a JSON object body (repeatable; e.g. -F name=foo -F enabled=true). true/false/null and numbers are typed; everything else is a string. Flat keys only. Mutually exclusive with -d/--input.")
cmd.Flags().Bool("paginate", false, "Follow offset-based pagination (?page=N&page_size=M), merging all pages into a single {data, total} JSON response.")
cmdutil.AddFormatFlag(cmd, apiFields...)
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "raw HTTP passthrough to weknora-server API endpoints when typed subcommands are insufficient",
RequiredFlags: []string{"path (positional)"},
Examples: []string{
"weknora api /api/v1/knowledge-bases",
"weknora api /api/v1/knowledge-bases -d '{\"name\":\"foo\"}'",
"weknora api -X POST /api/v1/knowledge-bases -F name=\"Eng Docs\" -F enabled=true",
"weknora api -X DELETE /api/v1/knowledge-bases/kb_x -y",
"echo '{\"name\":\"foo\"}' | weknora api /api/v1/knowledge-bases --input -",
},
Output: "text mode: the raw server response body on stdout. " +
"json mode (default): the parsed server response is placed directly under envelope.data - " +
"project with --jq '.data...' at the server's own depth " +
"(e.g. '.data.data[]' for a list endpoint, '.data.data.id' for a created object). " +
"With --paginate, envelope.data is the merged {data, total}; " +
"text mode writes that merged JSON object with a trailing newline and no envelope.",
Warnings: []string{
"-X DELETE is destructive-gated and -X PUT/PATCH are write-gated (exit 10 / input.confirmation_required unless -y), matching typed delete/update. -X POST (create-shaped) and GET are unguarded — you own the safety of creates made through this escape hatch.",
"Raw passthrough: the typed error envelope does NOT fully apply. The server's own response goes under envelope.data at its native depth; a non-2xx HTTP status surfaces via the exit code, not a typed error.type/retry_argv. Do not rely on error.type/retryable for `api` the way you do for typed subcommands.",
"Raw HTTP passthrough; agents should prefer typed subcommands (kb/doc/session/...) when available.",
},
})
return cmd
}
// readInput reads opts.Input and returns its contents. "-" reads from
// opts.StdinReader (or iostreams.IO.In as the production default) for
// piped JSON payloads.
//
// The body is sent as a JSON document (the SDK marshals it as json.RawMessage),
// so a non-JSON / malformed payload is validated and rejected here as
// input.invalid_argument (exit 5). Without this, the failure surfaced from the
// SDK's marshal step as a confusing network.error (exit 7, "retryable") —
// looping an agent on a body that can never be sent.
func readInput(opts *Options) ([]byte, error) {
var b []byte
if opts.Input == "-" {
r := opts.StdinReader
if r == nil {
r = iostreams.IO.In
}
var err error
b, err = io.ReadAll(r)
if err != nil {
return nil, cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "read request body from stdin")
}
} else {
var err error
b, err = os.ReadFile(opts.Input)
if err != nil {
return nil, cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "read input file %s", opts.Input)
}
}
if len(bytes.TrimSpace(b)) > 0 && !json.Valid(b) {
return nil, cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
"--input must be valid JSON (the request body is sent as a JSON document)")
}
return b, nil
}
// resolveBody returns the request body bytes from -d/--data (inline) or
// --input (file/stdin), or nil when neither is set. Inline --data is
// validated as JSON here; --input is validated inside readInput. The two
// flags are mutually exclusive — checked here (rather than cobra's
// MarkFlagsMutuallyExclusive, whose violation surfaces as an unclassified
// internal.error / exit 1) so the conflict reports input.invalid_argument.
func resolveBody(opts *Options) ([]byte, error) {
set := 0
if opts.Data != "" {
set++
}
if opts.Input != "" {
set++
}
if len(opts.Fields) > 0 {
set++
}
if set > 1 {
return nil, cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
"-d/--data, --input, and -F/--field are mutually exclusive; supply the body one way")
}
if len(opts.Fields) > 0 {
return buildFieldBody(opts.Fields)
}
if opts.Data != "" {
if !json.Valid([]byte(opts.Data)) {
return nil, cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
"-d/--data must be valid JSON (the request body is sent as a JSON document)")
}
return []byte(opts.Data), nil
}
if opts.Input != "" {
return readInput(opts)
}
return nil, nil
}
// hasBody reports whether a request body was supplied via -d or --input.
func hasBody(opts *Options) bool {
return opts.Data != "" || opts.Input != "" || len(opts.Fields) > 0
}
// inferFieldValue maps a -F value string to a typed JSON scalar: literal
// true/false/null and integer/float literals become typed JSON; everything
// else stays a string. A value that looks numeric but must stay a string
// (e.g. a zero-padded id "007") can't be forced here — use -d/--data or
// --input for full control.
func inferFieldValue(v string) any {
switch v {
case "true":
return true
case "false":
return false
case "null":
return nil
}
if i, err := strconv.ParseInt(v, 10, 64); err == nil {
return i
}
if f, err := strconv.ParseFloat(v, 64); err == nil {
return f
}
return v
}
// buildFieldBody assembles -F/--field key=value pairs into a JSON object with
// type inference. Flat keys only. Returns input.invalid_argument (exit 5) for
// a malformed pair or an unsupported @file value.
func buildFieldBody(fields []string) ([]byte, error) {
obj := make(map[string]any, len(fields))
for _, f := range fields {
k, v, ok := strings.Cut(f, "=")
if !ok || k == "" {
return nil, cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
fmt.Sprintf("-F/--field must be key=value, got %q", f))
}
if strings.HasPrefix(v, "@") {
return nil, cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
fmt.Sprintf("-F %q: @file values are not supported; read a file body with --input", f))
}
obj[k] = inferFieldValue(v)
}
return json.Marshal(obj)
}
// resolveMethod implements the auto-method behavior: explicit -X wins;
// otherwise body presence (-d/--data or --input) promotes GET → POST.
func resolveMethod(opts *Options) string {
if opts.Method != "" {
return strings.ToUpper(opts.Method)
}
if hasBody(opts) {
return "POST"
}
return "GET"
}
// apiRetryArgv reconstructs a directly-executable `weknora api` argv (with -y)
// for the write-confirmation gate, preserving the method, path and body flags
// the caller passed so an agent can re-run the exact mutation after approval.
func apiRetryArgv(opts *Options, method, path string) []string {
argv := []string{"weknora", "api", "-X", method, path}
switch {
case opts.Data != "":
argv = append(argv, "-d", opts.Data)
case opts.Input != "":
argv = append(argv, "--input", opts.Input)
default:
for _, f := range opts.Fields {
argv = append(argv, "-F", f)
}
}
return append(argv, "-y")
}
// runAPI is the testable core: validate inputs, dispatch via Service.Raw,
// classify status, and emit either the raw body or a JSON object. The
// caller is responsible for resolving the method (defaults / auto-POST)
// and uppercasing it; runAPI guards against unsupported values like
// `-X PATCH-INVALID` reaching the wire.
//
// When paginate is true and method is GET, all offset-based pages are
// fetched and merged into a single {data, total} JSON response. For
// non-GET methods paginate is silently ignored (no offset semantic).
func runAPI(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, svc Service, method, path string, paginate bool) error {
if paginate && method == http.MethodGet {
return runAPIPaginated(ctx, opts, fopts, svc, path)
}
return runAPISingle(ctx, opts, fopts, svc, method, path)
}
// runAPISingle is the original single-call implementation of runAPI.
func runAPISingle(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, svc Service, method, path string) error {
if method == "" {
return cmdutil.NewFlagError(fmt.Errorf("--method cannot be empty"))
}
if !strings.HasPrefix(path, "/") {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("path must start with /: %s", path))
}
// Resolve request body from -d/--data (inline) or --input (file / `-`).
// Empty input is treated as no body rather than an empty JSON document
// (which fails to marshal).
contents, err := resolveBody(opts)
if err != nil {
return err
}
var body any
if len(bytes.TrimSpace(contents)) > 0 {
body = json.RawMessage(contents)
}
resp, err := svc.Raw(ctx, method, path, body)
if err != nil {
// Transport / DNS failure (Raw never returns a typed HTTP error of its
// own; non-2xx responses still surface as resp != nil, err == nil).
return cmdutil.WrapHTTP(err, "%s %s", method, path)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return cmdutil.Wrapf(cmdutil.CodeNetworkError, err, "read response body")
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
code := cmdutil.ClassifyHTTPStatus(resp.StatusCode)
ce := cmdutil.NewError(code, fmt.Sprintf("HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(respBody))))
if v := resp.Header.Get("Retry-After"); v != "" {
if s, perr := strconv.Atoi(v); perr == nil && s > 0 {
ce = ce.WithRetryAfter(s)
}
}
return ce
}
return emitRawBody(respBody, fopts)
}
// emitRawBody writes a server response body under the active format. JSON mode
// places the parsed body directly under envelope.data — no {status, headers,
// body} wrapper — so `--jq '.data...'` projects at the server's own shape
// (e.g. `.data.data[]` for a list endpoint) rather than a triple-nested
// `.data.body.data[]`; non-JSON decodes best-effort to a raw string. Text mode
// writes the body verbatim with a trailing newline. Shared by the single and
// paginated-fallback paths so both project identically.
func emitRawBody(body []byte, fopts *cmdutil.FormatOptions) error {
out := iostreams.IO.Out
if fopts.WantsJSON() {
var bodyAny any
if len(body) > 0 {
if err := json.Unmarshal(body, &bodyAny); err != nil {
bodyAny = string(body)
}
}
return fopts.Emit(out, bodyAny, nil)
}
if _, err := out.Write(body); err != nil {
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "write response body")
}
if len(body) > 0 && body[len(body)-1] != '\n' {
_, _ = out.Write([]byte{'\n'})
}
return nil
}
// runAPIPaginated fetches all offset-based pages for a GET request and writes
// a single merged {data, total} JSON object to stdout. If the first page
// response does not carry pagination metadata (total + page_size), the raw
// response is passed through via passThroughFallback which respects the
// --format envelope contract (same shape as runAPISingle's fallback path).
func runAPIPaginated(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, svc Service, path string) error {
if fopts.Mode == cmdutil.FormatText && fopts.JQ != "" {
return cmdutil.NewFlagError(fmt.Errorf("--jq requires --format json|ndjson"))
}
if !strings.HasPrefix(path, "/") {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("path must start with /: %s", path))
}
pageSize := extractPageSize(path)
if pageSize == 0 {
pageSize = 50
}
allData := []json.RawMessage{}
var lastTotal int64
page := 1
for {
curPath := setPageParam(path, page, pageSize)
resp, err := svc.Raw(ctx, http.MethodGet, curPath, nil)
if err != nil {
return cmdutil.WrapHTTP(err, "GET %s", curPath)
}
body, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return cmdutil.Wrapf(cmdutil.CodeNetworkError, err, "read response body")
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
code := cmdutil.ClassifyHTTPStatus(resp.StatusCode)
return cmdutil.NewError(code, fmt.Sprintf("HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(body))))
}
var pageResp struct {
Data []json.RawMessage `json:"data"`
Total int64 `json:"total"`
Page int `json:"page"`
PageSize int `json:"page_size"`
}
if err := json.Unmarshal(body, &pageResp); err != nil {
// Non-JSON response on first page — fall back through the envelope.
if page == 1 {
return emitRawBody(body, fopts)
}
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
fmt.Sprintf("--paginate: page %d response not in expected shape: %v", page, err))
}
// Heuristic: if the first page lacks pagination metadata, treat the
// response as non-paginated and fall back through the envelope.
if page == 1 && pageResp.Total == 0 && pageResp.PageSize == 0 {
return emitRawBody(body, fopts)
}
allData = append(allData, pageResp.Data...)
lastTotal = pageResp.Total
// Termination: accumulated count (not page*pageSize) handles server-capped page sizes.
if int64(len(allData)) >= pageResp.Total || len(pageResp.Data) == 0 {
break
}
page++
}
merged := map[string]any{
"data": allData,
"total": lastTotal,
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, merged, nil)
}
if err := json.NewEncoder(iostreams.IO.Out).Encode(merged); err != nil {
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "write response body")
}
return nil
}
// extractPageSize parses the page_size query parameter from path, returning 0
// if absent or unparseable.
func extractPageSize(path string) int {
u, err := url.Parse(path)
if err != nil {
return 0
}
if v := u.Query().Get("page_size"); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 {
return n
}
}
return 0
}
// setPageParam rewrites the page and page_size query parameters in path,
// preserving all other query parameters.
func setPageParam(path string, page, pageSize int) string {
u, err := url.Parse(path)
if err != nil {
return path
}
q := u.Query()
q.Set("page", strconv.Itoa(page))
q.Set("page_size", strconv.Itoa(pageSize))
u.RawQuery = q.Encode()
return u.String()
}
// compile-time check: the production SDK client implements Service.
var _ Service = (*sdk.Client)(nil)
+199
View File
@@ -0,0 +1,199 @@
package api
import (
"encoding/json"
"errors"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
sdk "github.com/Tencent/WeKnora/client"
)
// apiDryRunFactory builds a Factory whose Client closure panics if invoked —
// dry-run must early-exit before any SDK call.
func apiDryRunFactory(t *testing.T) *cmdutil.Factory {
t.Helper()
return &cmdutil.Factory{
Client: func() (*sdk.Client, error) {
t.Fatal("dry-run path must not call Factory.Client(); SDK side effect leaked")
return nil, nil
},
Prompter: func() prompt.Prompter {
t.Fatal("dry-run path must not call Factory.Prompter(); confirm-prompt side effect leaked")
return nil
},
}
}
// TestApi_DryRunWithGet_FlagError: default-method GET + --dry-run must return
// FlagError (exit 2). The only meaningful target for --dry-run on `api` is a
// mutation method; allowing GET to silently succeed would let agents waste a
// round-trip previewing a no-op.
func TestApi_DryRunWithGet_FlagError(t *testing.T) {
iostreams.SetForTest(t)
root := withRootHarness(NewCmd(apiDryRunFactory(t)),
"/api/v1/knowledge-bases", "--dry-run")
err := root.Execute()
require.Error(t, err, "GET + --dry-run must error")
var fe *cmdutil.FlagError
require.True(t, errors.As(err, &fe), "expected *cmdutil.FlagError, got %T %v", err, err)
assert.Equal(t, 2, cmdutil.ExitCode(err), "FlagError must map to exit 2")
assert.Contains(t, err.Error(), "explicit -X POST/PUT/PATCH/DELETE",
"error message must point users to the concrete repair")
}
// TestApi_DryRunWithExplicitGet_FlagError: explicit `-X GET` + --dry-run is
// also rejected. The reject condition is "method is GET", not "method flag is
// unset"; passing -X GET explicitly must produce the same error so users
// can't bypass the guard by being verbose.
func TestApi_DryRunWithExplicitGet_FlagError(t *testing.T) {
iostreams.SetForTest(t)
root := withRootHarness(NewCmd(apiDryRunFactory(t)),
"/api/v1/knowledge-bases", "-X", "GET", "--dry-run")
err := root.Execute()
require.Error(t, err, "explicit -X GET + --dry-run must error")
var fe *cmdutil.FlagError
require.True(t, errors.As(err, &fe), "expected *cmdutil.FlagError, got %T %v", err, err)
assert.Equal(t, 2, cmdutil.ExitCode(err))
}
// TestApi_DryRunWithInputAutoPromotes_EmitsPlan: --input on its own (no
// explicit -X) must auto-promote GET → POST in the dry-run path too,
// matching the live behavior in resolveMethod. Before the fix the dry-run
// branch built `method` directly from `strings.ToUpper(opts.Method)`, which
// is empty when -X is unset, then defaulted to GET — so --input was ignored
// at preview time, producing the misleading "GET is read-only" error.
func TestApi_DryRunWithInputAutoPromotes_EmitsPlan(t *testing.T) {
out, _ := iostreams.SetForTest(t)
iostreams.IO.In = strings.NewReader(`{}`)
root := withRootHarness(NewCmd(apiDryRunFactory(t)),
"/api/v1/knowledge-bases", "--input", "-", "--dry-run", "--format", "json")
require.NoError(t, root.Execute(), "--input + --dry-run must succeed (POST auto-promotion)")
var env struct {
OK bool `json:"ok"`
Meta struct {
DryRun bool `json:"dry_run"`
Plan map[string]any `json:"plan"`
} `json:"meta"`
}
require.NoError(t, json.Unmarshal(out.Bytes(), &env), "expected valid JSON envelope, got %q", out.String())
assert.True(t, env.OK)
assert.True(t, env.Meta.DryRun)
assert.Equal(t, "api.post", env.Meta.Plan["action"], "plan.action must reflect auto-promoted POST")
assert.Equal(t, "POST", env.Meta.Plan["method"])
}
// TestApi_DryRunWithPost_EmitsPlan: POST + --dry-run + --input - must emit
// the standard envelope with action=api.post, method/path echoed, and the
// stdin body parsed as JSON under plan.body. No SDK call expected (factory
// would panic if Client() were touched).
func TestApi_DryRunWithPost_EmitsPlan(t *testing.T) {
out, _ := iostreams.SetForTest(t)
cmd := NewCmd(apiDryRunFactory(t))
// StdinReader is on Options; set it via the recovered options binding by
// running through the root harness with --input - and trusting iostreams.IO.In.
// Simplest path: write to IO.In directly via SetForTest's reader swap.
iostreams.IO.In = strings.NewReader(`{"name":"foo"}`)
root := withRootHarness(cmd,
"/api/v1/knowledge-bases", "-X", "POST", "--input", "-", "--dry-run", "--format", "json")
require.NoError(t, root.Execute(), "POST + --dry-run must succeed (exit 0) without SDK")
var env struct {
OK bool `json:"ok"`
Meta struct {
DryRun bool `json:"dry_run"`
Plan map[string]any `json:"plan"`
} `json:"meta"`
}
require.NoError(t, json.Unmarshal(out.Bytes(), &env), "expected valid JSON envelope, got %q", out.String())
assert.True(t, env.OK)
assert.True(t, env.Meta.DryRun)
assert.Equal(t, "api.post", env.Meta.Plan["action"], "plan.action must lowercase the method")
assert.Equal(t, "POST", env.Meta.Plan["method"], "plan.method must be uppercase")
assert.Equal(t, "/api/v1/knowledge-bases", env.Meta.Plan["path"])
// Body decoded as JSON object (best-effort) for downstream agent inspection.
body, ok := env.Meta.Plan["body"].(map[string]any)
require.True(t, ok, "plan.body must be a JSON object when --input is valid JSON, got %T", env.Meta.Plan["body"])
assert.Equal(t, "foo", body["name"])
}
// TestApi_FieldBody_TypedDryRun: -F/--field builds a typed JSON object body —
// true/false/null and numbers are typed, everything else stays a string — and
// the resolved body is surfaced in the dry-run plan for agent inspection.
func TestApi_FieldBody_TypedDryRun(t *testing.T) {
out, _ := iostreams.SetForTest(t)
root := withRootHarness(NewCmd(apiDryRunFactory(t)),
"/api/v1/x", "-X", "POST",
"-F", "name=Hello", "-F", "enabled=true", "-F", "count=3",
"-F", "ratio=1.5", "-F", "empty=null",
"--dry-run", "--format", "json")
require.NoError(t, root.Execute(), "-F + --dry-run must succeed without SDK")
var env struct {
Meta struct {
Plan map[string]any `json:"plan"`
} `json:"meta"`
}
require.NoError(t, json.Unmarshal(out.Bytes(), &env), "envelope: %q", out.String())
body, ok := env.Meta.Plan["body"].(map[string]any)
require.True(t, ok, "plan.body must be a JSON object, got %T", env.Meta.Plan["body"])
assert.Equal(t, "Hello", body["name"], "non-numeric stays string")
assert.Equal(t, true, body["enabled"], "true -> JSON bool")
assert.Equal(t, float64(3), body["count"], "integer -> JSON number")
assert.Equal(t, 1.5, body["ratio"], "float -> JSON number")
assert.Nil(t, body["empty"], "null -> JSON null")
}
// TestApi_FieldBody_AutoPromotesPost: -F on its own (no -X) auto-promotes
// GET -> POST, matching -d/--input body behavior.
func TestApi_FieldBody_AutoPromotesPost(t *testing.T) {
out, _ := iostreams.SetForTest(t)
root := withRootHarness(NewCmd(apiDryRunFactory(t)),
"/api/v1/x", "-F", "a=b", "--dry-run", "--format", "json")
require.NoError(t, root.Execute())
var env struct {
Meta struct {
Plan map[string]any `json:"plan"`
} `json:"meta"`
}
require.NoError(t, json.Unmarshal(out.Bytes(), &env))
assert.Equal(t, "POST", env.Meta.Plan["method"], "-F must auto-promote GET -> POST")
}
// TestApi_FieldBody_ConflictsWithData: -F and -d are mutually exclusive — the
// conflict is reported as input.invalid_argument (exit 5), consistent with the
// existing -d/--input conflict.
func TestApi_FieldBody_ConflictsWithData(t *testing.T) {
iostreams.SetForTest(t)
root := withRootHarness(NewCmd(apiDryRunFactory(t)),
"/api/v1/x", "-X", "POST", "-F", "a=b", "-d", "{}", "--dry-run", "--format", "json")
err := root.Execute()
require.Error(t, err, "-F + -d must conflict")
var ce *cmdutil.Error
require.ErrorAs(t, err, &ce)
assert.Equal(t, cmdutil.CodeInputInvalidArgument, ce.Code)
assert.Equal(t, 5, cmdutil.ExitCode(err))
}
// TestApi_FieldBody_Malformed: a -F value without '=' (or empty key) is a typed
// input error, not a panic or a silently-dropped field.
func TestApi_FieldBody_Malformed(t *testing.T) {
iostreams.SetForTest(t)
root := withRootHarness(NewCmd(apiDryRunFactory(t)),
"/api/v1/x", "-X", "POST", "-F", "nope", "--dry-run", "--format", "json")
err := root.Execute()
require.Error(t, err)
var ce *cmdutil.Error
require.ErrorAs(t, err, &ce)
assert.Equal(t, cmdutil.CodeInputInvalidArgument, ce.Code)
assert.Contains(t, err.Error(), "key=value")
}
+711
View File
@@ -0,0 +1,711 @@
package api
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
sdk "github.com/Tencent/WeKnora/client"
)
// fakeAPISvc is a test double for Service that delegates each call to a
// caller-supplied do function, giving full control over per-call responses.
type fakeAPISvc struct {
do func(method, path string, body any) (*http.Response, error)
}
func (f *fakeAPISvc) Raw(_ context.Context, method, path string, body any) (*http.Response, error) {
return f.do(method, path, body)
}
// newTestClient stands up an httptest server with the supplied handler and
// returns an *sdk.Client targeting it plus a teardown closure. The real SDK is
// used so we exercise the same Raw() code path as production (header
// injection, JSON marshalling, etc.).
func newTestClient(t *testing.T, h http.HandlerFunc) (*sdk.Client, func()) {
t.Helper()
srv := httptest.NewServer(h)
return sdk.NewClient(srv.URL), srv.Close
}
func TestAPI_GetSuccess(t *testing.T) {
out, _ := iostreams.SetForTest(t)
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet || r.URL.Path != "/api/v1/foo" {
t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"hello":"world"}`))
})
defer stop()
if err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "GET", "/api/v1/foo", false); err != nil {
t.Fatalf("runAPI: %v", err)
}
got := out.String()
if !strings.Contains(got, `"hello":"world"`) {
t.Errorf("expected raw JSON body in stdout, got %q", got)
}
if !strings.HasSuffix(got, "\n") {
t.Errorf("expected trailing newline appended, got %q", got)
}
}
func TestAPI_GetSuccess_JSON(t *testing.T) {
out, _ := iostreams.SetForTest(t)
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Request-Id", "req-123")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"value":42}`))
})
defer stop()
if err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, cli, "GET", "/api/v1/foo", false); err != nil {
t.Fatalf("runAPI: %v", err)
}
// The server response is passed through directly under envelope.data — no
// {status, headers, body} wrapper — so consumers project at the server's
// own depth (e.g. .data.value here).
var env struct {
OK bool `json:"ok"`
Data map[string]any `json:"data"`
}
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
t.Fatalf("decode envelope JSON: %v\n%s", err, out.String())
}
if !env.OK {
t.Errorf("envelope ok: want true, got false")
}
if v, ok := env.Data["value"]; !ok || v.(float64) != 42 {
t.Errorf("data.value: want 42 directly under .data (no .body nesting), got %v", env.Data)
}
}
// TestAPI_InlineDataBody verifies -d/--data sends an inline JSON body and
// auto-promotes the method to POST.
func TestAPI_InlineDataBody(t *testing.T) {
_, _ = iostreams.SetForTest(t)
var seenBody []byte
var seenMethod string
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
seenMethod = r.Method
seenBody, _ = io.ReadAll(r.Body)
_, _ = w.Write([]byte(`{"id":"new"}`))
})
defer stop()
opts := &Options{Data: `{"name":"foo"}`}
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, resolveMethod(opts), "/api/v1/things", false); err != nil {
t.Fatalf("runAPI: %v", err)
}
if seenMethod != http.MethodPost {
t.Errorf("inline -d should auto-promote to POST, got %s", seenMethod)
}
if string(seenBody) != `{"name":"foo"}` {
t.Errorf("server received body %q, want the inline --data JSON", seenBody)
}
}
// TestAPI_InlineDataMalformed_RejectedAsInput pins that a malformed -d body is
// rejected as input.invalid_argument before any request.
func TestAPI_InlineDataMalformed_RejectedAsInput(t *testing.T) {
_, _ = iostreams.SetForTest(t)
called := false
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
called = true
_, _ = w.Write([]byte(`{}`))
})
defer stop()
opts := &Options{Data: `{bad`}
err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, cli, "POST", "/api/v1/things", false)
var typed *cmdutil.Error
if !errors.As(err, &typed) || typed.Code != cmdutil.CodeInputInvalidArgument {
t.Errorf("want input.invalid_argument for malformed -d, got %v", err)
}
if called {
t.Error("server must not be called with a malformed inline body")
}
}
func TestAPI_PostWithStdinInput(t *testing.T) {
_, _ = iostreams.SetForTest(t)
var seenBody []byte
var seenMethod, seenPath string
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
seenMethod = r.Method
seenPath = r.URL.Path
seenBody, _ = io.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"id":"new"}`))
})
defer stop()
opts := &Options{Input: "-", StdinReader: strings.NewReader(`{"name":"foo"}`)}
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "POST", "/api/v1/things", false); err != nil {
t.Fatalf("runAPI: %v", err)
}
if seenMethod != http.MethodPost || seenPath != "/api/v1/things" {
t.Errorf("server saw %s %s, want POST /api/v1/things", seenMethod, seenPath)
}
if string(seenBody) != `{"name":"foo"}` {
t.Errorf("server received body %q, want %q", seenBody, `{"name":"foo"}`)
}
}
// TestAPI_MalformedInputJSON_RejectedAsInput pins that a non-JSON --input body
// is rejected with input.invalid_argument (exit 5) at the boundary, not the
// confusing network.error (exit 7, "retryable") the SDK's marshal step
// produced. The server must never be called.
func TestAPI_MalformedInputJSON_RejectedAsInput(t *testing.T) {
_, _ = iostreams.SetForTest(t)
called := false
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
called = true
_, _ = w.Write([]byte(`{}`))
})
defer stop()
opts := &Options{Input: "-", StdinReader: strings.NewReader(`{bad json`)}
err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, cli, "POST", "/api/v1/things", false)
if err == nil {
t.Fatal("expected an error for malformed --input JSON")
}
var typed *cmdutil.Error
if !errors.As(err, &typed) || typed.Code != cmdutil.CodeInputInvalidArgument {
t.Errorf("want input.invalid_argument, got %v", err)
}
if called {
t.Error("server must not be called with a malformed body")
}
}
// TestAPI_InputFile verifies --input <file> reads the request body from disk.
func TestAPI_InputFile(t *testing.T) {
_, _ = iostreams.SetForTest(t)
tmp := filepath.Join(t.TempDir(), "body.json")
payload := `{"k":"from-file"}`
if err := os.WriteFile(tmp, []byte(payload), 0o600); err != nil {
t.Fatalf("write temp: %v", err)
}
var seenBody []byte
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
seenBody, _ = io.ReadAll(r.Body)
_, _ = w.Write([]byte(`{}`))
})
defer stop()
opts := &Options{Input: tmp}
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "POST", "/api/v1/x", false); err != nil {
t.Fatalf("runAPI: %v", err)
}
if string(seenBody) != payload {
t.Errorf("body from --input: got %q, want %q", seenBody, payload)
}
}
// TestAPI_InputDash_Stdin verifies the "--input -" form: the payload comes
// from opts.StdinReader (production-default iostreams.IO.In).
func TestAPI_InputDash_Stdin(t *testing.T) {
_, _ = iostreams.SetForTest(t)
var seenBody []byte
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
seenBody, _ = io.ReadAll(r.Body)
_, _ = w.Write([]byte(`{}`))
})
defer stop()
payload := `{"k":"from-stdin"}`
opts := &Options{Input: "-", StdinReader: strings.NewReader(payload)}
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "POST", "/api/v1/x", false); err != nil {
t.Fatalf("runAPI: %v", err)
}
if string(seenBody) != payload {
t.Errorf("body from --input -: got %q, want %q", seenBody, payload)
}
}
func TestAPI_NotFound(t *testing.T) {
_, _ = iostreams.SetForTest(t)
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"error":"missing"}`))
})
defer stop()
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, "GET", "/api/v1/missing", false)
if err == nil {
t.Fatal("expected error for 404")
}
if !cmdutil.IsNotFound(err) {
t.Errorf("expected resource.not_found, got %v", err)
}
}
func TestAPI_AcceptsArbitraryMethod(t *testing.T) {
_, _ = iostreams.SetForTest(t)
var seenMethod string
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
seenMethod = r.Method
w.WriteHeader(http.StatusOK)
})
defer stop()
for _, m := range []string{"OPTIONS", "PATCH", "TRACE", "CUSTOM"} {
t.Run(m, func(t *testing.T) {
seenMethod = ""
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, cli, m, "/api/v1/things", false)
if err != nil {
t.Fatalf("expected method %q to be accepted, got %v", m, err)
}
if seenMethod != m {
t.Errorf("server saw method %q, want %q", seenMethod, m)
}
})
}
}
func TestAPI_EmptyMethodRejected(t *testing.T) {
_, _ = iostreams.SetForTest(t)
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, nil, "", "/api/v1/things", false)
if err == nil {
t.Fatal("expected error for empty method")
}
var fe *cmdutil.FlagError
if !errors.As(err, &fe) {
t.Errorf("expected FlagError, got %T %v", err, err)
}
}
func TestAPI_PathWithoutSlash(t *testing.T) {
_, _ = iostreams.SetForTest(t)
err := runAPI(context.Background(), &Options{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, nil, "GET", "api/v1/things", false)
if err == nil {
t.Fatal("expected error for missing leading slash")
}
var ce *cmdutil.Error
if !asTypedError(err, &ce) || ce.Code != cmdutil.CodeInputInvalidArgument {
t.Errorf("expected input.invalid_argument, got %v", err)
}
}
// withRootHarness wraps `weknora api ...` under a synthetic root cmd that
// registers the global persistent flags (mirrors addGlobalFlags in
// cmd/root.go). Required because api's NewCmd doesn't register --yes /
// --format / --jq itself — it inherits them from root in production.
func withRootHarness(api *cobra.Command, args ...string) *cobra.Command {
root := &cobra.Command{Use: "weknora"}
pf := root.PersistentFlags()
pf.BoolP("yes", "y", false, "")
pf.String("format", "", "")
pf.StringP("jq", "q", "", "")
root.AddCommand(api)
root.SetArgs(append([]string{"api"}, args...))
root.SetContext(context.Background())
root.SilenceErrors = true
root.SilenceUsage = true
return root
}
// TestAPI_DELETE_RequiresConfirmation pins the exit-10 protocol on the
// escape-hatch DELETE path: agent invokes `weknora api DELETE /...` without
// -y/--yes, must get input.confirmation_required + exit 10. Confirmation is
// enforced in NewCmd.RunE (not runAPI), so the test drives the cobra cmd.
func TestAPI_DELETE_RequiresConfirmation(t *testing.T) {
iostreams.SetForTest(t) // non-TTY
f := &cmdutil.Factory{
Client: func() (*sdk.Client, error) { return nil, nil },
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
}
root := withRootHarness(NewCmd(f), "/api/v1/knowledge-bases/kb_xxx", "-X", "DELETE")
err := root.Execute()
if err == nil {
t.Fatal("expected confirmation_required error for DELETE without -y")
}
var ce *cmdutil.Error
if !asTypedError(err, &ce) || ce.Code != cmdutil.CodeInputConfirmationRequired {
t.Errorf("want input.confirmation_required, got %v", err)
}
if got := cmdutil.ExitCode(err); got != 10 {
t.Errorf("exit code = %d, want 10", got)
}
}
// TestAPI_DELETE_WithYes_Proceeds: -y/--yes opt-in skips confirmation and
// dispatches to the SDK. Server returns 200 to verify the happy-path lands
// on the response body emit.
func TestAPI_DELETE_WithYes_Proceeds(t *testing.T) {
iostreams.SetForTest(t)
called := false
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete {
t.Errorf("expected DELETE, got %s", r.Method)
}
called = true
w.WriteHeader(http.StatusOK)
})
defer stop()
f := &cmdutil.Factory{
Client: func() (*sdk.Client, error) { return cli, nil },
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
}
root := withRootHarness(NewCmd(f), "/api/v1/knowledge-bases/kb_xxx", "-X", "DELETE", "-y")
if err := root.Execute(); err != nil {
t.Fatalf("execute: %v", err)
}
if !called {
t.Error("DELETE handler not called - confirmation may have blocked")
}
}
// asTypedError is a tiny wrapper around errors.As that keeps the call sites
// concise. Returns true on success, populating dst.
func asTypedError(err error, dst **cmdutil.Error) bool {
for e := err; e != nil; {
if t, ok := e.(*cmdutil.Error); ok {
*dst = t
return true
}
type unwrapper interface{ Unwrap() error }
u, ok := e.(unwrapper)
if !ok {
return false
}
e = u.Unwrap()
}
return false
}
func TestAPI_PaginateTruncatedHTTPBody(t *testing.T) {
for _, mode := range []cmdutil.FormatMode{cmdutil.FormatJSON, cmdutil.FormatText} {
t.Run(string(mode), func(t *testing.T) {
out, _ := iostreams.SetForTest(t)
var calls atomic.Int32
cli, stop := newTestClient(t, func(w http.ResponseWriter, _ *http.Request) {
calls.Add(1)
body := `{"data":[{"id":"1"}`
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", fmt.Sprint(len(body)+1))
_, _ = io.WriteString(w, body)
})
defer stop()
fopts := &cmdutil.FormatOptions{Mode: mode}
err := runAPI(context.Background(), &Options{}, fopts, cli, "GET", "/api/v1/items", true)
require.ErrorIs(t, err, io.ErrUnexpectedEOF, "stdout: %q", out.String())
var ce *cmdutil.Error
require.ErrorAs(t, err, &ce)
assert.Equal(t, cmdutil.CodeNetworkError, ce.Code)
assert.Empty(t, out.String(), "stdout must be empty on a failed transfer")
assert.Equal(t, int32(1), calls.Load())
})
}
}
type apiResponseBody struct {
data string
err error
closeCalls int
}
func (b *apiResponseBody) Read(p []byte) (int, error) {
n := copy(p, b.data)
b.data = b.data[n:]
if len(b.data) == 0 {
return n, b.err
}
return n, nil
}
func (b *apiResponseBody) Close() error {
b.closeCalls++
return nil
}
func TestAPI_PaginateReadError(t *testing.T) {
readErr := errors.New("response body read failed")
for _, tt := range []struct {
name string
failedPage int
body string
status int
}{
{"first complete page", 1, `{"data":[{"id":"1"}],"total":1,"page_size":1}`, http.StatusOK},
{"first non-paginated response", 1, `{"hello":"world"}`, http.StatusOK},
{"later complete page", 2, `{"data":[{"id":"2"}],"total":2,"page_size":1}`, http.StatusOK},
{"later truncated page", 2, `{"data":[`, http.StatusOK},
{"later page with more results", 2, `{"data":[{"id":"2"}],"total":3,"page_size":1}`, http.StatusOK},
{"error status", 1, `{"error":"unavailable"}`, http.StatusBadGateway},
} {
for _, mode := range []cmdutil.FormatMode{cmdutil.FormatJSON, cmdutil.FormatText} {
t.Run(tt.name+"/"+string(mode), func(t *testing.T) {
out, _ := iostreams.SetForTest(t)
var bodies []*apiResponseBody
calls := 0
svc := &fakeAPISvc{do: func(_, _ string, _ any) (*http.Response, error) {
calls++
if calls > tt.failedPage {
return nil, errors.New("requested another page after a failed read")
}
for i, body := range bodies {
assert.Equal(t, 1, body.closeCalls, "page %d must close before the next request", i+1)
}
body := &apiResponseBody{
data: `{"data":[{"id":"1"}],"total":3,"page_size":1}`,
err: io.EOF,
}
status := http.StatusOK
if calls == tt.failedPage {
body.data, body.err, status = tt.body, readErr, tt.status
}
bodies = append(bodies, body)
return &http.Response{StatusCode: status, Body: body, Header: make(http.Header)}, nil
}}
fopts := &cmdutil.FormatOptions{Mode: mode}
err := runAPI(context.Background(), &Options{}, fopts, svc, "GET", "/api/v1/items", true)
require.ErrorIs(t, err, readErr, "stdout: %q; requests: %d", out.String(), calls)
var ce *cmdutil.Error
require.ErrorAs(t, err, &ce)
assert.Equal(t, cmdutil.CodeNetworkError, ce.Code)
assert.Equal(t, "read response body", ce.Message)
assert.Empty(t, out.String(), "stdout must not contain partial results")
assert.Equal(t, tt.failedPage, calls)
for i, body := range bodies {
assert.Equal(t, 1, body.closeCalls, "page %d body must close exactly once", i+1)
}
})
}
}
}
func TestAPI_PaginateMergesPages(t *testing.T) {
pages := [][]byte{
[]byte(`{"success":true,"data":[{"id":"1"},{"id":"2"}],"total":5,"page":1,"page_size":2}`),
[]byte(`{"success":true,"data":[{"id":"3"},{"id":"4"}],"total":5,"page":2,"page_size":2}`),
[]byte(`{"success":true,"data":[{"id":"5"}],"total":5,"page":3,"page_size":2}`),
}
idx := 0
svc := &fakeAPISvc{do: func(method, path string, _ any) (*http.Response, error) {
if idx >= len(pages) {
return nil, fmt.Errorf("too many calls; idx=%d", idx)
}
body := pages[idx]
idx++
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader(body)),
Header: make(http.Header),
}, nil
}}
out, _ := iostreams.SetForTest(t)
opts := &Options{}
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "GET", "/api/v1/knowledge-base?page=1&page_size=2", true); err != nil {
t.Fatalf("runAPI: %v", err)
}
var env struct {
OK bool `json:"ok"`
Data struct {
Data []map[string]string `json:"data"`
Total int `json:"total"`
} `json:"data"`
}
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
t.Fatalf("unmarshal: %v\n%s", err, out.String())
}
got := env.Data
if len(got.Data) != 5 || got.Total != 5 {
t.Errorf("got %d records (total %d), want 5/5", len(got.Data), got.Total)
}
if idx != 3 {
t.Errorf("called %d times, want 3", idx)
}
}
func TestAPI_PaginateIgnoredForPOST(t *testing.T) {
// --paginate should be a no-op for non-GET methods (no pagination
// semantic for POST/PUT/DELETE). Single call expected.
called := 0
svc := &fakeAPISvc{do: func(method, path string, _ any) (*http.Response, error) {
called++
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader([]byte(`{"success":true,"data":[],"total":5,"page":1,"page_size":2}`))),
Header: make(http.Header),
}, nil
}}
_, _ = iostreams.SetForTest(t)
opts := &Options{Input: "-", StdinReader: strings.NewReader(`{"name":"foo"}`)}
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "POST", "/api/v1/knowledge-base", true); err != nil {
t.Fatalf("runAPI: %v", err)
}
if called != 1 {
t.Errorf("called %d times, want 1 (POST should not paginate)", called)
}
}
func TestAPI_PaginateNoMetadataPassesThrough(t *testing.T) {
// If response doesn't look paginated (no total/page/page_size), --paginate
// should fall back to single-call envelope behavior (same shape as api without --paginate).
called := 0
svc := &fakeAPISvc{do: func(method, path string, _ any) (*http.Response, error) {
called++
hdr := make(http.Header)
hdr.Set("Content-Type", "application/json")
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader([]byte(`{"hello":"world"}`))),
Header: hdr,
}, nil
}}
out, _ := iostreams.SetForTest(t)
opts := &Options{}
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "GET", "/api/v1/whoami", true); err != nil {
t.Fatalf("runAPI: %v", err)
}
if called != 1 {
t.Errorf("called %d times, want 1 (non-paginated response)", called)
}
// The non-paginated fallback must emit the SAME flat shape as a single
// call: the server response directly under .data (no {status,headers,body}
// wrapper), so --paginate and single-call project identically.
var env struct {
OK bool `json:"ok"`
Data map[string]any `json:"data"`
}
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
t.Fatalf("non-paginated fallback must emit envelope JSON, unmarshal failed: %v\n%s", err, out.String())
}
if !env.OK {
t.Errorf("envelope ok: want true, got false")
}
if v, ok := env.Data["hello"]; !ok || v.(string) != "world" {
t.Errorf("fallback must pass the body through flat under .data (.data.hello), got %v", env.Data)
}
}
// TestAPI_PaginateServerCapsPageSize covers the case where the user
// requests --page_size=50 but the server caps page_size at a smaller
// value (e.g. 2). Termination must count actually-collected records
// (len(allData)) not requested-page-count (page*pageSize) — otherwise
// we'd break early and silently truncate results.
func TestAPI_PaginateServerCapsPageSize(t *testing.T) {
// User asks page_size=10; server only ever returns 2 per page (cap).
// Total = 5 records; should make 3 calls (2+2+1) and return all 5.
pages := [][]byte{
[]byte(`{"success":true,"data":[{"id":"1"},{"id":"2"}],"total":5,"page":1,"page_size":2}`),
[]byte(`{"success":true,"data":[{"id":"3"},{"id":"4"}],"total":5,"page":2,"page_size":2}`),
[]byte(`{"success":true,"data":[{"id":"5"}],"total":5,"page":3,"page_size":2}`),
}
idx := 0
svc := &fakeAPISvc{do: func(_, _ string, _ any) (*http.Response, error) {
if idx >= len(pages) {
return nil, fmt.Errorf("too many calls; idx=%d", idx)
}
body := pages[idx]
idx++
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader(body)),
Header: make(http.Header),
}, nil
}}
var stdout bytes.Buffer
iostreams.IO.Out = &stdout
defer func() { iostreams.IO.Out = os.Stdout }()
opts := &Options{}
// User requests page_size=10; server caps at 2 each response.
if err := runAPI(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, svc, "GET", "/api/v1/items?page=1&page_size=10", true); err != nil {
t.Fatalf("runAPI: %v", err)
}
var env struct {
OK bool `json:"ok"`
Data struct {
Data []map[string]string `json:"data"`
Total int `json:"total"`
} `json:"data"`
}
if err := json.Unmarshal(stdout.Bytes(), &env); err != nil {
t.Fatalf("unmarshal: %v\n%s", err, stdout.String())
}
got := env.Data
if len(got.Data) != 5 {
t.Errorf("got %d records, want 5 (server-capped page_size should not cause truncation)", len(got.Data))
}
}
// TestAPI_PUT_RequiresConfirmation pins the exit-10 write gate on the
// escape-hatch PUT path: `weknora api -X PUT /...` mutates server state the
// same way a typed `kb update` does, so it must require -y (exit 10) rather
// than silently writing. Regression: only DELETE was gated, letting an agent
// bypass the write-confirmation protocol via raw PUT/PATCH.
func TestAPI_PUT_RequiresConfirmation(t *testing.T) {
for _, method := range []string{"PUT", "PATCH"} {
t.Run(method, func(t *testing.T) {
iostreams.SetForTest(t) // non-TTY
f := &cmdutil.Factory{
Client: func() (*sdk.Client, error) { return nil, nil },
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
}
root := withRootHarness(NewCmd(f), "/api/v1/knowledge-bases/kb_xxx", "-X", method, "-F", "name=x")
err := root.Execute()
if err == nil {
t.Fatalf("expected confirmation_required for %s without -y", method)
}
var ce *cmdutil.Error
if !asTypedError(err, &ce) || ce.Code != cmdutil.CodeInputConfirmationRequired {
t.Errorf("want input.confirmation_required, got %v", err)
}
if got := cmdutil.ExitCode(err); got != 10 {
t.Errorf("exit code = %d, want 10", got)
}
})
}
}
// TestAPI_POST_NotGated: POST is create-shaped and, like typed `kb create`,
// intentionally ungated — it must reach the SDK without a confirmation gate.
func TestAPI_POST_NotGated(t *testing.T) {
iostreams.SetForTest(t)
called := false
cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {
called = true
w.WriteHeader(http.StatusOK)
})
defer stop()
f := &cmdutil.Factory{
Client: func() (*sdk.Client, error) { return cli, nil },
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
}
root := withRootHarness(NewCmd(f), "/api/v1/knowledge-bases", "-X", "POST", "-F", "name=x")
if err := root.Execute(); err != nil {
t.Fatalf("execute: %v", err)
}
if !called {
t.Error("POST handler not called - POST must not be gated")
}
}
+237
View File
@@ -0,0 +1,237 @@
package api_test
import (
"bytes"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/cmd"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
func TestAPI_PaginateFormats(t *testing.T) {
one := []string{`{"data":[{"id":"1"}],"total":1,"page":1,"page_size":1}`}
pages := []string{
`{"data":[{"id":"1"}],"total":3,"page":1,"page_size":1}`,
`{"data":[{"id":"2"}],"total":3,"page":2,"page_size":1}`,
`{"data":[{"id":"3"}],"total":3,"page":3,"page_size":1}`,
}
empty := []string{`{"data":[],"total":0,"page":1,"page_size":1}`}
merged := `{"data":[{"id":"1"},{"id":"2"},{"id":"3"}],"total":3}`
envelope := `{"ok":true,"data":` + merged + `}`
preciseData := `[9007199254740993,{"n":9007199254740993,"nested":[1.25e+3,true,null,"007"]}]`
precise := []string{`{"data":` + preciseData + `,"total":2,"page_size":2}`}
preciseMerged := `{"data":` + preciseData + `,"total":2}`
cases := []struct {
name string
bodies []string
flags []string
env string
json string
raw string
tty bool
post bool
single bool
wantExit int
}{
{
name: "text single page", bodies: one, flags: []string{"--format", "text"},
json: `{"data":[{"id":"1"}],"total":1}`,
},
{name: "text multiple capped pages", bodies: pages, flags: []string{"--format", "text"}, json: merged},
{name: "text empty", bodies: empty, flags: []string{"--format", "text"}, json: `{"data":[],"total":0}`},
{name: "text environment", bodies: pages, env: "text", json: merged},
{
name: "text flag overrides json environment", bodies: pages, env: "json",
flags: []string{"--format", "text"}, json: merged,
},
{
name: "json flag overrides text environment", bodies: pages, env: "text",
flags: []string{"--format", "json"}, json: envelope,
},
{name: "default pipe", bodies: pages, json: envelope},
{name: "default tty", bodies: pages, tty: true, json: envelope},
{name: "json", bodies: pages, flags: []string{"--format", "json"}, json: envelope},
{name: "ndjson", bodies: pages, flags: []string{"--format", "ndjson"}, json: merged},
{
name: "json jq", bodies: pages, env: "text",
flags: []string{"--format", "json", "--jq", ".data.data | length"}, json: "3",
},
{
name: "ndjson jq", bodies: pages, env: "text",
flags: []string{"--format", "ndjson", "--jq", ".data | length"}, json: "3",
},
{
name: "text environment jq rejected", bodies: pages, env: "text",
flags: []string{"--jq", ".data | length"}, wantExit: 2,
},
{
name: "text environment malformed jq rejected", bodies: pages, env: "text",
flags: []string{"--jq", "["}, wantExit: 2,
},
{name: "text jq rejected", bodies: pages, flags: []string{"--format", "text", "--jq", ".data"}, wantExit: 2},
{name: "text precise values", bodies: precise, flags: []string{"--format", "text"}, json: preciseMerged},
{
name: "json precise values", bodies: precise, flags: []string{"--format", "json"},
json: `{"ok":true,"data":` + preciseMerged + `}`,
},
{name: "ndjson precise values", bodies: precise, flags: []string{"--format", "ndjson"}, json: preciseMerged},
{
name: "text no metadata", bodies: []string{` {"data":[9007199254740993]} `},
flags: []string{"--format", "text"}, raw: " {\"data\":[9007199254740993]} \n",
},
{
name: "text non json fallback", bodies: []string{"healthy"},
flags: []string{"--format", "text"}, raw: "healthy\n",
},
{
name: "text fallback existing newline", bodies: []string{"healthy\n"},
flags: []string{"--format", "text"}, raw: "healthy\n",
},
{name: "text fallback empty body", bodies: []string{""}, flags: []string{"--format", "text"}},
{name: "text non GET", bodies: one, flags: []string{"--format", "text"}, post: true, raw: one[0] + "\n"},
{
name: "text non paginated", bodies: one, flags: []string{"--format", "text"},
single: true, raw: one[0] + "\n",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("WEKNORA_FORMAT", tc.env)
t.Setenv("WEKNORA_PROFILE", "")
out, errOut := iostreams.SetForTest(t)
if tc.tty {
out, errOut = iostreams.SetForTestWithTTY(t)
}
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
n := int(calls.Add(1))
assert.Equal(t, "/api/v1/items", r.URL.Path)
assert.Equal(t, "active", r.URL.Query().Get("status"))
method := http.MethodGet
if tc.post {
method = http.MethodPost
}
assert.Equal(t, method, r.Method)
if !tc.post && !tc.single {
assert.Equal(t, strconv.Itoa(n), r.URL.Query().Get("page"))
assert.Equal(t, "50", r.URL.Query().Get("page_size"))
} else {
assert.Empty(t, r.URL.Query().Get("page"))
}
if n > len(tc.bodies) {
t.Errorf("unexpected request %d", n)
http.Error(w, "too many requests", http.StatusInternalServerError)
return
}
_, _ = io.WriteString(w, tc.bodies[n-1])
}))
defer srv.Close()
f := &cmdutil.Factory{Client: func() (*sdk.Client, error) { return sdk.NewClient(srv.URL), nil }}
root := cmd.NewRootCmd(f)
root.SetOut(out)
root.SetErr(errOut)
args := append([]string{}, tc.flags...)
args = append(args, "api", "/api/v1/items?status=active")
if !tc.single {
args = append(args, "--paginate")
}
if tc.post {
args = append(args, "-X", "POST")
}
root.SetArgs(args)
err := root.Execute()
if tc.wantExit != 0 {
require.Error(t, err)
assert.Equal(t, tc.wantExit, cmdutil.ExitCode(err))
assert.Contains(t, err.Error(), "--jq requires --format json|ndjson")
assert.Zero(t, calls.Load())
assert.Empty(t, out.String())
return
}
require.NoError(t, err)
assert.Equal(t, int32(len(tc.bodies)), calls.Load())
assert.Empty(t, errOut.String())
if tc.json == "" {
assert.Equal(t, tc.raw, out.String())
return
}
assert.True(t, strings.HasSuffix(out.String(), "\n"))
// UseNumber keeps this comparison sensitive to RawMessage precision loss.
decode := func(s string) any {
d := json.NewDecoder(strings.NewReader(s))
d.UseNumber()
var v any
require.NoError(t, d.Decode(&v))
var extra any
require.ErrorIs(t, d.Decode(&extra), io.EOF, "expected one JSON value")
return v
}
assert.Equal(t, decode(tc.json), decode(out.String()))
if !tc.tty {
assert.Equal(t, 1, strings.Count(out.String(), "\n"))
}
})
}
}
type paginationFailWriter struct {
body bytes.Buffer
err error
tail bool
}
func (w *paginationFailWriter) Write(p []byte) (int, error) {
if w.tail {
// Fail on the newline even if the encoder writes it with the body.
if i := bytes.IndexByte(p, '\n'); i >= 0 {
n, _ := w.body.Write(p[:i])
return n, w.err
}
return w.body.Write(p)
}
return 0, w.err
}
func TestAPI_PaginateTextWriteError(t *testing.T) {
for _, tail := range []bool{false, true} {
t.Run(strconv.FormatBool(tail), func(t *testing.T) {
t.Setenv("WEKNORA_PROFILE", "")
iostreams.SetForTest(t)
sentinel := errors.New("synthetic output failure")
out := &paginationFailWriter{err: sentinel, tail: tail}
iostreams.IO.Out = out
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = io.WriteString(w, `{"data":[{"id":"1"}],"total":1,"page_size":1}`)
}))
defer srv.Close()
f := &cmdutil.Factory{Client: func() (*sdk.Client, error) { return sdk.NewClient(srv.URL), nil }}
root := cmd.NewRootCmd(f)
root.SetArgs([]string{"api", "/api/v1/items", "--paginate", "--format", "text"})
err := root.Execute()
require.ErrorIs(t, err, sentinel)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeLocalFileIO, typed.Code)
assert.Equal(t, 1, cmdutil.ExitCode(err))
if tail {
assert.NotEmpty(t, out.body.String())
} else {
assert.Empty(t, out.body.String())
}
})
}
}
+51
View File
@@ -0,0 +1,51 @@
// Package auth holds the cobra commands for authentication
// (login / logout / list / refresh / status / token).
package auth
import (
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
)
// Credential-mode tokens used in the JSON output of auth list / login /
// status / token. The string names describe the HTTP credential type rather
// than the login flow (e.g. JWT → bearer regardless of whether it was
// obtained via password or refresh) so an agent can branch directly on the
// header to construct: `Authorization: Bearer <token>` (ModeBearer) or
// `X-API-Key: <token>` (ModeAPIKey).
const (
ModeBearer = "bearer"
ModeAPIKey = "api-key"
ModeUnknown = "unknown"
)
// modeFromRefs maps the per-profile TokenRef / APIKeyRef presence to a
// canonical credential-mode token. Bearer wins when both are present -
// matches the precedence in cmdutil.buildClient.
func modeFromRefs(apiKeyRef, tokenRef string) string {
switch {
case tokenRef != "":
return ModeBearer
case apiKeyRef != "":
return ModeAPIKey
default:
return ModeUnknown
}
}
// NewCmdAuth builds the `weknora auth` command tree and registers its
// subcommands. Called from cli/cmd/root.go.
func NewCmdAuth(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "auth",
Short: "Manage authentication credentials and profiles",
}
cmd.AddCommand(NewCmdLogin(f, nil))
cmd.AddCommand(NewCmdLogout(f))
cmd.AddCommand(NewCmdList(f))
cmd.AddCommand(NewCmdRefresh(f))
cmd.AddCommand(NewCmdStatus(f))
cmd.AddCommand(NewCmdToken(f))
return cmd
}
+132
View File
@@ -0,0 +1,132 @@
package auth
import (
"context"
"strings"
"testing"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
"github.com/Tencent/WeKnora/cli/internal/secrets"
"github.com/Tencent/WeKnora/cli/internal/testutil"
sdk "github.com/Tencent/WeKnora/client"
)
func TestNewCmdAuth_TreeShape(t *testing.T) {
cmd := NewCmdAuth(&cmdutil.Factory{})
assert.Equal(t, "auth", cmd.Use)
subs := map[string]*cobra.Command{}
for _, c := range cmd.Commands() {
subs[c.Use] = c
}
assert.Contains(t, subs, "login")
assert.Contains(t, subs, "status")
}
func TestNewCmdLogin_FlagsRegistered(t *testing.T) {
cmd := NewCmdLogin(&cmdutil.Factory{}, nil)
// --format is a persistent root flag (v0.7); only per-command flags here.
assert.NotNil(t, cmd.Flags().Lookup("with-token"), "flag with-token missing")
// login authenticates the active profile; host/name come from config
// (created via `profile add`), so these flags are gone.
assert.Nil(t, cmd.Flags().Lookup("host"), "auth login must not declare --host (v0.9)")
assert.Nil(t, cmd.Flags().Lookup("name"), "auth login must not declare --name (v0.9)")
// --profile is the global persistent override; local registration would
// silently shadow it.
assert.Nil(t, cmd.Flags().Lookup("profile"), "auth login must not declare a local --profile flag (use the global --profile)")
}
func TestNewCmdLogin_InvokesRunF(t *testing.T) {
iostreams.SetForTest(t)
called := false
store := secrets.NewMemStore()
f := &cmdutil.Factory{
Secrets: func() (secrets.Store, error) { return store, nil },
}
cmd := NewCmdLogin(f, func(_ context.Context, opts *LoginOptions, _ *cmdutil.FormatOptions, _ *cmdutil.Factory, _ LoginService) error {
called = true
// host/profile resolve inside runLogin from the active profile;
// the runF seam just receives the parsed flags.
assert.True(t, opts.WithToken)
return nil
})
cmd.SetArgs([]string{"--with-token"})
require.NoError(t, cmd.Execute())
assert.True(t, called)
}
func TestLoginServiceFor(t *testing.T) {
assert.Nil(t, loginServiceFor(""))
assert.NotNil(t, loginServiceFor("https://x"))
}
func TestPersistAPIKey_WritesContext(t *testing.T) {
iostreams.SetForTest(t)
testutil.XDGTempDir(t)
store := secrets.NewMemStore()
f := &cmdutil.Factory{
Config: func() (*config.Config, error) { return config.Load() },
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
Secrets: func() (secrets.Store, error) { return store, nil },
}
// persistAPIKey MERGES into the existing active profile record (created
// via `profile add`) rather than creating it; seed it first.
require.NoError(t, config.Save(&config.Config{
CurrentProfile: "ci",
Profiles: map[string]config.Profile{"ci": {Host: "https://kb.example.com"}},
}))
opts := &LoginOptions{
Host: "https://kb.example.com",
Profile: "ci",
APIKey: "sk-zzz",
}
require.NoError(t, persistAPIKey(opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil))
v, _ := store.Get("ci", "api_key")
assert.Equal(t, "sk-zzz", v)
cfg, _ := f.Config()
assert.Equal(t, "ci", cfg.CurrentProfile, "active profile unchanged by login")
assert.Equal(t, "https://kb.example.com", cfg.Profiles["ci"].Host, "existing host preserved by merge")
// APIKeyRef should be the mem:// URI from the store's Ref method.
assert.Equal(t, "mem://ci/api_key", cfg.Profiles["ci"].APIKeyRef)
}
func TestPersistJWT_StoresBothTokens(t *testing.T) {
iostreams.SetForTest(t)
testutil.XDGTempDir(t)
store := secrets.NewMemStore()
f := &cmdutil.Factory{
Config: func() (*config.Config, error) { return config.Load() },
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
Secrets: func() (secrets.Store, error) { return store, nil },
}
opts := &LoginOptions{
Host: "https://x",
Profile: "p",
}
resp := &sdk.LoginResponse{
Token: "jwt-acc",
RefreshToken: "jwt-ref",
User: &sdk.AuthUser{Email: "a@b.c", TenantID: 7},
}
require.NoError(t, persistJWT(opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, f, resp))
a, _ := store.Get("p", "access")
r, _ := store.Get("p", "refresh")
assert.Equal(t, "jwt-acc", a)
assert.Equal(t, "jwt-ref", r)
}
func TestReadStdinTrimmed(t *testing.T) {
out, err := readStdinTrimmed(strings.NewReader(" hello \n"))
require.NoError(t, err)
assert.Equal(t, "hello", out)
out, err = readStdinTrimmed(nil)
require.NoError(t, err)
assert.Equal(t, "", out)
}
+124
View File
@@ -0,0 +1,124 @@
// Package auth — dryrun_validation_test.go asserts that --dry-run on
// auth subcommands rejects identically to the live path. Before the
// surrounding fix, validation lived in runX() and was reached only after
// HandleDryRun short-circuited, so --dry-run accepted invocations the live
// path would reject.
package auth
import (
"context"
"errors"
"testing"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
"github.com/Tencent/WeKnora/cli/internal/secrets"
sdk "github.com/Tencent/WeKnora/client"
)
// authDryRunFactory builds a Factory whose Client closure panics if invoked —
// dry-run must early-exit before any SDK call. Config is supplied via the cfg
// argument so each test gets isolated state.
func authDryRunFactory(t *testing.T, cfg *config.Config) *cmdutil.Factory {
t.Helper()
return &cmdutil.Factory{
Config: func() (*config.Config, error) { return cfg, nil },
Client: func() (*sdk.Client, error) {
t.Fatal("dry-run path must not call Factory.Client(); SDK side effect leaked")
return nil, nil
},
Prompter: func() prompt.Prompter {
t.Fatal("dry-run path must not call Factory.Prompter(); confirm-prompt side effect leaked")
return nil
},
Secrets: func() (secrets.Store, error) { return secrets.NewMemStore(), nil },
}
}
// withRootHarnessAuth wraps an auth subcommand under a synthetic root cmd
// that registers the global persistent flags.
func withRootHarnessAuth(sub *cobra.Command, args ...string) *cobra.Command {
root := &cobra.Command{Use: "weknora"}
pf := root.PersistentFlags()
pf.BoolP("yes", "y", false, "")
pf.String("format", "", "")
pf.StringP("jq", "q", "", "")
root.AddCommand(sub)
root.SetArgs(append([]string{sub.Name()}, args...))
root.SetContext(context.Background())
root.SilenceErrors = true
root.SilenceUsage = true
return root
}
// TestAuthLogout_DryRun_RejectsNoProfiles: empty config → live path returns
// auth.unauthenticated; --dry-run must do the same.
func TestAuthLogout_DryRun_RejectsNoProfiles(t *testing.T) {
iostreams.SetForTest(t)
cfg := &config.Config{}
root := withRootHarnessAuth(NewCmdLogout(authDryRunFactory(t, cfg)),
"--dry-run", "--format", "json")
err := root.Execute()
require.Error(t, err, "dry-run must reject empty config")
var typed *cmdutil.Error
require.True(t, errors.As(err, &typed), "expected *cmdutil.Error, got %T %v", err, err)
assert.Equal(t, cmdutil.CodeAuthUnauthenticated, typed.Code)
}
// TestAuthLogout_DryRun_RejectsMissingActiveProfile: the active profile name
// (e.g. set via the global --profile) has no config entry → live path returns
// local.profile_not_found; --dry-run must do the same.
func TestAuthLogout_DryRun_RejectsMissingActiveProfile(t *testing.T) {
iostreams.SetForTest(t)
cfg := &config.Config{
CurrentProfile: "ghost", // active profile with no matching entry
Profiles: map[string]config.Profile{"prod": {Host: "https://prod"}},
}
root := withRootHarnessAuth(NewCmdLogout(authDryRunFactory(t, cfg)),
"--dry-run", "--format", "json")
err := root.Execute()
require.Error(t, err, "dry-run must reject a missing active profile")
var typed *cmdutil.Error
require.True(t, errors.As(err, &typed), "expected *cmdutil.Error, got %T %v", err, err)
assert.Equal(t, cmdutil.CodeLocalProfileNotFound, typed.Code)
}
// TestAuthRefresh_DryRun_RejectsNoCurrentProfile: no current profile → live
// path returns auth.unauthenticated; --dry-run must do the same.
func TestAuthRefresh_DryRun_RejectsNoCurrentProfile(t *testing.T) {
iostreams.SetForTest(t)
cfg := &config.Config{}
root := withRootHarnessAuth(NewCmdRefresh(authDryRunFactory(t, cfg)),
"--dry-run", "--format", "json")
err := root.Execute()
require.Error(t, err)
var typed *cmdutil.Error
require.True(t, errors.As(err, &typed))
assert.Equal(t, cmdutil.CodeAuthUnauthenticated, typed.Code)
}
// TestAuthRefresh_DryRun_RejectsMissingRefreshToken: API-key-only profile →
// live path returns input.invalid_argument ("no refresh token"); --dry-run
// must do the same.
func TestAuthRefresh_DryRun_RejectsMissingRefreshToken(t *testing.T) {
iostreams.SetForTest(t)
cfg := &config.Config{
CurrentProfile: "prod",
Profiles: map[string]config.Profile{
"prod": {Host: "https://prod", APIKeyRef: "k"},
},
}
root := withRootHarnessAuth(NewCmdRefresh(authDryRunFactory(t, cfg)),
"--dry-run", "--format", "json")
err := root.Execute()
require.Error(t, err)
var typed *cmdutil.Error
require.True(t, errors.As(err, &typed))
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)
}
+94
View File
@@ -0,0 +1,94 @@
package auth
import (
"fmt"
"sort"
"text/tabwriter"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/output"
)
type ListOptions struct{}
// authListFields enumerates the fields surfaced for `--format json` discovery on
// `auth list`. Each entry is a per-profile summary row.
var authListFields = []string{
"name", "host", "user", "mode", "current",
}
type listEntry struct {
Name string `json:"name"`
Host string `json:"host"`
User string `json:"user,omitempty"`
Mode string `json:"mode"` // ModeBearer / ModeAPIKey / ModeUnknown
Current bool `json:"current"`
}
// NewCmdList builds `weknora auth list`. Per-host enumeration: render one
// row per registered profile, marking the active one. Reads only
// ~/.config/weknora/config.yaml - no network, no keyring touch.
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Short: "List configured authentication profiles",
Long: `Show every configured profile (name, host, user, mode, current). Read-only; no network or keyring access.`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
return runList(fopts, f)
},
}
cmdutil.AddFormatFlag(cmd, authListFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "list configured profiles and their credential mode (bearer / api-key)",
Examples: []string{"weknora auth list", "weknora auth list --jq '.data[].name'"},
Output: "envelope.data is an array of profiles with name, host, mode, and which is active",
})
return cmd
}
func runList(fopts *cmdutil.FormatOptions, f *cmdutil.Factory) error {
cfg, err := f.Config()
if err != nil {
return err
}
entries := make([]listEntry, 0, len(cfg.Profiles))
for name, c := range cfg.Profiles {
entries = append(entries, listEntry{
Name: name,
Host: c.Host,
User: c.User,
Mode: modeFromRefs(c.APIKeyRef, c.TokenRef),
Current: name == cfg.CurrentProfile,
})
}
sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name })
if fopts.WantsJSON() {
meta := &output.Meta{Count: output.IntPtr(len(entries))}
return fopts.Emit(iostreams.IO.Out, entries, meta)
}
if len(entries) == 0 {
fmt.Fprintln(iostreams.IO.Out, "No profiles configured. Run `weknora auth login` to create one.")
return nil
}
tw := tabwriter.NewWriter(iostreams.IO.Out, 0, 0, 2, ' ', 0)
fmt.Fprintln(tw, " NAME\tHOST\tUSER\tMODE")
for _, e := range entries {
marker := " "
if e.Current {
marker = "* "
}
fmt.Fprintf(tw, "%s%s\t%s\t%s\t%s\n", marker, e.Name, e.Host, format.DashIfEmpty(e.User), e.Mode)
}
return tw.Flush()
}
+86
View File
@@ -0,0 +1,86 @@
package auth
import (
"encoding/json"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
)
func newListFactory(cfg *config.Config) *cmdutil.Factory {
return &cmdutil.Factory{
Config: func() (*config.Config, error) { return cfg, nil },
}
}
func TestList_TextRender(t *testing.T) {
out, _ := iostreams.SetForTest(t)
cfg := &config.Config{
CurrentProfile: "prod",
Profiles: map[string]config.Profile{
"prod": {Host: "https://prod", User: "alice@example.com", TokenRef: "keychain://prod/access"},
"staging": {Host: "https://staging", APIKeyRef: "keychain://staging/api_key"},
},
}
require.NoError(t, runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newListFactory(cfg)))
got := out.String()
// One row per profile, current marked with `*`.
assert.Contains(t, got, "* prod")
assert.Contains(t, got, " staging")
// Mode column.
assert.Contains(t, got, ModeBearer)
assert.Contains(t, got, ModeAPIKey)
// Sorted alphabetically - prod after staging? No: "prod" < "staging".
assert.Less(t, strings.Index(got, "prod"), strings.Index(got, "staging"),
"profiles should render sorted by name")
}
func TestList_Empty(t *testing.T) {
out, _ := iostreams.SetForTest(t)
require.NoError(t, runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newListFactory(&config.Config{})))
assert.Contains(t, out.String(), "No profiles configured")
}
func TestList_JSON_BareArray(t *testing.T) {
out, _ := iostreams.SetForTest(t)
cfg := &config.Config{
CurrentProfile: "prod",
Profiles: map[string]config.Profile{
"prod": {Host: "https://prod", User: "alice", TokenRef: "tok"},
"staging": {Host: "https://staging", APIKeyRef: "key"},
},
}
require.NoError(t, runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, newListFactory(cfg)))
var env struct {
OK bool `json:"ok"`
Data []listEntry `json:"data"`
}
require.NoError(t, json.Unmarshal(out.Bytes(), &env))
assert.True(t, env.OK)
got := env.Data
require.Len(t, got, 2)
// Sorted: prod < staging.
assert.Equal(t, "prod", got[0].Name)
assert.True(t, got[0].Current)
assert.Equal(t, ModeBearer, got[0].Mode)
assert.Equal(t, "staging", got[1].Name)
assert.False(t, got[1].Current)
assert.Equal(t, ModeAPIKey, got[1].Mode)
}
func TestModeFromRefs(t *testing.T) {
// Hand-edited config with neither ref set - surface "unknown" rather
// than pretending the profile is a valid login.
assert.Equal(t, ModeUnknown, modeFromRefs("", ""))
assert.Equal(t, ModeBearer, modeFromRefs("", "tok"))
assert.Equal(t, ModeAPIKey, modeFromRefs("key", ""))
assert.Equal(t, ModeBearer, modeFromRefs("key", "tok"), "JWT wins when both set")
}
+400
View File
@@ -0,0 +1,400 @@
package auth
import (
"context"
"fmt"
"io"
"strings"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/secrets"
sdk "github.com/Tencent/WeKnora/client"
)
// authLoginFields enumerates the fields surfaced for `--format json` discovery on
// `auth login`. The post-login summary has no token values - they stay in the
// keyring; agents who need to verify the credential should re-run
// `auth status`.
var authLoginFields = []string{
"profile", "host", "mode", "email", "tenant_id",
}
// LoginOptions is the configuration captured from flags + prompts. Host and
// Profile are resolved from the active profile in config (not from flags) -
// `auth login` authenticates the already-existing active profile, created
// beforehand with `weknora profile add <name> --host <h> --use`.
type LoginOptions struct {
Host string // resolved from the active profile's Host in config
Profile string // resolved active profile name (honors global --profile)
WithToken bool // --with-token: read api key from stdin instead of prompting password
APIKey string // populated by --with-token from stdin
Email string
Password string
StdinReader io.Reader // override for tests
}
// LoginService is the narrow SDK surface auth login depends on.
// *sdk.Client satisfies it implicitly via the new Login(ctx, LoginRequest)
// signature added in client/auth.go.
type LoginService interface {
Login(ctx context.Context, req sdk.LoginRequest) (*sdk.LoginResponse, error)
}
// apiKeyValidator probes /auth/me with the supplied API key so a bad key
// fails fast at `auth login --with-token` time rather than on the next
// authenticated call.
//
// Returns the resolved user (used to populate Profile.User / TenantID at
// rest, so later `auth list` reflects who owns the key).
type apiKeyValidator func(ctx context.Context, host, apiKey string) (*sdk.AuthUser, error)
// defaultAPIKeyValidator builds a one-shot SDK client with the supplied key
// and calls /auth/me. Side-effect-free; no persistence.
var defaultAPIKeyValidator apiKeyValidator = func(ctx context.Context, host, apiKey string) (*sdk.AuthUser, error) {
resp, err := sdk.NewClient(host, sdk.WithAPIKey(apiKey)).GetCurrentUser(ctx)
if err != nil {
return nil, err
}
if !resp.Success || resp.Data.User == nil {
return nil, fmt.Errorf("server rejected the API key (no user returned)")
}
return resp.Data.User, nil
}
// NewCmdLogin builds the `weknora auth login` command. runF is the testable
// entrypoint (left nil for production; see cli/cmd/auth/login_test.go).
func NewCmdLogin(f *cmdutil.Factory, runF func(context.Context, *LoginOptions, *cmdutil.FormatOptions, *cmdutil.Factory, LoginService) error) *cobra.Command {
opts := &LoginOptions{}
cmd := &cobra.Command{
Use: "login",
Short: "Authenticate the active profile against its WeKnora server",
Long: `Authenticate the active profile by email + password (interactive prompt) or
pipe an API key with --with-token.
` + "`auth login`" + ` operates on the active profile (override with the global
--profile flag). Create the profile first with
` + "`weknora profile add <name> --host <h> --use`" + `, then run ` + "`weknora auth login`" + `.
Credentials are persisted to the OS keyring when available; otherwise to a
0600 file under $XDG_CONFIG_HOME/weknora/secrets.`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
if opts.StdinReader == nil {
opts.StdinReader = iostreams.IO.In
}
if runF != nil {
// Test seam: the injected runF supplies its own service and
// (where needed) seeds opts.Host / opts.Profile itself.
return runF(c.Context(), opts, fopts, f, nil)
}
return runLogin(c.Context(), opts, fopts, f, nil)
},
}
cmd.Flags().BoolVar(&opts.WithToken, "with-token", false, "Read an API key from stdin instead of prompting for password")
cmdutil.AddFormatFlag(cmd, authLoginFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "authenticate the active profile; --with-token reads an API key from stdin (non-interactive)",
Examples: []string{`echo "$WEKNORA_API_KEY" | weknora auth login --with-token`},
Output: "envelope.data is {profile, host, mode, email, tenant_id} on success (email matches `auth status`)",
Warnings: []string{
"a profile must exist and be active first (`weknora profile add <n> --host <url> --use`)",
"password login is interactive-only (no flags) — agents must use --with-token with the key piped to stdin",
},
})
return cmd
}
// resolveActiveProfile loads config and resolves the active profile (honoring
// the global --profile override) plus its persisted Host. `auth login`
// authenticates an already-existing profile; profile creation is `profile
// add`'s job. Returns typed errors when no active profile is configured or
// the profile lacks a host.
func resolveActiveProfile(f *cmdutil.Factory) (name, host string, err error) {
// f.Config() already folds the global --profile / WEKNORA_PROFILE override
// into cfg.CurrentProfile (same source f.ActiveProfile reads), so one load
// resolves the active profile — matches logout/refresh.
cfg, err := f.Config()
if err != nil {
return "", "", err
}
active := cfg.CurrentProfile
if active == "" {
msg := "no active profile; run `weknora profile add <name> --host <h> --use` first"
if envActive, kind := cmdutil.EnvCredential(); envActive {
msg = "no active profile to log in — you are already authenticated this session via " + kind +
"; `auth login` only persists a named profile, so run `weknora profile add <name> --host <h> --use` first if you want one"
}
return "", "", cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, msg)
}
prof, ok := cfg.Profiles[active]
if !ok {
return "", "", cmdutil.NewError(cmdutil.CodeLocalProfileNotFound,
fmt.Sprintf("active profile %q not found in config", active))
}
if prof.Host == "" {
return "", "", cmdutil.NewError(cmdutil.CodeLocalConfigCorrupt,
fmt.Sprintf("profile %q has no host", active))
}
return active, prof.Host, nil
}
// loginServiceFor returns a fresh SDK client targeting host. login.go cannot
// reuse Factory.Client because that closure requires an existing profile.
func loginServiceFor(host string) LoginService {
if host == "" {
return nil
}
return sdk.NewClient(host)
}
func runLogin(ctx context.Context, opts *LoginOptions, fopts *cmdutil.FormatOptions, f *cmdutil.Factory, svc LoginService) error {
// Resolve the target profile + host from the active profile in config.
// `auth login` no longer takes --host / --name; it authenticates the
// already-existing active profile (override via the global --profile).
name, host, err := resolveActiveProfile(f)
if err != nil {
return err
}
opts.Profile = name
opts.Host = host
if svc == nil {
svc = loginServiceFor(host)
}
if err := validateHost(opts.Host); err != nil {
return err
}
// Reject shell-metacharacter / path-like names up-front so opts.Profile
// stays safe to interpolate into the keyring namespace, config.yaml
// keys, and envelope.error.retry_argv. Matches `profile add`.
if err := cmdutil.ValidateProfileName(opts.Profile); err != nil {
return err
}
if opts.WithToken {
key, err := readStdinTrimmed(opts.StdinReader)
if err != nil {
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "read stdin")
}
if key == "" {
return cmdutil.NewError(cmdutil.CodeInputMissingFlag, "--with-token requires an API key piped to stdin")
}
opts.APIKey = key
// Validate against the server before persisting so a typo'd /
// expired / wrong-host key fails fast at login time. The probe
// is /auth/me - read-only, side-effect-free.
user, err := defaultAPIKeyValidator(ctx, opts.Host, key)
if err != nil {
// Transport errors (connection refused, DNS failure) must not be
// surfaced as auth.bad_credential — the key may be fine but the
// host is unreachable. Classify via WrapHTTP so network errors
// get CodeNetworkError and the hint points at `weknora doctor`.
if cmdutil.ClassifyHTTPError(err) == cmdutil.CodeNetworkError {
return cmdutil.Wrapf(cmdutil.CodeNetworkError, err, "validate API key: check host reachability")
}
return cmdutil.Wrapf(cmdutil.CodeAuthBadCredential, err, "validate API key")
}
return persistAPIKey(opts, fopts, f, user)
}
// Interactive: prompt for email + password. svc is always set by now
// (loginServiceFor returns non-nil because resolveActiveProfile guarantees
// a non-empty host).
if opts.Email == "" || opts.Password == "" {
p := f.Prompter()
if opts.Email == "" {
email, err := p.Input("Email", "")
if err != nil {
return cmdutil.Wrapf(cmdutil.CodeInputMissingFlag, err, "email prompt")
}
opts.Email = email
}
if opts.Password == "" {
pw, err := p.Password("Password")
if err != nil {
return cmdutil.Wrapf(cmdutil.CodeInputMissingFlag, err, "password prompt")
}
opts.Password = pw
}
}
resp, err := svc.Login(ctx, sdk.LoginRequest{Email: opts.Email, Password: opts.Password})
if err != nil {
// Transport errors (connection refused, DNS failure) must not be
// surfaced as auth.bad_credential — credentials may be fine but the
// host is unreachable. Classify so network errors get CodeNetworkError.
if cmdutil.ClassifyHTTPError(err) == cmdutil.CodeNetworkError {
return cmdutil.Wrapf(cmdutil.CodeNetworkError, err, "login: check host reachability")
}
return cmdutil.Wrapf(cmdutil.CodeAuthBadCredential, err, "login")
}
if !resp.Success || resp.Token == "" {
return cmdutil.NewError(cmdutil.CodeAuthBadCredential, fmt.Sprintf("login refused: %s", resp.Message))
}
return persistJWT(opts, fopts, f, resp)
}
// persistAPIKey saves the --with-token API key and writes the profile.
// user is the principal returned by /auth/me during pre-persist validation,
// used to populate Profile.User / TenantID so `auth list` reflects who
// owns the key.
func persistAPIKey(opts *LoginOptions, fopts *cmdutil.FormatOptions, f *cmdutil.Factory, user *sdk.AuthUser) error {
store, err := f.Secrets()
if err != nil {
return err
}
warnOnFileFallback(store)
if err := store.Set(opts.Profile, "api_key", opts.APIKey); err != nil {
return cmdutil.Wrapf(cmdutil.CodeLocalKeychainDenied, err, "save api key")
}
// Switching credential mode: this profile is now an API-key profile, so
// any leftover JWT refs (from a prior password login) are stale. Set the
// api-key ref and clear the token/refresh refs; keep Host + existing
// User/TenantID (merged in saveProfileRef via applyUser).
mutate := func(prof *config.Profile) {
prof.APIKeyRef = store.Ref(opts.Profile, "api_key")
prof.TokenRef = ""
prof.RefreshRef = ""
applyUser(prof, user)
}
return saveProfileRef(opts, fopts, f, mutate, ModeAPIKey, user)
}
// persistJWT saves access + refresh tokens and writes the profile.
func persistJWT(opts *LoginOptions, fopts *cmdutil.FormatOptions, f *cmdutil.Factory, resp *sdk.LoginResponse) error {
store, err := f.Secrets()
if err != nil {
return err
}
warnOnFileFallback(store)
if err := store.Set(opts.Profile, "access", resp.Token); err != nil {
return cmdutil.Wrapf(cmdutil.CodeLocalKeychainDenied, err, "save access token")
}
if resp.RefreshToken != "" {
if err := store.Set(opts.Profile, "refresh", resp.RefreshToken); err != nil {
return cmdutil.Wrapf(cmdutil.CodeLocalKeychainDenied, err, "save refresh token")
}
}
// Switching to a JWT profile: set token refs and drop any stale api-key
// ref; keep Host + existing User/TenantID (merged in saveProfileRef via applyUser).
mutate := func(prof *config.Profile) {
prof.TokenRef = store.Ref(opts.Profile, "access")
prof.RefreshRef = store.Ref(opts.Profile, "refresh")
prof.APIKeyRef = ""
applyUser(prof, resp.User)
}
return saveProfileRef(opts, fopts, f, mutate, ModeBearer, resp.User)
}
// applyUser overwrites prof.User / prof.TenantID only when the server actually
// returned them. A nil user (or empty email) must NOT wipe an existing User
// that was set during `profile add` or a prior login.
func applyUser(prof *config.Profile, user *sdk.AuthUser) {
if user == nil {
return
}
if user.Email != "" {
prof.User = user.Email
}
if user.TenantID != 0 {
prof.TenantID = user.TenantID
}
}
// loginResult is the typed payload emitted by `--format json`. mode is derived from
// whether the server returned a user (password flow) vs API-key flow.
type loginResult struct {
Profile string `json:"profile"`
Host string `json:"host"`
Mode string `json:"mode"` // ModeBearer or ModeAPIKey
// Email is the authenticated principal's email. Named "email" (not
// "user") so the identity field matches `auth status`, which also
// exposes it as `email` — one key for one concept across both commands.
Email string `json:"email,omitempty"`
TenantID uint64 `json:"tenant_id,omitempty"`
}
// saveProfileRef MERGES the new credential refs into the EXISTING profile
// record and prints success. The active profile already exists (created via
// `profile add`, carrying Host and possibly User/TenantID); mutate sets only
// the credential refs + any server-returned user, so re-login never clobbers
// the host or wipes an existing user. cfg.CurrentProfile is left untouched -
// `auth login` authenticates the already-active profile, it doesn't switch.
func saveProfileRef(opts *LoginOptions, fopts *cmdutil.FormatOptions, f *cmdutil.Factory, mutate func(*config.Profile), mode string, user *sdk.AuthUser) error {
cfg, err := f.Config()
if err != nil {
return err
}
if cfg.Profiles == nil {
cfg.Profiles = map[string]config.Profile{}
}
prof := cfg.Profiles[opts.Profile] // existing record (Host, User, TenantID)
mutate(&prof)
cfg.Profiles[opts.Profile] = prof
if err := config.Save(cfg); err != nil {
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "save config")
}
if fopts.WantsJSON() {
// mode reflects the credential actually stored (passed by the caller),
// not whether the server happened to return a user — an API-key login
// validates via /auth/me and DOES get a user, so deriving mode from
// user != nil would mislabel it as bearer.
result := loginResult{Profile: opts.Profile, Host: opts.Host, Mode: mode}
if user != nil {
result.Email = user.Email
result.TenantID = user.TenantID
}
return fopts.Emit(iostreams.IO.Out, result, nil)
}
who := opts.Profile
if user != nil {
who = user.Email
}
fmt.Fprintf(iostreams.IO.Out, "✓ Logged in to %s as %s (profile=%s)\n", opts.Host, who, opts.Profile)
return nil
}
// validateHost rejects empty / non-http URLs early so we surface a clean
// flag error instead of failing inside the SDK transport.
func validateHost(host string) error {
_, err := cmdutil.NormalizeHost(host)
return err
}
// warnOnFileFallback prints a one-shot stderr advisory when the secrets
// store fell back to the plaintext 0600 file backend (keychain unavailable
// - typical on headless CI, WSL without DBus, agent containers). Helps
// users notice that credentials are NOT in the OS keychain before they're
// surprised by it later. doctor's credential_storage check carries the
// same info but agents that bypass doctor would otherwise miss it.
func warnOnFileFallback(store secrets.Store) {
if _, isFile := store.(*secrets.FileStore); !isFile {
return
}
fmt.Fprintln(iostreams.IO.Err, "warning: OS keychain unavailable - credentials will be saved to a 0600 file under $XDG_CONFIG_HOME/weknora/secrets/.")
fmt.Fprintln(iostreams.IO.Err, " install / unlock the keyring (or use `weknora doctor` to inspect) for OS-backed storage.")
}
// readStdinTrimmed reads all of r and returns the result with surrounding
// whitespace stripped. Empty result is returned as-is for the caller to
// validate.
func readStdinTrimmed(r io.Reader) (string, error) {
if r == nil {
return "", nil
}
b, err := io.ReadAll(r)
if err != nil {
return "", err
}
return strings.TrimSpace(string(b)), nil
}
+264
View File
@@ -0,0 +1,264 @@
package auth
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
"github.com/Tencent/WeKnora/cli/internal/secrets"
"github.com/Tencent/WeKnora/cli/internal/testutil"
sdk "github.com/Tencent/WeKnora/client"
)
// fakeLoginService captures the email/password it received.
type fakeLoginService struct {
resp *sdk.LoginResponse
err error
got struct{ email, password string }
}
func (f *fakeLoginService) Login(_ context.Context, req sdk.LoginRequest) (*sdk.LoginResponse, error) {
f.got.email = req.Email
f.got.password = req.Password
return f.resp, f.err
}
// scriptedPrompter satisfies prompt.Prompter with predetermined values.
type scriptedPrompter struct{ email, password string }
func (s scriptedPrompter) Input(string, string) (string, error) { return s.email, nil }
func (s scriptedPrompter) Password(string) (string, error) { return s.password, nil }
func (s scriptedPrompter) Confirm(string, bool) (bool, error) { return true, nil }
func newTestFactoryWithConfig(t *testing.T, p prompt.Prompter) (*cmdutil.Factory, *secrets.MemStore) {
t.Helper()
testutil.XDGTempDir(t)
store := secrets.NewMemStore()
return &cmdutil.Factory{
Config: func() (*config.Config, error) { return config.Load() },
Client: func() (*sdk.Client, error) { panic("client") },
Prompter: func() prompt.Prompter { return p },
Secrets: func() (secrets.Store, error) { return store, nil },
}, store
}
// seedActiveProfile writes an active profile to the (XDG-isolated) config so
// runLogin can resolve host/name from it - `auth login` authenticates the
// already-existing active profile rather than creating one. Returns nothing;
// callers read back via f.Config() to assert merge behavior.
func seedActiveProfile(t *testing.T, name string, prof config.Profile) {
t.Helper()
cfg := &config.Config{
CurrentProfile: name,
Profiles: map[string]config.Profile{name: prof},
}
require.NoError(t, config.Save(cfg))
}
func TestRunLogin_PasswordMode(t *testing.T) {
iostreams.SetForTest(t)
f, store := newTestFactoryWithConfig(t, scriptedPrompter{email: "a@b.c", password: "secret"})
seedActiveProfile(t, "prod", config.Profile{Host: "https://kb.example.com"})
svc := &fakeLoginService{resp: &sdk.LoginResponse{
Success: true,
Token: "jwt-access",
User: &sdk.AuthUser{ID: "u1", Email: "a@b.c", TenantID: 7},
}}
require.NoError(t, runLogin(context.Background(), &LoginOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, svc))
assert.Equal(t, "a@b.c", svc.got.email)
assert.Equal(t, "secret", svc.got.password)
got, _ := store.Get("prod", "access")
assert.Equal(t, "jwt-access", got)
cfg, _ := f.Config()
assert.Equal(t, "https://kb.example.com", cfg.Profiles["prod"].Host, "host must be preserved from the seeded profile")
}
func TestRunLogin_WithToken(t *testing.T) {
iostreams.SetForTest(t)
f, store := newTestFactoryWithConfig(t, prompt.AgentPrompter{})
seedActiveProfile(t, "ci", config.Profile{Host: "https://kb.example.com"})
restore := stubAPIKeyValidator(func(_ context.Context, _, _ string) (*sdk.AuthUser, error) {
return &sdk.AuthUser{ID: "u1", Email: "ci@example.com", TenantID: 7}, nil
})
defer restore()
opts := &LoginOptions{
WithToken: true,
StdinReader: strings.NewReader(" sk-1234 \n"),
}
require.NoError(t, runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil))
got, _ := store.Get("ci", "api_key")
assert.Equal(t, "sk-1234", got)
cfg, _ := f.Config()
assert.Equal(t, "ci@example.com", cfg.Profiles["ci"].User, "validator-returned user should be persisted")
assert.Equal(t, uint64(7), cfg.Profiles["ci"].TenantID)
assert.Equal(t, "https://kb.example.com", cfg.Profiles["ci"].Host, "host preserved from seeded profile")
}
func TestRunLogin_WithToken_JSONReportsAPIKeyMode(t *testing.T) {
out, _ := iostreams.SetForTest(t)
f, _ := newTestFactoryWithConfig(t, prompt.AgentPrompter{})
seedActiveProfile(t, "ci", config.Profile{Host: "https://kb.example.com"})
restore := stubAPIKeyValidator(func(_ context.Context, _, _ string) (*sdk.AuthUser, error) {
// API-key validation hits /auth/me, which DOES return a user. mode
// must still be reported as api-key (derived from credential type,
// not from "did the server return a user").
return &sdk.AuthUser{ID: "u1", Email: "ci@example.com", TenantID: 7}, nil
})
defer restore()
opts := &LoginOptions{WithToken: true, StdinReader: strings.NewReader("sk-1234")}
require.NoError(t, runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, f, nil))
var env struct {
Data struct {
Mode string `json:"mode"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(out.Bytes(), &env))
assert.Equal(t, "api-key", env.Data.Mode, "api-key login must report mode=api-key, not bearer")
}
func TestRunLogin_WithToken_ServerRejects(t *testing.T) {
iostreams.SetForTest(t)
f, _ := newTestFactoryWithConfig(t, prompt.AgentPrompter{})
seedActiveProfile(t, "ci", config.Profile{Host: "https://kb.example.com"})
restore := stubAPIKeyValidator(func(_ context.Context, _, _ string) (*sdk.AuthUser, error) {
// Use the SDK-format HTTP error message so ClassifyHTTPError detects
// this as an HTTP 401, not a transport/network failure.
return nil, errors.New("HTTP error 401: invalid api key")
})
defer restore()
opts := &LoginOptions{
WithToken: true,
StdinReader: strings.NewReader("sk-bad"),
}
err := runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeAuthBadCredential, typed.Code,
"server-side rejection must surface as auth.bad_credential, not persist the key")
}
// stubAPIKeyValidator swaps defaultAPIKeyValidator for the test and returns
// a restore func to defer.
func stubAPIKeyValidator(fn apiKeyValidator) func() {
saved := defaultAPIKeyValidator
defaultAPIKeyValidator = fn
return func() { defaultAPIKeyValidator = saved }
}
func TestRunLogin_WithToken_Empty(t *testing.T) {
iostreams.SetForTest(t)
f, _ := newTestFactoryWithConfig(t, prompt.AgentPrompter{})
seedActiveProfile(t, "ci", config.Profile{Host: "https://kb.example.com"})
// Validator must NOT be called when stdin is empty - verify by setting
// a panic-on-call sentinel.
restore := stubAPIKeyValidator(func(_ context.Context, _, _ string) (*sdk.AuthUser, error) {
t.Fatal("validator should not be called on empty stdin")
return nil, nil
})
defer restore()
opts := &LoginOptions{
WithToken: true,
StdinReader: strings.NewReader(""),
}
err := runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil)
require.Error(t, err)
assert.Contains(t, err.Error(), "input.missing_flag")
}
func TestRunLogin_BadHost(t *testing.T) {
iostreams.SetForTest(t)
f, _ := newTestFactoryWithConfig(t, prompt.AgentPrompter{})
// A non-http host stored on the active profile must be rejected by the
// post-resolution validateHost check (config corruption guard).
seedActiveProfile(t, "bad", config.Profile{Host: "ftp://nope"})
err := runLogin(context.Background(), &LoginOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil)
require.Error(t, err)
assert.Contains(t, err.Error(), "input.invalid_argument")
}
func TestRunLogin_LoginRefused(t *testing.T) {
iostreams.SetForTest(t)
f, _ := newTestFactoryWithConfig(t, scriptedPrompter{email: "a@b.c", password: "x"})
seedActiveProfile(t, "p", config.Profile{Host: "https://x"})
svc := &fakeLoginService{resp: &sdk.LoginResponse{Success: false, Message: "bad password"}}
err := runLogin(context.Background(), &LoginOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, svc)
require.Error(t, err)
assert.Contains(t, err.Error(), "auth.bad_credential")
}
func TestValidateHost(t *testing.T) {
require.NoError(t, validateHost("https://kb.example.com"))
require.NoError(t, validateHost("http://localhost:8080"))
require.Error(t, validateHost(""))
require.Error(t, validateHost("ftp://x"))
require.Error(t, validateHost("not a url"))
}
// TestLogin_NoHostNoName asserts the --host / --name flags are gone: `auth
// login` now authenticates the active profile (create it via `profile add`).
func TestLogin_NoHostNoName(t *testing.T) {
iostreams.SetForTest(t)
f, _ := newTestFactoryWithConfig(t, prompt.AgentPrompter{})
cmd := NewCmdLogin(f, nil)
assert.Nil(t, cmd.Flags().Lookup("host"), "--host flag must be removed")
assert.Nil(t, cmd.Flags().Lookup("name"), "--name flag must be removed")
assert.NotNil(t, cmd.Flags().Lookup("with-token"), "--with-token must remain")
}
// TestLogin_NoActiveProfile_Errors asserts that with no active profile
// configured, login returns a clear auth.unauthenticated error pointing the
// user at `profile add`.
func TestLogin_NoActiveProfile_Errors(t *testing.T) {
iostreams.SetForTest(t)
f, _ := newTestFactoryWithConfig(t, prompt.AgentPrompter{})
// No seedActiveProfile: empty config.
err := runLogin(context.Background(), &LoginOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeAuthUnauthenticated, typed.Code)
assert.Contains(t, err.Error(), "profile add")
}
// TestLogin_UsesActiveProfileHost asserts login persists credentials under the
// active profile using that profile's stored host, and that an existing User
// is NOT clobbered when the server (API-key validator) returns it unchanged.
func TestLogin_UsesActiveProfileHost(t *testing.T) {
iostreams.SetForTest(t)
f, store := newTestFactoryWithConfig(t, prompt.AgentPrompter{})
// Pre-seed "prod" with a host AND a user that must survive re-login.
seedActiveProfile(t, "prod", config.Profile{Host: "https://prod.example.com", User: "existing@owner.com"})
restore := stubAPIKeyValidator(func(_ context.Context, host, _ string) (*sdk.AuthUser, error) {
assert.Equal(t, "https://prod.example.com", host, "validator must be called with the active profile's host")
// Server returns nil user (e.g. /auth/me gave no email) - must NOT
// wipe the existing User.
return &sdk.AuthUser{}, nil
})
defer restore()
opts := &LoginOptions{WithToken: true, StdinReader: strings.NewReader("sk-prod")}
require.NoError(t, runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil))
got, _ := store.Get("prod", "api_key")
assert.Equal(t, "sk-prod", got, "api key must be stored under the active profile")
cfg, _ := f.Config()
prof := cfg.Profiles["prod"]
assert.Equal(t, "https://prod.example.com", prof.Host, "host must be preserved, not clobbered")
assert.Equal(t, "existing@owner.com", prof.User, "existing User must NOT be wiped when server returns none")
assert.NotEmpty(t, prof.APIKeyRef, "api-key ref must be set")
assert.Equal(t, "prod", cfg.CurrentProfile, "active profile unchanged")
}
+197
View File
@@ -0,0 +1,197 @@
package auth
import (
"fmt"
"strings"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/secrets"
)
type LogoutOptions struct {
All bool // --all: clear every profile
Yes bool // sourced from the global -y/--yes persistent flag
DryRun bool
}
// authLogoutFields enumerates the fields surfaced for `--format json` discovery
// on `auth logout`. The result is the list of profile names that were
// logged out.
var authLogoutFields = []string{"removed"}
// logoutResult is the typed payload emitted under data.
type logoutResult struct {
Removed []string `json:"removed"`
}
// NewCmdLogout builds `weknora auth logout`. Clears stored credentials
// (keyring + file fallback) and removes the profile entry from config.yaml.
// No server-side revocation - local-only credential clear.
func NewCmdLogout(f *cmdutil.Factory) *cobra.Command {
opts := &LogoutOptions{}
cmd := &cobra.Command{
Use: "logout",
Short: "Remove stored credentials for a profile",
Long: `Clear keyring + file-fallback secrets for one profile (or all of
them with --all) and drop the profile entry from ~/.config/weknora/config.yaml.
Note: this does NOT revoke the credential server-side - for API keys, you
must rotate them in the server UI; for JWT, the token will continue to be
accepted until it expires.`,
Example: ` weknora auth logout # active profile
weknora --profile staging auth logout # specific profile
weknora auth logout --all`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
opts.Yes, _ = c.Flags().GetBool("yes")
// Pure-local validation runs before the dry-run gate so --dry-run
// rejects identically to the live path. Same typed errors as
// runLogout (kept there for direct-call callers).
cfg, cfgErr := f.Config()
if cfgErr != nil {
return cfgErr
}
if len(cfg.Profiles) == 0 {
if active, kind := cmdutil.EnvCredential(); active {
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
"authenticated via "+kind+" (stateless env credential) — nothing is stored to log out; unset "+kind+" to drop it")
}
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "no profiles configured; nothing to log out")
}
if _, err := pickLogoutTargets(opts, cfg); err != nil {
return err
}
if opts.DryRun {
planArgs := map[string]any{"profile": cfg.CurrentProfile}
if opts.All {
planArgs = map[string]any{"all": true}
}
if handled, err := cmdutil.HandleDryRun(c, true, cmdutil.DryRunPlan{
Action: "auth.logout",
Args: planArgs,
}); handled {
return err
}
}
return runLogout(opts, fopts, f)
},
}
cmd.Flags().BoolVar(&opts.All, "all", false, "Log out of every configured profile")
cmdutil.AddFormatFlag(cmd, authLogoutFields...)
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
cmdutil.SetRisk(cmd, "auth.logout")
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "clear stored credentials for the active profile (or --all); the profile itself stays registered (host preserved) so `auth login` can re-auth it — use `profile remove` to delete the profile entirely",
Examples: []string{
"weknora auth logout",
"weknora --profile staging auth logout",
"weknora auth logout --all",
},
Output: "envelope.data is {removed: [profile names cleared]}",
Warnings: []string{
"Requires explicit user approval (exit 10 / input.confirmation_required); never auto-add -y.",
"auth logout clears local credentials for this profile; server-side session continues until expiry.",
},
})
return cmd
}
func runLogout(opts *LogoutOptions, fopts *cmdutil.FormatOptions, f *cmdutil.Factory) error {
cfg, err := f.Config()
if err != nil {
return err
}
if len(cfg.Profiles) == 0 {
if active, kind := cmdutil.EnvCredential(); active {
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
"authenticated via "+kind+" (stateless env credential) — nothing is stored to log out; unset "+kind+" to drop it")
}
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "no profiles configured; nothing to log out")
}
targets, err := pickLogoutTargets(opts, cfg)
if err != nil {
return err
}
// Destructive-write protocol: confirm before clearing credentials.
scope := fmt.Sprintf("%d profile(s) [%s]", len(targets), strings.Join(targets, ", "))
retryCmd := []string{"weknora", "auth", "logout", "-y"}
if opts.All {
retryCmd = []string{"weknora", "auth", "logout", "--all", "-y"}
}
if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, fopts.WantsJSON(), "delete", "auth credentials", scope, "auth.logout", retryCmd); err != nil {
return err
}
store, err := f.Secrets()
if err != nil {
return err
}
for _, name := range targets {
clearProfileSecrets(store, cfg.Profiles[name], name)
// Keep the profile registered (its host stays) — only clear the
// credential refs so it reads as logged-out and can be re-authed with
// `auth login`. Deleting the profile entirely is `profile remove`'s job;
// that clean logout(who)/remove(what) split matches gh / lark.
p := cfg.Profiles[name]
p.APIKeyRef = ""
p.TokenRef = ""
p.RefreshRef = ""
cfg.Profiles[name] = p
}
if err := config.Save(cfg); err != nil {
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "save config")
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, logoutResult{Removed: targets}, nil)
}
fmt.Fprintf(iostreams.IO.Out, "✓ Logged out of %d profile(s): %s\n", len(targets), strings.Join(targets, ", "))
return nil
}
// pickLogoutTargets resolves the set of profiles to clear from flags + config.
func pickLogoutTargets(opts *LogoutOptions, cfg *config.Config) ([]string, error) {
if opts.All {
names := make([]string, 0, len(cfg.Profiles))
for n := range cfg.Profiles {
names = append(names, n)
}
return names, nil
}
name := cfg.CurrentProfile
if name == "" {
return nil, cmdutil.NewError(cmdutil.CodeInputMissingFlag,
"no active profile set; use the global --profile <profile> or --all")
}
if _, ok := cfg.Profiles[name]; !ok {
return nil, cmdutil.NewError(cmdutil.CodeLocalProfileNotFound,
fmt.Sprintf("profile %q not found in config", name))
}
return []string{name}, nil
}
// clearProfileSecrets best-effort deletes every secret slot the profile
// references. Errors are swallowed because a missing secret is a no-op
// (tested in keyring_test.go) - we don't want a stale ref to block logout.
func clearProfileSecrets(store secrets.Store, c config.Profile, name string) {
if c.TokenRef != "" {
_ = store.Delete(name, "access")
}
if c.RefreshRef != "" {
_ = store.Delete(name, "refresh")
}
if c.APIKeyRef != "" {
_ = store.Delete(name, "api_key")
}
}
+165
View File
@@ -0,0 +1,165 @@
package auth
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
"github.com/Tencent/WeKnora/cli/internal/secrets"
)
// newLogoutFactory builds a Factory whose Config closure mutates the supplied
// cfg in place - runLogout writes back via config.Save which touches disk, so
// tests use t.Setenv("XDG_CONFIG_HOME", t.TempDir()) at the call site to
// isolate the on-disk file.
func newLogoutFactory(t *testing.T, cfg *config.Config, store secrets.Store) *cmdutil.Factory {
t.Helper()
return &cmdutil.Factory{
Config: func() (*config.Config, error) { return cfg, nil },
Secrets: func() (secrets.Store, error) { return store, nil },
Prompter: func() prompt.Prompter { return &prompt.AgentPrompter{} },
}
}
func isolateConfig(t *testing.T) {
t.Helper()
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
}
func TestLogout_CurrentProfile(t *testing.T) {
isolateConfig(t)
_, _ = iostreams.SetForTest(t)
store := secrets.NewMemStore()
require.NoError(t, store.Set("prod", "access", "jwt-prod"))
require.NoError(t, store.Set("prod", "refresh", "rfr-prod"))
require.NoError(t, store.Set("staging", "api_key", "sk-staging"))
cfg := &config.Config{
CurrentProfile: "prod",
Profiles: map[string]config.Profile{
"prod": {Host: "https://prod", TokenRef: store.Ref("prod", "access"), RefreshRef: store.Ref("prod", "refresh")},
"staging": {Host: "https://staging", APIKeyRef: store.Ref("staging", "api_key")},
},
}
require.NoError(t, runLogout(&LogoutOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, store)))
assert.Equal(t, "prod", cfg.CurrentProfile, "active profile stays selected — logout clears creds, not the profile")
require.Contains(t, cfg.Profiles, "prod", "profile stays registered after logout")
assert.Empty(t, cfg.Profiles["prod"].APIKeyRef, "credential ref cleared")
assert.Empty(t, cfg.Profiles["prod"].TokenRef, "credential ref cleared")
assert.Empty(t, cfg.Profiles["prod"].RefreshRef, "credential ref cleared")
assert.Equal(t, "https://prod", cfg.Profiles["prod"].Host, "host preserved for re-login")
assert.Contains(t, cfg.Profiles, "staging", "non-target profile untouched")
// Secrets gone for the removed profile, kept for the survivor.
if _, err := store.Get("prod", "access"); err == nil {
t.Error("prod access secret should be deleted")
}
if v, _ := store.Get("staging", "api_key"); v != "sk-staging" {
t.Errorf("staging secret unexpectedly cleared: %q", v)
}
}
// TestLogout_ActiveProfileViaOverride exercises targeting a non-default
// profile. Production resolves this via the global --profile flag (which
// rewrites cfg.CurrentProfile in Factory.Config); here we simulate that by
// setting CurrentProfile=staging directly, since runLogout's single target is
// the active profile.
func TestLogout_ActiveProfileViaOverride(t *testing.T) {
isolateConfig(t)
_, _ = iostreams.SetForTest(t)
store := secrets.NewMemStore()
require.NoError(t, store.Set("staging", "api_key", "sk-staging"))
cfg := &config.Config{
CurrentProfile: "staging", // global --profile staging resolves to this
Profiles: map[string]config.Profile{
"prod": {Host: "https://prod", TokenRef: "tok"},
"staging": {Host: "https://staging", APIKeyRef: store.Ref("staging", "api_key")},
},
}
require.NoError(t, runLogout(&LogoutOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, store)))
require.Contains(t, cfg.Profiles, "staging", "target profile stays registered (creds cleared, not removed)")
assert.Empty(t, cfg.Profiles["staging"].APIKeyRef, "target's credential ref cleared")
assert.Contains(t, cfg.Profiles, "prod", "non-target profile untouched")
}
func TestLogout_All(t *testing.T) {
isolateConfig(t)
_, _ = iostreams.SetForTest(t)
store := secrets.NewMemStore()
cfg := &config.Config{
CurrentProfile: "prod",
Profiles: map[string]config.Profile{
"prod": {Host: "https://prod"},
"staging": {Host: "https://staging"},
},
}
require.NoError(t, runLogout(&LogoutOptions{All: true, Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, store)))
// --all clears every profile's credentials but keeps the profiles registered.
require.NotEmpty(t, cfg.Profiles, "profiles stay registered after logout --all")
for name, p := range cfg.Profiles {
assert.Empty(t, p.APIKeyRef, "%s api-key ref cleared", name)
assert.Empty(t, p.TokenRef, "%s token ref cleared", name)
assert.Empty(t, p.RefreshRef, "%s refresh ref cleared", name)
}
assert.Equal(t, "prod", cfg.CurrentProfile, "active selection is preserved; logout clears creds, not the profile")
}
func TestLogout_NoProfiles(t *testing.T) {
isolateConfig(t)
_, _ = iostreams.SetForTest(t)
cfg := &config.Config{}
err := runLogout(&LogoutOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeAuthUnauthenticated, typed.Code)
}
// TestLogout_ActiveProfileMissing covers the corrupt-config case where the
// active profile name (e.g. set via --profile ghost) has no matching entry.
func TestLogout_ActiveProfileMissing(t *testing.T) {
isolateConfig(t)
_, _ = iostreams.SetForTest(t)
cfg := &config.Config{
CurrentProfile: "ghost", // points at a non-existent entry
Profiles: map[string]config.Profile{"prod": {Host: "https://prod"}},
}
err := runLogout(&LogoutOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeLocalProfileNotFound, typed.Code)
}
func TestLogout_NoCurrentNoFlag(t *testing.T) {
isolateConfig(t)
_, _ = iostreams.SetForTest(t)
cfg := &config.Config{
Profiles: map[string]config.Profile{"prod": {Host: "https://prod"}},
}
err := runLogout(&LogoutOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeInputMissingFlag, typed.Code)
}
// TestLogout_NoNameFlag asserts the --name flag is gone (logout now targets
// the active profile / global --profile) while --all stands alone.
func TestLogout_NoNameFlag(t *testing.T) {
isolateConfig(t)
_, _ = iostreams.SetForTest(t)
cfg := &config.Config{Profiles: map[string]config.Profile{"a": {}}}
cmd := NewCmdLogout(newLogoutFactory(t, cfg, secrets.NewMemStore()))
assert.Nil(t, cmd.Flags().Lookup("name"), "--name flag must be removed")
assert.NotNil(t, cmd.Flags().Lookup("all"), "--all flag must remain")
}
+169
View File
@@ -0,0 +1,169 @@
package auth
import (
"context"
"fmt"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
type RefreshOptions struct {
DryRun bool
}
// authRefreshFields enumerates the fields surfaced for `--format json` discovery
// on `auth refresh`. Token values are intentionally omitted - see refreshResult.
var authRefreshFields = []string{"profile"}
// refreshResult is the typed payload emitted under data on success. Token
// values are intentionally NOT included - emitting them would leak secrets
// into stdout / agent transcripts. Agents needing to verify the new token
// can re-run `weknora auth status` (live API check).
type refreshResult struct {
Profile string `json:"profile"`
}
// NewCmdRefresh builds `weknora auth refresh`. Renews the JWT access
// token by spending the stored refresh_token via POST /auth/refresh -
// the standard OAuth refresh-token grant.
//
// API-key profiles are rejected - they have no refresh semantic;
// rotate the key via the server UI instead.
func NewCmdRefresh(f *cmdutil.Factory) *cobra.Command {
opts := &RefreshOptions{}
cmd := &cobra.Command{
Use: "refresh",
Short: "Renew the JWT access token using the stored refresh token",
Long: `Reads the refresh token previously stored by ` + "`weknora auth login`" + ` and
exchanges it for a new access + refresh token pair via POST /api/v1/auth/refresh.
Both new tokens replace the existing entries in the OS keyring.
API-key profiles are rejected with input.invalid_argument - they have no
refresh semantic. Rotate the key in the server UI instead.`,
Example: ` weknora auth refresh # refresh the active profile
weknora --profile staging auth refresh # refresh a specific profile`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
// Pure-local validation runs before the dry-run gate so --dry-run
// rejects identically to the live path. Same typed errors as
// runRefresh (kept there for direct-call callers).
cfg, cfgErr := f.Config()
if cfgErr != nil {
return cfgErr
}
name := cfg.CurrentProfile
if name == "" {
if active, kind := cmdutil.EnvCredential(); active {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
"authenticated via "+kind+" (stateless env credential): there is no stored JWT to refresh — env credentials are supplied fresh each call, so no refresh is needed")
}
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
"no active profile configured; run `weknora auth login` to set one up")
}
prof, ok := cfg.Profiles[name]
if !ok {
return cmdutil.NewError(cmdutil.CodeLocalProfileNotFound,
fmt.Sprintf("profile not found: %s", name))
}
if prof.Host == "" {
return cmdutil.NewError(cmdutil.CodeLocalConfigCorrupt,
fmt.Sprintf("profile %q has no host", name))
}
if prof.RefreshRef == "" {
hint := "api-key profiles can't be refreshed - rotate the key in the server UI and run `weknora auth login --with-token`"
if prof.APIKeyRef == "" {
hint = "no refresh token stored - run `weknora auth login` to authenticate"
}
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: fmt.Sprintf("profile %q has no refresh token", name),
Hint: hint,
}
}
if handled, err := cmdutil.HandleDryRun(c, opts.DryRun, cmdutil.DryRunPlan{
Action: "auth.refresh",
Args: map[string]any{},
}); handled {
return err
}
return runRefresh(c.Context(), opts, fopts, f, defaultRefresher)
},
}
cmdutil.AddFormatFlag(cmd, authRefreshFields...)
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "Renew the JWT access token for the active profile (override with the global --profile) using the stored refresh token. API-key profiles are rejected.",
Output: "envelope.data has profile name that was refreshed",
Examples: []string{
"weknora auth refresh",
"weknora --profile staging auth refresh",
},
})
return cmd
}
// defaultRefresher constructs a fresh, unauthenticated SDK client targeting
// host - the /auth/refresh endpoint reads the refresh token from the body,
// so no bearer / api-key header is needed.
func defaultRefresher(host string) cmdutil.Refresher {
return sdk.NewClient(host)
}
func runRefresh(ctx context.Context, opts *RefreshOptions, fopts *cmdutil.FormatOptions, f *cmdutil.Factory, refresherFor func(host string) cmdutil.Refresher) error {
cfg, err := f.Config()
if err != nil {
return err
}
name := cfg.CurrentProfile
if name == "" {
if active, kind := cmdutil.EnvCredential(); active {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument,
"authenticated via "+kind+" (stateless env credential): there is no stored JWT to refresh — env credentials are supplied fresh each call, so no refresh is needed")
}
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
"no active profile configured; run `weknora auth login` to set one up")
}
c, ok := cfg.Profiles[name]
if !ok {
return cmdutil.NewError(cmdutil.CodeLocalProfileNotFound,
fmt.Sprintf("profile not found: %s", name))
}
if c.Host == "" {
return cmdutil.NewError(cmdutil.CodeLocalConfigCorrupt,
fmt.Sprintf("profile %q has no host", name))
}
if c.RefreshRef == "" {
hint := "api-key profiles can't be refreshed - rotate the key in the server UI and run `weknora auth login --with-token`"
if c.APIKeyRef == "" {
hint = "no refresh token stored - run `weknora auth login` to authenticate"
}
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: fmt.Sprintf("profile %q has no refresh token", name),
Hint: hint,
}
}
store, err := f.Secrets()
if err != nil {
return err
}
if _, err := cmdutil.RefreshAndPersist(ctx, store, refresherFor(c.Host), name); err != nil {
return err
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, refreshResult{Profile: name}, nil)
}
fmt.Fprintf(iostreams.IO.Out, "✓ Refreshed access token for profile %s\n", name)
return nil
}
+237
View File
@@ -0,0 +1,237 @@
package auth
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
"github.com/Tencent/WeKnora/cli/internal/secrets"
"github.com/Tencent/WeKnora/cli/internal/testutil"
sdk "github.com/Tencent/WeKnora/client"
)
// fakeRefreshService scripts a RefreshToken response.
type fakeRefreshService struct {
resp *sdk.RefreshTokenResponse
err error
gotTok string
}
func (f *fakeRefreshService) RefreshToken(_ context.Context, refreshToken string) (*sdk.RefreshTokenResponse, error) {
f.gotTok = refreshToken
return f.resp, f.err
}
// stubSvc returns a closure conforming to the refresherFor signature; it
// ignores host since the fake doesn't talk to the network.
func stubSvc(s cmdutil.Refresher) func(string) cmdutil.Refresher {
return func(string) cmdutil.Refresher { return s }
}
func newRefreshFactory(t *testing.T, cfg *config.Config, store *secrets.MemStore) *cmdutil.Factory {
t.Helper()
testutil.XDGTempDir(t)
require.NoError(t, config.Save(cfg))
return &cmdutil.Factory{
Config: func() (*config.Config, error) { return config.Load() },
Client: func() (*sdk.Client, error) { panic("client") },
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
Secrets: func() (secrets.Store, error) { return store, nil },
}
}
func TestRefresh_Happy(t *testing.T) {
iostreams.SetForTest(t)
store := secrets.NewMemStore()
require.NoError(t, store.Set("prod", "access", "old-access"))
require.NoError(t, store.Set("prod", "refresh", "old-refresh"))
cfg := &config.Config{
CurrentProfile: "prod",
Profiles: map[string]config.Profile{
"prod": {
Host: "https://kb.example.com",
TokenRef: "mem://prod/access",
RefreshRef: "mem://prod/refresh",
User: "alice@example.com",
},
},
}
f := newRefreshFactory(t, cfg, store)
svc := &fakeRefreshService{resp: &sdk.RefreshTokenResponse{
Success: true,
AccessToken: "new-access",
RefreshToken: "new-refresh",
}}
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(svc)))
assert.Equal(t, "old-refresh", svc.gotTok, "must pass stored refresh token to SDK")
gotAccess, _ := store.Get("prod", "access")
gotRefresh, _ := store.Get("prod", "refresh")
assert.Equal(t, "new-access", gotAccess)
assert.Equal(t, "new-refresh", gotRefresh)
}
// TestRefresh_ActiveProfileViaOverride exercises refreshing a non-default
// profile. Production resolves this via the global --profile flag (which
// rewrites cfg.CurrentProfile in Factory.Config); here we set
// CurrentProfile=staging directly, since runRefresh's target is the active
// profile.
func TestRefresh_ActiveProfileViaOverride(t *testing.T) {
iostreams.SetForTest(t)
store := secrets.NewMemStore()
require.NoError(t, store.Set("staging", "refresh", "stg-refresh"))
cfg := &config.Config{
CurrentProfile: "staging", // global --profile staging resolves to this
Profiles: map[string]config.Profile{
"prod": {Host: "https://prod", TokenRef: "mem://prod/access", RefreshRef: "mem://prod/refresh"},
"staging": {Host: "https://stg", TokenRef: "mem://staging/access", RefreshRef: "mem://staging/refresh"},
},
}
f := newRefreshFactory(t, cfg, store)
svc := &fakeRefreshService{resp: &sdk.RefreshTokenResponse{
Success: true, AccessToken: "new-stg-access", RefreshToken: "new-stg-refresh",
}}
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(svc)))
assert.Equal(t, "stg-refresh", svc.gotTok, "active profile staging must be refreshed")
// prod (non-active) is untouched
if v, _ := store.Get("prod", "access"); v != "" {
t.Errorf("prod must not have been touched, got %q", v)
}
}
// TestRefresh_NoNameFlag asserts the --name flag is gone; refresh targets the
// active profile (override via the global --profile).
func TestRefresh_NoNameFlag(t *testing.T) {
iostreams.SetForTest(t)
cfg := &config.Config{Profiles: map[string]config.Profile{"a": {Host: "https://a"}}}
f := newRefreshFactory(t, cfg, secrets.NewMemStore())
cmd := NewCmdRefresh(f)
assert.Nil(t, cmd.Flags().Lookup("name"), "--name flag must be removed")
}
func TestRefresh_NoCurrentProfile(t *testing.T) {
iostreams.SetForTest(t)
f := newRefreshFactory(t, &config.Config{}, secrets.NewMemStore())
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(&fakeRefreshService{}))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeAuthUnauthenticated, typed.Code)
}
func TestRefresh_APIKeyContext(t *testing.T) {
iostreams.SetForTest(t)
store := secrets.NewMemStore()
require.NoError(t, store.Set("ci", "api_key", "sk-123"))
cfg := &config.Config{
CurrentProfile: "ci",
Profiles: map[string]config.Profile{"ci": {Host: "https://kb", APIKeyRef: "mem://ci/api_key"}},
}
f := newRefreshFactory(t, cfg, store)
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(&fakeRefreshService{}))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code)
assert.Contains(t, typed.Hint, "api-key", "hint should explain api-key profiles cannot be refreshed")
}
func TestRefresh_NoRefreshTokenStored(t *testing.T) {
iostreams.SetForTest(t)
cfg := &config.Config{
CurrentProfile: "prod",
Profiles: map[string]config.Profile{
"prod": {Host: "https://kb", TokenRef: "mem://prod/access", RefreshRef: "mem://prod/refresh"},
},
}
// MemStore is empty - RefreshRef points to a slot that doesn't exist.
f := newRefreshFactory(t, cfg, secrets.NewMemStore())
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(&fakeRefreshService{}))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeAuthTokenExpired, typed.Code)
assert.Contains(t, typed.Hint, "auth login")
}
func TestRefresh_ServerRefused(t *testing.T) {
iostreams.SetForTest(t)
store := secrets.NewMemStore()
require.NoError(t, store.Set("prod", "refresh", "stale-refresh"))
cfg := &config.Config{
CurrentProfile: "prod",
Profiles: map[string]config.Profile{"prod": {Host: "https://kb", TokenRef: "mem://prod/access", RefreshRef: "mem://prod/refresh"}},
}
f := newRefreshFactory(t, cfg, store)
svc := &fakeRefreshService{resp: &sdk.RefreshTokenResponse{Success: false, Message: "refresh token expired"}}
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(svc))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeAuthTokenExpired, typed.Code)
assert.Contains(t, typed.Hint, "auth login")
// stored access must NOT have been overwritten with empty
if v, _ := store.Get("prod", "access"); v == "" {
// Was never set in this test, that's fine - main thing is no panic.
_ = v
}
}
func TestRefresh_TransportError(t *testing.T) {
iostreams.SetForTest(t)
store := secrets.NewMemStore()
require.NoError(t, store.Set("prod", "refresh", "ok-refresh"))
cfg := &config.Config{
CurrentProfile: "prod",
Profiles: map[string]config.Profile{"prod": {Host: "https://kb", TokenRef: "mem://prod/access", RefreshRef: "mem://prod/refresh"}},
}
f := newRefreshFactory(t, cfg, store)
svc := &fakeRefreshService{err: errors.New("connection reset")}
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(svc))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
// network/transport classified as network.error (mirrors auth login's
// CodeAuthBadCredential mapping pattern; here we keep network errors
// distinct since auth/refresh treats them as retryable).
assert.Equal(t, cmdutil.CodeNetworkError, typed.Code)
}
func TestRefresh_JSONOutput(t *testing.T) {
out, _ := iostreams.SetForTest(t)
store := secrets.NewMemStore()
require.NoError(t, store.Set("prod", "refresh", "ok-refresh"))
cfg := &config.Config{
CurrentProfile: "prod",
Profiles: map[string]config.Profile{"prod": {Host: "https://kb", TokenRef: "mem://prod/access", RefreshRef: "mem://prod/refresh"}},
}
f := newRefreshFactory(t, cfg, store)
svc := &fakeRefreshService{resp: &sdk.RefreshTokenResponse{Success: true, AccessToken: "a", RefreshToken: "r"}}
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, f, stubSvc(svc)))
body := out.String()
// payload must not leak the actual token values.
assert.NotContains(t, body, "ok-refresh", "output must not leak refresh token")
assert.NotContains(t, body, "\"a\"", "output must not leak the new access token")
assert.NotContains(t, body, "\"r\"", "output must not leak the new refresh token")
// must mention the profile name so agents can confirm what was refreshed
assert.True(t, strings.Contains(body, "prod"), "output should reference the refreshed profile")
// v0.7 envelope: ok:true is expected
var env struct {
OK bool `json:"ok"`
}
require.NoError(t, json.Unmarshal([]byte(body), &env))
assert.True(t, env.OK, "envelope.ok must be true")
}
+140
View File
@@ -0,0 +1,140 @@
package auth
import (
"context"
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
// authStatusFields enumerates the fields surfaced for `--format json` discovery
// on `auth status`. Single-resource shape: filter applies to data itself.
var authStatusFields = []string{
"profile", "host", "auth_source", "user_id", "username", "email", "is_active",
"can_access_all_tenants", "tenant_id", "tenant_name",
}
// StatusService is the narrow SDK surface auth status depends on.
type StatusService interface {
GetCurrentUser(ctx context.Context) (*sdk.CurrentUserResponse, error)
}
// statusResult is the typed payload emitted by `--format json`. Mirrors the
// SDK AuthUser + AuthTenant projection so agents can branch on
// can_access_all_tenants (cross-tenant admin) and is_active (disabled
// account) without a second round-trip.
type statusResult struct {
Profile string `json:"profile"`
Host string `json:"host,omitempty"`
AuthSource string `json:"auth_source,omitempty"`
UserID string `json:"user_id,omitempty"`
Username string `json:"username,omitempty"`
Email string `json:"email,omitempty"`
IsActive bool `json:"is_active,omitempty"`
CanAccessAllTenants bool `json:"can_access_all_tenants,omitempty"`
TenantID uint64 `json:"tenant_id,omitempty"`
TenantName string `json:"tenant_name,omitempty"`
}
// NewCmdStatus builds the `weknora auth status` command.
func NewCmdStatus(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "status",
Short: "Show the active profile, principal, and token state",
Long: `Live-check the active credential by calling /auth/me. Reports the user
and tenant the server resolves the credential to.
Exits with auth.unauthenticated when the token is invalid or missing - run
` + "`weknora auth login`" + ` (or ` + "`auth refresh`" + ` for JWT profiles) to recover.
For JWT profiles the SDK transparently refreshes on 401, so this command
usually only surfaces a hard auth failure.`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, args []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
cli, err := f.Client()
if err != nil {
return err
}
return runStatus(c.Context(), fopts, f, cli)
},
}
cmdutil.AddFormatFlag(cmd, authStatusFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "show the active profile, the authenticated principal, and token state",
Examples: []string{"weknora auth status", "weknora auth status --jq .data.tenant_id"},
Output: "envelope.data is {profile, host, auth_source, user_id, username, email, tenant_id, tenant_name, ...}; auth_source is 'profile + keyring' or a stateless env credential; exit 3 if unauthenticated",
})
return cmd
}
func runStatus(ctx context.Context, fopts *cmdutil.FormatOptions, f *cmdutil.Factory, svc StatusService) error {
if svc == nil {
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "no SDK client available; run `weknora auth login`")
}
resp, err := svc.GetCurrentUser(ctx)
if err != nil {
return cmdutil.WrapHTTP(err, "fetch current user")
}
user := resp.Data.User
tenant := resp.Data.Tenant
cfg, err := f.Config()
if err != nil {
return err
}
// Effective host + auth source. Stateless env credentials
// (WEKNORA_TOKEN/WEKNORA_API_KEY) override the profile + keyring for the
// client, so report the host they authenticate against (WEKNORA_HOST) and
// that they are in effect — not the bypassed config profile's host.
host := ""
if c, ok := cfg.Profiles[cfg.CurrentProfile]; ok {
host = c.Host
}
authSource := "profile + keyring"
if active, kind := cmdutil.EnvCredential(); active {
authSource = kind + " env (stateless)"
if h := strings.TrimSpace(os.Getenv("WEKNORA_HOST")); h != "" {
host = h
}
}
if fopts.WantsJSON() {
result := statusResult{Profile: cfg.CurrentProfile, Host: host, AuthSource: authSource}
if user != nil {
result.UserID = user.ID
result.Username = user.Username
result.Email = user.Email
result.IsActive = user.IsActive
result.CanAccessAllTenants = user.CanAccessAllTenants
result.TenantID = user.TenantID
}
if tenant != nil {
result.TenantName = tenant.Name
}
return fopts.Emit(iostreams.IO.Out, result, nil)
}
fmt.Fprintf(iostreams.IO.Out, "profile: %s\n", cfg.CurrentProfile)
fmt.Fprintf(iostreams.IO.Out, "auth_source: %s\n", authSource)
fmt.Fprintf(iostreams.IO.Out, "host: %s\n", host)
if user != nil {
fmt.Fprintf(iostreams.IO.Out, "user: %s (%s)\n", user.Email, user.ID)
fmt.Fprintf(iostreams.IO.Out, "tenant: %d", user.TenantID)
if tenant != nil {
fmt.Fprintf(iostreams.IO.Out, " (%s)", tenant.Name)
}
fmt.Fprintln(iostreams.IO.Out)
}
return nil
}
+32
View File
@@ -0,0 +1,32 @@
package auth
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestStatusJQPreservesTenantID(t *testing.T) {
out, _ := iostreams.SetForTest(t)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "/api/v1/auth/me", r.URL.Path)
_, _ = w.Write([]byte(`{"success":true,"data":{"user":{"id":"user-test","tenant_id":9007199254740993}}}`))
}))
defer server.Close()
f := &cmdutil.Factory{Config: func() (*config.Config, error) {
return &config.Config{CurrentProfile: "test", Profiles: map[string]config.Profile{
"test": {Host: server.URL},
}}, nil
}}
require.NoError(t, runStatus(context.Background(),
&cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, JQ: ".data.tenant_id"}, f, sdk.NewClient(server.URL)))
assert.Equal(t, "9007199254740993\n", out.String())
}
+112
View File
@@ -0,0 +1,112 @@
package auth
import (
"context"
"encoding/json"
"errors"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/prompt"
"github.com/Tencent/WeKnora/cli/internal/testutil"
sdk "github.com/Tencent/WeKnora/client"
)
type fakeStatusService struct {
resp *sdk.CurrentUserResponse
err error
}
func (f *fakeStatusService) GetCurrentUser(_ context.Context) (*sdk.CurrentUserResponse, error) {
return f.resp, f.err
}
func newCurrentUserResponse(user *sdk.AuthUser, tenant *sdk.AuthTenant) *sdk.CurrentUserResponse {
r := &sdk.CurrentUserResponse{Success: true}
r.Data.User = user
r.Data.Tenant = tenant
return r
}
func TestRunStatus_TextOutput(t *testing.T) {
out, _ := iostreams.SetForTest(t)
testutil.XDGTempDir(t)
require.NoError(t, config.Save(&config.Config{
CurrentProfile: "prod",
Profiles: map[string]config.Profile{
"prod": {Host: "https://kb.example.com", TenantID: 7},
},
}))
f := &cmdutil.Factory{
Config: func() (*config.Config, error) { return config.Load() },
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
}
svc := &fakeStatusService{
resp: newCurrentUserResponse(
&sdk.AuthUser{ID: "u1", Email: "alice@example.com", TenantID: 7},
&sdk.AuthTenant{ID: 7, Name: "Acme"},
),
}
require.NoError(t, runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, svc))
got := out.String()
assert.Contains(t, got, "profile: prod")
assert.Contains(t, got, "auth_source: profile + keyring")
assert.Contains(t, got, "host: https://kb.example.com")
assert.Contains(t, got, "alice@example.com")
assert.Contains(t, got, "Acme")
}
func TestRunStatus_JSONOutput(t *testing.T) {
out, _ := iostreams.SetForTest(t)
testutil.XDGTempDir(t)
require.NoError(t, config.Save(&config.Config{
CurrentProfile: "prod",
Profiles: map[string]config.Profile{"prod": {Host: "https://x"}},
}))
f := &cmdutil.Factory{Config: func() (*config.Config, error) { return config.Load() }}
svc := &fakeStatusService{resp: newCurrentUserResponse(&sdk.AuthUser{ID: "u1", Email: "a@b.c", TenantID: 7}, nil)}
require.NoError(t, runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, f, svc))
got := out.String()
var env struct {
OK bool `json:"ok"`
Data map[string]any `json:"data"`
}
require.NoError(t, json.Unmarshal([]byte(got), &env), "expected valid JSON envelope, got: %q", got)
assert.True(t, env.OK, "envelope.ok must be true")
assert.Equal(t, "prod", env.Data["profile"], "profile field should be prod")
assert.Contains(t, got, `"email":"a@b.c"`)
}
func TestRunStatus_NoSDKClient(t *testing.T) {
iostreams.SetForTest(t)
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &cmdutil.Factory{}, nil)
require.Error(t, err)
assert.True(t, cmdutil.IsAuthError(err))
}
func TestRunStatus_SDKError_Transport(t *testing.T) {
iostreams.SetForTest(t)
testutil.XDGTempDir(t)
require.NoError(t, config.Save(&config.Config{CurrentProfile: "p", Profiles: map[string]config.Profile{"p": {Host: "https://x"}}}))
f := &cmdutil.Factory{Config: func() (*config.Config, error) { return config.Load() }}
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, &fakeStatusService{err: assert.AnError})
require.Error(t, err)
// Non-HTTP errors (DNS / TCP) are transport problems, not auth problems -
// classify network.error so retry logic / exit code 7 / IsTransient apply.
assert.True(t, cmdutil.IsTransient(err), "expected transient/network classification, got %v", err)
}
func TestRunStatus_SDKError_HTTP401(t *testing.T) {
iostreams.SetForTest(t)
testutil.XDGTempDir(t)
require.NoError(t, config.Save(&config.Config{CurrentProfile: "p", Profiles: map[string]config.Profile{"p": {Host: "https://x"}}}))
f := &cmdutil.Factory{Config: func() (*config.Config, error) { return config.Load() }}
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, &fakeStatusService{err: errors.New("HTTP error 401: invalid token")})
require.Error(t, err)
assert.True(t, cmdutil.IsAuthError(err))
}
+183
View File
@@ -0,0 +1,183 @@
package auth
import (
"fmt"
"os"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
)
// authTokenFields lists fields surfaced in `--help` as a hint for `--jq`
// projection. Single-resource shape: emits the bare token object directly.
var authTokenFields = []string{"token", "mode", "profile"}
type tokenResult struct {
Token string `json:"token"`
Mode string `json:"mode"` // ModeBearer (JWT) or ModeAPIKey
Profile string `json:"profile"`
}
// NewCmdToken builds `weknora auth token`. Prints the active profile's
// credential to stdout for use in shell pipelines, e.g.
//
// WEKNORA_TOKEN=$(weknora auth token)
// curl -H "Authorization: Bearer $WEKNORA_TOKEN" ... # JWT mode
// curl -H "X-API-Key: $WEKNORA_TOKEN" ... # api-key mode
//
// The user is responsible for constructing the appropriate header -
// `auth list` shows which mode each profile uses.
//
// Default output: raw token on stdout, no trailing newline (clean $(...)).
// `--format json[=fields]` emits a bare {token, mode, profile} object.
func NewCmdToken(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "token",
Short: "Print the active profile's credential to stdout",
Long: `Print the active profile's credential to stdout, with no trailing
newline, suitable for shell command substitution.
The credential is the long-lived API key (mode: api-key) or the access JWT
(mode: bearer), depending on how the profile was created. Run ` + "`weknora auth list`" + `
to see which mode each profile uses, and construct the matching HTTP header:
Authorization: Bearer <token> # bearer mode
X-API-Key: <token> # api-key mode
` + "`--profile <name>`" + ` (global flag) selects a non-active profile to read from.`,
Example: ` WEKNORA_TOKEN=$(weknora auth token)
weknora auth token --profile staging
weknora auth token --format json`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
// `auth token` is a scalar scripting helper (WEKNORA_TOKEN=$(...)),
// so it defaults to the raw token — overriding the global json
// default, the same way `doc download` streams raw bytes. Explicit
// --format json / WEKNORA_FORMAT=json still emit the
// {token,mode,profile} envelope.
fopts.FromEnv()
if fopts.Mode == "" {
// --jq implies JSON (it filters the envelope); without it,
// default to the raw token for clean $(...) capture.
if fopts.JQ != "" {
fopts.Mode = cmdutil.FormatJSON
} else {
fopts.Mode = cmdutil.FormatText
}
}
return runToken(f, fopts)
},
}
cmdutil.AddFormatFlag(cmd, authTokenFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "print the active profile's raw credential to stdout for shell capture",
Examples: []string{
"WEKNORA_TOKEN=$(weknora auth token)",
"weknora auth token --profile staging",
"weknora auth token --format json",
},
Output: "raw token on stdout (no envelope, no trailing newline) by default; --format json emits {token, mode, profile}",
Warnings: []string{
"default output is the bare token, NOT the JSON envelope — it is a scripting helper for shell capture",
},
})
return cmd
}
func runToken(f *cmdutil.Factory, fopts *cmdutil.FormatOptions) error {
// Env credentials are the active credential on the headless path — `auth
// token` must surface them (they ARE the token / api key) instead of
// erroring on the absence of a stored profile.
if active, kind := cmdutil.EnvCredential(); active {
mode := ModeBearer
if kind == "WEKNORA_API_KEY" {
mode = ModeAPIKey
}
return emitToken(fopts, os.Getenv(kind), mode, "(env)")
}
cfg, err := f.Config()
if err != nil {
return err
}
profileName := cfg.CurrentProfile
if f.ProfileOverride != "" {
profileName = f.ProfileOverride
}
if profileName == "" {
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
"no active profile configured")
}
ctx, ok := cfg.Profiles[profileName]
if !ok {
return cmdutil.NewError(cmdutil.CodeLocalProfileNotFound,
fmt.Sprintf("profile %q not found", profileName))
}
store, err := f.Secrets()
if err != nil {
return cmdutil.Wrapf(cmdutil.CodeLocalKeychainDenied, err, "init secrets store")
}
// Resolve the stored credential. Prefer bearer (JWT) when both refs
// are present - JWT is the more capable mode and what `buildClient`
// uses for the Authorization header (see factory.go buildClient).
var token, mode string
switch {
case ctx.TokenRef != "":
v, ferr := cmdutil.LoadSecret(store, profileName, "access")
if ferr != nil {
return ferr
}
token, mode = v, ModeBearer
case ctx.APIKeyRef != "":
v, ferr := cmdutil.LoadSecret(store, profileName, "api_key")
if ferr != nil {
return ferr
}
token, mode = v, ModeAPIKey
default:
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
fmt.Sprintf("profile %q has no stored credential; run `weknora auth login`", profileName))
}
if token == "" {
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
fmt.Sprintf("profile %q credential is empty in keyring; run `weknora auth login`", profileName))
}
return emitToken(fopts, token, mode, profileName)
}
// emitToken renders a resolved credential: the {token, mode, profile} envelope
// under --format json, else the raw token on stdout (no trailing newline, for
// clean $(weknora auth token) capture) with a TTY-only leak hint on stderr.
func emitToken(fopts *cmdutil.FormatOptions, token, mode, profile string) error {
if token == "" {
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "active credential is empty")
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, tokenResult{Token: token, Mode: mode, Profile: profile}, nil)
}
// No trailing newline - clean $(weknora auth token) substitution.
fmt.Fprint(iostreams.IO.Out, token)
// Defensive hint to stderr when stdout is an interactive terminal:
// the user likely didn't mean to display the secret on screen.
// stderr-only so scripts (always non-TTY) are unaffected. Mode-specific
// because api-key tokens are long-lived and rotation is the only
// recourse on leak - bearer tokens self-expire via refresh.
if iostreams.IO.IsStdoutTTY() {
fmt.Fprintln(iostreams.IO.Err)
fmt.Fprintln(iostreams.IO.Err, "hint: pipe to $(weknora auth token) to capture; this terminal scrollback now contains the secret")
if mode == ModeAPIKey {
fmt.Fprintln(iostreams.IO.Err, "note: api-key credentials are long-lived - rotate via your auth provider if exposed (no `auth refresh` path)")
}
}
return nil
}
+354
View File
@@ -0,0 +1,354 @@
package auth
import (
"encoding/json"
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/secrets"
)
// tokenTestFactory wires a config + in-memory secrets store the same way
// the production Factory does, so runToken exercises the real LoadSecret
// path.
func tokenTestFactory(t *testing.T, cfg *config.Config, store *secrets.MemStore) *cmdutil.Factory {
t.Helper()
f := &cmdutil.Factory{
Config: func() (*config.Config, error) { return cfg, nil },
Secrets: func() (secrets.Store, error) { return store, nil },
}
return f
}
// TestAuthToken_DefaultIsRawToken locks the scripting contract: with no
// explicit --format, `weknora auth token` emits the raw token (so
// WEKNORA_TOKEN=$(weknora auth token) works), NOT the JSON envelope — even
// though the global --format default is json. Explicit --format json still
// emits the {token,mode,profile} envelope (covered by the JSON test below).
func TestAuthToken_DefaultIsRawToken(t *testing.T) {
cfg := &config.Config{
CurrentProfile: "prod",
Profiles: map[string]config.Profile{
"prod": {Host: "https://kb.example.com", TokenRef: "prod:access"},
},
}
store := secrets.NewMemStore()
_ = store.Set("prod", "access", "jwt-default-xyz")
out, _ := iostreams.SetForTest(t)
cmd := NewCmdToken(tokenTestFactory(t, cfg, store))
cmd.PersistentFlags().String("format", "", "") // mirror the root persistent flag, unset
cmd.SetArgs([]string{})
if err := cmd.Execute(); err != nil {
t.Fatalf("execute: %v", err)
}
if got := out.String(); got != "jwt-default-xyz" {
t.Errorf("default output must be the raw token (not an envelope); got %q", got)
}
}
// TestAuthToken_JQImpliesJSON: --jq filters the envelope, so passing it without
// an explicit --format must resolve to JSON (not the raw-token default), else
// the filter would be silently dropped.
func TestAuthToken_JQImpliesJSON(t *testing.T) {
cfg := &config.Config{
CurrentProfile: "prod",
Profiles: map[string]config.Profile{
"prod": {Host: "https://kb.example.com", TokenRef: "prod:access"},
},
}
store := secrets.NewMemStore()
_ = store.Set("prod", "access", "jwt-jq-xyz")
out, _ := iostreams.SetForTest(t)
cmd := NewCmdToken(tokenTestFactory(t, cfg, store))
cmd.PersistentFlags().String("format", "", "")
cmd.PersistentFlags().StringP("jq", "q", "", "")
// Structural projection: proves jq ran on the JSON envelope (object out),
// not the raw-token text path (which would print the bare string).
cmd.SetArgs([]string{"--jq", ".data | {token}"})
if err := cmd.Execute(); err != nil {
t.Fatalf("execute: %v", err)
}
var got map[string]any
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
t.Fatalf("--jq without --format must filter the JSON envelope, got non-JSON %q: %v", out.String(), err)
}
if got["token"] != "jwt-jq-xyz" {
t.Errorf("jq projection wrong: %+v", got)
}
}
func TestAuthToken_BearerMode_PlainOutput(t *testing.T) {
cfg := &config.Config{
CurrentProfile: "prod",
Profiles: map[string]config.Profile{
"prod": {Host: "https://kb.example.com", TokenRef: "prod:access", RefreshRef: "prod:refresh"},
},
}
store := secrets.NewMemStore()
_ = store.Set("prod", "access", "jwt-token-xyz")
out, _ := iostreams.SetForTest(t)
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
if err != nil {
t.Fatalf("runToken: %v", err)
}
got := out.String()
if got != "jwt-token-xyz" {
t.Errorf("expected raw token, got %q", got)
}
if strings.HasSuffix(got, "\n") {
t.Errorf("output must NOT end with newline (clean $(...) substitution); got %q", got)
}
}
func TestAuthToken_APIKeyMode_PlainOutput(t *testing.T) {
cfg := &config.Config{
CurrentProfile: "ci",
Profiles: map[string]config.Profile{
"ci": {Host: "https://kb.example.com", APIKeyRef: "ci:api_key"},
},
}
store := secrets.NewMemStore()
_ = store.Set("ci", "api_key", "sk_test_apikey_42")
out, _ := iostreams.SetForTest(t)
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
t.Fatalf("runToken: %v", err)
}
if got := out.String(); got != "sk_test_apikey_42" {
t.Errorf("expected api-key value, got %q", got)
}
}
func TestAuthToken_JSON(t *testing.T) {
cfg := &config.Config{
CurrentProfile: "prod",
Profiles: map[string]config.Profile{
"prod": {Host: "https://kb.example.com", TokenRef: "prod:access"},
},
}
store := secrets.NewMemStore()
_ = store.Set("prod", "access", "jwt-xyz")
out, _ := iostreams.SetForTest(t)
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}); err != nil {
t.Fatalf("runToken: %v", err)
}
var env struct {
OK bool `json:"ok"`
Data struct {
Token string `json:"token"`
Mode string `json:"mode"`
Profile string `json:"profile"`
} `json:"data"`
}
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
t.Fatalf("parse: %v\n%s", err, out.String())
}
got := env.Data
if got.Token != "jwt-xyz" || got.Mode != "bearer" || got.Profile != "prod" {
t.Errorf("payload wrong: %+v", got)
}
}
func TestAuthToken_JSON_JQProjection(t *testing.T) {
cfg := &config.Config{
CurrentProfile: "ci",
Profiles: map[string]config.Profile{
"ci": {Host: "https://kb.example.com", APIKeyRef: "ci:api_key"},
},
}
store := secrets.NewMemStore()
_ = store.Set("ci", "api_key", "sk_42")
out, _ := iostreams.SetForTest(t)
// jq projects from the envelope; .data | {token} extracts from the data object inside envelope.
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, JQ: ".data | {token}"}
if err := runToken(tokenTestFactory(t, cfg, store), fopts); err != nil {
t.Fatalf("runToken: %v", err)
}
var got map[string]any
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
t.Fatalf("parse: %v", err)
}
if _, has := got["mode"]; has {
t.Errorf("mode should be filtered out: %+v", got)
}
if got["token"] != "sk_42" {
t.Errorf("token wrong: %+v", got)
}
}
func TestAuthToken_NoCurrentProfile(t *testing.T) {
cfg := &config.Config{}
store := secrets.NewMemStore()
iostreams.SetForTest(t)
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
if err == nil {
t.Fatal("expected error, got nil")
}
if !cmdutil.IsAuthError(err) {
t.Errorf("want auth.* code, got %v", err)
}
}
func TestAuthToken_ProfileOverride(t *testing.T) {
cfg := &config.Config{
CurrentProfile: "prod",
Profiles: map[string]config.Profile{
"prod": {Host: "https://prod.example.com", TokenRef: "prod:access"},
"staging": {Host: "https://staging.example.com", APIKeyRef: "staging:api_key"},
},
}
store := secrets.NewMemStore()
_ = store.Set("prod", "access", "prod-jwt")
_ = store.Set("staging", "api_key", "staging-key")
f := tokenTestFactory(t, cfg, store)
f.ProfileOverride = "staging"
out, _ := iostreams.SetForTest(t)
if err := runToken(f, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
t.Fatalf("runToken: %v", err)
}
if got := out.String(); got != "staging-key" {
t.Errorf("expected staging-key (override), got %q", got)
}
}
func TestAuthToken_NoStoredCredential(t *testing.T) {
cfg := &config.Config{
CurrentProfile: "prod",
Profiles: map[string]config.Profile{
"prod": {Host: "https://kb.example.com", TokenRef: "prod:access"},
},
}
store := secrets.NewMemStore()
// no Set - keyring is empty
iostreams.SetForTest(t)
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
if err == nil {
t.Fatal("expected auth.unauthenticated, got nil")
}
if !cmdutil.IsAuthError(err) {
t.Errorf("want auth.*, got %v", err)
}
}
func TestAuthToken_ContextWithNoCredentialRefs(t *testing.T) {
cfg := &config.Config{
CurrentProfile: "empty",
Profiles: map[string]config.Profile{
"empty": {Host: "https://kb.example.com"}, // no TokenRef or APIKeyRef
},
}
store := secrets.NewMemStore()
iostreams.SetForTest(t)
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
if err == nil {
t.Fatal("expected auth.unauthenticated, got nil")
}
if !cmdutil.IsAuthError(err) {
t.Errorf("want auth.*, got %v", err)
}
}
// --- stderr advisory tests --------------------------------------------------
//
// auth token prints the token to stdout unconditionally. When stdout is an
// interactive terminal, it ALSO writes a stderr advisory ("you just put the
// secret in your scrollback") + a mode-specific rotation note for api-key
// credentials. The stdout half must stay clean under all modes so $(...)
// substitution is unaffected - tests assert both axes.
func makeBearerCfg() (*config.Config, *secrets.MemStore) {
cfg := &config.Config{
CurrentProfile: "prod",
Profiles: map[string]config.Profile{
"prod": {Host: "https://kb.example.com", TokenRef: "prod:access"},
},
}
store := secrets.NewMemStore()
_ = store.Set("prod", "access", "jwt-xyz")
return cfg, store
}
func makeAPIKeyCfg() (*config.Config, *secrets.MemStore) {
cfg := &config.Config{
CurrentProfile: "ci",
Profiles: map[string]config.Profile{
"ci": {Host: "https://kb.example.com", APIKeyRef: "ci:api_key"},
},
}
store := secrets.NewMemStore()
_ = store.Set("ci", "api_key", "sk_42")
return cfg, store
}
func TestAuthToken_NonTTY_NoStderrHint(t *testing.T) {
cfg, store := makeBearerCfg()
out, errBuf := iostreams.SetForTest(t)
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
t.Fatalf("runToken: %v", err)
}
if out.String() != "jwt-xyz" {
t.Errorf("stdout = %q, want %q", out.String(), "jwt-xyz")
}
if errBuf.Len() != 0 {
t.Errorf("non-TTY stderr should be empty (scripts depend on this), got %q", errBuf.String())
}
}
func TestAuthToken_TTY_BearerMode_StderrHintNoRotationNote(t *testing.T) {
cfg, store := makeBearerCfg()
out, errBuf := iostreams.SetForTestWithTTY(t)
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
t.Fatalf("runToken: %v", err)
}
if out.String() != "jwt-xyz" {
t.Errorf("stdout = %q, want raw token only", out.String())
}
if !strings.Contains(errBuf.String(), "scrollback") {
t.Errorf("expected stderr scrollback hint on TTY, got %q", errBuf.String())
}
if strings.Contains(errBuf.String(), "api-key") {
t.Errorf("bearer mode should not surface the api-key rotation note: %q", errBuf.String())
}
}
func TestAuthToken_TTY_APIKeyMode_IncludesRotationNote(t *testing.T) {
cfg, store := makeAPIKeyCfg()
out, errBuf := iostreams.SetForTestWithTTY(t)
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
t.Fatalf("runToken: %v", err)
}
if out.String() != "sk_42" {
t.Errorf("stdout = %q, want raw token only", out.String())
}
stderr := errBuf.String()
if !strings.Contains(stderr, "scrollback") {
t.Errorf("api-key TTY stderr should still include the scrollback hint, got %q", stderr)
}
if !strings.Contains(stderr, "long-lived") || !strings.Contains(stderr, "rotate") {
t.Errorf("api-key mode should include rotation note, got %q", stderr)
}
}
func TestAuthToken_TTY_JSONMode_NoStderrHint(t *testing.T) {
// --format json output mode targets script/agent consumers even when stdout
// happens to be a TTY (e.g. an IDE running the CLI on the user's
// behalf). Hint would pollute their parsing - suppress.
cfg, store := makeBearerCfg()
_, errBuf := iostreams.SetForTestWithTTY(t)
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}); err != nil {
t.Fatalf("runToken: %v", err)
}
if errBuf.Len() != 0 {
t.Errorf("JSON mode should not emit stderr hint, got %q", errBuf.String())
}
}
+358
View File
@@ -0,0 +1,358 @@
// Package chat implements `weknora chat <text>` - the streaming RAG answer
// entry point.
//
// Three output modes share a single SDK call:
//
// - JSON mode (--format json, the default): buffer a bounded projection of
// the stream into one success envelope. The default projection contains
// answer events only; --reference adds indexed citations and --verbose
// adds reasoning, tools, and lifecycle frames.
//
// - Text mode (--format text): render the same projection as JSON
// directly to iostreams.IO.Out as it arrives.
//
// - NDJSON mode (--format ndjson): inject a CLI "init" event at stream
// head, then pass through every SDK event verbatim as NDJSON lines —
// the raw protocol trace, for debugging / advanced consumers.
//
// The SDK's KnowledgeQAStream callback contract is invoked sequentially on
// one goroutine, so no mode needs locking. The runChat core takes a
// ChatService interface so tests inject a fake without standing up a real
// SSE server.
package chat
import (
"context"
"fmt"
"strings"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/output"
"github.com/Tencent/WeKnora/cli/internal/sse"
sdk "github.com/Tencent/WeKnora/client"
)
// chatFields enumerates the fields surfaced for `--jq` projection discovery
// on `chat`: the json object's data fields + the raw SDK event vocabulary
// used by --format ndjson.
var chatFields = []string{
"events", "session_id", "assistant_message_id", "kb_id", "query",
// NDJSON init + SDK event fields.
"type", "kb_id", "profile", "response_type", "content", "done", "knowledge_references", "data",
}
type Options struct {
Query string
KBID string
SessionID string
// Reference adds bounded kb_id/chunk_id reference events to JSON/text.
Reference bool
// Verbose surfaces the projected execution trace in JSON/text,
// including reasoning, tools, and lifecycle events.
// NDJSON is always raw and is unaffected by presentation flags.
Verbose bool
}
// ChatService is the narrow SDK surface this command depends on. *sdk.Client
// satisfies it; tests substitute a fake. Compile-time check is at the bottom
// of this file.
type ChatService interface {
CreateSession(ctx context.Context, req *sdk.CreateSessionRequest) (*sdk.Session, error)
KnowledgeQAStream(ctx context.Context, sessionID string, req *sdk.KnowledgeQARequest, cb func(*sdk.StreamResponse) error, opts ...sdk.ResourceURLOptions) error
}
// NewCmd builds `weknora chat <text>`.
func NewCmd(f *cmdutil.Factory) *cobra.Command {
opts := &Options{}
cmd := &cobra.Command{
Use: `chat "<text>"`,
Short: "Ask a streaming RAG question against a knowledge base",
Long: `Send a query to the WeKnora knowledge-chat endpoint and stream the
answer back. By default a fresh session is created on first invocation; pass
--session to continue an existing conversation.
Modes:
--format json (default): one JSON envelope with answer events
--format text: live human-readable answer stream
--format ndjson: raw NDJSON event stream — init line (session_id,
kb_id) then SDK events verbatim. Debug / advanced.
Pass --reference to include bounded kb_id/chunk_id reference indexes. Pass
--verbose to include reasoning, tool activity, and lifecycle frames. Combine
both flags for the complete projected stream.`,
Example: ` weknora chat "What is RRF?" --kb a32a63ff-fb36-4874-bcaa-30f48570a694
weknora chat "Summarise this design doc" --kb my-kb --format json
weknora chat "Continue?" --session sess_abc`,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
opts.Query = strings.TrimSpace(args[0])
if opts.Query == "" {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "query argument cannot be empty")
}
fopts, err := cmdutil.CheckFormatFlag(c)
if err != nil {
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
kbID, err := f.ResolveKB(c)
if err != nil {
return err
}
opts.KBID = kbID
cli, err := f.Client()
if err != nil {
return err
}
return runChat(c.Context(), opts, fopts, cli)
},
}
cmdutil.AddKBFlag(cmd)
cmd.Flags().StringVar(&opts.SessionID, "session", "", "Continue an existing chat session (skip auto-create)")
cmd.Flags().BoolVar(&opts.Reference, "reference", false, "Include indexed references in JSON/text output")
cmd.Flags().BoolVar(&opts.Verbose, "verbose", false, "Include reasoning, tools, and lifecycle events in JSON/text output")
cmdutil.AddFormatFlag(cmd, chatFields...)
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "Ask a RAG question against a knowledge base. Default JSON returns a bounded answer-event projection. --reference adds indexed citations; --verbose adds reasoning, tools, and lifecycle events. --format ndjson streams raw SDK events; --format text renders the selected events live.",
RequiredFlags: []string{"<text> (positional)", "--kb"},
Examples: []string{
`weknora chat "What is RRF?" --kb kb_abc`,
`weknora chat "What is RRF?" --kb kb_abc --jq '[.data.events[].content] | join("")'`,
},
Output: "Default --format json: {ok,data:{events:[answer...],session_id,kb_id,query}}. --reference adds kb_id/chunk_id reference events; --verbose adds execution events. --format ndjson remains raw.",
})
return cmd
}
// runChat is the testable core: validate, ensure a session, dispatch the
// stream, and route output. Returns a typed error.
func runChat(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, svc ChatService) error {
if opts.Query == "" {
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, "query argument cannot be empty")
}
if opts.KBID == "" {
// Defensive: the cobra layer resolves KB before runChat; this guards
// the direct-test entry point.
return cmdutil.NewError(cmdutil.CodeKBIDRequired, "kb id is required")
}
if svc == nil {
return cmdutil.NewError(cmdutil.CodeServerError, "chat: no SDK client available")
}
// --format selects the output shape: json (default) accumulates and
// emits one object, ndjson streams raw SDK events, text renders live.
sessionID := opts.SessionID
autoCreated := false
if sessionID == "" {
sess, err := svc.CreateSession(ctx, &sdk.CreateSessionRequest{Title: "weknora chat"})
if err != nil {
// Ctrl-C during session creation: classify as cancelled so the
// hint nudges the user toward retry-with-signal-clean, not
// "pass --session" as session_create_failed would.
if cmdutil.IsCancelled(ctx, err) {
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, err, "chat cancelled")
}
// Map HTTP-shaped failures, but tag generic transport / unknown
// errors as session_create_failed so the dedicated hint fires.
code := cmdutil.ClassifyHTTPError(err)
if code == cmdutil.CodeNetworkError || code == cmdutil.CodeServerError {
code = cmdutil.CodeSessionCreateFailed
}
return cmdutil.Wrapf(code, err, "create chat session")
}
sessionID = sess.ID
autoCreated = true
}
if fopts != nil && fopts.Mode == cmdutil.FormatNDJSON {
return runChatNDJSON(ctx, opts, sessionID, svc)
}
if fopts != nil && fopts.Mode == cmdutil.FormatJSON {
return runChatJSON(ctx, opts, fopts, sessionID, svc)
}
// Surface the auto-created session ID up-front so a user who hits ^C
// mid-stream still has the pointer to resume - no need to scroll back
// past tokens. Skipped in json/ndjson mode (session_id is in the output).
if autoCreated {
fmt.Fprintf(iostreams.IO.Err, "session: %s (use --session to continue)\n", sessionID)
}
return runChatText(ctx, opts, sessionID, autoCreated, svc)
}
// runChatNDJSON handles the --format ndjson path: emits a CLI init event at
// stream head, then passes every SDK event through verbatim as NDJSON lines.
// No buffering — callers parse the stream incrementally.
func runChatNDJSON(ctx context.Context, opts *Options, sessionID string, svc ChatService) error {
w := iostreams.IO.Out
// 1. Inject the CLI-managed init event at the head of the stream.
// Carries the session pointer + retrieval context callers need for
// follow-up threading.
initEv := output.InitEvent{
SessionID: sessionID,
KBID: opts.KBID,
Profile: cmdutil.GetProfile(),
}
if err := output.EmitInit(w, initEv); err != nil {
return err
}
// 2. Open SDK stream and pass each event through as a bare NDJSON line.
req := &sdk.KnowledgeQARequest{
Query: opts.Query,
KnowledgeBaseIDs: []string{opts.KBID},
AgentEnabled: false,
WebSearchEnabled: false,
Channel: "api",
}
cb := func(r *sdk.StreamResponse) error {
// NDJSON is the raw protocol/debug surface: do not filter events or
// mutate their payloads. JSON/text modes own presentation filtering.
return output.EmitSDKEvent(w, r)
}
if err := svc.KnowledgeQAStream(ctx, sessionID, req, cb); err != nil {
if cmdutil.IsCancelled(ctx, err) {
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, err, "chat cancelled")
}
return cmdutil.WrapStream(err, "knowledge qa stream")
}
return nil
}
// runChatText handles the --format text path. It renders the same
// projection as JSON immediately for both terminals and pipes.
func runChatText(ctx context.Context, opts *Options, sessionID string, autoCreated bool, svc ChatService) error {
req := &sdk.KnowledgeQARequest{
Query: opts.Query,
KnowledgeBaseIDs: []string{opts.KBID},
AgentEnabled: false,
WebSearchEnabled: false,
Channel: "api",
}
projector := sse.NewProjector(opts.Verbose, opts.Reference, opts.KBID)
renderer := sse.NewTextRenderer(iostreams.IO.Out, opts.Verbose)
cb := func(r *sdk.StreamResponse) error {
event, include := projector.Chat(r)
if !include {
return nil
}
return renderer.Write(event)
}
streamErr := svc.KnowledgeQAStream(ctx, sessionID, req, cb)
if streamErr != nil {
// Re-surface the auto-created session id on failure so a user who
// missed the start-of-stream notice (it scrolls past mid-stream
// tokens, especially on ^C) can still recover with --session.
if autoCreated {
fmt.Fprintf(iostreams.IO.Err, "session: %s (resume with --session %s)\n", sessionID, sessionID)
}
// Context cancelled (Ctrl-C) → user-aborted, exit 130 lineage.
if cmdutil.IsCancelled(ctx, streamErr) {
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, streamErr, "chat cancelled")
}
// Stream began (we observed at least one event) but never reached a
// terminal Done frame: typed as sse_stream_aborted so the hint
// nudges the user toward a retry.
if projector.Seen() && !projector.Done() {
return cmdutil.Wrapf(cmdutil.CodeSSEStreamAborted, streamErr, "stream aborted before completion")
}
// Pre-stream HTTP / transport failure: route through the canonical
// classifier so 401 / 404 / 5xx still surface their specific codes.
return cmdutil.WrapStream(streamErr, "knowledge qa stream")
}
// SDK returned nil but we never saw a Done event - server closed the
// connection cleanly mid-stream. Treat as aborted so the user sees the
// truncation rather than a silent partial answer. Includes the empty-body
// case (Done frame never arrived AND no content): better to surface the
// abort than emit ok=true with answer="" - agents can't distinguish the
// model genuinely had nothing to say from the stream getting cut.
if !projector.Done() {
return cmdutil.NewError(cmdutil.CodeSSEStreamAborted, "stream ended without a terminal event")
}
return renderer.Close()
}
// runChatJSON handles the --format json path (the default): collect the
// projection and emit it in one normal success envelope.
func runChatJSON(ctx context.Context, opts *Options, fopts *cmdutil.FormatOptions, sessionID string, svc ChatService) error {
req := &sdk.KnowledgeQARequest{
Query: opts.Query,
KnowledgeBaseIDs: []string{opts.KBID},
AgentEnabled: false,
WebSearchEnabled: false,
Channel: "api",
}
projector := sse.NewProjector(opts.Verbose, opts.Reference, opts.KBID)
events := make([]sse.ProjectedEvent, 0)
cb := func(r *sdk.StreamResponse) error {
if event, include := projector.Chat(r); include {
events = append(events, event)
}
return nil
}
if err := svc.KnowledgeQAStream(ctx, sessionID, req, cb); err != nil {
if cmdutil.IsCancelled(ctx, err) {
return chatStreamError(cmdutil.Wrapf(cmdutil.CodeOperationCancelled, err, "chat cancelled"), sessionID, projector.AssistantMessageID())
}
return chatStreamError(cmdutil.WrapStream(err, "knowledge qa stream"), sessionID, projector.AssistantMessageID())
}
if !projector.Done() {
return chatStreamError(
cmdutil.NewError(cmdutil.CodeSSEStreamAborted, "stream ended without a terminal event"),
sessionID,
projector.AssistantMessageID(),
)
}
sid := projector.SessionID()
if sid == "" {
sid = sessionID
}
data := chatResult{
Events: events,
SessionID: sid,
AssistantMessageID: projector.AssistantMessageID(),
KBID: opts.KBID,
Query: opts.Query,
}
// Reaching here means fopts.Mode is FormatJSON (the only caller). Route
// through FormatOptions.Emit so --jq projection and the success-envelope
// contract apply, matching every other non-streaming command. A nil fopts
// (direct-test entry) defaults to JSON so the object still emits.
if fopts == nil {
fopts = &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
}
return fopts.Emit(iostreams.IO.Out, data, nil)
}
func chatStreamError(err *cmdutil.Error, sessionID, assistantMessageID string) *cmdutil.Error {
detail := map[string]any{"session_id": sessionID}
if assistantMessageID != "" {
detail["assistant_message_id"] = assistantMessageID
}
return err.WithDetail(detail)
}
// chatResult is the --format json data payload. The projector controls default
// versus verbose coverage.
type chatResult struct {
Events []sse.ProjectedEvent `json:"events"`
SessionID string `json:"session_id"`
AssistantMessageID string `json:"assistant_message_id,omitempty"`
KBID string `json:"kb_id"`
Query string `json:"query"`
}
// compile-time check: the production SDK client implements ChatService.
var _ ChatService = (*sdk.Client)(nil)
+656
View File
@@ -0,0 +1,656 @@
package chat
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/sse"
sdk "github.com/Tencent/WeKnora/client"
)
// fakeChatService implements ChatService for unit tests. Tests configure the
// callback driver via streamEvents (delivered in order) and observe captured
// inputs through the exported fields.
type fakeChatService struct {
createSessionResp *sdk.Session
createSessionErr error
createCalled bool
streamErr error
streamEvents []*sdk.StreamResponse
gotSessionID string
gotRequest *sdk.KnowledgeQARequest
streamCalled bool
cbReturnsError error // if set, callback aborts after first event with this error
}
func (f *fakeChatService) CreateSession(_ context.Context, req *sdk.CreateSessionRequest) (*sdk.Session, error) {
f.createCalled = true
if f.createSessionErr != nil {
return nil, f.createSessionErr
}
if f.createSessionResp != nil {
return f.createSessionResp, nil
}
// Default: return a deterministic session id derived from the title so
// JSON assertions don't depend on uuid generation.
return &sdk.Session{ID: "sess_auto", Title: req.Title}, nil
}
func (f *fakeChatService) KnowledgeQAStream(ctx context.Context, sessionID string, req *sdk.KnowledgeQARequest, cb func(*sdk.StreamResponse) error, opts ...sdk.ResourceURLOptions) error {
f.streamCalled = true
f.gotSessionID = sessionID
f.gotRequest = req
for _, ev := range f.streamEvents {
if err := cb(ev); err != nil {
return err
}
if f.cbReturnsError != nil {
return f.cbReturnsError
}
}
return f.streamErr
}
// Sanity: fakeChatService must satisfy ChatService. Mirrors the production
// var _ ChatService = (*sdk.Client)(nil) check at the bottom of chat.go.
var _ ChatService = (*fakeChatService)(nil)
// textOpts returns a FormatOptions configured for the text render path —
// the most common shape under test.
func textOpts() *cmdutil.FormatOptions {
return &cmdutil.FormatOptions{Mode: cmdutil.FormatText}
}
func TestChat_StreamMode(t *testing.T) {
out, errBuf := iostreams.SetForTestWithTTY(t)
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{
{ResponseType: sdk.ResponseTypeAnswer, Content: "Hello "},
{ResponseType: sdk.ResponseTypeAnswer, Content: "world"},
{ResponseType: sdk.ResponseTypeReferences, KnowledgeReferences: []*sdk.SearchResult{
{KnowledgeID: "k1", KnowledgeTitle: "Doc One", Score: 0.42},
}},
{ResponseType: sdk.ResponseTypeComplete, Done: true},
},
}
opts := &Options{Query: "hi", KBID: "kb_1"}
if err := runChat(context.Background(), opts, textOpts(), svc); err != nil {
t.Fatalf("runChat: %v", err)
}
got := out.String()
if !strings.Contains(got, "Hello world") {
t.Errorf("stdout missing streamed content: %q", got)
}
if strings.Contains(got, "references") || strings.Contains(got, "Doc One") {
t.Errorf("default text output leaked references: %q", got)
}
// auto-created session must announce itself on stderr
if !strings.Contains(errBuf.String(), "session: sess_auto") {
t.Errorf("expected stderr session hint, got %q", errBuf.String())
}
if !svc.createCalled {
t.Error("expected CreateSession invocation when SessionID empty")
}
if svc.gotSessionID != "sess_auto" {
t.Errorf("stream sessionID: got %q want sess_auto", svc.gotSessionID)
}
if svc.gotRequest == nil || svc.gotRequest.Channel != "api" {
t.Errorf("expected Channel=api, got %+v", svc.gotRequest)
}
}
// TestChat_NDJSON_FirstLineIsInit verifies that the NDJSON path (--format ndjson)
// always injects an "init" line first carrying session_id and kb_id.
func TestChat_NDJSON_FirstLineIsInit(t *testing.T) {
out, errBuf := iostreams.SetForTest(t)
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{
{ResponseType: sdk.ResponseTypeAnswer, Content: "answer"},
{ResponseType: sdk.ResponseTypeComplete, Done: true},
},
}
opts := &Options{Query: "q", KBID: "kb_42"}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatNDJSON}
if err := runChat(context.Background(), opts, fopts, svc); err != nil {
t.Fatalf("runChat: %v", err)
}
// NDJSON mode must NOT print the session hint to stderr.
if errBuf.Len() != 0 {
t.Errorf("expected empty stderr in NDJSON mode, got %q", errBuf.String())
}
lines := strings.Split(strings.TrimRight(out.String(), "\n"), "\n")
if len(lines) == 0 {
t.Fatal("no output")
}
var first struct {
Type string `json:"type"`
SessionID string `json:"session_id"`
KBID string `json:"kb_id"`
}
if err := json.Unmarshal([]byte(lines[0]), &first); err != nil {
t.Fatalf("first line not JSON: %v\n %s", err, lines[0])
}
if first.Type != "init" {
t.Errorf("first line type: got %q, want init", first.Type)
}
if first.SessionID != "sess_auto" {
t.Errorf("init.session_id: got %q, want sess_auto", first.SessionID)
}
if first.KBID != "kb_42" {
t.Errorf("init.kb_id: got %q, want kb_42", first.KBID)
}
}
// TestChat_NDJSON_PassthroughEvents verifies that the NDJSON path emits
// init + N SDK events = N+1 total lines (no buffering, no extra wrapping).
func TestChat_NDJSON_PassthroughEvents(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{
{ResponseType: sdk.ResponseTypeAnswer, Content: "hello"},
{ResponseType: sdk.ResponseTypeComplete, Done: true},
},
}
opts := &Options{Query: "q", KBID: "kb_x"}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatNDJSON}
if err := runChat(context.Background(), opts, fopts, svc); err != nil {
t.Fatalf("runChat: %v", err)
}
lines := strings.Split(strings.TrimRight(out.String(), "\n"), "\n")
// 1 init + 2 SDK events = 3 lines.
if len(lines) != 3 {
t.Fatalf("got %d lines, want 3:\n%s", len(lines), out.String())
}
// Each must be valid JSON.
for i, line := range lines {
var obj map[string]any
if err := json.Unmarshal([]byte(line), &obj); err != nil {
t.Errorf("line %d not valid JSON: %v\n %s", i+1, err, line)
}
}
}
func TestChat_NonTTY_StreamsSameProjection(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{
{ResponseType: sdk.ResponseTypeAnswer, Content: "piped"},
{ResponseType: sdk.ResponseTypeComplete, Done: true},
},
}
opts := &Options{Query: "q", KBID: "kb"}
if err := runChat(context.Background(), opts, textOpts(), svc); err != nil {
t.Fatalf("runChat: %v", err)
}
if !strings.Contains(out.String(), "piped") {
t.Errorf("expected accumulated answer, got %q", out.String())
}
}
func TestChat_NonTTY_VerboseIncludesThinking(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{
{ResponseType: sdk.ResponseTypeThinking, Content: "REASONING"},
{ResponseType: sdk.ResponseTypeAnswer, Content: "answer"},
{ResponseType: sdk.ResponseTypeComplete, Done: true},
},
}
opts := &Options{Query: "q", KBID: "kb", Verbose: true}
if err := runChat(context.Background(), opts, textOpts(), svc); err != nil {
t.Fatalf("runChat: %v", err)
}
if got := out.String(); !strings.Contains(got, "REASONING") || !strings.Contains(got, "answer") {
t.Errorf("non-TTY verbose output missing thinking or answer: %q", got)
}
}
func TestChat_SessionIDProvided(t *testing.T) {
_, errBuf := iostreams.SetForTestWithTTY(t)
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{{ResponseType: sdk.ResponseTypeComplete, Done: true}},
}
opts := &Options{Query: "q", KBID: "kb", SessionID: "sess_existing"}
if err := runChat(context.Background(), opts, textOpts(), svc); err != nil {
t.Fatalf("runChat: %v", err)
}
if svc.createCalled {
t.Error("CreateSession must NOT be invoked when --session is provided")
}
if svc.gotSessionID != "sess_existing" {
t.Errorf("stream sessionID: got %q want sess_existing", svc.gotSessionID)
}
// No auto-create message because the user supplied the id.
if strings.Contains(errBuf.String(), "session:") {
t.Errorf("unexpected session hint emitted with explicit --session: %q", errBuf.String())
}
}
func TestChat_KBIDRequired(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeChatService{}
// Run with KBID empty (bypassing the cobra resolver).
opts := &Options{Query: "q"}
err := runChat(context.Background(), opts, textOpts(), svc)
if err == nil {
t.Fatal("expected error, got nil")
}
var typed *cmdutil.Error
if !errors.As(err, &typed) {
t.Fatalf("expected *cmdutil.Error, got %T", err)
}
if typed.Code != cmdutil.CodeKBIDRequired {
t.Errorf("code: got %q want %q", typed.Code, cmdutil.CodeKBIDRequired)
}
if svc.createCalled || svc.streamCalled {
t.Error("KB validation must short-circuit before any SDK call")
}
}
func TestChat_EmptyQuery(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeChatService{}
opts := &Options{Query: "", KBID: "kb"}
err := runChat(context.Background(), opts, textOpts(), svc)
if err == nil {
t.Fatal("expected error, got nil")
}
var typed *cmdutil.Error
if !errors.As(err, &typed) {
t.Fatalf("expected *cmdutil.Error, got %T", err)
}
if typed.Code != cmdutil.CodeInputInvalidArgument {
t.Errorf("code: got %q want %q", typed.Code, cmdutil.CodeInputInvalidArgument)
}
}
func TestChat_SDKError_PreStream(t *testing.T) {
// SDK fails before any event arrives → ClassifyHTTPError mapping.
// "HTTP error 401: ..." → auth.unauthenticated.
_, _ = iostreams.SetForTest(t)
svc := &fakeChatService{
streamErr: errors.New("HTTP error 401: token rejected"),
}
opts := &Options{Query: "q", KBID: "kb"}
err := runChat(context.Background(), opts, textOpts(), svc)
if err == nil {
t.Fatal("expected error, got nil")
}
var typed *cmdutil.Error
if !errors.As(err, &typed) {
t.Fatalf("expected *cmdutil.Error, got %T", err)
}
if typed.Code != cmdutil.CodeAuthUnauthenticated {
t.Errorf("code: got %q want %q", typed.Code, cmdutil.CodeAuthUnauthenticated)
}
}
func TestChat_SDKError_MidStream_AbortsAsSSE(t *testing.T) {
// Some content arrived, then the stream errored without a Done event →
// CodeSSEStreamAborted (separate from generic transport failure).
_, _ = iostreams.SetForTest(t)
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{{Content: "partial"}},
streamErr: errors.New("connection reset"),
}
opts := &Options{Query: "q", KBID: "kb"}
err := runChat(context.Background(), opts, textOpts(), svc)
if err == nil {
t.Fatal("expected error, got nil")
}
var typed *cmdutil.Error
if !errors.As(err, &typed) {
t.Fatalf("expected *cmdutil.Error, got %T", err)
}
if typed.Code != cmdutil.CodeSSEStreamAborted {
t.Errorf("code: got %q want %q", typed.Code, cmdutil.CodeSSEStreamAborted)
}
}
func TestChat_TerminalSSEError_ClassifiesAsServerError(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{
{ResponseType: sdk.ResponseTypeAnswer, Content: "partial"},
{ResponseType: sdk.ResponseTypeError, Content: "boom", Done: true},
},
streamErr: sdk.NewSSEStreamError("boom"),
}
opts := &Options{Query: "q", KBID: "kb"}
err := runChat(context.Background(), opts, textOpts(), svc)
if err == nil {
t.Fatal("expected error, got nil")
}
var typed *cmdutil.Error
if !errors.As(err, &typed) {
t.Fatalf("expected *cmdutil.Error, got %T", err)
}
if typed.Code != cmdutil.CodeServerError {
t.Errorf("code: got %q want %q", typed.Code, cmdutil.CodeServerError)
}
}
func TestChat_ContextCancelled(t *testing.T) {
_, _ = iostreams.SetForTest(t)
ctx, cancel := context.WithCancel(context.Background())
cancel() // simulate Ctrl-C delivered before the SDK returns.
svc := &fakeChatService{streamErr: context.Canceled}
opts := &Options{Query: "q", KBID: "kb"}
err := runChat(ctx, opts, textOpts(), svc)
if err == nil {
t.Fatal("expected error, got nil")
}
var typed *cmdutil.Error
if !errors.As(err, &typed) {
t.Fatalf("expected *cmdutil.Error, got %T", err)
}
if typed.Code != cmdutil.CodeOperationCancelled {
t.Errorf("code: got %q want %q", typed.Code, cmdutil.CodeOperationCancelled)
}
}
func TestChat_SessionCreateFails(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeChatService{
createSessionErr: errors.New("dial tcp: connection refused"),
}
opts := &Options{Query: "q", KBID: "kb"}
err := runChat(context.Background(), opts, textOpts(), svc)
if err == nil {
t.Fatal("expected error, got nil")
}
var typed *cmdutil.Error
if !errors.As(err, &typed) {
t.Fatalf("expected *cmdutil.Error, got %T", err)
}
if typed.Code != cmdutil.CodeSessionCreateFailed {
t.Errorf("code: got %q want %q", typed.Code, cmdutil.CodeSessionCreateFailed)
}
if svc.streamCalled {
t.Error("stream must not be invoked after session creation failed")
}
}
func TestChat_SessionCreate404SurfacesNotFound(t *testing.T) {
// HTTP-shaped session-create failures should NOT collapse into the
// session_create_failed bucket; they keep their canonical mapping so
// agents can react to e.g. resource.not_found.
_, _ = iostreams.SetForTest(t)
svc := &fakeChatService{
createSessionErr: errors.New("HTTP error 404: tenant not found"),
}
opts := &Options{Query: "q", KBID: "kb"}
err := runChat(context.Background(), opts, textOpts(), svc)
if err == nil {
t.Fatal("expected error, got nil")
}
var typed *cmdutil.Error
if !errors.As(err, &typed) {
t.Fatalf("expected *cmdutil.Error, got %T", err)
}
if typed.Code != cmdutil.CodeResourceNotFound {
t.Errorf("code: got %q want %q", typed.Code, cmdutil.CodeResourceNotFound)
}
}
// TestChat_NDJSON_InitIncludesProfile verifies that when a profile is set,
// the NDJSON init event carries the profile field.
func TestChat_NDJSON_InitIncludesProfile(t *testing.T) {
cmdutil.SetProfile("prod")
t.Cleanup(func() { cmdutil.SetProfile("") })
out, _ := iostreams.SetForTest(t)
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{
{ResponseType: sdk.ResponseTypeComplete, Done: true},
},
}
opts := &Options{Query: "q", KBID: "kb_x"}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatNDJSON}
if err := runChat(context.Background(), opts, fopts, svc); err != nil {
t.Fatalf("runChat: %v", err)
}
lines := strings.Split(strings.TrimRight(out.String(), "\n"), "\n")
if len(lines) == 0 {
t.Fatal("no output")
}
var initLine struct {
Type string `json:"type"`
Profile string `json:"profile"`
}
if err := json.Unmarshal([]byte(lines[0]), &initLine); err != nil {
t.Fatalf("first line not JSON: %v\n %s", err, lines[0])
}
if initLine.Type != "init" {
t.Errorf("type: got %q, want init", initLine.Type)
}
if initLine.Profile != "prod" {
t.Errorf("profile: got %q, want prod", initLine.Profile)
}
}
func TestChat_FormatNDJSON_PassthroughsSDKEvents(t *testing.T) {
// NDJSON is the raw protocol surface: every SDK event passes through,
// including reasoning, regardless of the presentation-oriented --verbose.
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{
{ResponseType: sdk.ResponseTypeThinking, Content: "search KB"},
{ResponseType: sdk.ResponseTypeAnswer, Content: "hello"},
{ResponseType: sdk.ResponseTypeComplete, Done: true, SessionID: "sess_x"},
},
}
out, _ := iostreams.SetForTest(t)
opts := &Options{Query: "hi", KBID: "kb_x"}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatNDJSON}
if err := runChat(context.Background(), opts, fopts, svc); err != nil {
t.Fatalf("runChat: %v", err)
}
lines := strings.Split(strings.TrimRight(out.String(), "\n"), "\n")
// 1 init + thinking + answer + complete = 4 lines.
if len(lines) != 4 {
t.Fatalf("got %d lines, want 4:\n%s", len(lines), out.String())
}
sawThinking := false
for i, line := range lines {
var ev map[string]any
if err := json.Unmarshal([]byte(line), &ev); err != nil {
t.Fatalf("line %d not JSON: %v", i+1, err)
}
if ev["response_type"] == "thinking" {
sawThinking = true
}
}
if !sawThinking {
t.Error("thinking event was filtered from raw NDJSON output")
}
// First line: CLI-injected init event.
var initLine map[string]any
if err := json.Unmarshal([]byte(lines[0]), &initLine); err != nil {
t.Fatalf("line 1 (init) not JSON: %v", err)
}
if initLine["type"] != "init" {
t.Errorf("first line type=%v, want init", initLine["type"])
}
}
func TestChat_FormatNDJSON_VerboseDoesNotAlterRawStream(t *testing.T) {
// --verbose is presentation-only; NDJSON remains the same raw stream and
// therefore still contains thinking alongside answer + complete.
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{
{ResponseType: sdk.ResponseTypeThinking, Content: "search KB"},
{ResponseType: sdk.ResponseTypeAnswer, Content: "hello"},
{ResponseType: sdk.ResponseTypeComplete, Done: true, SessionID: "sess_x"},
},
}
out, _ := iostreams.SetForTest(t)
opts := &Options{Query: "hi", KBID: "kb_x", Verbose: true}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatNDJSON}
if err := runChat(context.Background(), opts, fopts, svc); err != nil {
t.Fatalf("runChat: %v", err)
}
lines := strings.Split(strings.TrimRight(out.String(), "\n"), "\n")
// 1 init + thinking + answer + complete = 4 lines.
if len(lines) != 4 {
t.Fatalf("got %d lines, want 4:\n%s", len(lines), out.String())
}
var second map[string]any
if err := json.Unmarshal([]byte(lines[1]), &second); err != nil {
t.Fatalf("line 2 not JSON: %v", err)
}
if second["response_type"] != "thinking" {
t.Errorf("second event response_type=%v, want thinking", second["response_type"])
}
}
func TestChat_FormatJSON_ReferenceAddsIndexes(t *testing.T) {
out, _ := iostreams.SetForTest(t)
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{
{ResponseType: sdk.ResponseTypeAnswer, Content: "the answer"},
{ResponseType: sdk.ResponseTypeReferences, KnowledgeReferences: []*sdk.SearchResult{
{ID: "c1", Content: "BULKY FULL CHUNK CONTENT", ParentChunkID: "p1", KnowledgeTitle: "Doc One", Score: 0.5},
}},
{ResponseType: sdk.ResponseTypeComplete, Done: true, SessionID: "sess_auto"},
},
}
opts := &Options{Query: "hi", KBID: "kb_1", Reference: true}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}
if err := runChat(context.Background(), opts, fopts, svc); err != nil {
t.Fatalf("runChat: %v", err)
}
// A single envelope, not multiple NDJSON lines.
outStr := strings.TrimRight(out.String(), "\n")
if strings.Contains(outStr, "\n") {
t.Fatalf("expected single-line envelope, got multiple lines:\n%s", outStr)
}
var env struct {
OK bool `json:"ok"`
Data struct {
Events []sse.ProjectedEvent `json:"events"`
SessionID string `json:"session_id"`
} `json:"data"`
}
if err := json.Unmarshal([]byte(outStr), &env); err != nil {
t.Fatalf("envelope not JSON: %v\n%s", err, outStr)
}
if !env.OK {
t.Error("ok=false, want true")
}
wantTypes := []string{"answer", "references"}
if len(env.Data.Events) != len(wantTypes) {
t.Fatalf("events=%+v", env.Data.Events)
}
for i, want := range wantTypes {
if env.Data.Events[i].ResponseType != want {
t.Errorf("events[%d].response_type=%q, want %q", i, env.Data.Events[i].ResponseType, want)
}
}
refs := env.Data.Events[1].KnowledgeReferences
if len(refs) != 1 || refs[0].KBID != "kb_1" || refs[0].ChunkID != "c1" || refs[0].ParentChunkID != "p1" {
t.Errorf("reference indexes=%+v", refs)
}
if env.Data.SessionID == "" {
t.Error("session_id empty")
}
}
func TestChat_FormatNDJSON_PreservesReflection(t *testing.T) {
// Reflection is part of the raw SDK protocol and must not be filtered.
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{
{ResponseType: sdk.ResponseTypeReflection, Content: "reflecting"},
{ResponseType: sdk.ResponseTypeAnswer, Content: "hello"},
{ResponseType: sdk.ResponseTypeComplete, Done: true, SessionID: "sess_x"},
},
}
out, _ := iostreams.SetForTest(t)
opts := &Options{Query: "hi", KBID: "kb_x"}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatNDJSON}
if err := runChat(context.Background(), opts, fopts, svc); err != nil {
t.Fatalf("runChat: %v", err)
}
sawReflection := false
for i, line := range strings.Split(strings.TrimRight(out.String(), "\n"), "\n") {
var ev map[string]any
if err := json.Unmarshal([]byte(line), &ev); err != nil {
t.Fatalf("line %d not JSON: %v", i+1, err)
}
if ev["response_type"] == "reflection" {
sawReflection = true
}
}
if !sawReflection {
t.Error("reflection event was filtered from raw NDJSON output")
}
}
func TestChat_FormatJSON_HonorsJQ(t *testing.T) {
// --format json routes through FormatOptions.Emit, so --jq projects the
// envelope instead of dumping it whole. Guards the agent output protocol
// contract: consumers can join answer event fragments.
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{
{ResponseType: sdk.ResponseTypeAnswer, Content: "the answer"},
{ResponseType: sdk.ResponseTypeReferences, KnowledgeReferences: []*sdk.SearchResult{
{ID: "c1", Content: "bulk", KnowledgeTitle: "Doc"},
}},
{ResponseType: sdk.ResponseTypeComplete, Done: true, SessionID: "sess_x"},
},
}
out, _ := iostreams.SetForTest(t)
opts := &Options{Query: "hi", KBID: "kb_1"}
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, JQ: `[.data.events[].content] | join("")`}
if err := runChat(context.Background(), opts, fopts, svc); err != nil {
t.Fatalf("runChat: %v", err)
}
got := strings.TrimSpace(out.String())
if !strings.Contains(got, "the answer") {
t.Errorf("jq output missing projected answer: %q", got)
}
// A projection must not dump the full envelope scaffolding.
if strings.Contains(got, "references") || strings.Contains(got, "session_id") {
t.Errorf("jq output looks like a full envelope, not a projection: %q", got)
}
}
func TestChat_FormatJSON_StreamErrorIncludesSessionDetail(t *testing.T) {
_, _ = iostreams.SetForTest(t)
svc := &fakeChatService{
streamEvents: []*sdk.StreamResponse{{
ResponseType: sdk.ResponseTypeAgentQuery,
AssistantMessageID: "msg_123",
}},
streamErr: errors.New("connection reset"),
}
err := runChat(
context.Background(),
&Options{Query: "q", KBID: "kb"},
&cmdutil.FormatOptions{Mode: cmdutil.FormatJSON},
svc,
)
var typed *cmdutil.Error
if !errors.As(err, &typed) {
t.Fatalf("expected *cmdutil.Error, got %v", err)
}
detail, ok := typed.Detail.(map[string]any)
if !ok || detail["session_id"] != "sess_auto" || detail["assistant_message_id"] != "msg_123" {
t.Errorf("error detail=%v, want session and assistant message ids", typed.Detail)
}
}
Loaded 100 of 5769 files, more files were not shown because too many files have changed in this diff. Show more