Commit 4a9533a6 by DigHuang Committed by GitHub

feat(skill): edit-debug iframe via standalone sandbox-proxy (#6879)

* refactor(sandbox-proxy): add subdomain proxy auth foundation

Squashes:
- 545b5b767 refactor(sandbox): subdomain-routed proxy with cookie auth and direct execd
- 3bfeb1384 fix(sandbox): align proxy token TTL handling
- 62a642ce8 refactor(sandbox-proxy): consolidate auth/token modules and simplify tests

* style(skill): refine header and background UI

* feat(skill): add version switch

* feat(sandbox-proxy): manage code-server sessions

Squashes:
- e5c07bf5f refactor: refine sandbox-proxy architecture
- d95a7e539 feat: implement code-server session management and update sandbox proxy configuration/permissions
- fe9f1476e refactor: replace manual Map-based cache with lru-cache for session and backoff management

* feat(sandbox): adapt devbox code-server

* fix(sandbox): stabilize debug sessions and sandbox reuse

Squashes:
- c07e2070d fix(debug): route skill preview chat controls through debug session APIs
- 0e251569c fix(sandbox): stabilize agent skill sandbox reuse
- 9f8b672c3 fix(sandbox): split FastGPT sandboxId from providerSandboxId

* refactor(sandbox): clean up provider and proxy routing

Squashes:
- f18361444 feat: sandbox-proxy images and provider cleanup
- dfc27ba3b refactor(sandbox): move resource cleanup into SandboxClient
- 65015efb8 refactor(sandbox-proxy): derive sandbox id from host label

* refactor(sandbox): use stable sandbox instances

Squashes:
- a9f18f873 refactor(sandbox): sandbox to use stable sandboxId
- 3a2ad1691 refactor(db): sandbox DB ops into instance module

* feat(sandbox): preserve folder structure with generated ids

Squashes:
- 8e1374491 fix(sandboxId): use generateSandboxId no matter mode
- 78b5ce27f feat(sandbox): keep sandbox folder struct
- 9f0382305 fix(sandbox): remove unused skill reference params

* fix(skill): tighten sandbox permission handling

* fix(sandbox-proxy): add friendly iframe error fallback

* feat: improve skill sandbox availability checks and prompts

* fix: requestIds required

* feat: sandbox provider handling and proxy revision

* fix(skill): require write permission for edit-debug sandbox proxy token

* fix: type test

* fix(switch): create failed when switch version

* feat(skill): create pending skills asynchronously

* rewrite skill runtime

* fix(switch): create failed when switch version

* feat(skill): skillIds filter and deleted-skill UI

* feat(skill): DeleteConfirmInput and modal support

* feat(sandbox): retry sandbox exec on timeout; UI/i18n updates

* rewrite skill diractory

* feat(skill): use safe skill directory name in edit sandbox & UI label updates

* rewrite skill schema

* refactor(skill): transactional delete, sandbox resource cleanup, and test cleanup

* perf: loading animation

* refactor(app): extract SaveAndPublishModal as common component and support custom title

* fix(skill): align package creation and edit sandbox flow

* perf: api

* fix(skill): tighten skill mutation validation

* feat(skill): introduce inline SandboxEditor & fileOp API, remove legacy sandbox-proxy

* fix(sandbox): support binary file uploading and fix preview corruption in sandbox editor

* test(sandbox): remove obsolete heartbeat test for legacy sandbox proxy

* chore: rm sandbox endpoint types; add runtimeTools

* feat(sandbox): support team plan verification, file optimistic updates and   custom avatar for skill imports

* perf: sandbox code

* doc

* fix(sandbox): fix pro test failure and unify sandbox API auth

- Update pro submodule commit to eacfd364b to solve obsolete agentSkills imports

- Refactor sandbox API endpoints to use Unified authSandboxSession auth

- Support teamId parameter in getSandboxClient and resolve runtime permission check

* perf: stop chat in skill edit

* refactor(sandbox): adjust sandbox permission check and migrate skill APIs to parseApiInput

* refactor(sandbox): extract sandbox files state and actions to useSandboxFileStore hook

* perf: prompt and list recursive

* submodule

* feat: fileOp queue

* doc

* check empty response

* fix(sandbox): prevent duplicate file loading in editor and add hover title for tabs

* show skill

* feat: update sandboxEditor modal

* perf: storage code

* skill ui

* fix(skill): preserve skills root directory structure in sandbox workspace

* fix: adapt

* fix(skill): normalize sandbox zip extraction paths and cleanup unused sandbox checks

* loading ui

* fix: export import and perf loading

* submodule

* fix: repair skill edit sandbox ci

* fix(skill): harden sandbox edit and cleanup flows

* ui

* perf: sealos default workspace

* perf: code

* perf: code

* select skill

* perf: docker secret

* perf: skill editor ui

* fix: test

---------

Co-authored-by: archer <545436317@qq.com>
parent 06d590c3
# FastGPT 开发命令
本文档记录本仓库常用开发命令。执行前请确认位于仓库根目录 `/Volumes/code/FastGPT`,并使用 `pnpm` workspace 环境。
## 项目专用命令
### 主应用(`projects/app/`)
- `cd projects/app && pnpm dev` - 启动 NextJS 开发服务器
- `cd projects/app && pnpm build` - 构建 NextJS 应用
- `cd projects/app && pnpm start` - 启动生产服务器
### 代码沙箱(`projects/code-sandbox/`)
- `cd projects/code-sandbox && pnpm dev` - 以监视模式启动(Bun)
- `cd projects/code-sandbox && pnpm build` - 构建沙箱服务
- `cd projects/code-sandbox && pnpm test` - 运行 Vitest 测试
### MCP 服务器(`projects/mcp_server/`)
- `cd projects/mcp_server && bun dev` - 使用 Bun 以监视模式启动
- `cd projects/mcp_server && bun build` - 构建 MCP 服务器
- `cd projects/mcp_server && bun start` - 启动 MCP 服务器
## 工具命令
- `pnpm lint` - 对所有 TypeScript 文件运行 ESLint 并自动修复
- `pnpm initIcon` - 初始化图标资源
- `pnpm gen:theme-typings` - 生成 Chakra UI 主题类型定义
name: Build fastgpt-sandbox-proxy images
on:
workflow_dispatch:
push:
paths:
- '.github/workflows/build-sandbox-proxy.yml'
- 'projects/sandbox-proxy/**'
tags:
- 'v*'
jobs:
detect_sandbox_proxy:
runs-on: ubuntu-24.04
outputs:
has_dockerfile: ${{ steps.detect.outputs.has_dockerfile }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Detect sandbox-proxy Dockerfile
id: detect
run: |
if [[ -f projects/sandbox-proxy/Dockerfile ]]; then
echo "has_dockerfile=true" >> "$GITHUB_OUTPUT"
else
echo "has_dockerfile=false" >> "$GITHUB_OUTPUT"
fi
build-fastgpt-sandbox-proxy-images:
permissions:
packages: write
contents: read
attestations: write
id-token: write
needs: detect_sandbox_proxy
if: ${{ needs.detect_sandbox_proxy.outputs.has_dockerfile == 'true' }}
strategy:
matrix:
include:
- arch: amd64
- arch: arm64
runs-on: ubuntu-24.04-arm
runs-on: ${{ matrix.runs-on || 'ubuntu-24.04' }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
with:
driver-opts: network=host
- name: Cache Docker layers
uses: actions/cache@v4
with:
path: /tmp/.buildx-cache
key: ${{ runner.os }}-sandbox-proxy-buildx-${{ github.sha }}
restore-keys: |
${{ runner.os }}-sandbox-proxy-buildx-
- name: Login to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build for ${{ matrix.arch }}
id: build
uses: docker/build-push-action@v6
with:
context: .
file: projects/sandbox-proxy/Dockerfile
platforms: linux/${{ matrix.arch }}
labels: |
org.opencontainers.image.source=https://github.com/${{ github.repository }}
org.opencontainers.image.description=fastgpt-sandbox-proxy image
outputs: type=image,"name=ghcr.io/${{ github.repository_owner }}/fastgpt-sandbox-proxy",push-by-digest=true,push=true
cache-from: type=local,src=/tmp/.buildx-cache
cache-to: type=local,dest=/tmp/.buildx-cache
- 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@v4
with:
name: digests-fastgpt-sandbox-proxy-${{ github.sha }}-${{ matrix.arch }}
path: ${{ runner.temp }}/digests/*
if-no-files-found: error
retention-days: 1
release-fastgpt-sandbox-proxy-images:
permissions:
packages: write
contents: read
attestations: write
id-token: write
needs:
- detect_sandbox_proxy
- build-fastgpt-sandbox-proxy-images
if: ${{ needs.detect_sandbox_proxy.outputs.has_dockerfile == 'true' }}
runs-on: ubuntu-24.04
steps:
- name: Login to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Login to Ali Hub
uses: docker/login-action@v3
with:
registry: registry.cn-hangzhou.aliyuncs.com
username: ${{ secrets.FASTGPT_ALI_IMAGE_USER }}
password: ${{ secrets.FASTGPT_ALI_IMAGE_PSW }}
- name: Download digests
uses: actions/download-artifact@v4
with:
path: ${{ runner.temp }}/digests
pattern: digests-fastgpt-sandbox-proxy-${{ github.sha }}-*
merge-multiple: true
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Set image name and tag
run: |
if [[ "${{ github.ref_name }}" == "main" ]]; then
echo "Git_Tag=ghcr.io/${{ github.repository_owner }}/fastgpt-sandbox-proxy:latest" >> "$GITHUB_ENV"
echo "Git_Latest=ghcr.io/${{ github.repository_owner }}/fastgpt-sandbox-proxy:latest" >> "$GITHUB_ENV"
echo "Ali_Tag=${{ secrets.FASTGPT_ALI_IMAGE_PREFIX }}/fastgpt-sandbox-proxy:latest" >> "$GITHUB_ENV"
echo "Ali_Latest=${{ secrets.FASTGPT_ALI_IMAGE_PREFIX }}/fastgpt-sandbox-proxy:latest" >> "$GITHUB_ENV"
else
echo "Git_Tag=ghcr.io/${{ github.repository_owner }}/fastgpt-sandbox-proxy:${{ github.ref_name }}" >> "$GITHUB_ENV"
echo "Git_Latest=ghcr.io/${{ github.repository_owner }}/fastgpt-sandbox-proxy:latest" >> "$GITHUB_ENV"
echo "Ali_Tag=${{ secrets.FASTGPT_ALI_IMAGE_PREFIX }}/fastgpt-sandbox-proxy:${{ github.ref_name }}" >> "$GITHUB_ENV"
echo "Ali_Latest=${{ secrets.FASTGPT_ALI_IMAGE_PREFIX }}/fastgpt-sandbox-proxy:latest" >> "$GITHUB_ENV"
fi
- name: Create manifest list and push
working-directory: ${{ runner.temp }}/digests
run: |
TAGS="$(echo -e "${Git_Tag}\n${Git_Latest}\n${Ali_Tag}\n${Ali_Latest}")"
for TAG in $TAGS; do
docker buildx imagetools create -t "$TAG" \
$(printf 'ghcr.io/${{ github.repository_owner }}/fastgpt-sandbox-proxy@sha256:%s ' *)
sleep 5
done
......@@ -40,4 +40,5 @@ document/.source
projects/app/worker/
pro/admin/worker/
.turbo
\ No newline at end of file
.turbo
.antigravitycli
\ No newline at end of file
......@@ -34,26 +34,7 @@ FastGPT 是一个 AI Agent 构建平台,通过 Flow 提供开箱即用的数据
## 开发命令
### 项目专用命令
**主应用 (projects/app/)**:
- `cd projects/app && pnpm dev` - 启动 NextJS 开发服务器
- `cd projects/app && pnpm build` - 构建 NextJS 应用
- `cd projects/app && pnpm start` - 启动生产服务器
**代码沙箱 (projects/code-sandbox/)**:
- `cd projects/code-sandbox && pnpm dev` - 以监视模式启动(Bun)
- `cd projects/code-sandbox && pnpm build` - 构建沙箱服务
- `cd projects/code-sandbox && pnpm test` - 运行 Vitest 测试
**MCP 服务器 (projects/mcp_server/)**:
- `cd projects/mcp_server && bun dev` - 使用 Bun 以监视模式启动
- `cd projects/mcp_server && bun build` - 构建 MCP 服务器
- `cd projects/mcp_server && bun start` - 启动 MCP 服务器
### 工具命令
- `pnpm lint` - 对所有 TypeScript 文件运行 ESLint 并自动修复
- `pnpm initIcon` - 初始化图标资源
- `pnpm gen:theme-typings` - 生成 Chakra UI 主题类型定义
常用开发命令见 [FastGPT 开发命令](./.codex/code/commands.md)。
## 测试
......@@ -133,6 +114,12 @@ const { body, query } = parseApiInput({
- 避免写无意义注释,例如只复述“设置变量”“返回结果”。如果函数逻辑简单且语义已经完全由命名表达,可以不写冗余注释。
- 对复杂函数内部的关键判断,也应补充简短中文注释,说明为什么这样处理,而不是逐行解释代码。
### 子函数位置
- 拆分子函数时,优先把只被单个函数使用的 helper 放在该函数内部,减少模块级私有函数的暴露范围和阅读负担。
- 只有跨函数复用、需要单独导出测试、或语义上属于模块公共能力的 helper,才放到模块级;放到模块级时应补充函数级注释说明职责和边界。
- 对于递归、错误处理、权限校验、路径处理、计费/requestId 等容易误解的局部 helper,应在局部函数或关键分支旁补充简短中文注释说明设计原因。
## 运行要求
### 性格
......
......@@ -5,17 +5,17 @@ description: 'FastGPT V4.14.10 更新说明'
## 升级指南
### 1. 增加 agent-sandbox 相关配置
### 1. 增加 agent-sandbox 相关配置
以下针对的是 `docker compose` 部署方案的配置调整,使用`sealos`的商业版用户,可私信支持人员,提供在线的沙盒服务方案。
以下针对的是 `docker compose` 部署方案的配置调整,使用 `sealos` 的商业版用户,可私信支持人员,提供在线的沙盒服务方案。
参考[最新 yml 部署文件](https://github.com/labring/FastGPT/blob/main/deploy/docker/cn/docker-compose.pg.yml),调整本地 yml 文件,加入以下内容:
1. 在文件顶部增加 `x-volume-manager-auth-token: &x-volume-manager-auth-token 'vmtoken'` 变量配置。
2. 增加 5 组 services: `opensandbox-server`,`opensandbox-agent-sandbox-image`,`opensandbox-execd-image`,`opensandbox-egress-image`,`fastgpt-volume-manager`
2. 增加 5 组 services: `opensandbox-server` , `opensandbox-agent-sandbox-image` , `opensandbox-execd-image` , `opensandbox-egress-image` , `fastgpt-volume-manager`
3. 调整 `networks`,可参考最新的 yml 完全修改。
4. 增加 `configs`配置, 文件底部可找到该内容,直接复制添加。
5. 修改 `fastgpt-app`/`fastgpt-pro` 环境变量, 增加以下变量:
4. 增加 `configs` 配置, 文件底部可找到该内容,直接复制添加。
5. 修改 `fastgpt-app` / `fastgpt-pro` 环境变量,增加以下变量:
```bash
# ==================== Agent sandbox 配置 ====================
......@@ -35,7 +35,7 @@ AGENT_SANDBOX_VOLUME_MANAGER_TOKEN: *x-volume-manager-auth-token
### 2. 修改 sandbox 镜像名
原先的 `sandbox` 服务的镜像名,需要从`fastgpt-sandbox`改成`fastgpt-code-sandbox`。
原先的 `sandbox` 服务的镜像名,需要从 `fastgpt-sandbox` 改成 `fastgpt-code-sandbox`。
目的是为了区分 agent-sandbox 和 code-sandbox。
......@@ -77,4 +77,4 @@ AGENT_SANDBOX_VOLUME_MANAGER_TOKEN: *x-volume-manager-auth-token
5. 修复登录接口安全问题
6. 修复 MCP SSRF 安全问题
7. 修复工作流工具错误未成功捕获问题
8. 修复子工作流全局变量默认值未生效
\ No newline at end of file
8. 修复子工作流全局变量默认值未生效
---
title: 'V4.14.21 (In Progress)'
title: 'V4.14.21'
description: 'FastGPT V4.14.21 release notes'
---
......@@ -12,6 +12,5 @@ description: 'FastGPT V4.14.21 release notes'
## 🐛 Fixes
1. Fixed an issue where the workflow's default selected model was not synced back to the form value, causing the displayed model to differ from the model used at runtime.
2. Fixed a risk where edges could be lost during workflow autosave.
3. Fixed an error that occurred when admins edited the system notification modal.
1. Made `name` optional for file types in the completions API.
2. Fixed an OSS initialization error.
---
title: 'V4.14.21(进行中)'
title: 'V4.14.21'
description: 'FastGPT V4.14.21 更新说明'
---
......@@ -10,9 +10,7 @@ description: 'FastGPT V4.14.21 更新说明'
- 更新 fastgpt-app(fastgpt 主服务) 镜像 tag: v4.14.21
- 更新 fastgpt-pro(fastgpt 商业版) 镜像 tag: v4.14.21
## 🐛 修复
## 变更说明
1. 工作流默认选中模型未回传表单值,导致看到的模型和实际运行模型不一致。
2. 工作流自动保存时,存在边丢失风险。
3. admin 修改系统通知弹窗时候报错。
4. 工作流混用思考/非思考模型,可能出现独立 reason 字段上下文,导致模型调用报错。
1. completions API 文件类型,name 变成可选
2. 修复 OSS 初始化异常
---
title: 'V4.14.22'
description: 'FastGPT V4.14.22 release notes'
---
## Upgrade Guide
### 1. Update image tags
- Update the fastgpt-app image tag (FastGPT main service): v4.14.22
- Update the fastgpt-pro image tag (FastGPT commercial edition): v4.14.22
## 🐛 Fixes
1. Fixed an issue where the workflow's default selected model was not synced back to the form value, causing the displayed model to differ from the model used at runtime.
2. Fixed a risk where edges could be lost during workflow autosave.
3. Fixed an error that occurred when admins edited the system notification modal.
---
title: 'V4.14.22'
description: 'FastGPT V4.14.22 更新说明'
---
## 升级指南
### 1. 更新镜像 tag
- 更新 fastgpt-app(fastgpt 主服务) 镜像 tag: v4.14.22
- 更新 fastgpt-pro(fastgpt 商业版) 镜像 tag: v4.14.22
## 🐛 修复
1. 工作流默认选中模型未回传表单值,导致看到的模型和实际运行模型不一致。
2. 工作流自动保存时,存在边丢失风险。
3. admin 修改系统通知弹窗时候报错。
4. 工作流混用思考/非思考模型,可能出现独立 reason 字段上下文,导致模型调用报错。
......@@ -2,6 +2,7 @@
"title": "4.14.x",
"description": "",
"pages": [
"41422",
"41421",
"41420",
"41419",
......
......@@ -2,6 +2,7 @@
"title": "4.14.x",
"description": "",
"pages": [
"41422",
"41421",
"41420",
"41419",
......
......@@ -3,10 +3,15 @@ title: 'V4.15.0-beta2(进行中)'
description: 'FastGPT V4.15.0-beta2 更新说明'
---
## 更新指南
1. AGENT_SANDBOX_VOLUME_MANAGER_MOUNT_PATH 不再生效,opensandbox 固定挂载持久化数据到 `/workspace`,旧的沙盒持久化会受到影响。
## 🚀 新增内容
1. 重写 agentV2 loop 逻辑。
2. 知识库搜索支持原生多模态 embedding 模型以及图搜图。
1. 支持 Skill 编辑,Agent 支持 Skill 使用,目前仅支持静态 Skill,无法反向调用系统工具。
2. 重写 agentV2 loop 逻辑。
3. 知识库搜索支持原生多模态 embedding 模型以及图搜图。
## ⚙️ 优化
......@@ -16,23 +21,24 @@ description: 'FastGPT V4.15.0-beta2 更新说明'
4. 知识库搜索测试交互。
5. 知识库数据编辑弹窗。
6. reason hide 开关完善,确保只是 UI 不显示,但是 request llm 时候依然可以保留。
7. **流恢复暂停体验**:暂停后会等待后端返回真实生成态;若工作流尚未收尾,输入区保持禁发并提示「停止中」,避免上一轮未结束就发送下一轮。
8. **异常中断会话更快恢复**:服务崩溃或重启后,结合 Redis stream 活动检测(约 2 分钟无心跳)更快将卡住的「生成中」会话纠正为已完成;仍保留 30 分钟 Mongo 兜底,Redis 短暂异常时不会误改正在生成的会话。
9. **切换应用记住最近会话**:同一浏览器内切换应用时,会按应用恢复上次打开的 chatId,不再共用单一全局会话 id。
10. **响应详情展示优化**:完整响应弹窗中,表单输入节点的文件字段以文件列表形式展示,而不仅是 JSON 文本。
7. 流恢复暂停体验:暂停后会等待后端返回真实生成态;若工作流尚未收尾,输入区保持禁发并提示「停止中」,避免上一轮未结束就发送下一轮。
8. 异常中断会话更快恢复:服务崩溃或重启后,结合 Redis stream 活动检测(约 2 分钟无心跳)更快将卡住的「生成中」会话纠正为已完成;仍保留 30 分钟 Mongo 兜底,Redis 短暂异常时不会误改正在生成的会话。
9. 切换应用记住最近会话:同一浏览器内切换应用时,会按应用恢复上次打开的 chatId,不再共用单一全局会话 id。
10. 响应详情展示优化:完整响应弹窗中,表单输入节点的文件字段以文件列表形式展示,而不仅是 JSON 文本。
11. chat2messages adapt 优化,避免出现独立的 reason
## 🐛 修复
1. 工作流,单节点调试,存在异常默认值。
2. 模型配置,defaultConfig 覆盖异常。
3. 切换团队时,清除本地 chat 缓存。
4. **流恢复表单输入**:刷新或断线续传后,已提交的表单输入值(含 `fileSelect` 文件列表)能正确回填到交互节点内,不再出现空表单或文件消失。
5. **流恢复内容保留**:自动续传开始时保留已加载的 AI 输出与节点响应;completed 记录覆盖时不再丢失已恢复的交互表单值与 flow 节点响应。
6. **流恢复交互状态**:已提交表单后不再重复追加过期未提交交互;恢复过程中表单默认值能随 `formInputResult` 同步更新。
7. **流恢复历史标题**:新对话发起后,侧栏临时历史项优先展示用户输入生成的标题,服务端标题落库后再覆盖,避免长时间显示「新对话」。
8. **切换应用历史串线**:修复切换不同应用时,侧栏或会话内容短暂展示其他应用聊天记录的问题。
9. **停止对话提示**:移除停止时的 warning toast,改为与后端生成态同步的状态提示。
10. **Chat API dataId 校验**:`/v1/chat/completions`、`/v2/chat/completions` 与 `chatTest` 在工作流执行前校验本轮 `dataId` 是否与请求内或当前会话已有记录重复;重复时直接返回业务错误,避免脏数据进入工作流与流恢复合并逻辑。
4. 流恢复表单输入:刷新或断线续传后,已提交的表单输入值(含 `fileSelect` 文件列表)能正确回填到交互节点内,不再出现空表单或文件消失。
5. 流恢复内容保留:自动续传开始时保留已加载的 AI 输出与节点响应;completed 记录覆盖时不再丢失已恢复的交互表单值与 flow 节点响应。
6. 流恢复交互状态:已提交表单后不再重复追加过期未提交交互;恢复过程中表单默认值能随 `formInputResult` 同步更新。
7. 流恢复历史标题:新对话发起后,侧栏临时历史项优先展示用户输入生成的标题,服务端标题落库后再覆盖,避免长时间显示「新对话」。
8. 切换应用历史串线:修复切换不同应用时,侧栏或会话内容短暂展示其他应用聊天记录的问题。
9. 停止对话提示:移除停止时的 warning toast,改为与后端生成态同步的状态提示。
10. Chat API dataId 校验:`/v1/chat/completions`、`/v2/chat/completions` 与 `chatTest` 在工作流执行前校验本轮 `dataId` 是否与请求内或当前会话已有记录重复;重复时直接返回业务错误,避免脏数据进入工作流与流恢复合并逻辑。
## 代码优化
......
......@@ -130,6 +130,7 @@ description: FastGPT Toc
- [/en/self-host/upgrading/4-14/4142](/en/self-host/upgrading/4-14/4142)
- [/en/self-host/upgrading/4-14/41420](/en/self-host/upgrading/4-14/41420)
- [/en/self-host/upgrading/4-14/41421](/en/self-host/upgrading/4-14/41421)
- [/en/self-host/upgrading/4-14/41422](/en/self-host/upgrading/4-14/41422)
- [/en/self-host/upgrading/4-14/4143](/en/self-host/upgrading/4-14/4143)
- [/en/self-host/upgrading/4-14/4144](/en/self-host/upgrading/4-14/4144)
- [/en/self-host/upgrading/4-14/4145](/en/self-host/upgrading/4-14/4145)
......
......@@ -132,6 +132,7 @@ description: FastGPT 文档目录
- [/self-host/upgrading/4-14/4142](/self-host/upgrading/4-14/4142)
- [/self-host/upgrading/4-14/41420](/self-host/upgrading/4-14/41420)
- [/self-host/upgrading/4-14/41421](/self-host/upgrading/4-14/41421)
- [/self-host/upgrading/4-14/41422](/self-host/upgrading/4-14/41422)
- [/self-host/upgrading/4-14/4143](/self-host/upgrading/4-14/4143)
- [/self-host/upgrading/4-14/4144](/self-host/upgrading/4-14/4144)
- [/self-host/upgrading/4-14/4145](/self-host/upgrading/4-14/4145)
......
......@@ -157,8 +157,8 @@
"content/openapi/intro.mdx": "2026-04-26T21:08:47+08:00",
"content/openapi/share.en.mdx": "2026-04-26T21:08:47+08:00",
"content/openapi/share.mdx": "2026-04-26T21:08:47+08:00",
"content/self-host/config/env.en.mdx": "2026-05-08T20:36:05+08:00",
"content/self-host/config/env.mdx": "2026-05-08T20:36:05+08:00",
"content/self-host/config/env.en.mdx": "2026-05-23T11:22:44+08:00",
"content/self-host/config/env.mdx": "2026-05-23T11:22:44+08:00",
"content/self-host/config/json.en.mdx": "2026-04-26T21:08:47+08:00",
"content/self-host/config/json.mdx": "2026-04-26T21:08:47+08:00",
"content/self-host/config/model/intro.en.mdx": "2026-05-07T15:06:40+08:00",
......@@ -255,8 +255,10 @@
"content/self-host/upgrading/4-14/4142.mdx": "2026-04-26T21:08:47+08:00",
"content/self-host/upgrading/4-14/41420.en.mdx": "2026-05-21T15:39:08+08:00",
"content/self-host/upgrading/4-14/41420.mdx": "2026-05-19T14:44:21+08:00",
"content/self-host/upgrading/4-14/41421.en.mdx": "2026-05-21T15:39:08+08:00",
"content/self-host/upgrading/4-14/41421.mdx": "2026-05-21T23:24:07+08:00",
"content/self-host/upgrading/4-14/41421.en.mdx": "2026-05-22T18:20:28+08:00",
"content/self-host/upgrading/4-14/41421.mdx": "2026-05-22T18:20:28+08:00",
"content/self-host/upgrading/4-14/41422.en.mdx": "2026-05-22T18:20:28+08:00",
"content/self-host/upgrading/4-14/41422.mdx": "2026-05-22T18:20:28+08:00",
"content/self-host/upgrading/4-14/4143.en.mdx": "2026-04-26T21:08:47+08:00",
"content/self-host/upgrading/4-14/4143.mdx": "2026-04-26T21:08:47+08:00",
"content/self-host/upgrading/4-14/4144.en.mdx": "2026-04-26T21:08:47+08:00",
......@@ -276,7 +278,7 @@
"content/self-host/upgrading/4-14/4149.en.mdx": "2026-04-26T21:08:47+08:00",
"content/self-host/upgrading/4-14/4149.mdx": "2026-04-26T21:08:47+08:00",
"content/self-host/upgrading/4-15/4150.mdx": "2026-05-20T17:52:26+08:00",
"content/self-host/upgrading/4-15/41502.mdx": "2026-05-21T16:33:20+08:00",
"content/self-host/upgrading/4-15/41502.mdx": "2026-05-22T21:07:00+08:00",
"content/self-host/upgrading/outdated/40.en.mdx": "2026-04-26T21:08:47+08:00",
"content/self-host/upgrading/outdated/40.mdx": "2026-04-26T21:08:47+08:00",
"content/self-host/upgrading/outdated/41.en.mdx": "2026-04-26T21:08:47+08:00",
......@@ -417,6 +419,6 @@
"content/self-host/upgrading/outdated/499.mdx": "2026-05-07T15:06:40+08:00",
"content/self-host/upgrading/upgrade-intruction.en.mdx": "2026-04-26T21:08:47+08:00",
"content/self-host/upgrading/upgrade-intruction.mdx": "2026-04-26T21:08:47+08:00",
"content/toc.en.mdx": "2026-05-21T15:39:08+08:00",
"content/toc.mdx": "2026-05-21T15:39:08+08:00"
"content/toc.en.mdx": "2026-05-22T18:20:28+08:00",
"content/toc.mdx": "2026-05-22T18:20:28+08:00"
}
\ No newline at end of file
......@@ -23,7 +23,7 @@
"test:service": "turbo run test --filter=@fastgpt/service",
"test:service:integration": "turbo run test:integration --filter=@fastgpt/service",
"test:vector": "turbo run test:integration --filter=@fastgpt/service",
"build:sdks": "pnpm -r --filter @fastgpt-sdk/storage --filter @fastgpt-sdk/otel build"
"build:sdks": "pnpm -r --filter @fastgpt-sdk/storage --filter @fastgpt-sdk/otel --filter @fastgpt-sdk/sandbox-adapter build"
},
"devDependencies": {
"@chakra-ui/cli": "^2.4.1",
......
......@@ -150,6 +150,10 @@ const teamErr = [
{
statusText: TeamErrEnum.datasetFolderAmountNotEnough,
message: i18nT('common:code_error.team_error.dataset_folder_amount_not_enough')
},
{
statusText: TeamErrEnum.sandboxNotSupport,
message: i18nT('common:code_error.team_error.sandbox_not_support')
}
];
......
......@@ -9,7 +9,7 @@ import userErr from './code/user';
import commonErr from './code/common';
import s3Err from './code/s3';
import SystemErrEnum from './code/system';
import agentSkillErr from './code/agentSkill';
import agentSkillErr from './code/skill';
import { i18nT } from '../i18n/utils';
export const ERROR_CODE: { [key: number]: string } = {
......
......@@ -2,18 +2,25 @@ import { replaceSensitiveText } from '../string/tools';
import { ERROR_RESPONSE } from './errorCode';
export const getErrText = (err: any, def = ''): any => {
const msg: string =
typeof err === 'string'
? err || def
: err?.response?.data?.message ||
err?.response?.message ||
err?.message ||
err?.response?.data?.msg ||
err?.response?.msg ||
err?.msg ||
err?.error ||
err?.code ||
def;
const getRawMsg = (e: any): any => {
if (typeof e === 'string') return e;
if (!e) return '';
return (
e.system_error_text ||
e.errorText ||
e.response?.data?.message ||
e.response?.message ||
e.response?.data?.msg ||
e.response?.msg ||
e.message ||
e.msg ||
(typeof e.error === 'string' ? e.error : getRawMsg(e.error)) ||
e.code ||
''
);
};
const msg = getRawMsg(err) || def;
if (ERROR_RESPONSE[msg]) {
return ERROR_RESPONSE[msg].message;
......
......@@ -110,6 +110,7 @@ export type FastGPTFeConfigsType = {
websiteSyncLimitMinuted?: number;
agentSandboxMaxEditDebug?: number;
agentSandboxMaxSessionRuntime?: number;
agentSkillMaxUploadBytes?: number;
workflowParallelRunMaxConcurrency?: number;
};
......@@ -145,8 +146,6 @@ export type FastGPTFeConfigsType = {
// tmp
agentSandboxFree?: boolean;
// Beta features
show_skill?: boolean;
};
export type SystemEnvType = {
......
export * from '../../openapi/core/agentSkills/api';
import type { I18nStringType } from '../../common/i18n/type';
export enum AgentSkillSourceEnum {
system = 'system',
personal = 'personal'
}
export enum AgentSkillCategoryEnum {
search = 'search',
tool = 'tool',
coding = 'coding',
data = 'data',
analysis = 'analysis',
communication = 'communication',
other = 'other'
}
export const AgentSkillCategoryMap: Record<
`${AgentSkillCategoryEnum}`,
{ label: I18nStringType; icon: string }
> = {
[AgentSkillCategoryEnum.search]: {
label: {
'zh-CN': '搜索',
'zh-Hant': '搜索',
en: 'Search'
},
icon: 'core/agentSkill/search'
},
[AgentSkillCategoryEnum.tool]: {
label: {
'zh-CN': '工具',
'zh-Hant': '工具',
en: 'Tool'
},
icon: 'core/agentSkill/tool'
},
[AgentSkillCategoryEnum.coding]: {
label: {
'zh-CN': '编程',
'zh-Hant': '編程',
en: 'Coding'
},
icon: 'core/agentSkill/coding'
},
[AgentSkillCategoryEnum.data]: {
label: {
'zh-CN': '数据处理',
'zh-Hant': '數據處理',
en: 'Data Processing'
},
icon: 'core/agentSkill/data'
},
[AgentSkillCategoryEnum.analysis]: {
label: {
'zh-CN': '分析',
'zh-Hant': '分析',
en: 'Analysis'
},
icon: 'core/agentSkill/analysis'
},
[AgentSkillCategoryEnum.communication]: {
label: {
'zh-CN': '通信',
'zh-Hant': '通訊',
en: 'Communication'
},
icon: 'core/agentSkill/communication'
},
[AgentSkillCategoryEnum.other]: {
label: {
'zh-CN': '其他',
'zh-Hant': '其他',
en: 'Other'
},
icon: 'core/agentSkill/other'
}
};
export const agentSkillsCollectionName = 'agent_skills';
export const agentSkillsVersionCollectionName = 'agent_skills_versions';
export const skillSandboxCollectionName = 'skill_sandbox_info';
// Agent Skill types
export enum AgentSkillTypeEnum {
folder = 'folder',
skill = 'skill'
}
export const AgentSkillFolderTypeList = [AgentSkillTypeEnum.folder];
// Sandbox types
export enum SandboxTypeEnum {
editDebug = 'edit-debug',
sessionRuntime = 'session-runtime'
}
// Sandbox status states
export enum SandboxStateEnum {
pending = 'Pending',
running = 'Running',
failed = 'Failed',
succeeded = 'Succeeded',
unknown = 'Unknown'
}
// Sandbox protocol types
export enum SandboxProtocolEnum {
http = 'http',
https = 'https'
}
export const sandboxInstanceCollectionName = 'agent_sandbox_instances';
import { z } from 'zod';
import {
AgentSkillSourceEnum,
AgentSkillCategoryEnum,
AgentSkillTypeEnum,
SandboxProtocolEnum,
SandboxTypeEnum
} from './constants';
import { SandboxStatusEnum } from '../ai/sandbox/constants';
const LooseObjectSchema = z.object({}).catchall(z.any());
const BufferSchema = z.custom<Buffer>(
(value) => typeof Buffer !== 'undefined' && Buffer.isBuffer(value),
'Expected Buffer'
);
export const AgentSkillSourceSchema = z.enum(AgentSkillSourceEnum);
export const AgentSkillCategorySchema = z.enum(AgentSkillCategoryEnum);
export const AgentSkillTypeSchema = z.enum(AgentSkillTypeEnum);
export const SandboxProtocolSchema = z.enum(SandboxProtocolEnum);
export const SandboxTypeSchema = z.enum(SandboxTypeEnum);
export const SandboxStatusSchema = z.enum([
SandboxStatusEnum.running,
SandboxStatusEnum.stopped
] as const);
export const AgentSkillConfigParameterSchema = z.object({
name: z.string(),
type: z.string(),
description: z.string(),
required: z.boolean().optional(),
default: z.any().optional()
});
export const AgentSkillApiConfigSchema = z.object({
url: z.string(),
method: z.enum(['GET', 'POST', 'PUT', 'DELETE']),
headers: z.record(z.string(), z.string()).optional(),
timeout: z.number().optional()
});
export const AgentSkillConfigSchema = z
.object({
parameters: z.array(AgentSkillConfigParameterSchema).optional(),
api: AgentSkillApiConfigSchema.optional()
})
.catchall(z.any());
export type AgentSkillConfigType = z.infer<typeof AgentSkillConfigSchema>;
export const AgentSkillStorageSchema = z.object({
bucket: z.string(),
key: z.string(),
size: z.number()
});
export const SkillVersionStorageSchema = AgentSkillStorageSchema.extend({
checksum: z.string().optional()
});
export const AgentSkillSchema = z.object({
_id: z.string(),
parentId: z.string().nullable().optional(),
type: AgentSkillTypeSchema,
inheritPermission: z.boolean().optional(),
source: AgentSkillSourceSchema,
name: z.string(),
description: z.string(),
author: z.string(),
category: z.array(AgentSkillCategorySchema),
config: AgentSkillConfigSchema,
avatar: z.string().optional(),
teamId: z.string(),
tmbId: z.string(),
createTime: z.coerce.date(),
updateTime: z.coerce.date(),
deleteTime: z.coerce.date().nullable().optional(),
currentVersion: z.number(),
versionCount: z.number(),
currentStorage: AgentSkillStorageSchema.optional()
});
export type AgentSkillSchemaType = z.infer<typeof AgentSkillSchema>;
export const AgentSkillListItemSchema = z.object({
_id: z.string(),
source: AgentSkillSourceSchema,
type: AgentSkillTypeSchema,
parentId: z.string().nullable().optional(),
inheritPermission: z.boolean().optional(),
name: z.string(),
description: z.string(),
author: z.string(),
category: z.array(AgentSkillCategorySchema),
avatar: z.string().optional(),
createTime: z.coerce.date(),
updateTime: z.coerce.date(),
appCount: z.number().optional(),
sourceMember: z
.object({
name: z.string(),
avatar: z.string().nullable().optional(),
status: z.string()
})
.optional()
});
export type AgentSkillListItemType = z.infer<typeof AgentSkillListItemSchema>;
export const AgentSkillDetailSchema = AgentSkillSchema.extend({
appCount: z.number().optional(),
permission: z.any().optional()
});
export type AgentSkillDetailType = z.infer<typeof AgentSkillDetailSchema>;
export const AgentSkillsVersionImportSourceSchema = z.object({
originalFilename: z.string(),
importedAt: z.coerce.date()
});
export const AgentSkillsVersionSchema = z.object({
_id: z.string(),
skillId: z.string(),
tmbId: z.string(),
version: z.number(),
versionName: z.string().optional(),
storage: SkillVersionStorageSchema,
importSource: AgentSkillsVersionImportSourceSchema.optional(),
isActive: z.boolean(),
isDeleted: z.boolean(),
createdAt: z.coerce.date()
});
export type AgentSkillsVersionSchemaType = z.infer<typeof AgentSkillsVersionSchema>;
export const SkillPackageSkillSchema = z.object({
name: z.string(),
description: z.string(),
category: z.array(AgentSkillCategorySchema),
config: AgentSkillConfigSchema,
avatar: z.string().optional()
});
export const SkillPackageSchema = z.object({
skill: SkillPackageSkillSchema
});
export type SkillPackageType = z.infer<typeof SkillPackageSchema>;
export const ZipEntryInfoSchema = z.object({
name: z.string(),
size: z.number(),
isDirectory: z.boolean(),
uncompressedSize: z.number().optional(),
compressionMethod: z.number().optional()
});
export type ZipEntryInfo = z.infer<typeof ZipEntryInfoSchema>;
export const ExtractedSkillPackageSchema = z.object({
skillPackage: SkillPackageSchema,
zipBuffer: BufferSchema,
zipEntries: z.array(ZipEntryInfoSchema),
totalSize: z.number()
});
export type ExtractedSkillPackage = z.infer<typeof ExtractedSkillPackageSchema>;
export const SkillSandboxEndpointSchema = z.object({
host: z.string(),
port: z.number(),
protocol: SandboxProtocolSchema,
url: z.string()
});
export type SkillSandboxEndpointType = z.infer<typeof SkillSandboxEndpointSchema>;
export const SandboxImageConfigSchema = z.object({
repository: z.string(),
tag: z.string().optional()
});
export type SandboxImageConfigType = z.infer<typeof SandboxImageConfigSchema>;
export const SandboxProviderStatusSchema = z.object({
state: z.string(),
message: z.string().optional(),
reason: z.string().optional()
});
export const SandboxStorageSchema = AgentSkillStorageSchema.extend({
uploadedAt: z.coerce.date()
});
export const SandboxInstanceDetailSchema = z.object({
sandboxType: SandboxTypeSchema,
teamId: z.string(),
tmbId: z.string(),
skillId: z.string().optional(),
sessionId: z.string().optional(),
skillIds: z.array(z.string()).optional(),
provider: z.string(),
image: SandboxImageConfigSchema,
providerCreatedAt: z.coerce.date(),
endpoint: SkillSandboxEndpointSchema.optional(),
storage: SandboxStorageSchema.optional(),
metadata: z.union([z.map(z.string(), z.any()), LooseObjectSchema]).optional()
});
export const SandboxInstanceSchema = z.object({
_id: z.string(),
sandboxId: z.string(),
appId: z.string(),
userId: z.string(),
chatId: z.string(),
status: SandboxStatusSchema,
lastActiveAt: z.coerce.date(),
createdAt: z.coerce.date(),
detail: SandboxInstanceDetailSchema
});
export type SandboxInstanceSchemaType = z.infer<typeof SandboxInstanceSchema>;
import type { I18nStringType } from '../../../common/i18n/type';
import { hashStr } from '../../../common/string/tools';
import type { ChatCompletionTool } from '../llm/type';
import z from 'zod';
import {
SANDBOX_EDIT_FILE_TOOL_NAME,
SANDBOX_GET_FILE_URL_TOOL_NAME,
SANDBOX_READ_FILE_TOOL_NAME,
SANDBOX_SEARCH_TOOL_NAME,
SANDBOX_SHELL_TOOL_NAME,
SANDBOX_WRITE_FILE_TOOL_NAME
} from './tools';
// ---- 沙盒状态 ----
export const SandboxStatusEnum = {
......@@ -18,91 +23,16 @@ export const generateSandboxId = (appId: string, userId: string, chatId: string)
return hashStr(`${String(appId)}-${String(userId)}-${String(chatId)}`).slice(0, 16);
};
// Shell Tool
export const SANDBOX_NAME: I18nStringType = {
'zh-CN': '虚拟机',
'zh-Hant': '虛擬機',
en: 'Sandbox'
};
export const SANDBOX_ICON = 'core/app/sandbox/sandbox' as const;
export const SANDBOX_TOOL_NAME = 'sandbox_shell';
export const SANDBOX_SHELL_TOOL: ChatCompletionTool = {
type: 'function',
function: {
name: SANDBOX_TOOL_NAME,
description: '在独立 Linux 虚拟机环境中执行 shell 命令,支持文件操作、代码运行、包安装等',
parameters: {
type: 'object',
properties: {
command: { type: 'string', description: '要执行的 shell 命令' },
timeout: {
type: 'number',
description: '超时秒数',
max: 600,
min: 1
}
},
required: ['command']
}
}
};
// Get File URL Tool
export const SANDBOX_READ_FILE_TOOL_NAME: I18nStringType = {
'zh-CN': '虚拟机/获取文件链接',
'zh-Hant': '虛擬機/獲取文件鏈接',
en: 'Sandbox/Get File URL'
};
export const SANDBOX_GET_FILE_URL_TOOL_NAME = 'sandbox_get_file_url';
export const SANDBOX_GET_FILE_URL_TOOL: ChatCompletionTool = {
type: 'function',
function: {
name: SANDBOX_GET_FILE_URL_TOOL_NAME,
description: '从虚拟机读取指定文件,上传至云存储,返回 2 小时有效期的访问链接',
parameters: {
type: 'object',
properties: {
paths: {
type: 'array',
items: {
type: 'string',
description: '文件访问路径,例如: output.csv'
},
description: '文件访问路径,例如: ["output.csv", "output.txt"]'
}
},
required: ['paths']
}
}
};
// Prompt
export const SANDBOX_USER_FILES_PATH = 'user_files/';
export const SANDBOX_SYSTEM_PROMPT = `## 沙盒能力
你拥有一个独立的 Linux 沙盒环境(Ubuntu 22.04),可通过 ${SANDBOX_TOOL_NAME} 工具执行命令。
你拥有一个独立的 Linux 沙盒环境(Ubuntu 22.04),可通过 sandbox 工具操作文件和执行命令。
- 系统预装:bash / python3 / node / bun / git / curl
- 可自行安装软件包(apt / pip / npm)
- 生成的文件内容都保存在当前目录下即可
- 用户主动上传的文件存储在 ${SANDBOX_USER_FILES_PATH} 目录下
- 若需要将生成的文件链接,可使用 ${SANDBOX_GET_FILE_URL_TOOL_NAME} 工具获取文件的临时访问链接`;
// 聚合
export const sandboxToolMap: Record<
string,
{ schema: ChatCompletionTool; name: I18nStringType; avatar: string; toolDescription: string }
> = {
[SANDBOX_TOOL_NAME]: {
schema: SANDBOX_SHELL_TOOL,
name: SANDBOX_NAME,
avatar: SANDBOX_ICON,
toolDescription: SANDBOX_SHELL_TOOL.function.description!
},
[SANDBOX_GET_FILE_URL_TOOL_NAME]: {
schema: SANDBOX_GET_FILE_URL_TOOL,
name: SANDBOX_READ_FILE_TOOL_NAME,
avatar: SANDBOX_ICON,
toolDescription: SANDBOX_GET_FILE_URL_TOOL.function.description!
}
};
export const SANDBOX_TOOLS = Object.values(sandboxToolMap).map((item) => item.schema);
- 用户对话上传的文件存储在 ${SANDBOX_USER_FILES_PATH} 目录下
- 使用 ${SANDBOX_SHELL_TOOL_NAME} 执行命令、运行代码和安装依赖(apt / pip / npm)
- 使用 ${SANDBOX_READ_FILE_TOOL_NAME} 读取文本文件内容,可读取全文或指定行号范围
- 使用 ${SANDBOX_WRITE_FILE_TOOL_NAME} 创建或覆盖文本文件
- 使用 ${SANDBOX_EDIT_FILE_TOOL_NAME} 对已有文件做精确查找替换
- 使用 ${SANDBOX_SEARCH_TOOL_NAME} 搜索沙盒内的文件路径
- 生成的文件内容保存在当前工作区即可
- 若需要将生成的文件链接,可使用 ${SANDBOX_GET_FILE_URL_TOOL_NAME} 获取临时访问链接`;
import type { I18nStringType } from '../../../../common/i18n/type';
export const SANDBOX_NAME: I18nStringType = {
'zh-CN': '虚拟机',
'zh-Hant': '虛擬機',
en: 'Sandbox'
};
export const SANDBOX_ICON = 'core/app/sandbox/sandbox' as const;
import type { I18nStringType } from '../../../../common/i18n/type';
import type { ChatCompletionTool } from '../../llm/type';
export const SANDBOX_EDIT_FILE_TOOL_NAME = 'sandbox_edit_file';
export const SANDBOX_EDIT_FILE_NAME: I18nStringType = {
'zh-CN': '虚拟机/编辑文件',
'zh-Hant': '虛擬機/編輯文件',
en: 'Sandbox/Edit File'
};
export const SANDBOX_EDIT_FILE_TOOL: ChatCompletionTool = {
type: 'function',
function: {
name: SANDBOX_EDIT_FILE_TOOL_NAME,
description: '在虚拟机中按原文查找并替换文件内容,支持一次编辑多个文件',
parameters: {
type: 'object',
properties: {
entries: {
type: 'array',
items: {
type: 'object',
properties: {
path: {
type: 'string',
description: '文件路径,例如: src/index.ts 或 /home/sandbox/workspace/src/index.ts'
},
oldContent: {
type: 'string',
description: '需要被替换的原始内容'
},
newContent: {
type: 'string',
description: '替换后的新内容'
}
},
required: ['path', 'oldContent', 'newContent']
},
description: '编辑操作列表'
}
},
required: ['entries']
}
}
};
import type { I18nStringType } from '../../../../common/i18n/type';
import type { ChatCompletionTool } from '../../llm/type';
export const SANDBOX_GET_FILE_URL_NAME: I18nStringType = {
'zh-CN': '虚拟机/获取文件链接',
'zh-Hant': '虛擬機/獲取文件鏈接',
en: 'Sandbox/Get File URL'
};
export const SANDBOX_GET_FILE_URL_TOOL_NAME = 'sandbox_get_file_url';
export const SANDBOX_GET_FILE_URL_TOOL: ChatCompletionTool = {
type: 'function',
function: {
name: SANDBOX_GET_FILE_URL_TOOL_NAME,
description: '从虚拟机读取指定文件,上传至云存储,返回 2 小时有效期的访问链接',
parameters: {
type: 'object',
properties: {
paths: {
type: 'array',
items: {
type: 'string',
description: '文件访问路径,例如: output.csv'
},
description: '文件访问路径,例如: ["output.csv", "output.txt"]'
}
},
required: ['paths']
}
}
};
import type { I18nStringType } from '../../../../common/i18n/type';
import type { ChatCompletionTool } from '../../llm/type';
import { SANDBOX_ICON, SANDBOX_NAME } from './common';
import {
SANDBOX_EDIT_FILE_NAME,
SANDBOX_EDIT_FILE_TOOL,
SANDBOX_EDIT_FILE_TOOL_NAME
} from './editFile';
import {
SANDBOX_GET_FILE_URL_NAME,
SANDBOX_GET_FILE_URL_TOOL,
SANDBOX_GET_FILE_URL_TOOL_NAME
} from './getFileUrl';
import {
SANDBOX_READ_FILE_NAME,
SANDBOX_READ_FILE_TOOL,
SANDBOX_READ_FILE_TOOL_NAME
} from './readFile';
import { SANDBOX_SEARCH_NAME, SANDBOX_SEARCH_TOOL, SANDBOX_SEARCH_TOOL_NAME } from './search';
import { SANDBOX_SHELL_TOOL, SANDBOX_SHELL_TOOL_NAME } from './shell';
import {
SANDBOX_WRITE_FILE_NAME,
SANDBOX_WRITE_FILE_TOOL,
SANDBOX_WRITE_FILE_TOOL_NAME
} from './writeFile';
export { SANDBOX_ICON, SANDBOX_NAME } from './common';
export {
SANDBOX_EDIT_FILE_NAME,
SANDBOX_EDIT_FILE_TOOL,
SANDBOX_EDIT_FILE_TOOL_NAME
} from './editFile';
export {
SANDBOX_GET_FILE_URL_NAME,
SANDBOX_GET_FILE_URL_TOOL,
SANDBOX_GET_FILE_URL_TOOL_NAME
} from './getFileUrl';
export {
SANDBOX_READ_FILE_NAME,
SANDBOX_READ_FILE_TOOL,
SANDBOX_READ_FILE_TOOL_NAME
} from './readFile';
export { SANDBOX_SEARCH_NAME, SANDBOX_SEARCH_TOOL, SANDBOX_SEARCH_TOOL_NAME } from './search';
export { SANDBOX_SHELL_TOOL, SANDBOX_SHELL_TOOL_NAME } from './shell';
export {
SANDBOX_WRITE_FILE_NAME,
SANDBOX_WRITE_FILE_TOOL,
SANDBOX_WRITE_FILE_TOOL_NAME
} from './writeFile';
export const sandboxToolMap: Record<
string,
{ schema: ChatCompletionTool; name: I18nStringType; avatar: string; toolDescription: string }
> = {
[SANDBOX_SHELL_TOOL_NAME]: {
schema: SANDBOX_SHELL_TOOL,
name: SANDBOX_NAME,
avatar: SANDBOX_ICON,
toolDescription: SANDBOX_SHELL_TOOL.function.description!
},
[SANDBOX_READ_FILE_TOOL_NAME]: {
schema: SANDBOX_READ_FILE_TOOL,
name: SANDBOX_READ_FILE_NAME,
avatar: SANDBOX_ICON,
toolDescription: SANDBOX_READ_FILE_TOOL.function.description!
},
[SANDBOX_WRITE_FILE_TOOL_NAME]: {
schema: SANDBOX_WRITE_FILE_TOOL,
name: SANDBOX_WRITE_FILE_NAME,
avatar: SANDBOX_ICON,
toolDescription: SANDBOX_WRITE_FILE_TOOL.function.description!
},
[SANDBOX_EDIT_FILE_TOOL_NAME]: {
schema: SANDBOX_EDIT_FILE_TOOL,
name: SANDBOX_EDIT_FILE_NAME,
avatar: SANDBOX_ICON,
toolDescription: SANDBOX_EDIT_FILE_TOOL.function.description!
},
[SANDBOX_SEARCH_TOOL_NAME]: {
schema: SANDBOX_SEARCH_TOOL,
name: SANDBOX_SEARCH_NAME,
avatar: SANDBOX_ICON,
toolDescription: SANDBOX_SEARCH_TOOL.function.description!
},
[SANDBOX_GET_FILE_URL_TOOL_NAME]: {
schema: SANDBOX_GET_FILE_URL_TOOL,
name: SANDBOX_GET_FILE_URL_NAME,
avatar: SANDBOX_ICON,
toolDescription: SANDBOX_GET_FILE_URL_TOOL.function.description!
}
};
export const SANDBOX_TOOLS = Object.values(sandboxToolMap).map((item) => item.schema);
import type { I18nStringType } from '../../../../common/i18n/type';
import type { ChatCompletionTool } from '../../llm/type';
export const SANDBOX_READ_FILE_TOOL_NAME = 'sandbox_read_file';
export const SANDBOX_READ_FILE_NAME: I18nStringType = {
'zh-CN': '虚拟机/读取文件',
'zh-Hant': '虛擬機/讀取文件',
en: 'Sandbox/Read File'
};
export const SANDBOX_READ_FILE_TOOL: ChatCompletionTool = {
type: 'function',
function: {
name: SANDBOX_READ_FILE_TOOL_NAME,
description: '读取虚拟机中的文本文件内容,支持读取全文或按 1-based 行号范围读取',
parameters: {
type: 'object',
properties: {
path: {
type: 'string',
description: '文件路径,例如: src/index.ts 或 /home/sandbox/workspace/src/index.ts'
},
startLine: {
type: 'number',
description: '起始行号,1-based,可选。不传则从文件开头读取',
min: 1
},
endLine: {
type: 'number',
description: '结束行号,1-based,包含该行,可选。不传则读取到文件末尾',
min: 1
}
},
required: ['path']
}
}
};
import type { I18nStringType } from '../../../../common/i18n/type';
import type { ChatCompletionTool } from '../../llm/type';
export const SANDBOX_SEARCH_TOOL_NAME = 'sandbox_search';
export const SANDBOX_SEARCH_NAME: I18nStringType = {
'zh-CN': '虚拟机/搜索文件',
'zh-Hant': '虛擬機/搜尋文件',
en: 'Sandbox/Search Files'
};
export const SANDBOX_SEARCH_TOOL: ChatCompletionTool = {
type: 'function',
function: {
name: SANDBOX_SEARCH_TOOL_NAME,
description: '在虚拟机中按文件名或 glob 模式搜索文件路径',
parameters: {
type: 'object',
properties: {
pattern: {
type: 'string',
description: '搜索模式,例如: "*.py"、"package.json"'
},
path: {
type: 'string',
description: '起始目录,可选,例如: /home/sandbox/workspace'
}
},
required: ['pattern']
}
}
};
import type { ChatCompletionTool } from '../../llm/type';
export const SANDBOX_SHELL_TOOL_NAME = 'sandbox_shell';
export const SANDBOX_SHELL_TOOL: ChatCompletionTool = {
type: 'function',
function: {
name: SANDBOX_SHELL_TOOL_NAME,
description: '在独立 Linux 虚拟机环境中执行 shell 命令,支持文件操作、代码运行、包安装等',
parameters: {
type: 'object',
properties: {
command: { type: 'string', description: '要执行的 shell 命令' },
timeout: {
type: 'number',
description: '超时秒数',
max: 600,
min: 1
}
},
required: ['command']
}
}
};
import type { I18nStringType } from '../../../../common/i18n/type';
import type { ChatCompletionTool } from '../../llm/type';
export const SANDBOX_WRITE_FILE_TOOL_NAME = 'sandbox_write_file';
export const SANDBOX_WRITE_FILE_NAME: I18nStringType = {
'zh-CN': '虚拟机/写入文件',
'zh-Hant': '虛擬機/寫入文件',
en: 'Sandbox/Write File'
};
export const SANDBOX_WRITE_FILE_TOOL: ChatCompletionTool = {
type: 'function',
function: {
name: SANDBOX_WRITE_FILE_TOOL_NAME,
description: '在虚拟机中创建或覆盖指定文件,适合写入脚本、配置和中间数据',
parameters: {
type: 'object',
properties: {
path: {
type: 'string',
description: '文件路径,通常为相对路径。'
},
content: {
type: 'string',
description: '写入文件的文本内容'
}
},
required: ['path', 'content']
}
}
};
export * from '../../../openapi/core/ai/skill/api';
import type { UpdateClbPermissionProps } from '../../support/permission/collaborator';
import type { RequireOnlyOne } from '../../common/type/utils';
import type { UpdateClbPermissionProps } from '../../../support/permission/collaborator';
import type { RequireOnlyOne } from '../../../common/type/utils';
export type UpdateSkillCollaboratorBody = UpdateClbPermissionProps & {
skillId: string;
......
export enum AgentSkillSourceEnum {
system = 'system',
personal = 'personal'
}
export enum AgentSkillCategoryEnum {
search = 'search',
tool = 'tool',
coding = 'coding',
data = 'data',
analysis = 'analysis',
communication = 'communication',
other = 'other'
}
export const agentSkillsCollectionName = 'agent_skills';
export const agentSkillsVersionCollectionName = 'agent_skills_versions';
export enum AgentSkillCreationStatusEnum {
creating = 'creating',
ready = 'ready',
failed = 'failed'
}
// Agent Skill types
export enum AgentSkillTypeEnum {
folder = 'folder',
skill = 'skill'
}
// Sandbox types
export enum SandboxTypeEnum {
editDebug = 'edit-debug',
sessionRuntime = 'session-runtime'
}
import z from 'zod';
import {
AgentSkillSourceEnum,
AgentSkillCategoryEnum,
AgentSkillTypeEnum,
AgentSkillCreationStatusEnum,
SandboxTypeEnum
} from './constants';
import { SandboxStatusEnum } from '../sandbox/constants';
const LooseObjectSchema = z.object({}).catchall(z.any());
const BufferSchema = z.custom<Buffer>(
(value) => typeof Buffer !== 'undefined' && Buffer.isBuffer(value),
'Expected Buffer'
);
export const AgentSkillSourceSchema = z.enum(AgentSkillSourceEnum);
export const AgentSkillCategorySchema = z.enum(AgentSkillCategoryEnum);
export const AgentSkillTypeSchema = z.enum(AgentSkillTypeEnum);
export const AgentSkillCreationStatusSchema = z.enum(AgentSkillCreationStatusEnum);
export const SandboxTypeSchema = z.enum(SandboxTypeEnum);
export const SandboxStatusSchema = z.enum([
SandboxStatusEnum.running,
SandboxStatusEnum.stopped
] as const);
export const AgentSkillSchema = z.object({
_id: z.string(),
parentId: z.string().nullable().optional(),
type: AgentSkillTypeSchema,
inheritPermission: z.boolean().optional(),
source: AgentSkillSourceSchema,
name: z.string(),
description: z.string(),
category: z.array(AgentSkillCategorySchema),
avatar: z.string().optional(),
teamId: z.string(),
tmbId: z.string(),
createTime: z.coerce.date(),
updateTime: z.coerce.date(),
deleteTime: z.coerce.date().nullable().optional(),
currentVersionId: z.string().optional(),
creationStatus: AgentSkillCreationStatusSchema.optional(),
creationError: z.string().optional()
});
export type AgentSkillSchemaType = z.infer<typeof AgentSkillSchema>;
export const AgentSkillListItemSchema = z.object({
_id: z.string(),
source: AgentSkillSourceSchema,
type: AgentSkillTypeSchema,
parentId: z.string().nullable().optional(),
inheritPermission: z.boolean().optional(),
name: z.string(),
description: z.string(),
category: z.array(AgentSkillCategorySchema),
avatar: z.string().optional(),
currentVersionId: z.string().optional(),
creationStatus: AgentSkillCreationStatusSchema.optional(),
createTime: z.coerce.date(),
updateTime: z.coerce.date(),
appCount: z.number().optional(),
sourceMember: z
.object({
name: z.string(),
avatar: z.string().nullable().optional(),
status: z.string()
})
.optional()
});
export type AgentSkillListItemType = z.infer<typeof AgentSkillListItemSchema>;
export const AgentSkillDetailSchema = AgentSkillSchema.extend({
appCount: z.number().optional(),
permission: z.any().optional()
});
export type AgentSkillDetailType = z.infer<typeof AgentSkillDetailSchema>;
export const AgentSkillsVersionImportSourceSchema = z.object({
originalFilename: z.string(),
importedAt: z.coerce.date()
});
export const AgentSkillsVersionSchema = z.object({
_id: z.string(),
skillId: z.string(),
tmbId: z.string(),
versionName: z.string().optional(),
storageKey: z.string(),
importSource: AgentSkillsVersionImportSourceSchema.optional(),
createdAt: z.coerce.date()
});
export type AgentSkillsVersionSchemaType = z.infer<typeof AgentSkillsVersionSchema>;
export const SkillPackageSkillSchema = z.object({
name: z.string(),
description: z.string(),
category: z.array(AgentSkillCategorySchema),
avatar: z.string().optional()
});
export const SkillPackageSchema = z.object({
skill: SkillPackageSkillSchema
});
export type SkillPackageType = z.infer<typeof SkillPackageSchema>;
export const ZipEntryInfoSchema = z.object({
name: z.string(),
size: z.number(),
isDirectory: z.boolean(),
uncompressedSize: z.number().optional(),
compressionMethod: z.number().optional()
});
export type ZipEntryInfo = z.infer<typeof ZipEntryInfoSchema>;
export const ExtractedSkillPackageSchema = z.object({
skillPackage: SkillPackageSchema,
zipBuffer: BufferSchema,
zipEntries: z.array(ZipEntryInfoSchema),
totalSize: z.number()
});
export type ExtractedSkillPackage = z.infer<typeof ExtractedSkillPackageSchema>;
export const SandboxImageConfigSchema = z.object({
repository: z.string(),
tag: z.string().optional()
});
export type SandboxImageConfigType = z.infer<typeof SandboxImageConfigSchema>;
export const SandboxProviderStatusSchema = z.object({
state: z.string(),
message: z.string().optional(),
reason: z.string().optional()
});
export const SandboxStorageSchema = z.object({
key: z.string(),
uploadedAt: z.coerce.date()
});
export const SandboxInstanceDetailSchema = z.object({
type: SandboxTypeSchema,
teamId: z.string(),
tmbId: z.string(),
skillId: z.string().optional(),
sessionId: z.string().optional(),
skillIds: z.array(z.string()).optional(),
provider: z.string(),
image: SandboxImageConfigSchema,
providerCreatedAt: z.coerce.date(),
storage: SandboxStorageSchema.optional(),
metadata: z.union([z.map(z.string(), z.any()), LooseObjectSchema]).optional()
});
export const SandboxInstanceSchema = z.object({
_id: z.string(),
sandboxId: z.string(),
appId: z.string(),
userId: z.string(),
chatId: z.string(),
status: SandboxStatusSchema,
lastActiveAt: z.coerce.date(),
createdAt: z.coerce.date(),
detail: SandboxInstanceDetailSchema
});
export type SandboxInstanceSchemaType = z.infer<typeof SandboxInstanceSchema>;
export const SkillToolSchema = z.object({
id: z.string(),
......
......@@ -4,27 +4,18 @@ import { AppChatConfigTypeSchema, AppDatasetSearchParamsTypeSchema } from '../ty
import { FlowNodeTemplateTypeSchema } from '../../workflow/type/node';
import { NodeInputKeyEnum } from '../../workflow/constants';
export type AgentSubAppItemType = {};
export type AgentSubAppItemType = object;
/* ===== Agent Skill ===== */
export const SelectedAgentSkillItemTypeSchema = z.object({
skillId: z.string(),
name: z.string(),
description: z.string().default(''),
avatar: z.string().optional()
avatar: z.string().optional(),
isDeleted: z.boolean().default(false)
});
export type SelectedAgentSkillItemType = z.infer<typeof SelectedAgentSkillItemTypeSchema>;
/**
* 将 skills 输入值规范化为 skillId 字符串数组。
* 兼容两种格式:
* - string[]:debugChat 运行时直接传入的 skillId 数组
* - SelectedAgentSkillItemType[]:工作流 NodeAgent 存储的完整对象数组(含 name/avatar 等展示字段)
*/
export const normalizeSkillIds = (
skills: Array<string | SelectedAgentSkillItemType> | undefined
): string[] => (skills ?? []).map((s) => (typeof s === 'string' ? s : s.skillId)).filter(Boolean);
/* ===== Tool ===== */
export const SelectedToolItemTypeSchema = FlowNodeTemplateTypeSchema.extend({
configStatus: z.enum(['noConfig', 'waitingForConfig', 'configured', 'invalid']).optional()
......
......@@ -61,20 +61,12 @@ export type SandboxStatusPhase =
// Note: 'expiredDetected' and 'restarting' are internal and filtered server-side
export type SandboxStatusItemType = {
sandboxId: string; // sessionId or skillId (correlates events for same sandbox)
sandboxId: string; // FastGPT sandbox key; ready events use the persisted sandbox instance key
phase: SandboxStatusPhase;
isWarmStart?: boolean; // present on 'connecting' and 'ready'
skillName?: string; // present on 'deployingSkills', 'downloadingPackage',
// 'uploadingPackage', 'extractingPackage' in session-runtime
message?: string; // optional human-readable message
// Present on 'ready' phase for edit-debug sandboxes
endpoint?: {
host: string;
port: number;
protocol: 'http' | 'https';
url: string;
};
providerSandboxId?: string; // present on 'ready' for edit-debug
};
/* Skill module response */
......
......@@ -174,7 +174,7 @@ export enum NodeInputKeyEnum {
datasetParams = 'agent_datasetParams',
skills = 'skills',
useAgentSandbox = 'useAgentSandbox',
useEditDebugSandbox = 'useEditDebugSandbox',
editSkillId = 'editSkillId',
// dataset
datasetSelectList = 'datasets',
......
import type { I18nStringType, localeType } from '../../../../common/i18n/type';
import { sandboxToolMap } from '../../../ai/sandbox/constants';
import { skillToolsMap } from './skillTools';
import { sandboxToolMap } from '../../../ai/sandbox/tools';
import { parseI18nString } from '../../../../common/i18n/utils';
export enum SubAppIds {
......@@ -51,8 +50,7 @@ export const systemSubInfo: Record<
avatar: 'core/workflow/template/agent',
toolDescription: '调用 LLM 模型完成一些通用任务。'
},
...sandboxToolMap,
...skillToolsMap
...sandboxToolMap
};
export const getSystemToolInfo = (id: string, lang: localeType = 'en') => {
if (id in systemSubInfo) {
......
import z from 'zod';
import type { ChatCompletionTool } from '../../../ai/llm/type';
import type { I18nStringType, localeType } from '../../../../common/i18n/type';
import { parseI18nString } from '../../../../common/i18n/utils';
export enum SandboxToolIds {
writeFile = 'sandbox_write_file',
editFile = 'sandbox_edit_file',
execute = 'sandbox_execute',
search = 'sandbox_search',
fetchUserFile = 'sandbox_fetch_user_file'
}
export const skillToolsMap: Record<
string,
{ name: I18nStringType; avatar: string; toolDescription: string }
> = {
// Sandbox tools
[SandboxToolIds.writeFile]: {
name: {
'zh-CN': '写入文件',
'zh-Hant': '寫入文件',
en: 'WriteFile'
},
avatar: 'core/workflow/template/readFiles',
toolDescription:
'Create or overwrite a file in the sandbox. Used to write input data, create config files, etc.'
},
[SandboxToolIds.editFile]: {
name: {
'zh-CN': '编辑文件',
'zh-Hant': '編輯文件',
en: 'EditFile'
},
avatar: 'core/workflow/template/readFiles',
toolDescription:
'Edit files in the sandbox precisely by finding and replacing specified content. Supports batch editing across multiple files.'
},
[SandboxToolIds.execute]: {
name: {
'zh-CN': '执行命令',
'zh-Hant': '執行命令',
en: 'Execute'
},
avatar: 'core/workflow/template/codeRun',
toolDescription:
'Execute a shell command in the sandbox. Used to run scripts, install dependencies, execute skills, etc.'
},
[SandboxToolIds.search]: {
name: {
'zh-CN': '搜索文件',
'zh-Hant': '搜索文件',
en: 'SearchFile'
},
avatar: 'core/workflow/template/datasetSearch',
toolDescription:
'Search for files in the sandbox. Find matching file paths by filename pattern (glob).'
},
[SandboxToolIds.fetchUserFile]: {
name: {
'zh-CN': '获取用户文件',
'zh-Hant': '獲取用戶文件',
en: 'FetchUserFile'
},
avatar: 'core/workflow/template/readFiles',
toolDescription:
'Download a user-uploaded file (document or image) from the conversation and write it as a binary file into the sandbox filesystem. Use this when a skill script needs to process a raw file. Workflow: call this tool first to place the file at target_path (relative to workspace), then run skill scripts that read from that path.'
}
};
export const getSkillToolInfo = (
id: string,
lang: localeType = 'en'
): { name: string; avatar: string; toolDescription: string } | undefined => {
const toolInfo = skillToolsMap[id];
if (toolInfo) {
return {
name: parseI18nString(toolInfo.name, lang),
avatar: toolInfo.avatar,
toolDescription: toolInfo.toolDescription
};
}
};
// Zod parameter schemas (runtime validation)
export const SandboxWriteFileSchema = z.object({
path: z.string().describe('Absolute file path'),
content: z.string().describe('File content')
});
export const SandboxEditFileSchema = z.object({
entries: z.array(
z.object({
path: z.string().describe('Absolute file path'),
oldContent: z.string().describe('Original content to replace'),
newContent: z.string().describe('New content after replacement')
})
)
});
export const SandboxExecuteSchema = z.object({
command: z.string().describe('Shell command to execute'),
workingDirectory: z.string().optional().describe('Working directory (optional)'),
timeoutMs: z.number().optional().default(30000).describe('Timeout in milliseconds')
});
export const SandboxSearchSchema = z.object({
pattern: z.string().describe('Search pattern (filename or glob)'),
path: z.string().optional().describe('Starting path for search (optional)')
});
export const SandboxFetchUserFileSchema = z.object({
file_index: z.string().describe('File id from # Input Files (e.g. "current-0")'),
target_path: z
.string()
.describe(
'Relative path from workspace root to write the file (e.g. "uploads/document.pdf"). Do NOT use absolute paths or "..".'
)
});
// ChatCompletionTool definitions (exposed to LLM)
export const sandboxWriteFileTool: ChatCompletionTool = {
type: 'function',
function: {
name: SandboxToolIds.writeFile,
description: skillToolsMap[SandboxToolIds.writeFile].toolDescription,
parameters: {
type: 'object',
properties: {
path: { type: 'string', description: 'Absolute file path' },
content: { type: 'string', description: 'File content' }
},
required: ['path', 'content']
}
}
};
export const sandboxEditFileTool: ChatCompletionTool = {
type: 'function',
function: {
name: SandboxToolIds.editFile,
description: skillToolsMap[SandboxToolIds.editFile].toolDescription,
parameters: {
type: 'object',
properties: {
entries: {
type: 'array',
items: {
type: 'object',
properties: {
path: { type: 'string', description: 'Absolute file path' },
oldContent: { type: 'string', description: 'Original content to replace' },
newContent: { type: 'string', description: 'New content after replacement' }
},
required: ['path', 'oldContent', 'newContent']
},
description: 'Array of edit operations'
}
},
required: ['entries']
}
}
};
export const sandboxExecuteTool: ChatCompletionTool = {
type: 'function',
function: {
name: SandboxToolIds.execute,
description: skillToolsMap[SandboxToolIds.execute].toolDescription,
parameters: {
type: 'object',
properties: {
command: { type: 'string', description: 'Shell command to execute' },
workingDirectory: { type: 'string', description: 'Working directory (optional)' },
timeoutMs: { type: 'number', description: 'Timeout in milliseconds (default 30000)' }
},
required: ['command']
}
}
};
export const sandboxSearchTool: ChatCompletionTool = {
type: 'function',
function: {
name: SandboxToolIds.search,
description: skillToolsMap[SandboxToolIds.search].toolDescription,
parameters: {
type: 'object',
properties: {
pattern: { type: 'string', description: 'Search pattern (filename or glob)' },
path: { type: 'string', description: 'Starting path for search (optional)' }
},
required: ['pattern']
}
}
};
export const sandboxFetchUserFileTool: ChatCompletionTool = {
type: 'function',
function: {
name: SandboxToolIds.fetchUserFile,
description: skillToolsMap[SandboxToolIds.fetchUserFile].toolDescription,
parameters: {
type: 'object',
properties: {
file_index: {
type: 'string',
description: 'File id from # Input Files (e.g. "current-0")'
},
target_path: {
type: 'string',
description:
'Relative path from workspace root (e.g. "uploads/document.pdf"). Must not start with "/" or contain "..".'
}
},
required: ['file_index', 'target_path']
}
}
};
export const allSandboxTools: ChatCompletionTool[] = [
sandboxWriteFileTool,
sandboxEditFileTool,
sandboxExecuteTool,
sandboxSearchTool,
sandboxFetchUserFileTool
];
......@@ -2,8 +2,14 @@ import { OutLinkChatAuthSchema } from '../../../../support/permission/chat';
import z from 'zod';
const SandboxBaseSchema = z.object({
appId: z.string(),
chatId: z.string(),
appId: z.string().meta({
example: '68ad85a7463006c963799a05',
description: '应用 ID'
}),
chatId: z.string().meta({
example: 'bEdzC6PNupZrr1RoVutMF2DL',
description: '对话 ID'
}),
outLinkAuthData: OutLinkChatAuthSchema.optional().describe('外链鉴权数据')
});
......@@ -28,6 +34,81 @@ export const SandboxListResponseSchema = z.object({
});
export type SandboxListResponse = z.infer<typeof SandboxListResponseSchema>;
/* ============================================================================
* API: 递归列出沙盒目录
* Route: POST /api/core/ai/sandbox/listRecursive
* Method: POST
* Description: 一次性获取指定目录下的文件树,用于 Skill Edit 初始化文件列表
* Tags: ['Sandbox', 'Read']
* ============================================================================ */
export const SandboxListRecursiveBodySchema = SandboxListBodySchema.extend({
excludeNames: z
.array(z.string())
.optional()
.meta({
example: ['node_modules', '.git', 'dist'],
description: '需要跳过的文件或目录名称,仅按文件名匹配'
}),
maxDepth: z.number().int().min(0).max(20).default(20).meta({
example: 20,
description: '最大递归深度,0 表示只返回当前目录的直接子项'
})
});
export type SandboxListRecursiveBody = z.input<typeof SandboxListRecursiveBodySchema>;
export type SandboxFileTreeItem = SandboxFileItem & {
children?: SandboxFileTreeItem[];
level: number;
loaded?: boolean;
};
export const SandboxFileTreeItemSchema: z.ZodType<SandboxFileTreeItem> =
SandboxFileItemSchema.extend({
children: z
.lazy(() => z.array(SandboxFileTreeItemSchema))
.optional()
.meta({
description: '子节点。文件没有该字段,目录在未加载到更深层时可能为空数组'
}),
level: z.number().int().nonnegative().meta({
example: 0,
description: '节点层级,相对于请求 path 的直接子项为 0'
}),
loaded: z.boolean().optional().meta({
example: true,
description: '目录子节点是否已完整加载;达到 maxDepth 截断时为 false'
})
});
export const SandboxListRecursiveResponseSchema = z.object({
files: z.array(SandboxFileTreeItemSchema).meta({
description: '递归目录树',
example: [
{
name: 'src',
path: 'src',
type: 'directory',
level: 1,
loaded: true,
children: [
{
name: 'index.ts',
path: 'src/index.ts',
type: 'file',
size: 128,
level: 2
}
]
}
]
}),
expandedPaths: z.array(z.string()).meta({
example: ['src'],
description: '默认展开的目录路径'
})
});
export type SandboxListRecursiveResponse = z.infer<typeof SandboxListRecursiveResponseSchema>;
/**
* 写入文件 - 请求/响应
*/
......@@ -87,3 +168,19 @@ export type SandboxGetHtmlPreviewLinkBody = z.infer<typeof SandboxGetHtmlPreview
export type SandboxGetHtmlPreviewLinkResponse = z.infer<
typeof SandboxGetHtmlPreviewLinkResponseSchema
>;
/**
* 文件系统操作 - 请求/响应
*/
export const SandboxFileOpBodySchema = SandboxBaseSchema.extend({
type: z.enum(['mkdir', 'delete', 'move', 'copy']).describe('操作类型'),
path: z.string().describe('当前路径'),
destPath: z.string().optional().describe('目标路径')
});
export type SandboxFileOpBody = z.infer<typeof SandboxFileOpBodySchema>;
export const SandboxFileOpResponseSchema = z.object({
success: z.boolean(),
message: z.string().optional()
});
export type SandboxFileOpResponse = z.infer<typeof SandboxFileOpResponseSchema>;
......@@ -3,6 +3,8 @@ import { TagsMap } from '../../../tag';
import {
SandboxListBodySchema,
SandboxListResponseSchema,
SandboxListRecursiveBodySchema,
SandboxListRecursiveResponseSchema,
SandboxWriteBodySchema,
SandboxWriteResponseSchema,
SandboxReadBodySchema,
......@@ -12,7 +14,9 @@ import {
SandboxCheckExistBodySchema,
SandboxCheckExistResponseSchema,
SandboxGetHtmlPreviewLinkBodySchema,
SandboxGetHtmlPreviewLinkResponseSchema
SandboxGetHtmlPreviewLinkResponseSchema,
SandboxFileOpBodySchema,
SandboxFileOpResponseSchema
} from './api';
export const SandboxPath: OpenAPIPath = {
......@@ -41,6 +45,31 @@ export const SandboxPath: OpenAPIPath = {
}
},
'/core/ai/sandbox/listRecursive': {
post: {
summary: '递归列出沙盒目录',
description: '递归列出指定目录下的文件和子目录,并返回可直接渲染的目录树',
tags: [TagsMap.sandbox],
requestBody: {
content: {
'application/json': {
schema: SandboxListRecursiveBodySchema
}
}
},
responses: {
200: {
description: '递归目录树',
content: {
'application/json': {
schema: SandboxListRecursiveResponseSchema
}
}
}
}
}
},
'/core/ai/sandbox/write': {
post: {
summary: '写入沙盒文件',
......@@ -162,5 +191,30 @@ export const SandboxPath: OpenAPIPath = {
}
}
}
},
'/core/ai/sandbox/fileOp': {
post: {
summary: '文件系统操作',
description: '在沙盒中执行创建目录、删除、移动和复制等文件系统操作',
tags: [TagsMap.sandbox],
requestBody: {
content: {
'application/json': {
schema: SandboxFileOpBodySchema
}
}
},
responses: {
200: {
description: '操作成功',
content: {
'application/json': {
schema: SandboxFileOpResponseSchema
}
}
}
}
}
}
};
import { z } from 'zod';
import { TeamMemberStatusEnum } from '../../../../support/user/team/constant';
import {
AgentSkillCategorySchema,
AgentSkillCreationStatusSchema,
AgentSkillListItemSchema,
AgentSkillSourceSchema,
AgentSkillStorageSchema,
AgentSkillTypeSchema,
AgentSkillConfigSchema,
ExtractedSkillPackageSchema,
SandboxImageConfigSchema,
SandboxProviderStatusSchema,
SkillPackageSchema,
SkillSandboxEndpointSchema,
ZipEntryInfoSchema
} from '../../../core/agentSkills/type';
} from '../../../../core/ai/skill/type';
import { ChatGenerateStatusEnum } from '../../../../core/chat/constants';
const IdSchema = z.string().min(1).meta({ description: '资源 ID' });
const SandboxInstanceKeySchema = z.string().min(1).describe('FastGPT sandbox instance key');
const NullableParentIdSchema = z.string().nullable().optional().meta({
description: '父级目录 ID'
});
......@@ -25,9 +26,11 @@ export const ListSkillsQuerySchema = z.object({
searchKey: z.string().optional().describe('搜索关键词'),
category: AgentSkillCategorySchema.optional().describe('技能分类'),
type: AgentSkillTypeSchema.optional().describe('技能类型过滤'),
skillIds: z.array(IdSchema).optional().describe('按技能 ID 列表过滤,用于校验已关联技能状态'),
parentId: NullableParentIdSchema,
page: z.coerce.number().int().positive().optional().describe('页码'),
pageSize: z.coerce.number().int().positive().optional().describe('每页数量')
pageSize: z.coerce.number().int().positive().optional().describe('每页数量'),
withAppCount: z.boolean().optional().describe('是否返回引用应用数量')
});
export type ListSkillsQuery = z.infer<typeof ListSkillsQuerySchema>;
......@@ -44,7 +47,7 @@ export const ListSkillsResponseItemSchema = AgentSkillListItemSchema.omit({
.object({
name: z.string(),
avatar: z.string().nullable().optional(),
status: z.string()
status: z.nativeEnum(TeamMemberStatusEnum)
})
.optional()
});
......@@ -60,9 +63,7 @@ export const CreateSkillBodySchema = z.object({
name: z.string().describe('技能名称'),
description: z.string().optional().describe('技能描述'),
requirements: z.string().optional().describe('用于 AI 生成技能的需求描述'),
model: z.string().optional().describe('生成技能时使用的模型'),
category: z.array(AgentSkillCategorySchema).optional().describe('技能分类'),
config: AgentSkillConfigSchema.optional().describe('技能配置'),
avatar: z.string().optional().describe('技能头像')
});
export type CreateSkillBody = z.infer<typeof CreateSkillBodySchema>;
......@@ -75,7 +76,6 @@ export const UpdateSkillBodySchema = z.object({
name: z.string().optional(),
description: z.string().optional(),
category: z.array(AgentSkillCategorySchema).optional(),
config: AgentSkillConfigSchema.optional(),
avatar: z.string().optional(),
parentId: z
.string()
......@@ -111,6 +111,13 @@ export const GetSkillDetailQuerySchema = z.object({
});
export type GetSkillDetailQuery = z.infer<typeof GetSkillDetailQuerySchema>;
export const ResumeSkillInheritPermissionQuerySchema = z.object({
skillId: IdSchema
});
export type ResumeSkillInheritPermissionQuery = z.infer<
typeof ResumeSkillInheritPermissionQuerySchema
>;
export const GetSkillDetailResponseSchema = z.object({
_id: z.string(),
source: AgentSkillSourceSchema,
......@@ -119,12 +126,13 @@ export const GetSkillDetailResponseSchema = z.object({
inheritPermission: z.boolean().optional(),
name: z.string(),
description: z.string(),
author: z.string(),
category: z.array(AgentSkillCategorySchema),
config: AgentSkillConfigSchema,
avatar: z.string().optional(),
creationStatus: AgentSkillCreationStatusSchema.optional(),
creationError: z.string().optional(),
teamId: z.string().optional(),
tmbId: z.string().optional(),
currentVersionId: z.string().optional(),
createTime: z.string(),
updateTime: z.string(),
permission: z.any().optional(),
......@@ -150,9 +158,7 @@ export const CreateEditDebugSandboxBodySchema = z.object({
export type CreateEditDebugSandboxBody = z.infer<typeof CreateEditDebugSandboxBodySchema>;
export const CreateEditDebugSandboxResponseSchema = z.object({
sandboxId: z.string(),
providerSandboxId: z.string(),
endpoint: SkillSandboxEndpointSchema,
sandboxId: z.string().describe('FastGPT sandbox instance key'),
status: SandboxProviderStatusSchema.pick({
state: true,
message: true
......@@ -161,16 +167,14 @@ export const CreateEditDebugSandboxResponseSchema = z.object({
export type CreateEditDebugSandboxResponse = z.infer<typeof CreateEditDebugSandboxResponseSchema>;
export const GetSandboxInfoQuerySchema = z.object({
sandboxId: IdSchema
sandboxId: SandboxInstanceKeySchema
});
export type GetSandboxInfoQuery = z.infer<typeof GetSandboxInfoQuerySchema>;
export const GetSandboxInfoResponseSchema = z.object({
sandboxId: z.string(),
sandboxId: SandboxInstanceKeySchema,
skillId: z.string(),
sandboxType: z.string(),
providerSandboxId: z.string(),
endpoint: SkillSandboxEndpointSchema.optional(),
type: z.string(),
status: SandboxProviderStatusSchema.pick({
state: true,
message: true
......@@ -180,7 +184,7 @@ export const GetSandboxInfoResponseSchema = z.object({
export type GetSandboxInfoResponse = z.infer<typeof GetSandboxInfoResponseSchema>;
export const DeleteSandboxBodySchema = z.object({
sandboxId: IdSchema
sandboxId: SandboxInstanceKeySchema
});
export type DeleteSandboxBody = z.infer<typeof DeleteSandboxBodySchema>;
......@@ -196,9 +200,9 @@ export type SaveDeploySkillBody = z.infer<typeof SaveDeploySkillBodySchema>;
export const SaveDeploySkillResponseSchema = z.object({
skillId: z.string(),
version: z.number(),
versionId: z.string(),
versionName: z.string(),
storage: AgentSkillStorageSchema,
storageKey: z.string(),
createdAt: z.string()
});
export type SaveDeploySkillResponse = z.infer<typeof SaveDeploySkillResponseSchema>;
......@@ -208,11 +212,11 @@ export type {
ExtractedSkillPackage,
SkillPackageType,
ZipEntryInfo
} from '../../../core/agentSkills/type';
} from '../../../../core/ai/skill/type';
export const SkillDebugChatBodySchema = z.object({
skillId: IdSchema,
chatId: z.string(),
chatId: z.string().min(1),
responseChatItemId: z.string().optional(),
messages: z.array(LooseObjectSchema),
model: z.string().optional(),
......@@ -241,10 +245,23 @@ export type SkillDebugSessionListResponse = z.infer<typeof SkillDebugSessionList
export const SkillDebugSessionDeleteBodySchema = z.object({
skillId: IdSchema,
chatId: z.string()
chatId: z.string().min(1)
});
export type SkillDebugSessionDeleteBody = z.infer<typeof SkillDebugSessionDeleteBodySchema>;
export const SkillDebugSessionControlBodySchema = z.object({
skillId: IdSchema,
chatId: z.string().min(1)
});
export type SkillDebugSessionControlBody = z.infer<typeof SkillDebugSessionControlBodySchema>;
export const SkillDebugSessionStopResponseSchema = z.object({
success: z.boolean(),
completed: z.boolean().describe('工作流是否已在本次请求等待窗口内完成停止'),
chatGenerateStatus: z.enum(ChatGenerateStatusEnum).describe('当前对话生成状态')
});
export type SkillDebugSessionStopResponse = z.infer<typeof SkillDebugSessionStopResponseSchema>;
export const ListAppsBySkillIdQuerySchema = z.object({
skillId: IdSchema
});
......@@ -266,7 +283,10 @@ export const AppsBySkillIdItemSchema = z.object({
});
export type AppsBySkillIdItem = z.infer<typeof AppsBySkillIdItemSchema>;
export const ListAppsBySkillIdResponseSchema = z.array(AppsBySkillIdItemSchema);
export const ListAppsBySkillIdResponseSchema = z.object({
list: z.array(AppsBySkillIdItemSchema),
hiddenCount: z.number().int().nonnegative().describe('当前用户无权限查看的引用应用数量')
});
export type ListAppsBySkillIdResponse = z.infer<typeof ListAppsBySkillIdResponseSchema>;
export const CreateSkillFolderBodySchema = z.object({
......@@ -296,7 +316,8 @@ export const GetSkillFolderPathResponseSchema = z.array(
export type GetSkillFolderPathResponse = z.infer<typeof GetSkillFolderPathResponseSchema>;
export const ExportSkillQuerySchema = z.object({
skillId: IdSchema
skillId: IdSchema,
source: z.enum(['version', 'workspace']).optional().default('version')
});
export type ExportSkillQuery = z.infer<typeof ExportSkillQuerySchema>;
......@@ -329,7 +350,7 @@ export const ListSkillVersionsBodySchema = z.object({
skillId: IdSchema,
pageNum: z.number().int().positive().optional().describe('页码,从 1 开始'),
pageSize: z.number().int().positive().describe('每页数量'),
isActive: z.boolean().optional().describe('筛选是否为活跃版本')
isCurrent: z.boolean().optional().describe('筛选是否为当前版本')
});
export type ListSkillVersionsBody = z.infer<typeof ListSkillVersionsBodySchema>;
......@@ -337,9 +358,8 @@ export const SkillVersionListItemSchema = z.object({
_id: z.string(),
skillId: z.string(),
tmbId: z.string(),
version: z.number(),
versionName: z.string().optional(),
isActive: z.boolean(),
isCurrent: z.boolean().describe('是否为 skill 主表标记的当前版本'),
createdAt: z.string()
});
export type SkillVersionListItemType = z.infer<typeof SkillVersionListItemSchema>;
......@@ -375,7 +395,8 @@ export const ImportSkillMultipartRequestSchema = {
file: {
type: 'string' as const,
format: 'binary' as const,
description: '技能压缩包文件,支持 ZIP / TAR / TAR.GZ'
description:
'技能压缩包文件,支持 workspace 包(根目录包含非空 skills/)或单 skill 包(根目录或一级目录包含 SKILL.md),支持 ZIP / TAR / TAR.GZ'
},
name: {
type: 'string' as const,
......
import type { OpenAPIPath } from '../../type';
import { TagsMap } from '../../tag';
import type { OpenAPIPath } from '../../../type';
import { TagsMap } from '../../../tag';
import {
AppsBySkillIdItemSchema,
ListAppsBySkillIdResponseSchema,
CreateEditDebugSandboxBodySchema,
CreateEditDebugSandboxResponseSchema,
CreateSkillBodySchema,
......@@ -24,6 +24,8 @@ import {
SaveDeploySkillBodySchema,
SaveDeploySkillResponseSchema,
SkillDebugChatBodySchema,
SkillDebugSessionControlBodySchema,
SkillDebugSessionStopResponseSchema,
SkillDebugRecordsBodySchema,
SkillDebugRecordsResponseSchema,
SkillDebugSessionDeleteBodySchema,
......@@ -34,8 +36,8 @@ import {
UpdateSkillVersionBodySchema
} from './api';
export const AgentSkillsPath: OpenAPIPath = {
'/core/agentSkills/list': {
export const SkillPath: OpenAPIPath = {
'/core/ai/skill/list': {
post: {
summary: '获取技能列表',
description: '分页获取当前团队可见的系统技能或个人技能',
......@@ -59,7 +61,7 @@ export const AgentSkillsPath: OpenAPIPath = {
}
}
},
'/core/agentSkills/detail': {
'/core/ai/skill/detail': {
get: {
summary: '获取技能详情',
description: '根据 skillId 获取技能详情',
......@@ -79,7 +81,7 @@ export const AgentSkillsPath: OpenAPIPath = {
}
}
},
'/core/agentSkills/create': {
'/core/ai/skill/create': {
post: {
summary: '创建技能',
description: '创建一个新的技能,可选使用 AI 根据 requirements 生成 SKILL.md',
......@@ -103,7 +105,7 @@ export const AgentSkillsPath: OpenAPIPath = {
}
}
},
'/core/agentSkills/update': {
'/core/ai/skill/update': {
post: {
summary: '更新技能',
description: '更新技能名称、描述、分类和配置',
......@@ -122,7 +124,7 @@ export const AgentSkillsPath: OpenAPIPath = {
}
}
},
'/core/agentSkills/delete': {
'/core/ai/skill/delete': {
delete: {
summary: '删除技能',
description: '根据 skillId 删除技能',
......@@ -137,7 +139,7 @@ export const AgentSkillsPath: OpenAPIPath = {
}
}
},
'/core/agentSkills/import': {
'/core/ai/skill/import': {
post: {
summary: '导入技能',
description: '上传 ZIP / TAR / TAR.GZ 技能压缩包并导入为技能',
......@@ -161,7 +163,7 @@ export const AgentSkillsPath: OpenAPIPath = {
}
}
},
'/core/agentSkills/export': {
'/core/ai/skill/export': {
get: {
summary: '导出技能',
description: '下载技能 ZIP 包',
......@@ -184,7 +186,7 @@ export const AgentSkillsPath: OpenAPIPath = {
}
}
},
'/core/agentSkills/apps': {
'/core/ai/skill/apps': {
get: {
summary: '查询引用技能的应用',
description: '查询使用指定 skillId 的应用列表',
......@@ -197,14 +199,14 @@ export const AgentSkillsPath: OpenAPIPath = {
description: '成功返回引用应用列表',
content: {
'application/json': {
schema: AppsBySkillIdItemSchema.array()
schema: ListAppsBySkillIdResponseSchema
}
}
}
}
}
},
'/core/agentSkills/folder/create': {
'/core/ai/skill/folder/create': {
post: {
summary: '创建技能文件夹',
description: '在技能目录树中创建一个文件夹',
......@@ -228,7 +230,7 @@ export const AgentSkillsPath: OpenAPIPath = {
}
}
},
'/core/agentSkills/folder/path': {
'/core/ai/skill/folder/path': {
get: {
summary: '获取技能文件夹路径',
description: '根据当前 skillId 返回目录路径',
......@@ -248,7 +250,7 @@ export const AgentSkillsPath: OpenAPIPath = {
}
}
},
'/core/agentSkills/edit': {
'/core/ai/skill/edit': {
post: {
summary: '创建编辑调试沙盒',
description: '为技能创建 edit-debug 沙盒,返回 SSE sandboxStatus 事件流',
......@@ -272,7 +274,7 @@ export const AgentSkillsPath: OpenAPIPath = {
}
}
},
'/core/agentSkills/save-deploy': {
'/core/ai/skill/save-deploy': {
post: {
summary: '保存并发布技能',
description: '从 edit-debug 沙盒打包当前技能并创建新版本',
......@@ -296,7 +298,7 @@ export const AgentSkillsPath: OpenAPIPath = {
}
}
},
'/core/agentSkills/debugChat': {
'/core/ai/skill/debugChat': {
post: {
summary: '技能调试对话',
description: '基于 edit-debug 沙盒发起技能调试对话,返回 SSE 流',
......@@ -322,7 +324,7 @@ export const AgentSkillsPath: OpenAPIPath = {
}
}
},
'/core/agentSkills/debugSession/list': {
'/core/ai/skill/debugSession/list': {
get: {
summary: '获取技能调试会话列表',
description: '分页获取技能的调试会话',
......@@ -342,7 +344,7 @@ export const AgentSkillsPath: OpenAPIPath = {
}
}
},
'/core/agentSkills/debugSession/delete': {
'/core/ai/skill/debugSession/delete': {
post: {
summary: '删除技能调试会话',
description: '软删除一个技能调试会话',
......@@ -361,7 +363,31 @@ export const AgentSkillsPath: OpenAPIPath = {
}
}
},
'/core/agentSkills/debugSession/records': {
'/core/ai/skill/debugSession/stop': {
post: {
summary: '停止技能调试对话',
description: '停止指定技能调试会话中正在运行的工作流',
tags: [TagsMap.aiSkill],
requestBody: {
content: {
'application/json': {
schema: SkillDebugSessionControlBodySchema
}
}
},
responses: {
200: {
description: '成功停止调试对话',
content: {
'application/json': {
schema: SkillDebugSessionStopResponseSchema
}
}
}
}
}
},
'/core/ai/skill/debugSession/records': {
post: {
summary: '获取技能调试会话记录',
description: '分页获取技能调试会话的聊天记录',
......@@ -385,10 +411,10 @@ export const AgentSkillsPath: OpenAPIPath = {
}
}
},
'/core/agentSkills/version/list': {
'/core/ai/skill/version/list': {
post: {
summary: '获取技能版本列表',
description: '分页获取指定技能的版本列表,按版本号倒序排列',
description: '分页获取指定技能的版本列表,按创建时间倒序排列',
tags: [TagsMap.aiSkill],
requestBody: {
content: {
......@@ -409,7 +435,7 @@ export const AgentSkillsPath: OpenAPIPath = {
}
}
},
'/core/agentSkills/version/update': {
'/core/ai/skill/version/update': {
post: {
summary: '更新技能版本名称',
description: '更新指定技能版本的名称',
......@@ -428,10 +454,10 @@ export const AgentSkillsPath: OpenAPIPath = {
}
}
},
'/core/agentSkills/version/switch': {
'/core/ai/skill/version/switch': {
post: {
summary: '切换技能活跃版本',
description: '将指定版本设置为活跃版本,同时取消其他版本的活跃状态',
summary: '切换技能当前版本',
description: '将 skill 主表的当前版本指向指定版本',
tags: [TagsMap.aiSkill],
requestBody: {
content: {
......@@ -442,7 +468,7 @@ export const AgentSkillsPath: OpenAPIPath = {
},
responses: {
200: {
description: '成功切换活跃版本'
description: '成功切换当前版本'
}
}
}
......
......@@ -49,7 +49,8 @@ export const InitChatResponseSchema = z.object({
intro: z.string().describe('应用简介'),
canUse: z.boolean().optional().describe('是否可用'),
type: z.enum(AppTypeEnum).describe('应用类型'),
pluginInputs: z.array(FlowNodeInputItemTypeSchema).describe('插件输入')
pluginInputs: z.array(FlowNodeInputItemTypeSchema).describe('插件输入'),
useAgentSandbox: z.boolean().optional().describe('是否使用虚拟机')
})
.describe('应用配置')
});
......
......@@ -6,7 +6,7 @@ import { AppPath } from './core/app';
import { SupportPath } from './support';
import { DatasetPath } from './core/dataset';
import { AIPath } from './core/ai';
import { AgentSkillsPath } from './core/agentSkills';
import { SkillPath } from './core/ai/skill';
export const openAPIDocument = createDocument({
openapi: '3.1.0',
......@@ -22,7 +22,7 @@ export const openAPIDocument = createDocument({
...PluginPath,
...SupportPath,
...AIPath,
...AgentSkillsPath
...SkillPath
},
servers: [{ url: '/api' }],
'x-tagGroups': [
......@@ -36,7 +36,7 @@ export const openAPIDocument = createDocument({
},
{
name: 'AI 相关',
tags: [TagsMap.aiSkill, TagsMap.sandbox]
tags: [TagsMap.aiSkill, TagsMap.sandbox, TagsMap.aiCommon]
},
{
name: '对话模块配置',
......@@ -78,11 +78,6 @@ export const openAPIDocument = createDocument({
]
},
{
name: '通用-核心功能',
tags: [TagsMap.aiCommon]
},
{
name: '通用-辅助功能',
tags: [TagsMap.customDomain, TagsMap.apiKey]
},
......
{
"name": "@fastgpt/global",
"version": "1.0.0",
"type": "module",
"scripts": {
"test": "vitest run -c vitest.config.ts",
"test:watch": "vitest -c vitest.config.ts"
......
......@@ -45,6 +45,13 @@ describe('getErrText', () => {
expect(getErrText(err)).toBe('https://xxx xxx');
});
it('should parse errorText field', () => {
const err = {
errorText: 'Sandbox is not configured'
};
expect(getErrText(err)).toBe('Sandbox is not configured');
});
});
describe('UserError', () => {
......
......@@ -22,4 +22,15 @@ describe('generateSandboxId', () => {
expect(id).toHaveLength(16);
expect(id).toMatch(/^[0-9a-f]{16}$/);
});
it('should hash mixed-case source into a lowercase hex string', () => {
const id = generateSandboxId(
'69ce5237057b145f058436f4',
'69ce490acaad46cd13982521',
'debug-69ce5237057b145f058436f4-7BdojPlukIQw'
);
expect(id).toHaveLength(16);
expect(id).toMatch(/^[0-9a-f]{16}$/);
});
});
......@@ -7,7 +7,7 @@ import {
import { FlowNodeTypeEnum } from '@fastgpt/global/core/workflow/node/constant';
import { PublishChannelEnum } from '@fastgpt/global/support/outLink/constant';
import type { ChatItemMiniType, ChatHistoryItemResType } from '@fastgpt/global/core/chat/type';
import { SANDBOX_TOOL_NAME } from '@fastgpt/global/core/ai/sandbox/constants';
import { SANDBOX_SHELL_TOOL_NAME } from '@fastgpt/global/core/ai/sandbox/tools';
import {
concatHistories,
getChatTitleFromChatMessage,
......@@ -223,7 +223,7 @@ describe('filterPublicNodeResponseData', () => {
moduleName: 'Sandbox',
moduleType: FlowNodeTypeEnum.tool,
runningTime: 0.8,
toolId: SANDBOX_TOOL_NAME,
toolId: SANDBOX_SHELL_TOOL_NAME,
toolInput: {
command: 'ls'
},
......@@ -237,7 +237,7 @@ describe('filterPublicNodeResponseData', () => {
{
moduleType: FlowNodeTypeEnum.tool,
runningTime: 0.8,
toolId: SANDBOX_TOOL_NAME
toolId: SANDBOX_SHELL_TOOL_NAME
}
]);
});
......
......@@ -10,7 +10,6 @@ import {
import { getLogger, LogCategories } from '../logger';
import { newQueueRedisConnection, newWorkerRedisConnection } from '../redis';
import { delay } from '@fastgpt/global/common/system/utils';
import { getErrText } from '@fastgpt/global/common/error/utils';
const logger = getLogger(LogCategories.INFRA.QUEUE);
......@@ -28,10 +27,12 @@ export enum QueueNames {
evaluation = 'evaluation',
s3FileDelete = 's3FileDelete',
collectionUpdate = 'collectionUpdate',
agentSkillCreate = 'agentSkillCreate',
// Delete Queue
datasetDelete = 'datasetDelete',
appDelete = 'appDelete',
agentSkillDelete = 'agentSkillDelete',
teamDelete = 'teamDelete',
// Publish
......
......@@ -102,14 +102,28 @@ export const multer = {
return reject(new Error('File not found'));
}
const data = (() => {
if (!request.body?.data) return {};
const bodyFields =
request.body && typeof request.body === 'object'
? (request.body as Record<string, unknown>)
: {};
const plainFields = Object.fromEntries(
Object.entries(bodyFields).filter(([key]) => key !== 'data')
);
const parsedData = (() => {
const rawData = bodyFields.data;
if (typeof rawData !== 'string') return {};
try {
return JSON.parse(request.body.data);
const parsed = JSON.parse(rawData);
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
} catch {
return {};
}
})();
// 支持 data JSON 包装和普通 multipart 字段;data 中的值优先级更高,保持旧兼容语义。
const data = {
...plainFields,
...parsedData
} as T;
resolve({
data,
......
......@@ -132,7 +132,7 @@ export class S3BaseBucket {
}
async removeObject(objectKey: string): Promise<void> {
this.client.deleteObject({ key: objectKey }).catch((err) => {
await this.client.deleteObject({ key: objectKey }).catch((err) => {
if (isFileNotFoundError(err)) {
return Promise.resolve();
}
......
......@@ -37,36 +37,57 @@ export const addS3DelJob = async (data: S3MQJobData): Promise<void> => {
await queue.add('delete-s3-files', data, { jobId, ...jobOption });
};
const assertNoFailedKeys = (failedKeys: string[] | undefined, action: string) => {
if (!failedKeys || failedKeys.length === 0) return;
const sampleKeys = failedKeys.slice(0, 5).join(', ');
throw new Error(
`Failed to delete ${failedKeys.length} S3 object(s) by ${action}. Sample keys: ${sampleKeys}`
);
};
export const executeS3DeleteJob = async ({ prefix, bucketName, key, keys }: S3MQJobData) => {
const bucket = global.s3BucketMap?.[bucketName];
if (!bucket) {
logger.error('S3 bucket not found for delete job', { bucketName });
throw new Error(`S3 bucket not found for delete job: ${bucketName}`);
}
if (key) {
keys = [key];
}
if (keys) {
logger.debug('S3 delete by keys', { bucketName, count: keys.length });
const result = (await bucket.client.deleteObjectsByMultiKeys({ keys })) as
| { keys?: string[] }
| undefined;
assertNoFailedKeys(result?.keys, 'keys');
await batchRun(keys, async (key) => {
if (key.includes('-parsed/')) return;
const fileParsedPrefix = `${path.dirname(key)}/${path.basename(key, path.extname(key))}-parsed`;
const result = (await bucket.client.deleteObjectsByPrefix({ prefix: fileParsedPrefix })) as
| { keys?: string[] }
| undefined;
assertNoFailedKeys(result?.keys, `parsed prefix ${fileParsedPrefix}`);
});
}
if (prefix) {
logger.info('S3 delete by prefix started', { bucketName, prefix });
const result = (await bucket.client.deleteObjectsByPrefix({ prefix })) as
| { keys?: string[] }
| undefined;
assertNoFailedKeys(result?.keys, `prefix ${prefix}`);
logger.info('S3 delete by prefix completed', { bucketName, prefix });
}
};
export const startS3DelWorker = async () => {
return getWorker<S3MQJobData>(
QueueNames.s3FileDelete,
async (job) => {
let { prefix, bucketName, key, keys } = job.data;
const bucket = global.s3BucketMap[bucketName];
if (!bucket) {
logger.error('S3 bucket not found for delete job', { bucketName });
return;
}
if (key) {
keys = [key];
}
if (keys) {
logger.debug('S3 delete by keys', { bucketName, count: keys.length });
await bucket.client.deleteObjectsByMultiKeys({ keys });
await batchRun(keys, async (key) => {
if (key.includes('-parsed/')) return;
const fileParsedPrefix = `${path.dirname(key)}/${path.basename(key, path.extname(key))}-parsed`;
await bucket.client.deleteObjectsByPrefix({ prefix: fileParsedPrefix });
});
}
if (prefix) {
logger.info('S3 delete by prefix started', { bucketName, prefix });
bucket.client.deleteObjectsByPrefix({ prefix });
logger.info('S3 delete by prefix completed', { bucketName, prefix });
}
await executeS3DeleteJob(job.data);
},
{
concurrency: 6
......
import type { S3SkillSource } from './index';
declare global {
var skillBucket: S3SkillSource;
}
export {};
import type { ClientSession } from 'mongoose';
import { S3PrivateBucket } from '../../buckets/private';
import { removeS3TTL } from '../../utils';
const SKILL_PACKAGE_ROOT_PREFIX = 'agent-skills';
/**
* 生成某个 Skill 在私有对象存储中的包前缀。
*
* 删除 Skill 时按这个前缀异步清理所有版本包;具体版本包使用 Mongo versionId 作为对象名,
* 避免版本号重排或事务回滚导致 key 复用。
*/
export function getSkillPackagePrefix(params: { teamId: string; skillId: string }): string {
const { teamId, skillId } = params;
return `${[SKILL_PACKAGE_ROOT_PREFIX, teamId, skillId].join('/')}/`;
}
/**
* 生成 Skill 版本包的私有对象存储 key。
*/
export function getSkillPackageKey(params: {
teamId: string;
skillId: string;
packageObjectId: string;
}): string {
const { teamId, skillId, packageObjectId } = params;
return `${getSkillPackagePrefix({ teamId, skillId })}${packageObjectId}.zip`;
}
export class S3SkillSource extends S3PrivateBucket {
constructor() {
super();
}
/**
* 上传 Skill package,并沿用通用 S3 上传封装写入临时 TTL。
*
* 调用方在 Mongo 事务提交 version/currentVersionId 时移除 TTL;事务失败时保留 TTL,
* 由已有 S3 TTL cron 清理孤儿包。
*/
uploadPackage(params: {
teamId: string;
skillId: string;
packageObjectId: string;
body: Buffer;
expiredTime?: Date;
}) {
const { teamId, skillId, packageObjectId, body, expiredTime } = params;
const key = getSkillPackageKey({ teamId, skillId, packageObjectId });
return this.uploadFileByBody({
key,
body,
contentType: 'application/zip',
filename: 'package.zip',
...(expiredTime && { expiredTime })
});
}
deleteSkillPackagesByPrefix(params: { teamId: string; skillId: string }) {
return this.addDeleteJob({
prefix: getSkillPackagePrefix(params)
});
}
removePackageTTL(key: string, session?: ClientSession) {
return removeS3TTL({
key,
bucketName: 'private',
session
});
}
}
export function getS3SkillSource() {
if (global.skillBucket) {
return global.skillBucket;
}
global.skillBucket = new S3SkillSource();
return global.skillBucket;
}
......@@ -22,6 +22,10 @@ export const initFastGPTConfig = (config?: FastGPTConfigFileType) => {
config.feConfigs.customPdfParsePrice = config.systemEnv.customPdfParse?.price || 0;
config.feConfigs.uploadFileMaxSize = serviceEnv.UPLOAD_FILE_MAX_SIZE;
config.feConfigs.uploadFileMaxAmount = serviceEnv.UPLOAD_FILE_MAX_AMOUNT;
config.feConfigs.limit = {
...config.feConfigs.limit,
agentSkillMaxUploadBytes: serviceEnv.AGENT_SKILL_MAX_UPLOAD_SIZE * 1024 * 1024
};
global.feConfigs = config.feConfigs;
global.systemEnv = config.systemEnv;
......
import decompress from 'decompress';
export type ArchiveFormat = 'zip' | 'tar' | 'tar.gz';
export type ArchiveFileMap = Record<string, Buffer>;
/** Detect supported format from filename extension. Returns null if unsupported. */
export function getSupportedArchiveFormat(filename: string): ArchiveFormat | null {
const lower = filename.toLowerCase();
if (lower.endsWith('.tar.gz') || lower.endsWith('.tgz')) return 'tar.gz';
if (lower.endsWith('.tar')) return 'tar';
if (lower.endsWith('.zip')) return 'zip';
return null;
}
/**
* Extract archive file (zip/tar/tar.gz) to a file map.
* Path traversal entries are filtered out for security.
* Total uncompressed size is capped to prevent Zip Bomb OOM attacks.
*/
export async function extractToFileMap(
filePath: string,
maxUncompressedBytes = 200 * 1024 * 1024
): Promise<ArchiveFileMap> {
const files = await decompress(filePath);
const fileMap: ArchiveFileMap = {};
let totalSize = 0;
for (const file of files) {
if (file.type === 'directory') continue;
const normalized = file.path.replace(/\\/g, '/').replace(/^\/+/, '');
// Filter path traversal
if (!normalized || normalized.includes('../')) continue;
totalSize += file.data.length;
if (totalSize > maxUncompressedBytes) {
throw new Error(
`Uncompressed archive exceeds maximum allowed size (${maxUncompressedBytes / 1024 / 1024}MB)`
);
}
fileMap[normalized] = file.data;
}
return fileMap;
}
/** Find SKILL.md key in file map (case-insensitive, root or single-level subdir). */
export function findSkillMdKey(fileMap: ArchiveFileMap): string | null {
const paths = Object.keys(fileMap);
const rootKey = paths.find((p) => !p.includes('/') && p.toLowerCase() === 'skill.md');
if (rootKey) return rootKey;
return (
paths.find((p) => {
const parts = p.split('/');
return parts.length === 2 && parts[1].toLowerCase() === 'skill.md';
}) ?? null
);
}
/** Get root directory prefix from SKILL.md path (e.g. 'my-skill/' or ''). */
export function getRootPrefix(skillMdKey: string): string {
const idx = skillMdKey.lastIndexOf('/');
return idx === -1 ? '' : skillMdKey.slice(0, idx + 1);
}
/** Strip root prefix from all keys in file map. */
export function stripRootPrefix(fileMap: ArchiveFileMap, rootPrefix: string): ArchiveFileMap {
if (!rootPrefix) return fileMap;
const result: ArchiveFileMap = {};
for (const [key, value] of Object.entries(fileMap)) {
const stripped = key.startsWith(rootPrefix) ? key.slice(rootPrefix.length) : key;
if (stripped) result[stripped] = value;
}
return result;
}
/** SKILL.md content together with its relative path inside the archive. */
export type SkillMdInfo = { content: string; relativePath: string };
/**
* Extract SKILL.md content and its relative path from a ZIP buffer without writing to disk.
* Searches the same locations as findSkillMdKey:
* - root: SKILL.md
* - one level deep: {dir}/SKILL.md
* Returns null when SKILL.md is not found.
*/
export async function extractSkillMdInfoFromBuffer(buffer: Buffer): Promise<SkillMdInfo | null> {
const files = await decompress(buffer);
const target = files.find((f) => {
const p = f.path.replace(/\\/g, '/').replace(/^\//, '');
const parts = p.split('/');
if (parts.length === 1 && parts[0].toLowerCase() === 'skill.md') return true;
if (parts.length === 2 && parts[1].toLowerCase() === 'skill.md') return true;
return false;
});
if (!target || !target.data) return null;
const content = Buffer.isBuffer(target.data)
? target.data.toString('utf-8')
: String(target.data);
const relativePath = target.path.replace(/\\/g, '/').replace(/^\//, '');
return { content, relativePath };
}
/**
* Extract SKILL.md content from a ZIP buffer without writing to disk.
* Searches the same locations as findSkillMdKey:
* - root: SKILL.md
* - one level deep: {dir}/SKILL.md
* Returns null when SKILL.md is not found.
*/
export async function extractSkillMdContentFromBuffer(buffer: Buffer): Promise<string | null> {
const info = await extractSkillMdInfoFromBuffer(buffer);
return info ? info.content : null;
}
export { collectionName, MongoSandboxInstance } from '../ai/sandbox/schema';
/**
* Skill Storage Service
*
* Provides utilities for uploading, downloading, and managing skill packages
* in object storage (MinIO/S3) using @fastgpt-sdk/storage.
*/
import { S3PrivateBucket } from '../../common/s3/buckets/private';
import type { ClientSession } from '../../common/mongo';
import { getSkillSizeLimits } from './sandboxConfig';
export type SkillStorageInfo = {
bucket: string;
key: string;
size: number;
checksum?: string;
};
export type UploadSkillPackageParams = {
teamId: string;
skillId: string;
version: number;
zipBuffer: Buffer;
checksum?: string;
};
export type DownloadSkillPackageParams = {
storageInfo: SkillStorageInfo;
};
export type GetSkillStorageInfoParams = {
teamId: string;
skillId: string;
version: number;
};
/**
* Generate storage key for skill package
*/
export function getSkillStorageKey(teamId: string, skillId: string, version: number): string {
return `agent-skills/${teamId}/${skillId}/v${version}/package.zip`;
}
/**
* Parse storage key to extract teamId, skillId, and version
*/
export function parseSkillStorageKey(
key: string
): { teamId: string; skillId: string; version: number } | null {
const match = key.match(/^agent-skills\/([^/]+)\/([^/]+)\/v(\d+)\/package\.zip$/);
if (!match) return null;
return {
teamId: match[1],
skillId: match[2],
version: parseInt(match[3], 10)
};
}
/**
* Upload skill package to MinIO/S3 storage
*/
export async function uploadSkillPackage(
params: UploadSkillPackageParams
): Promise<SkillStorageInfo> {
const { teamId, skillId, version, zipBuffer, checksum } = params;
// Generate storage key
const key = getSkillStorageKey(teamId, skillId, version);
// Use S3PrivateBucket for upload
const bucket = new S3PrivateBucket();
await bucket.client.uploadObject({
key,
body: zipBuffer,
contentType: 'application/zip',
metadata: {
'x-amz-meta-team-id': teamId,
'x-amz-meta-skill-id': skillId,
'x-amz-meta-version': version.toString(),
...(checksum && { 'x-amz-meta-checksum': checksum })
}
});
return {
bucket: bucket.bucketName,
key,
size: zipBuffer.length,
...(checksum && { checksum })
};
}
/**
* Download skill package from MinIO/S3 storage
*/
export async function downloadSkillPackage(params: DownloadSkillPackageParams): Promise<Buffer> {
const { storageInfo } = params;
const { maxDownloadBytes } = getSkillSizeLimits();
const bucket = new S3PrivateBucket();
const response = await bucket.client.downloadObject({
key: storageInfo.key
});
if (!response.body) {
throw new Error(`Failed to download skill package: ${storageInfo.key}`);
}
// Convert stream to buffer with size limit to prevent OOM
const chunks: Buffer[] = [];
let totalSize = 0;
for await (const chunk of response.body) {
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
totalSize += buf.length;
if (totalSize > maxDownloadBytes) {
throw new Error(
`Skill package exceeds maximum allowed size (${maxDownloadBytes / 1024 / 1024}MB)`
);
}
chunks.push(buf);
}
return Buffer.concat(chunks);
}
/**
* Delete skill package from MinIO/S3 storage
*/
export async function deleteSkillPackage(storageInfo: SkillStorageInfo): Promise<void> {
const bucket = new S3PrivateBucket();
await bucket.client.deleteObject({
key: storageInfo.key
});
}
/**
* Delete all packages for a skill across all versions using prefix deletion.
* Fire-and-forget: enqueues to BullMQ and returns immediately.
* Prefix covers: agent-skills/{teamId}/{skillId}/ (all versions)
*/
export function deleteSkillAllPackages(teamId: string, skillId: string): void {
const prefix = `agent-skills/${teamId}/${skillId}/`;
const bucket = new S3PrivateBucket();
bucket.addDeleteJob({ prefix });
}
/**
* Check if skill package exists in storage
*/
export async function checkSkillPackageExists(storageInfo: SkillStorageInfo): Promise<boolean> {
try {
const bucket = new S3PrivateBucket();
const { exists } = await bucket.client.checkObjectExists({
key: storageInfo.key
});
return exists ?? false;
} catch {
return false;
}
}
/**
* Get skill storage info for a specific version
*/
export async function getSkillStorageInfo(
params: GetSkillStorageInfoParams
): Promise<SkillStorageInfo & { exists: boolean }> {
const { teamId, skillId, version } = params;
const key = getSkillStorageKey(teamId, skillId, version);
const bucket = new S3PrivateBucket();
// Check if object exists and get metadata
const { exists } = await bucket.client.checkObjectExists({ key });
if (!exists) {
return {
bucket: bucket.bucketName,
key,
size: 0,
exists: false
};
}
// Get object metadata to get size
try {
const metadata = await bucket.client.getObjectMetadata({ key });
return {
bucket: bucket.bucketName,
key,
size: metadata.contentLength ?? 0,
exists: true
};
} catch {
return {
bucket: bucket.bucketName,
key,
size: 0,
exists: true
};
}
}
/**
* Copy skill package to a new version
*/
export async function copySkillPackage(
sourceStorageInfo: SkillStorageInfo,
targetParams: Omit<UploadSkillPackageParams, 'zipBuffer' | 'checksum'>
): Promise<SkillStorageInfo> {
// Download the source package
const zipBuffer = await downloadSkillPackage({
storageInfo: sourceStorageInfo
});
// Upload to the new location
return uploadSkillPackage({
...targetParams,
zipBuffer
});
}
/**
* 获取会话制品列表
*/
export async function listSessionArtifacts(sessionId: string): Promise<string[]> {
const prefix = `agent-sessions/${sessionId}/`;
const bucket = new S3PrivateBucket();
const { keys } = await bucket.client.listObjects({ prefix });
return keys.map((key) => key.replace(prefix, ''));
}
/**
* 下载制品
*/
export async function downloadSessionArtifact(
sessionId: string,
filePath: string
): Promise<Buffer> {
const key = `agent-sessions/${sessionId}/${filePath}`;
const bucket = new S3PrivateBucket();
const response = await bucket.client.downloadObject({ key });
if (!response.body) {
throw new Error(`Failed to download artifact: ${key}`);
}
const chunks: Buffer[] = [];
for await (const chunk of response.body) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
}
return Buffer.concat(chunks);
}
/**
* 清理单个会话的所有制品
*/
export async function cleanSessionArtifacts(sessionId: string): Promise<{ deletedCount: number }> {
const prefix = `agent-sessions/${sessionId}/`;
const bucket = new S3PrivateBucket();
const { keys: failedKeys } = await bucket.client.deleteObjectsByPrefix({ prefix });
// deleteObjectsByPrefix 不返回实际删除数量,以 0 失败 key 数为成功标志
return { deletedCount: failedKeys.length === 0 ? 1 : 0 };
}
/**
* 批量清理多个会话的制品
*/
export async function cleanExpiredSessionArtifacts(
sessionIds: string[]
): Promise<{ deletedCount: number }> {
let totalDeleted = 0;
for (const sessionId of sessionIds) {
const { deletedCount } = await cleanSessionArtifacts(sessionId);
totalDeleted += deletedCount;
}
return { deletedCount: totalDeleted };
}
import type { SkillPackageType } from '@fastgpt/global/core/agentSkills/type';
import { AgentSkillCategoryEnum } from '@fastgpt/global/core/agentSkills/constants';
/**
* Parse YAML frontmatter from markdown content
* Returns { frontmatter: object, content: string }
*/
export function parseSkillMarkdown(markdown: string): {
frontmatter: Record<string, any>;
content: string;
error?: string;
} {
// Check for YAML frontmatter delimited by ---
const frontmatterRegex = /^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/;
const match = markdown.match(frontmatterRegex);
if (!match) {
return {
frontmatter: {},
content: markdown,
error: 'SKILL.md must contain YAML frontmatter (delimited by ---)'
};
}
const yamlContent = match[1];
const bodyContent = match[2];
try {
const frontmatter = parseYamlFrontmatter(yamlContent);
return {
frontmatter,
content: bodyContent
};
} catch (error: any) {
return {
frontmatter: {},
content: markdown,
error: `Failed to parse frontmatter: ${error.message}`
};
}
}
/**
* Simple YAML parser for frontmatter
* Handles simple key: value and nested objects
*/
function parseYamlFrontmatter(yaml: string): Record<string, any> {
const result: Record<string, any> = {};
const lines = yaml.split('\n');
let currentObj = result;
const stack: { key: string; obj: Record<string, any> }[] = [];
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
// Check for object nesting (metadata:)
if (trimmed.endsWith(':')) {
const key = trimmed.slice(0, -1).trim();
currentObj[key] = {};
stack.push({ key, obj: currentObj });
currentObj = currentObj[key] as Record<string, any>;
continue;
}
// Parse key: value
const colonIndex = line.indexOf(':');
if (colonIndex === -1) continue;
const key = line.slice(0, colonIndex).trim();
const value = line.slice(colonIndex + 1).trim();
// Handle different value types
if (value.startsWith('"') || value.startsWith("'")) {
// String literal
currentObj[key] = value.slice(1, -1);
} else if (value === 'true') {
currentObj[key] = true;
} else if (value === 'false') {
currentObj[key] = false;
} else if (!isNaN(Number(value)) && value !== '') {
currentObj[key] = Number(value);
} else if (value === 'null') {
currentObj[key] = null;
} else if (value.startsWith('[') && value.endsWith(']')) {
// Array
const arrayContent = value.slice(1, -1).trim();
currentObj[key] = arrayContent
? arrayContent.split(',').map((item) => item.trim().replace(/["']/g, ''))
: [];
} else {
// // Plain string
currentObj[key] = value;
}
}
return result;
}
/**
* Extract skill metadata from SKILL.md frontmatter
* Returns FastGPT skill object format
*/
export function extractSkillFromMarkdown(markdown: string): { skill: any; error?: string } {
const { frontmatter, content, error } = parseSkillMarkdown(markdown);
if (error) {
return { skill: null, error };
}
// Validate required fields
if (!frontmatter.name) {
return { skill: null, error: 'Frontmatter field "name" is required' };
}
if (!frontmatter.description) {
return { skill: null, error: 'Frontmatter field "description" is required' };
}
// Ensure name is always treated as a string (YAML parser may convert numeric names to number)
const skillName = String(frontmatter.name);
// Validate name format (lowercase, numbers, hyphens only; no consecutive hyphens; no leading/trailing hyphens)
const nameRegex = /^[a-z0-9]([a-z0-9]|-(?!-))*[a-z0-9]$|^[a-z0-9]$/;
if (!nameRegex.test(skillName)) {
return {
skill: null,
error:
'Name must contain only lowercase letters, numbers, and hyphens; cannot start/end with hyphen; no consecutive hyphens'
};
}
// Validate name length (max 64 per spec, but FastGPT uses 50)
if (skillName.length > 50) {
return { skill: null, error: 'Name must be less than 50 characters' };
}
// Truncate description if too long (max 500 characters)
const description = frontmatter.description.slice(0, 500);
// Build FastGPT skill object
const skill: any = {
name: skillName,
description,
category: [AgentSkillCategoryEnum.other], // default
config: {}
};
// Map frontmatter fields to FastGPT format
if (frontmatter.license) {
skill.config.license = frontmatter.license;
}
if (frontmatter.compatibility) {
skill.config.compatibility = frontmatter.compatibility;
}
if (frontmatter['allowed-tools']) {
skill.config['allowed-tools'] = frontmatter['allowed-tools'];
}
// Map metadata fields to config
if (frontmatter.metadata && typeof frontmatter.metadata === 'object') {
const metadata = frontmatter.metadata as Record<string, any>;
// category from metadata
if (metadata.category) {
if (Array.isArray(metadata.category)) {
skill.category = metadata.category;
} else if (typeof metadata.category === 'string') {
skill.category = metadata.category.split(',').map((c) => c.trim());
}
// Validate categories
const validCategories = Object.values(AgentSkillCategoryEnum);
const invalidCategories = skill.category.filter(
(c: string) => !validCategories.includes(c as AgentSkillCategoryEnum)
);
if (invalidCategories.length > 0) {
skill.category = ['other']; // fallback to default
}
}
// Copy other metadata to config
for (const [key, value] of Object.entries(metadata)) {
if (key !== 'category') {
skill.config[key] = value;
}
}
}
return { skill };
}
/**
* Validate skill package structure
*/
export function validateSkillPackage(data: any): { valid: boolean; error?: string } {
if (!data || typeof data !== 'object') {
return { valid: false, error: 'Invalid package format' };
}
const { skill } = data;
// Check required fields
if (!skill || typeof skill !== 'object') {
return { valid: false, error: 'Missing skill metadata' };
}
if (!skill.name || typeof skill.name !== 'string' || skill.name.trim().length === 0) {
return { valid: false, error: 'Skill name is required' };
}
if (skill.name.length > 50) {
return { valid: false, error: 'Skill name must be less than 50 characters' };
}
// Validate description length
if (skill.description && skill.description.length > 500) {
return { valid: false, error: 'Description must be less than 500 characters' };
}
// Validate category
if (skill.category) {
if (!Array.isArray(skill.category)) {
return { valid: false, error: 'Category must be an array' };
}
const validCategories = Object.values(AgentSkillCategoryEnum);
const invalidCategories = skill.category.filter(
(c: string) => !validCategories.includes(c as AgentSkillCategoryEnum)
);
if (invalidCategories.length > 0) {
return { valid: false, error: `Invalid categories: ${invalidCategories.join(', ')}` };
}
}
// Validate config
if (skill.config && typeof skill.config !== 'object') {
return { valid: false, error: 'Config must be an object' };
}
return { valid: true };
}
/**
* Parse skill package from JSON string or object
*/
export function parseSkillPackage(data: string | object): {
success: boolean;
package?: SkillPackageType;
error?: string;
} {
try {
const parsed = typeof data === 'string' ? JSON.parse(data) : data;
const validation = validateSkillPackage(parsed);
if (!validation.valid) {
return { success: false, error: validation.error };
}
return {
success: true,
package: parsed as SkillPackageType
};
} catch (error) {
return { success: false, error: 'Failed to parse skill package: ' + (error as Error).message };
}
}
/**
* Sanitize skill name for file system
*/
export function sanitizeSkillName(name: string): string {
return name
.trim()
.toLowerCase()
.replace(/[^a-z0-9\u4e00-\u9fa5]/g, '_') // Allow Chinese characters
.replace(/_+/g, '_')
.substring(0, 50);
}
/**
* Create default skill package template
*/
export function createSkillTemplate(name: string): SkillPackageType {
return {
skill: {
name: name || 'New Skill',
description: 'Enter a description for your skill',
category: [AgentSkillCategoryEnum.other],
config: {}
}
};
}
/**
* Skill Version Controller
*
* Provides CRUD operations for skill version management.
*/
import { MongoAgentSkillsVersion } from './schema';
import type { ClientSession } from '../../../common/mongo';
import type { AgentSkillsVersionSchemaType } from '@fastgpt/global/core/agentSkills/type';
export type CreateVersionData = {
skillId: string;
tmbId: string;
version: number;
versionName?: string;
storage: {
bucket: string;
key: string;
size: number;
checksum?: string;
};
importSource?: {
originalFilename: string;
importedAt: Date;
};
};
export type UpdateVersionData = Partial<Omit<CreateVersionData, 'skillId' | 'version'>>;
/**
* Create a new skill version
*/
export async function createVersion(
data: CreateVersionData,
session?: ClientSession
): Promise<string> {
const version = new MongoAgentSkillsVersion({
...data,
isActive: true,
isDeleted: false,
createdAt: new Date()
});
await version.save({ session });
return version._id.toString();
}
/**
* Get the next version number for a skill.
* Should be called inside a transaction session to avoid version number races.
*/
export async function getNextVersionNumber(
skillId: string,
session?: ClientSession
): Promise<number> {
const lastVersion = await MongoAgentSkillsVersion.findOne(
{ skillId, isDeleted: false },
{ version: 1 },
{ sort: { version: -1 }, session }
).lean();
return (lastVersion?.version ?? -1) + 1;
}
/**
* Get a specific version by skillId and version number
*/
export async function getVersionBySkillIdAndVersion(
skillId: string,
version: number
): Promise<AgentSkillsVersionSchemaType | null> {
const versionDoc = await MongoAgentSkillsVersion.findOne({
skillId,
version,
isDeleted: false
}).lean();
return versionDoc as AgentSkillsVersionSchemaType | null;
}
/**
* Get the active version for a skill
*/
export async function getActiveVersion(
skillId: string
): Promise<AgentSkillsVersionSchemaType | null> {
const version = await MongoAgentSkillsVersion.findOne({
skillId,
isActive: true,
isDeleted: false
}).lean();
return version as AgentSkillsVersionSchemaType | null;
}
/**
* List all versions for a skill
*/
export async function listVersions(
skillId: string,
options?: {
includeDeleted?: boolean;
sort?: 'asc' | 'desc';
}
): Promise<AgentSkillsVersionSchemaType[]> {
const query: Record<string, any> = { skillId };
if (!options?.includeDeleted) {
query.isDeleted = false;
}
const sortOrder = options?.sort === 'asc' ? 1 : -1;
const versions = await MongoAgentSkillsVersion.find(query).sort({ version: sortOrder }).lean();
return versions as AgentSkillsVersionSchemaType[];
}
/**
* Set a version as the active version for a skill
*/
export async function setActiveVersion(
skillId: string,
version: number,
session?: ClientSession
): Promise<void> {
// First, deactivate all versions for this skill
await MongoAgentSkillsVersion.updateMany(
{ skillId, isDeleted: false },
{ $set: { isActive: false } },
{ session }
);
// Then, activate the specified version
const result = await MongoAgentSkillsVersion.updateOne(
{ skillId, version, isDeleted: false },
{ $set: { isActive: true } },
{ session }
);
if (result.matchedCount === 0) {
throw new Error(`Version ${version} not found for skill ${skillId}`);
}
}
/**
* Soft delete a version.
* Active versions cannot be deleted — deactivate or switch to another version first.
*/
export async function deleteVersion(
skillId: string,
version: number,
session?: ClientSession
): Promise<void> {
const versionDoc = await MongoAgentSkillsVersion.findOne({
skillId,
version,
isDeleted: false
});
if (!versionDoc) {
throw new Error(`Version ${version} not found for skill ${skillId}`);
}
// Refuse to delete the currently active version to prevent data orphaning
if (versionDoc.isActive) {
throw new Error(
`Cannot delete active version ${version}. Switch to another version before deleting.`
);
}
await MongoAgentSkillsVersion.updateOne(
{ skillId, version },
{ $set: { isDeleted: true } },
{ session }
);
}
/**
* Restore a deleted version.
* The restored version is set back to isDeleted=false but remains inactive (isActive=false).
* Call setActiveVersion explicitly if you want to make it the active version.
*/
export async function restoreVersion(
skillId: string,
version: number,
session?: ClientSession
): Promise<void> {
const versionDoc = await MongoAgentSkillsVersion.findOne({
skillId,
version,
isDeleted: true
});
if (!versionDoc) {
throw new Error(`Deleted version ${version} not found for skill ${skillId}`);
}
await MongoAgentSkillsVersion.updateOne(
{ skillId, version },
{ $set: { isDeleted: false } },
{ session }
);
}
/**
* Update version metadata
*/
export async function updateVersion(
skillId: string,
version: number,
data: Partial<{
versionName: string;
}>,
session?: ClientSession
): Promise<void> {
const result = await MongoAgentSkillsVersion.updateOne(
{ skillId, version, isDeleted: false },
{ $set: data },
{ session }
);
if (result.matchedCount === 0) {
throw new Error(`Version ${version} not found for skill ${skillId}`);
}
}
/**
* Count versions for a skill
*/
export async function countVersions(
skillId: string,
options?: { includeDeleted?: boolean }
): Promise<number> {
const query: Record<string, any> = { skillId };
if (!options?.includeDeleted) {
query.isDeleted = false;
}
return MongoAgentSkillsVersion.countDocuments(query);
}
......@@ -189,9 +189,8 @@ export const loadSystemModels = async (init = false, language = 'en') => {
);
}
if (!_systemDefaultModel.helperBotLLM) {
_systemDefaultModel.helperBotLLM = _systemActiveModelList.find(
(item) => item.type === ModelTypeEnum.llm
);
// HELPER_BOT_MODEL 未配置或未命中已启用模型时,回退到系统默认 LLM。
_systemDefaultModel.helperBotLLM = _systemDefaultModel.llm;
}
if (!_systemDefaultModel.embedding) {
_systemDefaultModel.embedding = Array.from(_embeddingModelMap.values())[0];
......
......@@ -66,16 +66,16 @@ const stripSystemMessages = (messages: ChatCompletionMessageParam[]) =>
messages.filter((message) => message.role !== ChatCompletionRequestMessageRoleEnum.System);
const buildInitialMessages = ({
runtime,
input
input,
hasRuntimeTools
}: {
runtime: AgentLoopRuntime;
input: UnifiedAgentLoopInput;
hasRuntimeTools: boolean;
}): ChatCompletionMessageParam[] => [
createSystemMessage(
getMainAgentSystemPrompt({
systemPrompt: input.systemPrompt,
hasRuntimeTools: runtime.toolCatalog.runtimeTools.length > 0
hasRuntimeTools
})
),
...stripSystemMessages(input.messages)
......@@ -127,6 +127,8 @@ export const runUnifiedAgentLoop = async ({
toolCatalog: normalized
};
const hasRuntimeTools = normalized.runtimeTools.length > 0;
let activePlan = input.pendingMainContext?.activePlan ?? input.activePlan;
let pendingAsk:
| {
......@@ -164,7 +166,7 @@ export const runUnifiedAgentLoop = async ({
content: input.userAnswer || ''
} as ChatCompletionMessageParam
]
: buildInitialMessages({ runtime, input });
: buildInitialMessages({ input, hasRuntimeTools });
const askToolName = runtime.toolCatalog.askTool?.function.name;
const updatePlanToolName = runtime.toolCatalog.updatePlanTool?.function.name;
const internalToolNames = new Set([askToolName, updatePlanToolName].filter(Boolean));
......
......@@ -189,7 +189,6 @@ export const createLLMResponse = async <T extends ChatCompletionCreateParams>(
const isEmptyToolCallsFinish = finish_reason === 'tool_calls' && !toolCalls?.length;
const isNotResponse =
!answerText &&
!reasoningText &&
!toolCalls?.length &&
!error &&
(finish_reason === 'stop' || !finish_reason || isEmptyToolCallsFinish);
......
import { serviceEnv } from '../../../env';
import type {
OpenSandboxConfigType,
OpenSandboxConnectionConfig
} from '@fastgpt-sdk/sandbox-adapter';
import type { SandboxStorageType } from './type';
// ---- sealosdevbox ----
export type SealosConnectionConfig = {
baseUrl: string;
token: string;
sandboxId: string;
};
export const getSealosConnectionConfig = (sandboxId: string): SealosConnectionConfig => {
if (!serviceEnv.AGENT_SANDBOX_SEALOS_BASEURL || !serviceEnv.AGENT_SANDBOX_SEALOS_TOKEN) {
throw new Error('AGENT_SANDBOX_SEALOS_BASEURL / AGENT_SANDBOX_SEALOS_TOKEN required');
}
return {
baseUrl: serviceEnv.AGENT_SANDBOX_SEALOS_BASEURL,
token: serviceEnv.AGENT_SANDBOX_SEALOS_TOKEN,
sandboxId
};
};
// ---- opensandbox ----
export const getOpenSandboxConnectionConfig = ({
sessionId
}: {
sessionId: string;
}): OpenSandboxConnectionConfig => {
if (!serviceEnv.AGENT_SANDBOX_OPENSANDBOX_BASEURL) {
throw new Error('AGENT_SANDBOX_OPENSANDBOX_BASEURL is required');
}
return {
sessionId,
useServerProxy: serviceEnv.AGENT_SANDBOX_OPENSANDBOX_USE_SERVER_PROXY,
baseUrl: serviceEnv.AGENT_SANDBOX_OPENSANDBOX_BASEURL,
apiKey: serviceEnv.AGENT_SANDBOX_OPENSANDBOX_API_KEY,
runtime: serviceEnv.AGENT_SANDBOX_OPENSANDBOX_RUNTIME
};
};
export const buildOpenSandboxCreateConfig = (
opts: {
volumes?: OpenSandboxConfigType['volumes'];
resourceLimits?: OpenSandboxConfigType['resourceLimits'];
createConfig?: OpenSandboxConfigType;
} = {}
): OpenSandboxConfigType => {
if (!serviceEnv.AGENT_SANDBOX_OPENSANDBOX_IMAGE_REPO && !opts.createConfig?.image) {
throw new Error('AGENT_SANDBOX_OPENSANDBOX_IMAGE_REPO is required for opensandbox provider');
}
return {
image: {
repository: serviceEnv.AGENT_SANDBOX_OPENSANDBOX_IMAGE_REPO,
tag: serviceEnv.AGENT_SANDBOX_OPENSANDBOX_IMAGE_TAG
},
...(opts.resourceLimits ? { resourceLimits: opts.resourceLimits } : {}),
...opts.createConfig,
...(opts.volumes ? { volumes: opts.volumes } : {})
};
};
// ---- volume-manager ----
export type VolumeManagerConfig = {
url: string;
token?: string;
mountPath: string;
};
export type VolumeManagerResult = {
volumes: OpenSandboxConfigType['volumes'];
storage: SandboxStorageType;
};
const vmConfig = {
enable: serviceEnv.AGENT_SANDBOX_ENABLE_VOLUME,
url: serviceEnv.AGENT_SANDBOX_VOLUME_MANAGER_URL!,
token: serviceEnv.AGENT_SANDBOX_VOLUME_MANAGER_TOKEN,
mountPath: serviceEnv.AGENT_SANDBOX_VOLUME_MANAGER_MOUNT_PATH
};
export const buildVolumeConfig = (claimName: string, mountPath: string): VolumeManagerResult => {
return {
volumes: [{ name: 'workspace', pvc: { claimName }, mountPath }],
storage: {
volumes: [{ name: 'workspace', claimName, mountPath }],
mountPath
}
};
};
export const ensureSessionVolume = async (sessionId: string): Promise<string> => {
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
if (vmConfig.token) headers['Authorization'] = `Bearer ${vmConfig.token}`;
const res = await fetch(`${vmConfig.url}/v1/volumes/ensure`, {
method: 'POST',
headers,
body: JSON.stringify({ sessionId })
});
if (!res.ok) {
throw new Error(`volume-manager error: ${res.status} ${await res.text()}`);
}
const { claimName } = (await res.json()) as { claimName: string };
return claimName;
};
export const deleteSessionVolume = async (sessionId: string): Promise<void> => {
if (!vmConfig.enable) return;
const headers: Record<string, string> = {};
if (vmConfig.token) headers['Authorization'] = `Bearer ${vmConfig.token}`;
const res = await fetch(`${vmConfig.url}/v1/volumes/${encodeURIComponent(sessionId)}`, {
method: 'DELETE',
headers
});
if (!res.ok && res.status !== 404) {
throw new Error(`volume-manager error: ${res.status} ${await res.text()}`);
}
};
export const getVolumeManagerConfig = async (
sandboxId: string
): Promise<VolumeManagerResult | undefined> => {
if (!vmConfig.enable) return undefined;
if (!vmConfig.url) {
throw new Error(
'AGENT_SANDBOX_VOLUME_MANAGER_URL is required when AGENT_SANDBOX_ENABLE_VOLUME=true'
);
}
const claimName = await ensureSessionVolume(sandboxId);
const volumeResult = buildVolumeConfig(claimName, vmConfig.mountPath);
return volumeResult;
};
import {
generateSandboxId,
SandboxStatusEnum,
SANDBOX_SUSPEND_MINUTES
} from '@fastgpt/global/core/ai/sandbox/constants';
import { serviceEnv } from '../../../env';
import { MongoSandboxInstance } from './schema';
import {
createSandbox,
type ExecuteResult,
type ISandbox,
type ResourceLimits,
type OpenSandboxConfigType
} from '@fastgpt-sdk/sandbox-adapter';
import {
getOpenSandboxConnectionConfig,
getSealosConnectionConfig,
buildOpenSandboxCreateConfig,
getVolumeManagerConfig,
deleteSessionVolume,
type VolumeManagerResult
} from './config';
import { getLogger, LogCategories } from '../../../common/logger';
import { setCron } from '../../../common/system/cron';
import { subMinutes } from 'date-fns';
import { batchRun } from '@fastgpt/global/common/system/utils';
import { getErrText } from '@fastgpt/global/common/error/utils';
const logger = getLogger(LogCategories.MODULE.AI.SANDBOX);
type UnionIdType = {
appId: string;
userId: string;
chatId: string;
};
export class SandboxClient {
private appId?: string;
private userId?: string;
private chatId?: string;
private sandboxId: string;
readonly provider: ISandbox;
constructor(
private readonly props: {
sandboxId: string;
appId?: string;
userId?: string;
chatId?: string;
},
private readonly opts: {
resourceLimits?: ResourceLimits;
vmConfig?: VolumeManagerResult | undefined;
createConfig?: OpenSandboxConfigType;
}
) {
this.sandboxId = props.sandboxId;
this.appId = props.appId;
this.userId = props.userId;
this.chatId = props.chatId;
const providerName = serviceEnv.AGENT_SANDBOX_PROVIDER;
if (providerName === 'sealosdevbox') {
const config = getSealosConnectionConfig(this.sandboxId);
this.provider = createSandbox('sealosdevbox', config, undefined);
} else if (providerName === 'opensandbox') {
// volumes always come from vmConfig (ensures PVC binding is correct);
// custom createConfig takes priority for image/entrypoint/env/metadata
this.provider = createSandbox(
'opensandbox',
getOpenSandboxConnectionConfig({ sessionId: this.sandboxId }),
buildOpenSandboxCreateConfig({
resourceLimits: opts?.resourceLimits,
volumes: opts?.vmConfig?.volumes,
createConfig: opts?.createConfig
})
);
} else if (providerName === 'e2b') {
if (!serviceEnv.AGENT_SANDBOX_E2B_API_KEY) {
throw new Error('AGENT_SANDBOX_E2B_API_KEY required');
}
this.provider = createSandbox('e2b', {
apiKey: serviceEnv.AGENT_SANDBOX_E2B_API_KEY,
sandboxId: this.sandboxId
});
} else if (!providerName) {
throw new Error(
'AGENT_SANDBOX_PROVIDER is not configured. Please set it in your environment variables.'
);
} else {
throw new Error(`Unsupported sandbox provider: ${serviceEnv.AGENT_SANDBOX_PROVIDER}`);
}
}
async ensureAvailable() {
await MongoSandboxInstance.findOneAndUpdate(
{ provider: this.provider.provider, sandboxId: this.sandboxId },
{
$set: {
status: SandboxStatusEnum.running,
lastActiveAt: new Date()
},
$setOnInsert: {
...(this.appId ? { appId: this.appId } : {}),
...(this.userId ? { userId: this.userId } : {}),
...(this.chatId ? { chatId: this.chatId } : {}),
storage: this.opts?.vmConfig?.storage,
...(this.opts?.resourceLimits && {
limit: {
cpuCount: this.opts?.resourceLimits?.cpuCount,
memoryMiB: this.opts?.resourceLimits?.memoryMiB,
diskGiB: this.opts?.resourceLimits?.diskGiB
}
}),
metadata: {
volumeEnabled: !!this.opts?.vmConfig
},
createdAt: new Date()
}
},
{ upsert: true }
);
await this.provider.ensureRunning();
}
async exec(command: string, timeout?: number): Promise<ExecuteResult> {
try {
await this.ensureAvailable();
} catch (err) {
logger.error('Failed to ensure sandbox available', { sandboxId: this.sandboxId, error: err });
return {
stdout: '',
stderr: `Sandbox service is not available: ${getErrText(err)}`,
exitCode: -1
};
}
return await this.provider
.execute(command, {
timeoutMs: timeout ? timeout * 1000 : undefined
})
.catch((err) => {
logger.error('Failed to execute sandbox', { sandboxId: this.sandboxId, error: err });
return {
stdout: '',
stderr: `Failed to execute sandbox: ${getErrText(err)}`,
exitCode: -1
};
});
}
async delete() {
await this.provider.delete();
await deleteSessionVolume(this.sandboxId).catch((err) => {
logger.error('Failed to delete sandbox volume', { sandboxId: this.sandboxId, error: err });
});
await MongoSandboxInstance.deleteOne({ sandboxId: this.sandboxId });
}
async stop() {
await this.provider.stop();
await MongoSandboxInstance.updateOne(
{ sandboxId: this.sandboxId },
{ $set: { status: SandboxStatusEnum.stopped } }
);
}
}
export const getSandboxClient = async (
props:
| {
sandboxId: string;
}
| UnionIdType,
opts: {
resourceLimits?: ResourceLimits;
createConfig?: OpenSandboxConfigType;
} = {}
) => {
const sandboxId = (() => {
if ('sandboxId' in props) {
return props.sandboxId;
} else {
return generateSandboxId(props.appId, props.userId, props.chatId);
}
})();
const vmConfig = await getVolumeManagerConfig(sandboxId);
const sandbox = new SandboxClient({ ...props, sandboxId }, { ...opts, vmConfig });
await sandbox.ensureAvailable();
return sandbox;
};
// ==== Delete Sandboxes ====
export const deleteSandboxesByChatIds = async ({
appId,
chatIds
}: {
appId: string;
chatIds: string[];
}) => {
const instances = await MongoSandboxInstance.find({ appId, chatId: { $in: chatIds } }).lean();
if (!instances.length) return;
await Promise.allSettled(
instances.map(async (doc) => {
const client = await getSandboxClient({ sandboxId: doc.sandboxId });
await client.delete().catch((err) => {
logger.error('Failed to delete sandbox', { sandboxId: doc.sandboxId, error: err });
return Promise.reject(err);
});
})
);
};
export const deleteSandboxesByAppId = async (appId: string) => {
const instances = await MongoSandboxInstance.find({ appId }).lean();
if (!instances.length) return;
await Promise.allSettled(
instances.map(async (doc) => {
const client = await getSandboxClient({ sandboxId: doc.sandboxId });
await client.delete().catch((err) => {
logger.error('Failed to delete sandbox', { sandboxId: doc.sandboxId, error: err });
});
})
);
};
// 5 分钟检查一遍,暂停
export const cronJob = async () => {
setCron('*/5 * * * *', async () => {
const instances = await MongoSandboxInstance.find({
status: SandboxStatusEnum.running,
lastActiveAt: { $lt: subMinutes(new Date(), SANDBOX_SUSPEND_MINUTES) }
}).lean();
if (!instances.length) return;
logger.info('Found running sandboxes inactive > 5 min', { count: instances.length });
await batchRun(instances, async (doc) => {
const client = await getSandboxClient({ sandboxId: doc.sandboxId });
await client.stop().catch((err) => {
logger.error('Failed to stop sandbox', { sandboxId: doc.sandboxId, error: err });
});
});
});
};
export type { ISandbox } from '@fastgpt-sdk/sandbox-adapter';
import { isValidObjectId } from 'mongoose';
import type { SandboxStatusType } from '@fastgpt/global/core/ai/sandbox/constants';
import { SandboxStatusEnum } from '@fastgpt/global/core/ai/sandbox/constants';
import type { SandboxTypeEnum } from '@fastgpt/global/core/ai/skill/constants';
import { MongoSandboxInstance } from './schema';
import type { SandboxInstanceSchemaType, SandboxProviderType } from '../type';
/**
* 可直接用于 stop/delete 的实例记录最小字段。
*
* 清理流程只依赖 provider 和 sandboxId,避免把完整 Mongo 文档泄漏到 resource service。
*/
export type SandboxResourceDoc = Pick<
SandboxInstanceSchemaType,
'provider' | 'sandboxId' | 'type'
> & {
_id: unknown;
};
export type SandboxResourceRef = {
provider: SandboxProviderType;
sandboxId: string;
_id?: unknown;
};
/**
* 构造支持 sandboxId 或 Mongo ObjectId 的查询条件。
*
* 对外 API 允许用户传入展示用 sandboxId,也兼容部分历史接口传入实例 _id 的情况。
*/
export const buildSandboxInstanceLookup = (sandboxId: string) => ({
$or: [{ sandboxId }, ...(isValidObjectId(sandboxId) ? [{ _id: sandboxId }] : [])]
});
const buildSandboxResourceRecordFilter = (resource: SandboxResourceRef) => {
if (resource._id !== undefined) {
return { _id: resource._id };
}
return {
provider: resource.provider,
sandboxId: resource.sandboxId
};
};
/**
* 记录运行态 sandbox 的最新活跃状态;不存在时创建会话归属和资源元信息。
*
* 这是运行态 client 唯一的实例写入口,避免业务层直接拼 Mongo upsert 细节。
*/
export async function upsertRunningSandboxInstance(params: {
provider: SandboxProviderType;
sandboxId: string;
appId?: string;
userId?: string;
chatId?: string;
storage?: SandboxInstanceSchemaType['storage'];
limit?: Partial<NonNullable<SandboxInstanceSchemaType['limit']>>;
metadata?: Record<string, unknown>;
}) {
const { provider, sandboxId, appId, userId, chatId, storage, limit, metadata } = params;
return MongoSandboxInstance.findOneAndUpdate(
{ provider, sandboxId },
{
$set: {
status: SandboxStatusEnum.running,
lastActiveAt: new Date()
},
$setOnInsert: {
...(appId !== undefined ? { appId } : {}),
...(userId !== undefined ? { userId } : {}),
...(chatId !== undefined ? { chatId } : {}),
storage,
...(limit ? { limit } : {}),
metadata,
createdAt: new Date()
}
},
{ upsert: true }
);
}
/**
* 将一条资源记录标记为 stopped。
*
* resource service 在远端 stop 成功后调用这里同步本地状态。
*/
export async function markSandboxResourceStopped(resource: SandboxResourceRef) {
return MongoSandboxInstance.updateOne(buildSandboxResourceRecordFilter(resource), {
$set: { status: SandboxStatusEnum.stopped }
});
}
/**
* 删除一条 sandbox 实例记录。
*
* 优先使用 _id 精确删除;没有 _id 时退回 provider+sandboxId,避免 provider 切换后误删同名资源。
*/
export async function deleteSandboxResourceRecord(resource: SandboxResourceRef) {
return MongoSandboxInstance.deleteOne(buildSandboxResourceRecordFilter(resource));
}
/**
* 查询某个 app 下指定 chat 列表关联的资源记录。
*/
export async function findSandboxResourcesByChatIds(params: { appId: string; chatIds: string[] }) {
const { appId, chatIds } = params;
return MongoSandboxInstance.find({ appId, chatId: { $in: chatIds } }).lean<
SandboxResourceDoc[]
>();
}
/**
* 查询某个 app 下的所有 sandbox 资源记录。
*/
export async function findSandboxResourcesByAppId(appId: string) {
return MongoSandboxInstance.find({ appId }).lean<SandboxResourceDoc[]>();
}
/**
* 查询超过指定时间未活跃的运行中 sandbox 资源。
*
* cron 使用这个入口获得最小清理字段,后续由 resource service 按 provider 执行 stop。
*/
export async function findInactiveRunningSandboxResources(inactiveBefore: Date) {
return MongoSandboxInstance.find({
status: SandboxStatusEnum.running,
lastActiveAt: { $lt: inactiveBefore }
}).lean<SandboxResourceDoc[]>();
}
/**
* 按 sandboxId 查询业务归属 appId。
*
* 运行态入口允许只传 sandboxId 复用已有实例;权限校验需要先从实例记录反查 appId。
*/
export async function findSandboxAppIdBySandboxId(sandboxId: string) {
const doc = await MongoSandboxInstance.findOne({ sandboxId }, 'appId').lean<{
appId?: string;
} | null>();
return doc?.appId ? String(doc.appId) : undefined;
}
/**
* 按 app/chat/type 查询单条 sandbox 实例。
*
* provider 可选是为了兼容“当前 provider 查询”和“只按业务归属查询”两类场景。
*/
export async function findSandboxInstanceByAppChatType(params: {
provider?: SandboxProviderType;
appId: string;
chatId: string;
type: SandboxTypeEnum;
status?: SandboxStatusType;
}) {
const { provider, appId, chatId, type, status } = params;
return MongoSandboxInstance.findOne({
...(provider ? { provider } : {}),
appId,
chatId,
...(status ? { status } : {}),
type
});
}
/**
* 按 app/chat/type 查询资源清理所需的实例记录。
*/
export async function findSandboxResourcesByAppChatType(params: {
provider?: SandboxProviderType;
appId: string;
chatId: string;
type: SandboxTypeEnum;
}) {
const { provider, appId, chatId, type } = params;
return MongoSandboxInstance.find({
...(provider ? { provider } : {}),
appId,
chatId,
type
}).lean<SandboxResourceDoc[]>();
}
/**
* 查询同一业务会话下非当前 provider 的历史资源。
*
* provider 切换后用这个入口找出旧 provider 留下的实例,再逐条删除。
*/
export async function findSandboxResourcesByAppChatTypeExcludeProvider(params: {
provider: SandboxProviderType;
appId: string;
chatId: string;
type: SandboxTypeEnum;
}) {
const { provider, appId, chatId, type } = params;
return MongoSandboxInstance.find({
provider: { $ne: provider },
appId,
chatId,
type
}).lean<SandboxResourceDoc[]>();
}
/**
* 统计某种 sandbox 类型的运行中实例数量。
*
* 用于 edit-debug 等有并发上限的场景;provider 可选,传入时只统计当前 provider。
*/
export async function countRunningSandboxInstancesByType(
type: SandboxTypeEnum,
provider?: SandboxProviderType
) {
return MongoSandboxInstance.countDocuments({
...(provider ? { provider } : {}),
status: SandboxStatusEnum.running,
type
});
}
/**
* 按 Mongo _id 删除实例记录。
*
* 仅用于业务确认远端资源已经清理,或需要删除不可恢复的孤立记录时。
*/
export async function deleteSandboxInstanceRecord(instanceId: unknown) {
return MongoSandboxInstance.deleteOne({ _id: instanceId });
}
/**
* 更新指定 sandboxId 的业务归属和 metadata。
*
* provider 可选;传入 provider 时可以避免同 sandboxId 在不同 provider 下的历史记录互相影响。
*/
export async function updateSandboxInstanceRecordBySandboxId(params: {
provider?: SandboxProviderType;
sandboxId: string;
appId?: string;
userId?: string;
chatId?: string;
type?: SandboxTypeEnum;
metadata?: Record<string, unknown>;
}): Promise<SandboxInstanceSchemaType | null> {
const { provider, sandboxId, appId, userId, chatId, type, metadata } = params;
return MongoSandboxInstance.findOneAndUpdate(
{
sandboxId,
...(provider ? { provider } : {})
},
{
$set: {
...(appId !== undefined ? { appId } : {}),
...(userId !== undefined ? { userId } : {}),
...(chatId !== undefined ? { chatId } : {}),
...(type !== undefined ? { type } : {}),
...(metadata !== undefined ? { metadata } : {})
}
},
{ new: true }
);
}
/**
* 查询团队可访问的 sandbox 实例。
*
* 通过 metadata.teamId 做权限边界,支持 sandboxId 或实例 _id 两种输入。
*/
export async function findSandboxInstanceBySandboxIdAndTeam(params: {
provider?: SandboxProviderType;
sandboxId: string;
teamId: string;
}) {
const { provider, sandboxId, teamId } = params;
return MongoSandboxInstance.findOne({
...buildSandboxInstanceLookup(sandboxId),
...(provider ? { provider } : {}),
'metadata.teamId': teamId
});
}
/**
* 查询团队可访问的资源清理记录。
*
* 返回 lean 文档,供 deleteSandboxResource 直接按 provider/sandboxId 清理远端资源。
*/
export async function findSandboxResourceBySandboxIdAndTeam(params: {
provider?: SandboxProviderType;
sandboxId: string;
teamId: string;
}) {
const { provider, sandboxId, teamId } = params;
return MongoSandboxInstance.findOne({
...buildSandboxInstanceLookup(sandboxId),
...(provider ? { provider } : {}),
'metadata.teamId': teamId
}).lean<SandboxResourceDoc | null>();
}
/**
* 查询与一组 skill 相关的 sandbox 资源。
*
* skill 可能以 appId 作为编辑态归属,也可能记录在 metadata.skillId 中;删除 skill 时两种都要清理。
*/
export async function findSkillRelatedSandboxResources(skillIds: string[]) {
return MongoSandboxInstance.find({
$or: [{ appId: { $in: skillIds } }, { 'metadata.skillId': { $in: skillIds } }]
}).lean<SandboxResourceDoc[]>();
}
import { connectionMongo, getMongoModel } from '../../../common/mongo';
import { connectionMongo, getMongoModel } from '../../../../common/mongo';
const { Schema } = connectionMongo;
import type { SandboxInstanceSchemaType } from './type';
import type { SandboxInstanceSchemaType } from '../type';
import { SandboxStatusEnum } from '@fastgpt/global/core/ai/sandbox/constants';
import { SandboxProtocolEnum, SandboxTypeEnum } from '@fastgpt/global/core/agentSkills/constants';
import { SandboxLimitSchema, SandboxProviderSchema } from './type';
import { SandboxTypeEnum } from '@fastgpt/global/core/ai/skill/constants';
import { SandboxLimitSchema, SandboxProviderSchema } from '../type';
/**
* sandbox 实例记录集合。
*
* 记录 FastGPT 业务归属和远端 provider 资源的映射关系,远端资源本身不在 Mongo 中保存。
*/
export const collectionName = 'agent_sandbox_instances';
const SandboxInstanceSchema = new Schema({
......@@ -22,6 +27,10 @@ const SandboxInstanceSchema = new Schema({
appId: String,
userId: String,
chatId: String,
type: {
type: String,
enum: Object.values(SandboxTypeEnum)
},
status: {
type: String,
......@@ -72,13 +81,18 @@ SandboxInstanceSchema.index(
partialFilterExpression: {
appId: { $exists: true },
chatId: { $exists: true },
'metadata.sandboxType': { $exists: true }
type: { $exists: true }
}
}
);
SandboxInstanceSchema.index({ 'metadata.skillId': 1 });
SandboxInstanceSchema.index({ 'metadata.sandboxType': 1, chatId: 1 });
SandboxInstanceSchema.index({ type: 1, chatId: 1 });
/**
* sandbox 实例 Mongo model。
*
* 只在 instance/repository 中封装常规读写;需要跨层使用时优先新增 repository 方法。
*/
export const MongoSandboxInstance = getMongoModel<SandboxInstanceSchemaType>(
collectionName,
SandboxInstanceSchema
......
import { serviceEnv } from '../../../../env';
import {
createSandbox,
type ISandbox,
type ResourceLimits,
type SandboxCreateSpec
} from '@fastgpt-sdk/sandbox-adapter';
import { getSandboxAdapterConfig, type SandboxProviderConfig } from './config';
import type { SandboxProviderType } from '../type';
import type { VolumeManagerResult } from '../volume/service';
function assertNever(value: never): never {
throw new Error(`Unsupported sandbox provider: ${String(value)}`);
}
/**
* 根据明确的 provider 配置构造底层 sandbox adapter。
*
* 这个函数只负责把 FastGPT 的 provider 配置转换成 SDK adapter,不访问数据库,
* 也不执行 ensure/create/resume 等生命周期动作。
*/
export function buildSandboxAdapter(
providerConfig: SandboxProviderConfig,
props: {
sandboxId: string;
createConfig?: SandboxCreateSpec;
}
): ISandbox {
switch (providerConfig.provider) {
case 'opensandbox':
return createSandbox(
'opensandbox',
{
apiKey: providerConfig.apiKey,
baseUrl: providerConfig.baseUrl,
runtime: providerConfig.runtime,
useServerProxy: providerConfig.useServerProxy,
replaceDockerInternalWithLocalhost:
serviceEnv.SANDBOX_PROXY_REPLACE_DOCKER_INTERNAL_WITH_LOCALHOST,
sessionId: props.sandboxId
},
props.createConfig
);
case 'sealosdevbox':
return createSandbox(
'sealosdevbox',
{
baseUrl: providerConfig.baseUrl,
token: providerConfig.token,
sandboxId: props.sandboxId
},
props.createConfig
);
case 'e2b':
if (!providerConfig.apiKey) {
throw new Error('AGENT_SANDBOX_E2B_API_KEY required');
}
return createSandbox('e2b', {
apiKey: providerConfig.apiKey,
sandboxId: props.sandboxId
});
default:
return assertNever(providerConfig);
}
}
/**
* 构造当前运行态会话使用的 sandbox adapter。
*
* 运行态会话需要带 createConfig/volume/resourceLimits,因为 ensureAvailable 可能创建
* 或恢复 sandbox;历史资源清理不要走这个入口。
*/
export function buildRuntimeSandboxAdapter(
providerName: SandboxProviderType,
sandboxId: string,
opts: {
resourceLimits?: ResourceLimits;
vmConfig?: VolumeManagerResult | undefined;
createConfig?: SandboxCreateSpec;
} = {}
): ISandbox {
const config = getSandboxAdapterConfig({
provider: providerName,
runtime: true,
sessionId: sandboxId,
resourceLimits: opts.resourceLimits,
vmConfig: opts.vmConfig,
createConfig: opts.createConfig
});
return buildSandboxAdapter(config.providerConfig, {
sandboxId,
createConfig: config.createConfig
});
}
/**
* 构造历史资源清理用的 adapter。
*
* 清理入口只按资源记录里的 provider/sandboxId 操作已有资源,不补运行态 createConfig,
* 避免 stop/delete 反向依赖镜像、volume 或当前系统 provider。
*/
export function buildSandboxResourceAdapter(props: {
provider: SandboxProviderType;
sandboxId: string;
}): ISandbox {
const config = getSandboxAdapterConfig({
provider: props.provider
});
return buildSandboxAdapter(config.providerConfig, {
sandboxId: props.sandboxId,
createConfig: config.createConfig
});
}
import { serviceEnv } from '../../../../env';
import type { SandboxCreateSpec, SandboxProviderType } from '@fastgpt-sdk/sandbox-adapter';
import type { VolumeManagerResult } from '../volume/service';
import { getSandboxRuntimeProfile } from '../runtime/profile';
type SandboxRuntime = 'kubernetes' | 'docker';
export type OpenSandboxProviderConfig = {
provider: 'opensandbox';
baseUrl: string;
apiKey: string;
runtime: SandboxRuntime;
useServerProxy?: boolean;
};
export type SealosDevboxProviderConfig = {
provider: 'sealosdevbox';
baseUrl: string;
token: string;
};
export type E2BProviderConfig = {
provider: 'e2b';
apiKey: string;
};
export type SandboxProviderConfig =
| OpenSandboxProviderConfig
| SealosDevboxProviderConfig
| E2BProviderConfig;
export type SandboxCreateConfig = SandboxCreateSpec;
export type SandboxAdapterConfig = {
providerConfig: SandboxProviderConfig;
createConfig?: SandboxCreateConfig;
};
function assertNever(value: never): never {
throw new Error(`Unsupported sandbox provider: ${String(value)}`);
}
/**
* 获取当前或指定 provider 的连接配置。
*
* 这个入口只返回 provider 认证和连接信息,不包含运行态 createConfig;
* 适合权限校验、历史资源查询等只需要 provider 名称的场景。
*/
export function getSandboxProviderConfig(
provider: SandboxProviderType = serviceEnv.AGENT_SANDBOX_PROVIDER
): SandboxProviderConfig {
return getSandboxAdapterConfig({ provider }).providerConfig;
}
/**
* 校验 provider 连接配置是否足够构造 adapter。
*
* 启动运行态和清理历史资源都会经过这层校验,错误应直接暴露为环境配置问题。
*/
export function validateSandboxConfig(config: SandboxProviderConfig): void {
if (config.provider !== 'e2b' && !config.baseUrl) {
throw new Error('Sandbox provider base URL is required');
}
if (config.provider === 'opensandbox' && !['kubernetes', 'docker'].includes(config.runtime)) {
throw new Error(`Invalid runtime: ${config.runtime}`);
}
if (config.provider === 'opensandbox' && !config.apiKey) {
throw new Error('Sandbox provider apiKey is required for opensandbox');
}
if (config.provider === 'sealosdevbox' && !config.token) {
throw new Error('Sandbox provider token is required for sealosdevbox');
}
if (config.provider === 'e2b' && !config.apiKey) {
throw new Error('Sandbox provider apiKey is required for e2b');
}
}
/**
* 获取构造 sandbox adapter 所需的完整配置。
*
* 这里只处理 provider 连接配置和校验;运行态 createConfig 统一交给
* SandboxRuntimeProfile.buildConfig,避免这里再散落 provider 运行时分支。
*/
export function getSandboxAdapterConfig({
provider = serviceEnv.AGENT_SANDBOX_PROVIDER,
runtime = false,
resourceLimits,
vmConfig,
createConfig,
sessionId
}: {
provider?: SandboxProviderType;
runtime?: boolean;
resourceLimits?: SandboxCreateSpec['resourceLimits'];
vmConfig?: VolumeManagerResult | undefined;
createConfig?: SandboxCreateConfig;
sessionId?: string;
} = {}): SandboxAdapterConfig {
switch (provider) {
case 'opensandbox': {
const providerConfig: OpenSandboxProviderConfig = {
provider,
baseUrl: serviceEnv.AGENT_SANDBOX_OPENSANDBOX_BASEURL,
apiKey: serviceEnv.AGENT_SANDBOX_OPENSANDBOX_API_KEY ?? '',
runtime: serviceEnv.AGENT_SANDBOX_OPENSANDBOX_RUNTIME,
useServerProxy: serviceEnv.AGENT_SANDBOX_OPENSANDBOX_USE_SERVER_PROXY
};
validateSandboxConfig(providerConfig);
return {
providerConfig,
createConfig: runtime
? getSandboxRuntimeProfile(provider).buildConfig({
resourceLimits,
vmConfig,
createConfig
})
: undefined
};
}
case 'sealosdevbox': {
const providerConfig: SealosDevboxProviderConfig = {
provider,
baseUrl: serviceEnv.AGENT_SANDBOX_SEALOS_BASEURL ?? '',
token: serviceEnv.AGENT_SANDBOX_SEALOS_TOKEN ?? ''
};
validateSandboxConfig(providerConfig);
return {
providerConfig,
createConfig: runtime
? getSandboxRuntimeProfile(provider).buildConfig({
createConfig,
sessionId
})
: undefined
};
}
case 'e2b': {
const providerConfig: E2BProviderConfig = {
provider,
apiKey: serviceEnv.AGENT_SANDBOX_E2B_API_KEY ?? ''
};
validateSandboxConfig(providerConfig);
return {
providerConfig,
createConfig: runtime
? getSandboxRuntimeProfile(provider).buildConfig({
createConfig
})
: undefined
};
}
default:
return assertNever(provider);
}
}
This diff is collapsed. Click to expand it.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment