From 677b70cffeb31e33cd39a2d3dd6330325504e010 Mon Sep 17 00:00:00 2001 From: kicer Date: Mon, 31 Aug 2026 06:57:38 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8C=89=20README=20=E8=AE=BE=E8=AE=A1?= =?UTF-8?q?=E6=96=B9=E6=A1=88=E5=AE=9E=E7=8E=B0=20Agent=20=E7=B3=BB?= =?UTF-8?q?=E7=BB=9F=20app/=EF=BC=9A=E5=A4=9A=E6=A8=A1=E5=9E=8B=20FIFO=20?= =?UTF-8?q?=E8=B0=83=E5=BA=A6=E3=80=81Agent=20=E4=B8=BB=E5=BE=AA=E7=8E=AF?= =?UTF-8?q?=E3=80=8113=20=E4=B8=AA=E6=B2=99=E7=AE=B1=E5=B7=A5=E5=85=B7?= =?UTF-8?q?=EF=BC=88web=5Fsearch=20=E8=B5=B0=E5=86=85=E7=BD=91=20MCP?= =?UTF-8?q?=EF=BC=89=E3=80=81H5=20=E5=89=8D=E7=AB=AF=EF=BC=88SSE=20?= =?UTF-8?q?=E6=B5=81=E5=BC=8F=EF=BC=89=E3=80=81Docker=20=E9=83=A8=E7=BD=B2?= =?UTF-8?q?=E4=B8=8E=E7=AB=AF=E5=88=B0=E7=AB=AF=E5=86=92=E7=83=9F=E6=B5=8B?= =?UTF-8?q?=E8=AF=95=EF=BC=8825/25=20=E9=80=9A=E8=BF=87=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 7 + app/Dockerfile | 19 + app/README.md | 67 ++ app/config.example.yaml | 39 + app/docker-compose.yml | 11 + app/package-lock.json | 1453 ++++++++++++++++++++++++ app/package.json | 18 + app/server/config.js | 59 + app/server/db.js | 66 ++ app/server/engine.js | 434 +++++++ app/server/llm.js | 131 +++ app/server/public/css/style.css | 237 ++++ app/server/public/index.html | 102 ++ app/server/public/js/app.js | 472 ++++++++ app/server/routes/files.js | 138 +++ app/server/routes/messages.js | 62 + app/server/routes/sessions.js | 89 ++ app/server/server.js | 52 + app/server/sse.js | 39 + app/server/templates/system-prompt.txt | 155 +++ app/server/tools/definitions.json | 360 ++++++ app/server/tools/executor.js | 438 +++++++ app/test/config.test.yaml | 21 + app/test/dep-check.js | 4 + app/test/mock-upstream.js | 71 ++ app/test/smoke.js | 181 +++ docs/DEPLOY.md | 74 ++ scripts/gen-from-readme.js | 77 ++ 28 files changed, 4876 insertions(+) create mode 100644 app/Dockerfile create mode 100644 app/README.md create mode 100644 app/config.example.yaml create mode 100644 app/docker-compose.yml create mode 100644 app/package-lock.json create mode 100644 app/package.json create mode 100644 app/server/config.js create mode 100644 app/server/db.js create mode 100644 app/server/engine.js create mode 100644 app/server/llm.js create mode 100644 app/server/public/css/style.css create mode 100644 app/server/public/index.html create mode 100644 app/server/public/js/app.js create mode 100644 app/server/routes/files.js create mode 100644 app/server/routes/messages.js create mode 100644 app/server/routes/sessions.js create mode 100644 app/server/server.js create mode 100644 app/server/sse.js create mode 100644 app/server/templates/system-prompt.txt create mode 100644 app/server/tools/definitions.json create mode 100644 app/server/tools/executor.js create mode 100644 app/test/config.test.yaml create mode 100644 app/test/dep-check.js create mode 100644 app/test/mock-upstream.js create mode 100644 app/test/smoke.js create mode 100644 docs/DEPLOY.md create mode 100644 scripts/gen-from-readme.js diff --git a/.gitignore b/.gitignore index 6ba47b1..e88089d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,9 @@ /ai-xiaocai/ /zed_agent/ +node_modules/ +app/test/tmp/ +app/config.yaml +app/data/ +data/ +*.log +.DS_Store diff --git a/app/Dockerfile b/app/Dockerfile new file mode 100644 index 0000000..9502ef4 --- /dev/null +++ b/app/Dockerfile @@ -0,0 +1,19 @@ +FROM node:20-slim + +# 常用命令行工具:Agent 的 terminal 工具经常用到 +RUN apt-get update -y && apt-get install -y --no-install-recommends \ + ca-certificates curl git python3 ripgrep procps\ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /app + +COPY package.json package-lock.json ./ +RUN npm install --omit=dev --no-audit --no-fund + +COPY server ./server +COPY config.example.yaml ./ + +EXPOSE 8080 +ENV AGENT_CONFIG=/app/config.yaml + +CMD ["node", "server/server.js"] diff --git a/app/README.md b/app/README.md new file mode 100644 index 0000000..38c71cf --- /dev/null +++ b/app/README.md @@ -0,0 +1,67 @@ +# Agent 任务台(app) + +按仓库根目录 `README.md` 设计方案实现的自用通用 Agent 系统。 + +## 目录结构 + +``` +app/ +├── server/ +│ ├── server.js # 入口:装配配置/DB/总线/路由/静态资源 +│ ├── config.js # config.yaml 加载与校验 +│ ├── db.js # SQLite(better-sqlite3,WAL) +│ ├── engine.js # 会话管理 + 模型池 FIFO 调度 + Agent 主循环 +│ ├── llm.js # OpenAI 兼容上游流式调用(SSE 解析/工具分片合并) +│ ├── sse.js # 按会话分组的 SSE 事件总线 +│ ├── routes/ +│ │ ├── sessions.js # 会话 CRUD(10.1) +│ │ ├── messages.js # 消息/SSE/start/stop(10.2) +│ │ └── files.js # 文件上传/列表/下载/删除(10.3) +│ ├── tools/ +│ │ ├── definitions.json # 由 README 7.2 生成(npm run gen) +│ │ └── executor.js # 13 个工具执行器(任务目录沙箱) +│ ├── templates/system-prompt.txt # 由 README 7.1 生成 +│ └── public/ # H5 前端(Vanilla JS + SSE) +├── test/ # mock 上游 + 端到端冒烟测试 +├── scripts(在上层仓库根目录)gen-from-readme.js # README → 提示词/工具 schema +├── config.example.yaml +├── Dockerfile / docker-compose.yml +``` + +## 本地运行 + +```bash +cd app +npm install +cp config.example.yaml config.yaml # 修改 upstream_url / models +npm start # http://localhost:8080 +``` + +## 测试 + +```bash +cd app +npm test # 启动 mock 上游 + 真实 server 的端到端冒烟测试(25 项断言) +``` + +## 从 README 重新生成提示词与工具 schema + +README 是 system prompt 与工具 JSON schema 的唯一事实来源(与 Zed 逐字一致以利用前缀缓存): + +```bash +cd app +npm run gen # 读 ../README.md → templates/system-prompt.txt + tools/definitions.json +``` + +修改 `README.md` 第七章节后必须重跑 `npm run gen` 并重启服务。 + +## 关键行为速查 + +- 会话创建即尝试绑定空闲模型;无空闲则进全局队列 FIFO。 +- 每轮 AI 完成(无工具调)或用户终止后释放模型;新消息重新入队。 +- 规划阶段点「开始执行」:追加固定模板消息并切 execution。 +- 终止:置位标志 + kill 进程组 + 中止模型流,不再发新请求。 +- 所有文件路径解析到任务目录内,拒绝越界。 +- web_search 调用内网 MCP 服务(config.web_search.url/authorization,默认已内置);如服务不可用会返回错误文本。 + +部署见 `../docs/DEPLOY.md`。 diff --git a/app/config.example.yaml b/app/config.example.yaml new file mode 100644 index 0000000..657a151 --- /dev/null +++ b/app/config.example.yaml @@ -0,0 +1,39 @@ +# 自用通用 Agent 系统配置示例 +# 复制为 config.yaml 后按需修改;容器内通过 AGENT_CONFIG 指定路径。 + +# 模型池:多个 ID 共用同一个上游 URL(cli-proxy-api 按 ID 路由到不同账号)。 +# 同时活跃会话数上限 = 模型数量。 +models: + - id: ds1 + display_name: "AMD DeepSeek 1" + - id: ds2 + display_name: "AMD DeepSeek 2" + - id: ds3 + display_name: "AMD DeepSeek 3" + +# OpenAI 兼容上游(cli-proxy-api),会请求 {upstream_url}/chat/completions +upstream_url: "https://your-cli-proxy-api.example.com/v1" +# 若上游需要鉴权(可选) +api_key: "" + +workspace_root: "./data/tasks" +# db_path: "/data/.agent.db" + +terminal: + default_timeout_ms: 30000 + max_output_chars: 10000 + +agent: + temperature: 1.0 + max_tool_iterations: 50 + max_retries: 2 + +# 内置 basic auth(可选)。若已在前面放 nginx-proxy 做认证,此处留空即可。 +# auth: +# user: admin +# password: "change-me" + +# web_search 工具:直接调用内网 MCP 服务(JSON-RPC over HTTP,无状态,默认已内置) +web_search: + url: "https://web-search.ai.foresh.com/" + authorization: "Basic a2ljZXI6USF3MmUzcjQ=" diff --git a/app/docker-compose.yml b/app/docker-compose.yml new file mode 100644 index 0000000..4caf788 --- /dev/null +++ b/app/docker-compose.yml @@ -0,0 +1,11 @@ +services: + agent: + build: . + ports: + - "8080:8080" + volumes: + - ./data:/workspace/tasks + - ./config.yaml:/app/config.yaml:ro + environment: + - AGENT_CONFIG=/app/config.yaml + restart: unless-stopped diff --git a/app/package-lock.json b/app/package-lock.json new file mode 100644 index 0000000..f787c0c --- /dev/null +++ b/app/package-lock.json @@ -0,0 +1,1453 @@ +{ + "name": "agent-app", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "agent-app", + "version": "1.0.0", + "dependencies": { + "better-sqlite3": "11.3.0", + "express": "4.21.2", + "minimatch": "9.0.5", + "multer": "1.4.5-lts.1", + "yaml": "2.6.1" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "http://mirrors.tencentyun.com/npm/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/append-field": { + "version": "1.0.0", + "resolved": "http://mirrors.tencentyun.com/npm/append-field/-/append-field-1.0.0.tgz", + "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==", + "license": "MIT" + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "http://mirrors.tencentyun.com/npm/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", + "license": "MIT" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "http://mirrors.tencentyun.com/npm/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "license": "MIT" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "http://mirrors.tencentyun.com/npm/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/better-sqlite3": { + "version": "11.3.0", + "resolved": "http://mirrors.tencentyun.com/npm/better-sqlite3/-/better-sqlite3-11.3.0.tgz", + "integrity": "sha512-iHt9j8NPYF3oKCNOO5ZI4JwThjt3Z6J6XrcwG85VNMVzv1ByqrHWv5VILEbCMFWDsoHhXvQ7oC8vgRXFAKgl9w==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "bindings": "^1.5.0", + "prebuild-install": "^7.1.1" + } + }, + "node_modules/bindings": { + "version": "1.5.0", + "resolved": "http://mirrors.tencentyun.com/npm/bindings/-/bindings-1.5.0.tgz", + "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", + "license": "MIT", + "dependencies": { + "file-uri-to-path": "1.0.0" + } + }, + "node_modules/bl": { + "version": "4.1.0", + "resolved": "http://mirrors.tencentyun.com/npm/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/bl/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "http://mirrors.tencentyun.com/npm/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/body-parser": { + "version": "1.20.3", + "resolved": "http://mirrors.tencentyun.com/npm/body-parser/-/body-parser-1.20.3.tgz", + "integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.13.0", + "raw-body": "2.5.2", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/brace-expansion": { + "version": "2.1.4", + "resolved": "http://mirrors.tencentyun.com/npm/brace-expansion/-/brace-expansion-2.1.4.tgz", + "integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "http://mirrors.tencentyun.com/npm/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "http://mirrors.tencentyun.com/npm/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "license": "MIT" + }, + "node_modules/busboy": { + "version": "1.6.0", + "resolved": "http://mirrors.tencentyun.com/npm/busboy/-/busboy-1.6.0.tgz", + "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", + "dependencies": { + "streamsearch": "^1.1.0" + }, + "engines": { + "node": ">=10.16.0" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "http://mirrors.tencentyun.com/npm/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "http://mirrors.tencentyun.com/npm/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "http://mirrors.tencentyun.com/npm/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/chownr": { + "version": "1.1.4", + "resolved": "http://mirrors.tencentyun.com/npm/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", + "license": "ISC" + }, + "node_modules/concat-stream": { + "version": "1.6.2", + "resolved": "http://mirrors.tencentyun.com/npm/concat-stream/-/concat-stream-1.6.2.tgz", + "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", + "engines": [ + "node >= 0.8" + ], + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" + } + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "http://mirrors.tencentyun.com/npm/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "http://mirrors.tencentyun.com/npm/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.1", + "resolved": "http://mirrors.tencentyun.com/npm/cookie/-/cookie-0.7.1.tgz", + "integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "resolved": "http://mirrors.tencentyun.com/npm/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==", + "license": "MIT" + }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "http://mirrors.tencentyun.com/npm/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "license": "MIT" + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "http://mirrors.tencentyun.com/npm/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/decompress-response": { + "version": "6.0.0", + "resolved": "http://mirrors.tencentyun.com/npm/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", + "license": "MIT", + "dependencies": { + "mimic-response": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/deep-extend": { + "version": "0.6.0", + "resolved": "http://mirrors.tencentyun.com/npm/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "http://mirrors.tencentyun.com/npm/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "http://mirrors.tencentyun.com/npm/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "license": "MIT", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "http://mirrors.tencentyun.com/npm/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "http://mirrors.tencentyun.com/npm/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "http://mirrors.tencentyun.com/npm/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "http://mirrors.tencentyun.com/npm/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.5", + "resolved": "http://mirrors.tencentyun.com/npm/end-of-stream/-/end-of-stream-1.4.5.tgz", + "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", + "license": "MIT", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "http://mirrors.tencentyun.com/npm/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "http://mirrors.tencentyun.com/npm/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "http://mirrors.tencentyun.com/npm/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "http://mirrors.tencentyun.com/npm/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "http://mirrors.tencentyun.com/npm/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/expand-template": { + "version": "2.0.3", + "resolved": "http://mirrors.tencentyun.com/npm/expand-template/-/expand-template-2.0.3.tgz", + "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", + "license": "(MIT OR WTFPL)", + "engines": { + "node": ">=6" + } + }, + "node_modules/express": { + "version": "4.21.2", + "resolved": "http://mirrors.tencentyun.com/npm/express/-/express-4.21.2.tgz", + "integrity": "sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA==", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.3", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.7.1", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.3.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.12", + "proxy-addr": "~2.0.7", + "qs": "6.13.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.19.0", + "serve-static": "1.16.2", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/file-uri-to-path": { + "version": "1.0.0", + "resolved": "http://mirrors.tencentyun.com/npm/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", + "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", + "license": "MIT" + }, + "node_modules/finalhandler": { + "version": "1.3.1", + "resolved": "http://mirrors.tencentyun.com/npm/finalhandler/-/finalhandler-1.3.1.tgz", + "integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "http://mirrors.tencentyun.com/npm/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "http://mirrors.tencentyun.com/npm/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fs-constants": { + "version": "1.0.0", + "resolved": "http://mirrors.tencentyun.com/npm/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "license": "MIT" + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "http://mirrors.tencentyun.com/npm/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "http://mirrors.tencentyun.com/npm/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "http://mirrors.tencentyun.com/npm/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/github-from-package": { + "version": "0.0.0", + "resolved": "http://mirrors.tencentyun.com/npm/github-from-package/-/github-from-package-0.0.0.tgz", + "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", + "license": "MIT" + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "http://mirrors.tencentyun.com/npm/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "http://mirrors.tencentyun.com/npm/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "http://mirrors.tencentyun.com/npm/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "http://mirrors.tencentyun.com/npm/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "license": "MIT", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "http://mirrors.tencentyun.com/npm/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "http://mirrors.tencentyun.com/npm/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "http://mirrors.tencentyun.com/npm/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "http://mirrors.tencentyun.com/npm/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "http://mirrors.tencentyun.com/npm/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "http://mirrors.tencentyun.com/npm/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "license": "MIT" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "http://mirrors.tencentyun.com/npm/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "http://mirrors.tencentyun.com/npm/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "http://mirrors.tencentyun.com/npm/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "http://mirrors.tencentyun.com/npm/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "http://mirrors.tencentyun.com/npm/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "http://mirrors.tencentyun.com/npm/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "http://mirrors.tencentyun.com/npm/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mimic-response": { + "version": "3.1.0", + "resolved": "http://mirrors.tencentyun.com/npm/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimatch": { + "version": "9.0.5", + "resolved": "http://mirrors.tencentyun.com/npm/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "http://mirrors.tencentyun.com/npm/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mkdirp": { + "version": "0.5.6", + "resolved": "http://mirrors.tencentyun.com/npm/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "license": "MIT", + "dependencies": { + "minimist": "^1.2.6" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "resolved": "http://mirrors.tencentyun.com/npm/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==" + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "http://mirrors.tencentyun.com/npm/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/multer": { + "version": "1.4.5-lts.1", + "resolved": "http://mirrors.tencentyun.com/npm/multer/-/multer-1.4.5-lts.1.tgz", + "integrity": "sha512-ywPWvcDMeH+z9gQq5qYHCCy+ethsk4goepZ45GLD63fOu0YcNecQxi64nDs3qluZB+murG3/D4dJ7+dGctcCQQ==", + "deprecated": "Multer 1.x is impacted by a number of vulnerabilities, which have been patched in 2.x. You should upgrade to the latest 2.x version.", + "license": "MIT", + "dependencies": { + "append-field": "^1.0.0", + "busboy": "^1.0.0", + "concat-stream": "^1.5.2", + "mkdirp": "^0.5.4", + "object-assign": "^4.1.1", + "type-is": "^1.6.4", + "xtend": "^4.0.0" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/napi-build-utils": { + "version": "2.0.0", + "resolved": "http://mirrors.tencentyun.com/npm/napi-build-utils/-/napi-build-utils-2.0.0.tgz", + "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "http://mirrors.tencentyun.com/npm/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-abi": { + "version": "3.96.0", + "resolved": "http://mirrors.tencentyun.com/npm/node-abi/-/node-abi-3.96.0.tgz", + "integrity": "sha512-rebQ/lz7i0EkoLzUVSrKRzA69zMkwLp95kKMWoMDkkM00Suxz0D7zEQPwRml5fQum24mj7bPvmlgLAmu2JCiYg==", + "license": "MIT", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "http://mirrors.tencentyun.com/npm/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "http://mirrors.tencentyun.com/npm/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "http://mirrors.tencentyun.com/npm/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "http://mirrors.tencentyun.com/npm/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "http://mirrors.tencentyun.com/npm/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.12", + "resolved": "http://mirrors.tencentyun.com/npm/path-to-regexp/-/path-to-regexp-0.1.12.tgz", + "integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==", + "license": "MIT" + }, + "node_modules/prebuild-install": { + "version": "7.1.3", + "resolved": "http://mirrors.tencentyun.com/npm/prebuild-install/-/prebuild-install-7.1.3.tgz", + "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", + "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.", + "license": "MIT", + "dependencies": { + "detect-libc": "^2.0.0", + "expand-template": "^2.0.3", + "github-from-package": "0.0.0", + "minimist": "^1.2.3", + "mkdirp-classic": "^0.5.3", + "napi-build-utils": "^2.0.0", + "node-abi": "^3.3.0", + "pump": "^3.0.0", + "rc": "^1.2.7", + "simple-get": "^4.0.0", + "tar-fs": "^2.0.0", + "tunnel-agent": "^0.6.0" + }, + "bin": { + "prebuild-install": "bin.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "http://mirrors.tencentyun.com/npm/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", + "license": "MIT" + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "http://mirrors.tencentyun.com/npm/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/pump": { + "version": "3.0.4", + "resolved": "http://mirrors.tencentyun.com/npm/pump/-/pump-3.0.4.tgz", + "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/qs": { + "version": "6.13.0", + "resolved": "http://mirrors.tencentyun.com/npm/qs/-/qs-6.13.0.tgz", + "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.0.6" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "http://mirrors.tencentyun.com/npm/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.2", + "resolved": "http://mirrors.tencentyun.com/npm/raw-body/-/raw-body-2.5.2.tgz", + "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/rc": { + "version": "1.2.8", + "resolved": "http://mirrors.tencentyun.com/npm/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, + "node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "http://mirrors.tencentyun.com/npm/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/readable-stream/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "http://mirrors.tencentyun.com/npm/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "http://mirrors.tencentyun.com/npm/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "http://mirrors.tencentyun.com/npm/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "http://mirrors.tencentyun.com/npm/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "0.19.0", + "resolved": "http://mirrors.tencentyun.com/npm/send/-/send-0.19.0.tgz", + "integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "http://mirrors.tencentyun.com/npm/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.3", + "resolved": "http://mirrors.tencentyun.com/npm/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/serve-static": { + "version": "1.16.2", + "resolved": "http://mirrors.tencentyun.com/npm/serve-static/-/serve-static-1.16.2.tgz", + "integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.19.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "http://mirrors.tencentyun.com/npm/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "http://mirrors.tencentyun.com/npm/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "http://mirrors.tencentyun.com/npm/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "http://mirrors.tencentyun.com/npm/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "http://mirrors.tencentyun.com/npm/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "http://mirrors.tencentyun.com/npm/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/simple-get": { + "version": "4.0.1", + "resolved": "http://mirrors.tencentyun.com/npm/simple-get/-/simple-get-4.0.1.tgz", + "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, + "node_modules/statuses": { + "version": "2.0.1", + "resolved": "http://mirrors.tencentyun.com/npm/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/streamsearch": { + "version": "1.1.0", + "resolved": "http://mirrors.tencentyun.com/npm/streamsearch/-/streamsearch-1.1.0.tgz", + "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "http://mirrors.tencentyun.com/npm/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/string_decoder/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "http://mirrors.tencentyun.com/npm/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "http://mirrors.tencentyun.com/npm/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tar-fs": { + "version": "2.1.5", + "resolved": "http://mirrors.tencentyun.com/npm/tar-fs/-/tar-fs-2.1.5.tgz", + "integrity": "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==", + "license": "MIT", + "dependencies": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "http://mirrors.tencentyun.com/npm/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "license": "MIT", + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/tar-stream/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "http://mirrors.tencentyun.com/npm/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "http://mirrors.tencentyun.com/npm/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "http://mirrors.tencentyun.com/npm/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "http://mirrors.tencentyun.com/npm/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/typedarray": { + "version": "0.0.6", + "resolved": "http://mirrors.tencentyun.com/npm/typedarray/-/typedarray-0.0.6.tgz", + "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==", + "license": "MIT" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "http://mirrors.tencentyun.com/npm/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "http://mirrors.tencentyun.com/npm/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "http://mirrors.tencentyun.com/npm/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "http://mirrors.tencentyun.com/npm/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "http://mirrors.tencentyun.com/npm/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" + }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "http://mirrors.tencentyun.com/npm/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "license": "MIT", + "engines": { + "node": ">=0.4" + } + }, + "node_modules/yaml": { + "version": "2.6.1", + "resolved": "http://mirrors.tencentyun.com/npm/yaml/-/yaml-2.6.1.tgz", + "integrity": "sha512-7r0XPzioN/Q9kXBro/XPnA6kznR73DHq+GXh5ON7ZozRO6aMjbmiBuKste2wslTFkC5d1dw0GooOCepZXJ2SAg==", + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14" + } + } + } +} diff --git a/app/package.json b/app/package.json new file mode 100644 index 0000000..cee08fc --- /dev/null +++ b/app/package.json @@ -0,0 +1,18 @@ +{ + "name": "agent-app", + "version": "1.0.0", + "description": "自用通用 Agent 系统:多模型调度 + 任务目录 + 工具调用 + H5 Web UI", + "main": "server/server.js", + "scripts": { + "start": "node server/server.js", + "gen": "node ../scripts/gen-from-readme.js", + "test": "node test/smoke.js" + }, + "dependencies": { + "better-sqlite3": "11.3.0", + "express": "4.21.2", + "multer": "1.4.5-lts.1", + "minimatch": "9.0.5", + "yaml": "2.6.1" + } +} diff --git a/app/server/config.js b/app/server/config.js new file mode 100644 index 0000000..4e25e99 --- /dev/null +++ b/app/server/config.js @@ -0,0 +1,59 @@ +// 配置加载:AGENT_CONFIG 指向 config.yaml(见 config.example.yaml) +const fs = require('fs'); +const path = require('path'); +const YAML = require('yaml'); + +const DEFAULTS = { + port: 8080, + upstream_url: '', + api_key: '', + workspace_root: './data/tasks', + db_path: '', // 默认为 workspace_root/.agent.db + terminal: { default_timeout_ms: 30000, max_output_chars: 10000 }, + agent: { temperature: 1.0, max_tool_iterations: 50, max_retries: 2 }, + models: [], + auth: null, // { user, password },为空则不启用内置 basic auth(可交给 nginx-proxy) + // web_search 工具:内网 MCP 服务(JSON-RPC over HTTP,无状态) + web_search: { + url: 'https://web-search.ai.foresh.com/', + authorization: 'Basic a2ljZXI6USF3MmUzcjQ=', + }, +}; + +function deepMerge(base, extra) { + const out = Object.assign({}, base); + for (const [k, v] of Object.entries(extra || {})) { + if (v && typeof v === 'object' && !Array.isArray(v) && typeof base[k] === 'object' && base[k] !== null && !Array.isArray(base[k])) { + out[k] = deepMerge(base[k], v); + } else { + out[k] = v; + } + } + return out; +} + +function loadConfig(configPath) { + const p = configPath || process.env.AGENT_CONFIG || path.join(__dirname, '..', 'config.yaml'); + let raw = {}; + if (fs.existsSync(p)) { + raw = YAML.parse(fs.readFileSync(p, 'utf8')) || {}; + } + const cfg = deepMerge(DEFAULTS, raw); + + if (!Array.isArray(cfg.models) || cfg.models.length === 0) { + throw new Error('配置缺少 models:至少需要一个模型 {id, display_name}'); + } + for (const m of cfg.models) { + if (!m.id) throw new Error('models 中每项必须有 id'); + if (!m.display_name) m.display_name = m.id; + } + if (!cfg.upstream_url) throw new Error('配置缺少 upstream_url(cli-proxy-api 的 /v1 地址)'); + cfg.upstream_url = cfg.upstream_url.replace(/\/+$/, ''); + + cfg.workspace_root = path.resolve(cfg.workspace_root); + if (!cfg.db_path) cfg.db_path = path.join(cfg.workspace_root, '.agent.db'); + cfg.config_path = p; + return cfg; +} + +module.exports = { loadConfig }; diff --git a/app/server/db.js b/app/server/db.js new file mode 100644 index 0000000..a358617 --- /dev/null +++ b/app/server/db.js @@ -0,0 +1,66 @@ +// SQLite 数据层。表结构见 README 第九章;本模块同时提供常用查询。 +const Database = require('better-sqlite3'); +const path = require('path'); +const fs = require('fs'); + +function initDb(dbPath) { + fs.mkdirSync(path.dirname(dbPath), { recursive: true }); + const db = new Database(dbPath); + db.pragma('journal_mode = WAL'); + db.pragma('foreign_keys = ON'); + + db.exec(` + CREATE TABLE IF NOT EXISTS sessions ( + id TEXT PRIMARY KEY, + title TEXT DEFAULT '', + status TEXT NOT NULL, + phase TEXT NOT NULL DEFAULT 'planning', + model_id TEXT, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + completed_at INTEGER, + cancelled_at INTEGER + ); + + CREATE TABLE IF NOT EXISTS messages ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + session_id TEXT NOT NULL, + role TEXT NOT NULL, + content TEXT, + tool_calls TEXT, + tool_call_id TEXT, + name TEXT, + created_at INTEGER NOT NULL, + FOREIGN KEY (session_id) REFERENCES sessions(id) + ); + + CREATE TABLE IF NOT EXISTS files ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + session_id TEXT NOT NULL, + filename TEXT NOT NULL, + size INTEGER, + created_at INTEGER NOT NULL, + FOREIGN KEY (session_id) REFERENCES sessions(id) + ); + + CREATE TABLE IF NOT EXISTS model_pool ( + id TEXT PRIMARY KEY, + display_name TEXT, + is_busy INTEGER DEFAULT 0, + current_session_id TEXT + ); + + CREATE TABLE IF NOT EXISTS wait_queue ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + session_id TEXT NOT NULL, + queued_at INTEGER NOT NULL, + FOREIGN KEY (session_id) REFERENCES sessions(id) + ); + + CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_id, id); + CREATE INDEX IF NOT EXISTS idx_files_session ON files(session_id); + `); + return db; +} + +module.exports = { initDb }; diff --git a/app/server/engine.js b/app/server/engine.js new file mode 100644 index 0000000..73c8837 --- /dev/null +++ b/app/server/engine.js @@ -0,0 +1,434 @@ +// 核心引擎:会话管理、模型池调度(FIFO)、Agent 主循环、任务目录。 +// 单进程内存模型:JS 单线程 + better-sqlite3 同步 API,不存在跨进程竞争。 +const fs = require('fs'); +const path = require('path'); +const { buildMessages, callModel } = require('./llm'); +const { executeTool, resolveInTask } = require('./tools/executor'); + +const TOOL_DEFINITIONS = require('./tools/definitions.json'); + +const START_EXECUTION_MESSAGE = + '我说完了,你可以开始干活了。先把我上面说的需求整理成 task.md 文件写入任务目录,然后按照 task.md 开始执行。'; + +let cfg, db, bus; +const runs = new Map(); // session_id -> {cancelled, procs:Set, abortController, looping:boolean} + +// ---------- 小工具 ---------- +const now = () => Date.now(); + +function genTaskId() { + const d = new Date(); + const pad = n => String(n).padStart(2, '0'); + const day = d.getUTCFullYear() + pad(d.getUTCMonth() + 1) + pad(d.getUTCDate()); + const prefix = 'task-' + day + '-'; + const row = db.prepare("SELECT COUNT(*) AS c FROM sessions WHERE id LIKE ?").get(prefix + '%'); + let seq = row.c + 1; + let id = prefix + String(seq).padStart(3, '0'); + while (db.prepare('SELECT id FROM sessions WHERE id = ?').get(id)) { + seq++; + id = prefix + String(seq).padStart(3, '0'); + } + return id; +} + +function taskDirOf(sessionId) { + return path.join(cfg.workspace_root, sessionId); +} + +function getSession(sessionId) { + return db.prepare('SELECT * FROM sessions WHERE id = ?').get(sessionId); +} + +function touch(sessionId, fields) { + const sets = ['updated_at = ?']; + const vals = [now()]; + for (const [k, v] of Object.entries(fields || {})) { + sets.push(k + ' = ?'); + vals.push(v); + } + vals.push(sessionId); + db.prepare('UPDATE sessions SET ' + sets.join(', ') + ' WHERE id = ?').run(...vals); +} + +function loadHistory(sessionId) { + return db.prepare('SELECT * FROM messages WHERE session_id = ? ORDER BY id').all(sessionId); +} + +function saveMessage(sessionId, msg) { + const info = db.prepare( + 'INSERT INTO messages (session_id, role, content, tool_calls, tool_call_id, name, created_at) VALUES (?,?,?,?,?,?,?)' + ).run(sessionId, msg.role, msg.content || null, + msg.tool_calls ? JSON.stringify(msg.tool_calls) : null, + msg.tool_call_id || null, msg.name || null, now()); + return info.lastInsertRowid; +} + +function emitStatus(sessionId) { + const s = getSession(sessionId); + if (!s) return; + bus.emit(sessionId, 'status', { + session_id: sessionId, + status: s.status, + phase: s.phase, + model_id: s.model_id, + queue_pos: s.status === 'queued' ? queuePosition(sessionId) : null, + }); +} + +function queuePosition(sessionId) { + const row = db.prepare( + 'SELECT queued_at FROM wait_queue WHERE session_id = ?' + ).get(sessionId); + if (!row) return null; + const better = db.prepare('SELECT COUNT(*) AS c FROM wait_queue WHERE queued_at < ?').get(row.queued_at); + return better.c + 1; +} + +// ---------- 模型池调度 ---------- +function syncModelPool() { + const stmt = db.prepare( + 'INSERT INTO model_pool (id, display_name, is_busy, current_session_id) VALUES (?,?,0,NULL) ON CONFLICT(id) DO UPDATE SET display_name=excluded.display_name' + ); + for (const m of cfg.models) stmt.run(m.id, m.display_name); + // 清理配置中已删除的模型 + const ids = cfg.models.map(m => m.id); + for (const row of db.prepare('SELECT id FROM model_pool').all()) { + if (!ids.includes(row.id)) db.prepare('DELETE FROM model_pool WHERE id = ?').run(row.id); + } + // 进程重启后:释放所有绑定、把 active 会话退回队列 + db.prepare('UPDATE model_pool SET is_busy = 0, current_session_id = NULL').run(); + for (const s of db.prepare("SELECT id FROM sessions WHERE status = 'active'").all()) { + db.prepare("UPDATE sessions SET status='queued', model_id=NULL, updated_at=? WHERE id=?").run(now(), s.id); + enqueue(s.id); + } + // 兜底:queued 会话必须在队列中 + for (const s of db.prepare("SELECT id FROM sessions WHERE status='queued'").all()) enqueue(s.id); +} + +function freeModel() { + return db.prepare('SELECT * FROM model_pool WHERE is_busy = 0 ORDER BY id').get(); +} + +function modelDisplayName(modelId) { + const row = db.prepare('SELECT display_name FROM model_pool WHERE id = ?').get(modelId); + return row ? row.display_name : modelId; +} + +function enqueue(sessionId) { + const exists = db.prepare('SELECT id FROM wait_queue WHERE session_id = ?').get(sessionId); + if (!exists) db.prepare('INSERT INTO wait_queue (session_id, queued_at) VALUES (?,?)').run(sessionId, now()); +} + +function dequeue(sessionId) { + db.prepare('DELETE FROM wait_queue WHERE session_id = ?').run(sessionId); +} + +function bindModel(session, model) { + db.prepare('UPDATE model_pool SET is_busy = 1, current_session_id = ? WHERE id = ?').run(session.id, model.id); + db.prepare("UPDATE sessions SET status='active', model_id=?, updated_at=? WHERE id=?").run(model.id, now(), session.id); +} + +function releaseModel(sessionId) { + db.prepare('UPDATE model_pool SET is_busy = 0, current_session_id = NULL WHERE current_session_id = ?').run(sessionId); + db.prepare('UPDATE sessions SET model_id = NULL, updated_at = ? WHERE id = ?').run(now(), sessionId); +} + +// 是否还有待回应的新用户消息(最后一条非 tool 消息是 user) +function hasPendingUser(sessionId) { + const rows = loadHistory(sessionId); + for (let i = rows.length - 1; i >= 0; i--) { + if (rows[i].role === 'tool') continue; + return rows[i].role === 'user'; + } + return false; +} + +// 有空闲模型就按 FIFO 派发排队会话。 +function dispatchQueued() { + for (;;) { + const model = freeModel(); + if (!model) return; + const head = db.prepare('SELECT session_id FROM wait_queue ORDER BY queued_at, id').get(); + if (!head) return; + dequeue(head.session_id); + const session = getSession(head.session_id); + if (!session) continue; + if (session.status !== 'queued') continue; + bindModel(session, model); + emitStatus(session.id); + if (hasPendingUser(session.id)) runLoop(session.id); + } +} + +// ---------- 运行控制 ---------- +function getRun(sessionId, create) { + let run = runs.get(sessionId); + if (!run && create) { + run = { cancelled: false, procs: new Set(), abortController: null, looping: false }; + runs.set(sessionId, run); + } + return run; +} + +function killRunProcs(run) { + for (const proc of run.procs) { + try { process.kill(-proc.pid, 'SIGKILL'); } catch (_) { + try { proc.kill('SIGKILL'); } catch (__) {} + } + } + run.procs.clear(); +} + +// ---------- Agent 主循环 ---------- +async function runLoop(sessionId) { + const run = getRun(sessionId, true); + if (run.looping) return; // 已有循环在跑(下一轮迭代会自动带上最新消息) + run.looping = true; + try { + await runLoopInner(sessionId, run); + } catch (err) { + console.error('[engine] runLoop ' + sessionId + ' 异常:', err && err.stack || err); + bus.emit(sessionId, 'error', { message: String(err && err.message || err) }); + } finally { + run.looping = false; + finalize(sessionId, run); + } +} + +function finalize(sessionId, run) { + const s = getSession(sessionId); + if (!s || s.status !== 'active') { runs.delete(sessionId); return; } + const cancelled = run.cancelled; + touch(sessionId, { + status: cancelled ? 'cancelled' : 'completed', + cancelled_at: cancelled ? now() : null, + completed_at: cancelled ? null : now(), + }); + releaseModel(sessionId); + runs.delete(sessionId); + bus.emit(sessionId, 'done', { status: cancelled ? 'cancelled' : 'completed' }); + emitStatus(sessionId); + dispatchQueued(); +} + +async function runLoopInner(sessionId, run) { + let iter = 0; + // 已纳入模型请求的最大消息 id;用于判断是否有尚未被回应的新 user 消息 + // (不能用“最后一条非 tool 消息是 user”判断:流式输出期间到达的消息会排在 assistant 之前而被漏掉) + let lastIncludedId = 0; + const maxIter = cfg.agent.max_tool_iterations; + while (!run.cancelled && iter < maxIter) { + const session = getSession(sessionId); + if (!session || session.status !== 'active' || !session.model_id) break; + session.task_dir = taskDirOf(sessionId); + session.history = loadHistory(sessionId); + for (const m of session.history) if (m.id > lastIncludedId) lastIncludedId = m.id; + const messages = buildMessages(session, modelDisplayName(session.model_id)); + const tools = TOOL_DEFINITIONS; + + let result = null; + let lastErr = null; + for (let attempt = 0; attempt <= cfg.agent.max_retries && !run.cancelled; attempt++) { + try { + result = await streamAssistant(sessionId, run, session, messages, tools); + break; + } catch (err) { + lastErr = err; + const retriable = !err.upstream_status || err.upstream_status === 429 || err.upstream_status >= 500; + if (!retriable || attempt === cfg.agent.max_retries) break; + await sleep(2000 * (attempt + 1)); + } + } + if (run.cancelled) break; + if (!result) { + const text = '⚠️ 模型调用失败:' + (lastErr && lastErr.message || '未知错误'); + saveMessage(sessionId, { role: 'assistant', content: text }); + bus.emit(sessionId, 'assistant_message', { content: text, error: true }); + break; + } + + // 保存 assistant 消息 + const hasTools = result.tool_calls && result.tool_calls.length > 0; + const msgRow = { + role: 'assistant', + content: result.content || '', + tool_calls: hasTools ? result.tool_calls.map(tc => ({ + id: tc.id, type: 'function', + function: { name: tc.name, arguments: tc.arguments }, + })) : null, + }; + const assistantId = saveMessage(sessionId, msgRow); + bus.emit(sessionId, 'assistant_message', { id: assistantId, content: msgRow.content, tool_calls: msgRow.tool_calls }); + + if (!hasTools) { + // 回合结束;但若期间用户又发了新消息(live 投递),继续下一轮而不是收尾 + if (!hasUserSince(sessionId, lastIncludedId)) break; + continue; + } + + // 执行工具 + for (const tc of msgRow.tool_calls) { + if (run.cancelled) break; + const id = tc.id || ('call_' + Math.random().toString(36).slice(2, 10)); + bus.emit(sessionId, 'tool_call', { id, name: tc.function.name, arguments: tc.function.arguments }); + let output; + let isError = false; + try { + output = await executeTool({ sessionId, taskDir: taskDirOf(sessionId), run, cfg, db }, + tc.function.name, safeParse(tc.function.arguments)); + } catch (err) { + output = 'Error: ' + (err && err.message || String(err)); + isError = true; + } + if (run.cancelled && !isError) output = (output ? output + '\n' : '') + '(用户已终止任务)'; + bus.emit(sessionId, 'tool_result', { tool_call_id: id, name: tc.function.name, content: output.slice(0, 20000), is_error: isError }); + saveMessage(sessionId, { role: 'tool', tool_call_id: id, name: tc.function.name, content: output }); + } + iter++; + } + if (iter >= maxIter && !run.cancelled) { + const text = '⚠️ 已达到最大工具迭代次数(' + maxIter + '),自动停止。可继续输入让我接着干。'; + saveMessage(sessionId, { role: 'assistant', content: text }); + bus.emit(sessionId, 'assistant_message', { content: text }); + } +} + +// 流式接收 assistant 输出并转发 SSE。返回 callModel 结果。 +async function streamAssistant(sessionId, run, session, messages, tools) { + run.abortController = new AbortController(); + try { + return await callModel(cfg, session.model_id, messages, tools, { + signal: run.abortController.signal, + shouldCancel: () => run.cancelled, + onText: delta => bus.emit(sessionId, 'assistant_delta', { text: delta }), + }); + } finally { + run.abortController = null; + } +} + +function hasUserSince(sessionId, sinceId) { + const r = db.prepare( + "SELECT COUNT(*) AS c FROM messages WHERE session_id = ? AND role = 'user' AND id > ?" + ).get(sessionId, sinceId); + return r.c > 0; +} + +function safeParse(s) { + try { return JSON.parse(s || '{}'); } catch (_) { return {}; } +} + +function sleep(ms) { return new Promise(r => setTimeout(r, ms)); } + +// ---------- 对外 API ---------- +function createSession(title) { + const id = genTaskId(); + const dir = taskDirOf(id); + fs.mkdirSync(dir, { recursive: true }); + db.prepare( + "INSERT INTO sessions (id, title, status, phase, model_id, created_at, updated_at) VALUES (?,?,'queued','planning',NULL,?,?)" + ).run(id, title || '', now(), now()); + enqueue(id); + dispatchQueued(); + return getSession(id); +} + +// 用户消息(或“开始执行”的模板消息)入口。 +function postUserMessage(sessionId, content, opts) { + const session = getSession(sessionId); + if (!session) throw Object.assign(new Error('会话不存在'), { status_code: 404 }); + const messageId = saveMessage(sessionId, { role: 'user', content }); + if (!session.title) { + touch(sessionId, { title: content.slice(0, 24) }); + } + const run = runs.get(sessionId); + if (session.status === 'active' && run && run.looping) { + // 正在跑:下一轮迭代会从 DB 重新加载历史,自动带上这条消息 + return { message_id: messageId, delivered: 'live' }; + } + if (session.status === 'active' && (!run || !run.looping)) { + runLoop(sessionId); + return { message_id: messageId, delivered: 'live' }; + } + // 排队 / 已完成 / 已取消 → 重新入队 + touch(sessionId, { status: 'queued', cancelled_at: null, completed_at: null }); + enqueue(sessionId); + emitStatus(sessionId); + dispatchQueued(); + return { message_id: messageId, delivered: 'queued' }; +} + +function startExecution(sessionId) { + const session = getSession(sessionId); + if (!session) throw Object.assign(new Error('会话不存在'), { status_code: 404 }); + touch(sessionId, { phase: 'execution' }); + const ret = postUserMessage(sessionId, START_EXECUTION_MESSAGE); + bus.emit(sessionId, 'phase', { phase: 'execution' }); + return ret; +} + +function stop(sessionId) { + const session = getSession(sessionId); + if (!session) throw Object.assign(new Error('会话不存在'), { status_code: 404 }); + const run = runs.get(sessionId); + if (run) { + run.cancelled = true; + killRunProcs(run); + if (run.abortController) { try { run.abortController.abort(); } catch (_) {} } + } + dequeue(sessionId); + if (session.status === 'active') { + // run 在循环退出处会 finalize;若无循环在跑则直接收尾 + if (!run || !run.looping) { + touch(sessionId, { status: 'cancelled', cancelled_at: now() }); + releaseModel(sessionId); + runs.delete(sessionId); + bus.emit(sessionId, 'done', { status: 'cancelled' }); + } + } else { + touch(sessionId, { status: 'cancelled', cancelled_at: now(), model_id: null }); + } + emitStatus(sessionId); + dispatchQueued(); + return { ok: true }; +} + +function deleteSession(sessionId, deleteDir) { + const session = getSession(sessionId); + if (!session) throw Object.assign(new Error('会话不存在'), { status_code: 404 }); + stop(sessionId); + db.prepare('DELETE FROM messages WHERE session_id = ?').run(sessionId); + db.prepare('DELETE FROM files WHERE session_id = ?').run(sessionId); + db.prepare('DELETE FROM wait_queue WHERE session_id = ?').run(sessionId); + db.prepare('DELETE FROM sessions WHERE id = ?').run(sessionId); + if (deleteDir) { + try { fs.rmSync(taskDirOf(sessionId), { recursive: true, force: true }); } catch (_) {} + } + bus.closeAll(sessionId); + return { ok: true }; +} + +function setModelPool(cfg_, db_, bus_) { cfg = cfg_; db = db_; bus = bus_; } + +module.exports = { + setModelPool: setModelPool, + init: syncModelPool, + getDb: () => db, + getBus: () => bus, + getConfig: () => cfg, + createSession, + postUserMessage, + startExecution, + stop, + deleteSession, + getSession, + getRun, + taskDirOf, + loadHistory, + saveMessage, + queuePosition, + modelDisplayName, + dispatchQueued, + TOOL_DEFINITIONS, + START_EXECUTION_MESSAGE, +}; diff --git a/app/server/llm.js b/app/server/llm.js new file mode 100644 index 0000000..75dfa8b --- /dev/null +++ b/app/server/llm.js @@ -0,0 +1,131 @@ +// 上游调用:OpenAI 兼容 /chat/completions 流式接口(由 cli-proxy-api 代理)。 +// 累积 content 与 tool_calls 分片;支持 abort。 +const fs = require('fs'); +const path = require('path'); + +const SYSTEM_PROMPT_TEMPLATE = fs.readFileSync(path.join(__dirname, 'templates', 'system-prompt.txt'), 'utf8'); + +function buildSystemPrompt(session, modelDisplayName) { + const d = new Date(); + const pad = n => String(n).padStart(2, '0'); + const dateStr = d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate()); + return SYSTEM_PROMPT_TEMPLATE + .replace('{动态日期}', dateStr) + .replace('{任务目录路径}', session.task_dir) + .replace('{模型显示名}', modelDisplayName || session.model_id || ''); +} + +// 将 DB 消息行转为 OpenAI messages 数组(不含 system,由调用方拼接)。 +function buildMessages(session, modelDisplayName) { + const messages = [{ role: 'system', content: buildSystemPrompt(session, modelDisplayName) }]; + for (const row of session.history) { + if (row.role === 'assistant') { + const m = { role: 'assistant', content: row.content || '' }; + if (row.tool_calls) m.tool_calls = JSON.parse(row.tool_calls); + if (!m.content) delete m.content; + messages.push(m); + } else if (row.role === 'tool') { + messages.push({ role: 'tool', tool_call_id: row.tool_call_id, name: row.name, content: row.content || '' }); + } else { + messages.push({ role: row.role, content: row.content || '' }); + } + } + return messages; +} + +// 解析 SSE 行流,对每个 data: JSON 调用 onEvent。 +async function forEachSSEData(response, onEvent) { + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + let buf = ''; + while (true) { + const { done, value } = await reader.read(); + if (done) break; + buf += decoder.decode(value, { stream: true }); + let idx; + while ((idx = buf.indexOf('\n\n')) >= 0) { + const block = buf.slice(0, idx); + buf = buf.slice(idx + 2); + for (const line of block.split('\n')) { + const t = line.trim(); + if (!t.startsWith('data:')) continue; + const data = t.slice(5).trim(); + if (data === '[DONE]') return; + try { onEvent(JSON.parse(data)); } catch (_) { /* 忽略坏帧 */ } + } + } + } +} + +// 调模型一次。onText(textDelta) 回调流式文本。 +// 返回 { content, tool_calls: [{id,name,arguments(string)}], finish_reason, usage, aborted } +async function callModel(cfg, modelId, messages, tools, options) { + const opts = options || {}; + const controller = new AbortController(); + if (opts.signal) { + if (opts.signal.aborted) controller.abort(); + else opts.signal.addEventListener('abort', () => controller.abort()); + } + const body = { + model: modelId, + messages, + stream: true, + stream_options: { include_usage: true }, + temperature: cfg.agent.temperature, + }; + if (tools && tools.length) body.tools = tools; + + const headers = { 'Content-Type': 'application/json' }; + if (cfg.api_key) headers.Authorization = 'Bearer ' + cfg.api_key; + + const res = await fetch(cfg.upstream_url + '/chat/completions', { + method: 'POST', + headers, + body: JSON.stringify(body), + signal: controller.signal, + }); + if (!res.ok) { + const text = await res.text().catch(() => ''); + const err = new Error('上游返回 ' + res.status + ': ' + text.slice(0, 500)); + err.upstream_status = res.status; + throw err; + } + + let content = ''; + let finishReason = null; + let usage = null; + let aborted = false; + const toolCalls = new Map(); // index -> {id, name, arguments} + + try { + await forEachSSEData(res, evt => { + if (opts.shouldCancel && opts.shouldCancel()) { aborted = true; controller.abort(); return; } + if (evt.usage) usage = evt.usage; + const choice = evt.choices && evt.choices[0]; + if (!choice) return; + if (choice.finish_reason) finishReason = choice.finish_reason; + const delta = choice.delta || {}; + if (typeof delta.content === 'string' && delta.content.length) { + content += delta.content; + if (opts.onText) opts.onText(delta.content); + } + for (const tc of delta.tool_calls || []) { + const idx = tc.index || 0; + if (!toolCalls.has(idx)) toolCalls.set(idx, { id: '', name: '', arguments: '' }); + const acc = toolCalls.get(idx); + if (tc.id) acc.id = tc.id; + if (tc.function) { + if (tc.function.name) acc.name += tc.function.name; + if (tc.function.arguments) acc.arguments += tc.function.arguments; + } + } + }); + } catch (e) { + if (e && e.name === 'AbortError') aborted = true; else throw e; + } + if (opts.shouldCancel && opts.shouldCancel()) aborted = true; + + return { content, tool_calls: Array.from(toolCalls.values()), finish_reason: finishReason, usage, aborted }; +} + +module.exports = { callModel, buildMessages, buildSystemPrompt }; diff --git a/app/server/public/css/style.css b/app/server/public/css/style.css new file mode 100644 index 0000000..f6ede6f --- /dev/null +++ b/app/server/public/css/style.css @@ -0,0 +1,237 @@ +* { margin: 0; padding: 0; box-sizing: border-box; } +html, body { height: 100%; overscroll-behavior: none; } +body { + font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Helvetica Neue", Helvetica, Arial, sans-serif; + background: #f2f3f7; + font-size: 15px; + color: #222; +} + +.app { height: 100vh; height: 100dvh; overflow: hidden; position: relative; } +.hidden { display: none !important; } + +/* ---- 页面滑动 ---- */ +.page { + position: absolute; inset: 0; + display: flex; flex-direction: column; + background: #f2f3f7; + transition: transform 0.28s ease; + will-change: transform; +} +.page.off-right { transform: translateX(100%); } +.page.off-left { transform: translateX(-100%); } + +/* ---- 顶部栏 ---- */ +.header { + display: flex; align-items: center; + background: linear-gradient(135deg, #1e3c72, #2a5299); + color: #fff; padding: 12px 12px; + padding-top: calc(12px + env(safe-area-inset-top)); + gap: 8px; +} +.header-left { display: flex; align-items: center; gap: 8px; flex: 1; } +.header h2 { font-size: 17px; font-weight: 600; white-space: nowrap; } +.chat-title { + flex: 1; text-align: center; font-size: 16px; font-weight: 600; + overflow: hidden; text-overflow: ellipsis; white-space: nowrap; +} +.header-right { display: flex; gap: 2px; } + +.icon-btn { + background: none; border: none; cursor: pointer; + width: 36px; height: 36px; border-radius: 8px; + display: inline-flex; align-items: center; justify-content: center; + color: #fff; +} +.icon-btn:active { background: rgba(255,255,255,0.15); } +.icon-btn svg { width: 22px; height: 22px; stroke: currentColor; fill: none; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } +#files-panel .icon-btn, .files-panel-header .icon-btn { color: #555; } +#files-panel .icon-btn:active { background: #eee; } + +/* ---- 模型池条 ---- */ +.model-strip { + display: flex; gap: 6px; padding: 8px 12px 0; + flex-wrap: wrap; +} +.model-chip { + font-size: 11px; padding: 3px 8px; border-radius: 10px; + background: #e3f2e6; color: #217a34; +} +.model-chip.busy { background: #fdecea; color: #b3382c; } + +/* ---- 会话列表 ---- */ +.session-list { flex: 1; overflow-y: auto; padding: 10px 12px calc(16px + env(safe-area-inset-bottom)); } +.session-card { + background: #fff; border-radius: 12px; padding: 12px 14px; margin-bottom: 10px; + box-shadow: 0 1px 4px rgba(30,40,90,0.06); + display: flex; align-items: center; gap: 10px; cursor: pointer; +} +.session-card:active { background: #f7f8fb; } +.session-main { flex: 1; overflow: hidden; } +.session-name { font-weight: 600; font-size: 15px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.session-meta { font-size: 12px; color: #888; margin-top: 3px; display: flex; gap: 8px; flex-wrap: wrap; } +.badge { font-size: 11px; padding: 1px 7px; border-radius: 8px; white-space: nowrap; } +.badge.active { background: #e3f2e6; color: #217a34; } +.badge.queued { background: #fff4dc; color: #a06a00; } +.badge.completed { background: #eceff5; color: #5c6674; } +.badge.cancelled { background: #fdecea; color: #b3382c; } +.badge.execution { background: #e8ecfd; color: #3550b8; } +.session-del { color: #c33; background: none; border: none; font-size: 12px; padding: 6px; } + +/* ---- 阶段开关条 ---- */ +.phase-bar { + display: flex; align-items: center; justify-content: space-between; + padding: 8px 12px; background: #fff; border-bottom: 1px solid #e8e8ee; +} +.status-pill { font-size: 12px; color: #666; } +.phase-switch { + border: none; border-radius: 18px; padding: 8px 18px; + font-size: 14px; font-weight: 600; color: #fff; cursor: pointer; + box-shadow: inset 0 -2px 0 rgba(0,0,0,0.18); + transition: background 0.2s; +} +.phase-switch.planning { background: #2e9d54; } +.phase-switch.planning:active { background: #268547; } +.phase-switch.execution { background: #d2483c; } +.phase-switch.execution:active { background: #b13a2f; } + +/* ---- 消息 ---- */ +.messages { + flex: 1; overflow-y: auto; padding: 12px 12px 8px; + display: flex; flex-direction: column; gap: 10px; + scroll-behavior: smooth; +} +.msg { display: flex; flex-direction: column; max-width: 86%; } +.msg.me { align-self: flex-end; align-items: flex-end; } +.msg.other { align-self: flex-start; align-items: flex-start; } +.msg-user { font-size: 11px; color: #98a; margin-bottom: 3px; display: flex; gap: 6px; align-items: center; } +.ai-avatar { + width: 18px; height: 18px; border-radius: 50%; + background: linear-gradient(135deg, #2a5299, #4d7fd6); + display: inline-block; +} +.ai-avatar.gray { background: #b9bec9; filter: grayscale(); } +.msg-bubble { + padding: 9px 12px; border-radius: 12px; line-height: 1.55; + word-break: break-word; overflow-wrap: break-word; font-size: 14.5px; + background: #fff; box-shadow: 0 1px 3px rgba(30,40,90,0.07); +} +.msg.me .msg-bubble { background: #d7e7ff; border-bottom-right-radius: 4px; } +.msg.other .msg-bubble { border-bottom-left-radius: 4px; } +.msg-bubble pre { + background: #f0f2f6; padding: 8px 10px; border-radius: 8px; + overflow-x: auto; font-size: 12.5px; margin: 6px 0; +} +.msg-bubble code { background: #f0f2f6; padding: 1px 4px; border-radius: 4px; font-size: 12.5px; } +.msg-bubble pre code { background: none; padding: 0; } +.msg-bubble img { max-width: 100%; border-radius: 8px; } +.msg-bubble table { border-collapse: collapse; margin: 6px 0; display: block; overflow-x: auto; } +.msg-bubble th, .msg-bubble td { border: 1px solid #dde; padding: 4px 8px; font-size: 13px; } +.msg-bubble blockquote { border-left: 3px solid #ccd; padding-left: 8px; color: #667; margin: 4px 0; } +.msg-time { font-size: 10px; color: #aab; margin-top: 3px; } + +/* 工具卡片 */ +.tool-card { + align-self: stretch; max-width: 100%; + background: #fbf7ee; border: 1px solid #eadfc4; border-radius: 10px; + padding: 8px 12px; font-size: 13px; color: #6b5b2a; +} +.tool-card .tool-name { font-weight: 600; } +.tool-card summary { cursor: pointer; list-style: none; display: flex; gap: 8px; align-items: center; } +.tool-card summary::-webkit-details-marker { display: none; } +.tool-card .tool-args { color: #8a763b; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; font-size: 12px; } +.tool-card pre { + background: #f6f1e3; padding: 8px; border-radius: 8px; margin-top: 6px; + white-space: pre-wrap; overflow-x: auto; max-height: 300px; overflow-y: auto; + font-size: 12px; color: #55492a; +} +.tool-card.error { background: #fdecea; border-color: #f2c4bd; color: #a3352a; } +.tool-card .spin { display: inline-block; animation: rot 1s linear infinite; } +@keyframes rot { to { transform: rotate(360deg); } } + +/* ---- 文件面板 ---- */ +.files-panel { + position: absolute; left: 0; right: 0; bottom: 0; + max-height: 55%; background: #fff; border-radius: 16px 16px 0; + box-shadow: 0 -4px 20px rgba(20,30,70,0.15); z-index: 9; + display: flex; flex-direction: column; + padding-bottom: env(safe-area-inset-bottom); +} +.files-panel-header { + display: flex; justify-content: space-between; align-items: center; + padding: 12px 16px; font-weight: 600; border-bottom: 1px solid #eee; +} +.files-list { overflow-y: auto; padding: 6px 8px; } +.file-row { + display: flex; align-items: center; gap: 8px; padding: 8px 8px; + border-radius: 8px; font-size: 13.5px; +} +.file-row:active { background: #f4f5f9; } +.file-name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.file-size { color: #99a; font-size: 12px; } +.file-act { color: #2a5299; text-decoration: none; font-size: 13px; padding: 2px 6px; background: none; border: none; cursor: pointer; } +.file-act.del { color: #c33; } +.empty-tip { color: #99a; text-align: center; padding: 18px; font-size: 13px; } + +/* ---- 输入区 ---- */ +.input-area { + display: flex; align-items: flex-end; gap: 8px; + padding: 8px 10px calc(8px + env(safe-area-inset-bottom)); + background: #fff; border-top: 1px solid #e8e8ee; +} +.input-area textarea { + flex: 1; resize: none; border: none; outline: none; + background: #f2f3f7; border-radius: 18px; padding: 9px 14px; + font-size: 15px; line-height: 1.4; max-height: 120px; + font-family: inherit; +} +.file-upload-btn { + width: 38px; height: 38px; border-radius: 50%; + display: inline-flex; align-items: center; justify-content: center; + color: #667; cursor: pointer; flex-shrink: 0; +} +.file-upload-btn:active { background: #eee; } +.file-upload-btn svg { width: 22px; height: 22px; stroke: currentColor; fill: none; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } +.send-btn { + width: 38px; height: 38px; border-radius: 50%; border: none; cursor: pointer; + background: linear-gradient(135deg, #2a5299, #4d7fd6); + display: inline-flex; align-items: center; justify-content: center; flex-shrink: 0; +} +.send-btn:active { opacity: 0.8; } +.send-btn svg { width: 18px; height: 18px; stroke: #fff; fill: none; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } + +/* ---- 弹窗 ---- */ +.modal-overlay { + position: fixed; inset: 0; background: rgba(20,25,50,0.45); + display: flex; align-items: center; justify-content: center; z-index: 100; +} +.modal { + background: #fff; border-radius: 14px; padding: 20px; width: 84%; max-width: 360px; + position: relative; +} +.modal h3 { margin-bottom: 12px; font-size: 16px; } +.modal input { + width: 1; border: 1px solid #dde; border-radius: 8px; + padding: 10px 12px; font-size: 15px; margin-bottom: 10px; outline: none; +} +.modal input:focus { border-color: #2a5299; } +.modal-close-btn { + position: absolute; right: 10px; top: 10px; + background: none; border: none; cursor: pointer; color: #99a; + width: 28px; height: 28px; +} +.modal-close-btn svg { width: 18px; height: 18px; stroke: currentColor; fill: none; stroke-width: 2; stroke-linecap: round; } +.primary-btn { + width: 1; background: linear-gradient(135deg, #1e3c72, #2a5299); + color: #fff; border: none; border-radius: 10px; padding: 11px; + font-size: 15px; font-weight: 600; cursor: pointer; +} +.primary-btn:active { opacity: 0.9; } + +/* ---- Toast ---- */ +.toast { + position: fixed; left: 50%; bottom: 90px; transform: translateX(-50%); + background: rgba(20,25,45,0.85); color: #fff; + padding: 9px 16px; border-radius: 20px; font-size: 13.5px; z-index: 200; + max-width: 80%; text-align: center; +} diff --git a/app/server/public/index.html b/app/server/public/index.html new file mode 100644 index 0000000..97cd46e --- /dev/null +++ b/app/server/public/index.html @@ -0,0 +1,102 @@ + + + + + + Agent 任务台 + + + + + + + +
+ +
+
+
+ + + +

Agent 任务台

+
+
+ +
+
+
+
+
+ + + + + + +
+ + + + + + diff --git a/app/server/public/js/app.js b/app/server/public/js/app.js new file mode 100644 index 0000000..8cdd3ba --- /dev/null +++ b/app/server/public/js/app.js @@ -0,0 +1,472 @@ +// Agent 任务台前端:会话列表 / 聊天(SSE 流式)/ 文件管理 / 阶段开关 +// 交互风格参考 ai-xiaocai(移动优先、左右滑动切页)。 +'use strict'; + +if (typeof marked !== 'undefined') { + marked.setOptions({ breaks: true, gfm: true }); +} + +const state = { + sessionId: null, + phase: 'planning', + status: '', + es: null, + streamEl: null, + streamText: '', + toolCards: {}, + filePanelOpen: false, +}; + +// ---------- API ---------- +async function req(method, url, body, isForm) { + const opt = { method, headers: {} }; + if (body && !isForm) { + opt.headers['Content-Type'] = 'application/json'; + opt.body = JSON.stringify(body); + } else if (body && isForm) { + opt.body = body; + } + const res = await fetch(url, opt); + if (!res.ok) { + let msg = 'HTTP ' + res.status; + try { msg = (await res.json()).error || msg; } catch (_) {} + throw new Error(msg); + } + return res.json(); +} + +// ---------- 工具函数 ---------- +function $(id) { return document.getElementById(id); } +function esc(s) { const d = document.createElement('div'); d.textContent = s == null ? '' : String(s); return d.innerHTML; } +function fmtSize(n) { + if (n == null) return ''; + if (n < 1024) return n + ' B'; + if (n < 1024 * 1024) return (n / 1024).toFixed(1) + ' KB'; + return (n / 1024 / 1024).toFixed(1) + ' MB'; +} +function fmtTime(ts) { + if (!ts) return ''; + const d = new Date(ts); + const p = n => String(n).padStart(2, '0'); + const today = new Date().toDateString() === d.toDateString(); + return (today ? '' : (d.getMonth() + 1) + '/' + d.getDate() + ' ') + p(d.getHours()) + ':' + p(d.getMinutes()); +} +function toast(msg) { + const el = $('toast'); + el.textContent = msg; + el.classList.remove('hidden'); + clearTimeout(toast._t); + toast._t = setTimeout(() => el.classList.add('hidden'), 2500); +} +function toolArgsSummary(name, argsStr) { + let s = ''; + try { + const o = JSON.parse(argsStr || '{}'); + const key = ['path', 'command', 'regex', 'glob', 'url', 'query', 'source_path', 'destination_path']; + for (const k of key) if (o[k]) { s = String(o[k]); break; } + if (!s) s = argsStr || ''; + } catch (_) { s = argsStr || ''; } + if (s.length > 80) s = s.slice(0, 80) + '…'; + return s; +} + +// ---------- 页面切换 ---------- +function showChat() { + $('list-page').classList.add('off-left'); + $('chat-page').classList.remove('hidden'); + $('chat-page').classList.add('off-right'); + requestAnimationFrame(() => { + requestAnimationFrame(() => $('chat-page').classList.remove('off-right')); + }); +} +function showList() { + $('chat-page').classList.add('off-right'); + setTimeout(() => { + $('chat-page').classList.add('hidden'); + $('list-page').classList.remove('off-left'); + }, 50); +} + +// 滑动切换:聊天页右滑返回列表 +(function bindSwipe() { + let x0 = null, y0 = null; + $('chat-page').addEventListener('touchstart', e => { + if (e.touches.length !== 1) return; + x0 = e.touches[0].clientX; y0 = e.touches[0].clientY; + }, { passive: true }); + $('chat-page').addEventListener('touchend', e => { + if (x0 == null) return; + const t = e.changedTouches[0]; + const dx = t.clientX - x0, dy = t.clientY - y0; + x0 = null; + if (dx > 70 && Math.abs(dy) < 60) ui.backToList(); + }, { passive: true }); +})(); + +// ---------- 会话列表 ---------- +async function loadSessions() { + try { + const rows = await req('GET', '/api/sessions'); + const el = $('session-list'); + if (!rows.length) { + el.innerHTML = '
还没有任务,点右上角 + 新建
'; + return; + } + el.innerHTML = rows.map(s => { + const st = { queued: '排队中', active: '活跃中', completed: '已完成', cancelled: '已终止' }[s.status] || s.status; + const badge = '' + st + (s.status === 'queued' && s.queue_pos ? ' #' + s.queue_pos : '') + ''; + const phase = s.phase === 'execution' ? '执行中阶段' : ''; + return '
' + + '
' + + '
' + esc(s.title || s.id) + '
' + + '
' + esc(s.id) + '' + badge + phase + + (s.model_id ? '' + esc(s.model_id) + '' : '') + '
' + + '
' + + '' + + '
'; + }).join(''); + } catch (e) { toast('加载会话失败:' + e.message); } +} + +async function loadModels() { + try { + const rows = await req('GET', '/api/models'); + $('model-strip').innerHTML = rows.map(m => + '' + + esc(m.display_name || m.id) + (m.is_busy ? ' 忙' : ' 空闲') + '').join(''); + } catch (_) {} +} + +// ---------- 消息渲染 ---------- +function md(text) { + if (typeof marked === 'undefined') return esc(text); + try { return marked.parse(text || ''); } catch (_) { return esc(text); } +} + +function renderToolCard(id, name, argsStr) { + const div = document.createElement('div'); + div.className = 'tool-card'; + div.id = 'tool-' + id; + div.innerHTML = + '
◌' + + '' + esc(name) + '' + + '' + esc(toolArgsSummary(name, argsStr)) + '' + + '
执行中…
'; + return div; +} + +function fillToolResult(id, content, isError) { + const card = document.getElementById('tool-' + id); + if (!card) return; + if (isError) card.classList.add('error'); + card.querySelector('.spin').textContent = isError ? '✕' : '✓'; + card.querySelector('pre').textContent = content || '(空)'; +} + +function msgNode(m, cardMap) { + if (m.role === 'tool') { + if (m.tool_call_id && cardMap && cardMap[m.tool_call_id]) { + fillToolResult(m.tool_call_id, m.content, false); + } + return null; + } + const wrap = document.createElement('div'); + if (m.role === 'user') { + wrap.className = 'msg me'; + wrap.innerHTML = '
我
' + + '
' + esc(m.content) + '
' + + '
' + fmtTime(m.created_at) + '
'; + return wrap; + } + if (m.role === 'assistant') { + wrap.className = 'msg other'; + const gray = state.status === 'queued' ? ' gray' : ''; + let inner = '
AI' + + (m.model_tag ? ' · ' + esc(m.model_tag) : '') + '
'; + if (m.content) inner += '
' + md(m.content) + '
'; + inner += '
' + fmtTime(m.created_at) + '
'; + wrap.innerHTML = inner; + return wrap; + } + return null; +} + +function appendToolCardsFromAssistant(m, container) { + if (!m.tool_calls) return; + let calls; + try { calls = typeof m.tool_calls === 'string' ? JSON.parse(m.tool_calls) : m.tool_calls; } catch (_) { return; } + for (const c of calls) { + const id = c.id || ('c' + Math.random().toString(36).slice(2, 10)); + const card = renderToolCard(id, c.function.name, c.function.arguments); + container.appendChild(card); + state.toolCards[id] = card; + } +} + +async function renderDetail(detail) { + const box = $('messages'); + box.innerHTML = ''; + state.streamEl = null; + state.streamText = ''; + state.toolCards = {}; + const s = detail.session; + state.phase = s.phase; + state.status = s.status; + updatePhaseUI(); + $('chat-title').textContent = s.title || s.id; + for (const m of detail.messages) { + const node = msgNode(m, state.toolCards); + if (node) box.appendChild(node); + if (m.role === 'assistant') appendToolCardsFromAssistant(m, box); + } + if (!detail.messages.length) { + box.innerHTML = '
描述你的需求,AI 会先和你讨论(规划阶段)。
'; + } + scrollBottom(); + loadFiles(); +} + +function scrollBottom() { + const box = $('messages'); + box.scrollTop = box.scrollHeight; +} + +// ---------- SSE ---------- +function connectStream() { + if (state.es) { state.es.close(); state.es = null; } + const es = new EventSource('/api/sessions/' + state.sessionId + '/stream'); + state.es = es; + es.addEventListener('status', ev => { + const d = JSON.parse(ev.data); + state.status = d.status; + state.phase = d.phase; + updatePhaseUI(d); + }); + es.addEventListener('phase', ev => { + state.phase = JSON.parse(ev.data).phase; + updatePhaseUI(); + }); + es.addEventListener('assistant_delta', ev => { + const d = JSON.parse(ev.data); + if (!state.streamEl) { + const wrap = document.createElement('div'); + wrap.className = 'msg other'; + wrap.innerHTML = '
AI
' + + '
'; + state.streamEl = wrap.querySelector('.msg-bubble'); + state.streamText = ''; + $('messages').appendChild(wrap); + } + state.streamText += d.text; + state.streamEl.textContent = state.streamText; + scrollBottom(); + }); + es.addEventListener('assistant_message', ev => { + const d = JSON.parse(ev.data); + if (state.streamEl) { + const bubble = state.streamEl; + bubble.innerHTML = md(d.content || ''); + state.streamEl = null; + state.streamText = ''; + } else if (d.content) { + const box = $('messages'); + const wrap = document.createElement('div'); + wrap.className = 'msg other'; + wrap.innerHTML = '
AI
' + + '
' + md(d.content) + '
'; + box.appendChild(wrap); + } + if (d.tool_calls) { + appendToolCardsFromAssistant({ tool_calls: d.tool_calls }, $('messages')); + scrollBottom(); + } + }); + es.addEventListener('tool_call', ev => { + const d = JSON.parse(ev.data); + const card = renderToolCard(d.id, d.name, d.arguments); + $('messages').appendChild(card); + state.toolCards[d.id] = card; + scrollBottom(); + }); + es.addEventListener('tool_result', ev => { + const d = JSON.parse(ev.data); + fillToolResult(d.tool_call_id, d.content, d.is_error); + scrollBottom(); + }); + es.addEventListener('done', ev => { + loadSessions(); + loadModels(); + }); + es.addEventListener('error', ev => { + try { + const d = JSON.parse(ev.data); + if (d && d.message) toast('错误:' + d.message); + } catch (_) { /* EventSource 连接错误,自动重连 */ } + }); +} + +// ---------- 阶段开关 ---------- +function updatePhaseUI(d) { + const btn = $('phase-switch'); + const pill = $('status-pill'); + const stMap = { queued: '排队中', active: '活跃中', completed: '已完成', cancelled: '已终止' }; + let text = stMap[state.status] || state.status || '--'; + if (d && d.queue_pos) text += '(第 ' + d.queue_pos + ' 位)'; + if (state.status === 'active') { + const run = d && d.running; + text = '活跃中 · ' + (state.phase === 'execution' ? '执行' : '规划') + (d && d.model_id ? ' · ' + d.model_id : ''); + } + pill.textContent = text; + if (state.phase === 'execution') { + btn.textContent = '■ 终止'; + btn.className = 'phase-switch execution'; + } else { + btn.textContent = '▶ 开始执行'; + btn.className = 'phase-switch planning'; + } +} + +// ---------- 文件 ---------- +async function loadFiles() { + if (!state.sessionId) return; + try { + const files = await req('GET', '/api/sessions/' + state.sessionId + '/files'); + const el = $('files-list'); + if (!files.length) { + el.innerHTML = '
还没有文件。上传文件或在执行阶段让 AI 生成。
'; + return; + } + el.innerHTML = files.map(f => { + const url = '/api/sessions/' + state.sessionId + '/files/download?path=' + encodeURIComponent(f.filename); + return '
' + esc(f.filename) + '' + + '' + fmtSize(f.size) + '' + + '下载' + + '
'; + }).join(''); + } catch (e) { toast('读取文件失败:' + e.message); } +} + +// ---------- 主逻辑 ---------- +const ui = { + openCreate() { $('create-modal').classList.remove('hidden'); $('new-title').focus(); }, + closeCreate() { $('create-modal').classList.add('hidden'); }, + async createSession() { + try { + const title = $('new-title').value.trim(); + const s = await req('POST', '/api/sessions', { title }); + this.closeCreate(); + $('new-title').value = ''; + await loadSessions(); + this.openSession(s.id); + } catch (e) { toast('创建失败:' + e.message); } + }, + async deleteSession(id) { + if (!confirm('删除会话?')) return; + const delDir = confirm('同时删除任务目录(文件将不可恢复)?\n取消 = 仅删除会话记录'); + try { + await req('DELETE', '/api/sessions/' + id + '?delete_dir=' + (delDir ? 'true' : 'false')); + if (state.sessionId === id) this.backToList(); + loadSessions(); + } catch (e) { toast('删除失败:' + e.message); } + }, + async openSession(id) { + state.sessionId = id; + showChat(); + try { + const detail = await req('GET', '/api/sessions/' + id); + await renderDetail(detail); + connectStream(); + } catch (e) { toast('打开会话失败:' + e.message); } + }, + backToList() { + if (state.es) { state.es.close(); state.es = null; } + state.sessionId = null; + showList(); + loadSessions(); + loadModels(); + }, + async send() { + const ta = $('msg-input'); + const content = ta.value.trim(); + if (!content || !state.sessionId) return; + ta.value = ''; + ta.style.height = 'auto'; + const box = $('messages'); + const tip = box.querySelector('.empty-tip'); + if (tip) tip.remove(); + try { + const r = await req('POST', '/api/sessions/' + state.sessionId + '/messages', { content }); + const wrap = document.createElement('div'); + wrap.className = 'msg me'; + wrap.innerHTML = '
我' + (r.delivered === 'queued' ? '(排队中,暂存)' : '') + '
' + + '
' + esc(content) + '
'; + box.appendChild(wrap); + scrollBottom(); + } catch (e) { toast('发送失败:' + e.message); } + }, + async togglePhase() { + if (!state.sessionId) return; + try { + if (state.phase === 'planning') { + await req('POST', '/api/sessions/' + state.sessionId + '/start'); + state.phase = 'execution'; + updatePhaseUI(); + const box = $('messages'); + const wrap = document.createElement('div'); + wrap.className = 'msg me'; + wrap.innerHTML = '
我(开始执行)
' + + '
我说完了,你可以开始干活了。先把我上面说的需求整理成 task.md 文件写入任务目录,然后按照 task.md 开始执行。
'; + box.appendChild(wrap); + scrollBottom(); + } else { + await req('POST', '/api/sessions/' + state.sessionId + '/stop'); + toast('已发送终止指令'); + } + } catch (e) { toast('操作失败:' + e.message); } + }, + toggleFiles() { + state.filePanelOpen = !state.filePanelOpen; + $('files-panel').classList.toggle('hidden', !state.filePanelOpen); + if (state.filePanelOpen) loadFiles(); + }, + async uploadFiles(ev) { + const input = ev.target; + const files = input.files; + if (!files || !files.length || !state.sessionId) return; + const fd = new FormData(); + for (const f of files) fd.append('files', f); + input.value = ''; + try { + const r = await req('POST', '/api/sessions/' + state.sessionId + '/files', fd, true); + toast('已上传 ' + r.uploaded.length + ' 个文件'); + loadFiles(); + } catch (e) { toast('上传失败:' + e.message); } + }, + async deleteFile(name) { + if (!confirm('删除文件 ' + name + '?')) return; + try { + await req('DELETE', '/api/sessions/' + state.sessionId + '/files?path=' + encodeURIComponent(name)); + loadFiles(); + } catch (e) { toast('删除失败:' + e.message); } + }, +}; + +// ---------- 输入框行为 ---------- +document.addEventListener('input', e => { + if (e.target.id === 'msg-input') { + e.target.style.height = 'auto'; + e.target.style.height = Math.min(e.target.scrollHeight, 120) + 'px'; + } +}); +document.addEventListener('keydown', e => { + if (e.target.id === 'msg-input' && e.key === 'Enter' && !e.shiftKey) { + e.preventDefault(); + ui.send(); + } +}); + +// ---------- 启动 ---------- +showList(); +loadSessions(); +loadModels(); +setInterval(loadSessions, 8000); diff --git a/app/server/routes/files.js b/app/server/routes/files.js new file mode 100644 index 0000000..66e181f --- /dev/null +++ b/app/server/routes/files.js @@ -0,0 +1,138 @@ +// 文件管理 API(README 10.3):上传 / 列表 / 下载 / 删除 +const express = require('express'); +const fs = require('fs'); +const path = require('path'); +const multer = require('multer'); +const engine = require('../engine'); +const { listTaskFiles } = require('./sessions'); +const { resolveInTask } = require('../tools/executor'); + +const router = express.Router(); + +function taskDir(req) { + const dir = engine.taskDirOf(req.params.id); + fs.mkdirSync(dir, { recursive: true }); + return dir; +} + +function sanitizeName(original) { + let name = Buffer.from(original || 'file', 'latin1').toString('utf8'); + name = path.basename(name).replace(/[\/\x00-\x1f]/g, '_'); + while (name.startsWith('.')) name = name.slice(1); + return name || 'file'; +} + +const upload = multer({ + storage: multer.diskStorage({ + destination: function (req, file, cb) { + try { cb(null, taskDir(req)); } catch (err) { cb(err); } + }, + filename: function (req, file, cb) { + try { + const dir = taskDir(req); + const name = sanitizeName(file.originalname); + const ext = path.extname(name); + const stem = name.slice(0, name.length - ext.length); + let target = name; + let i = 0; + while (fs.existsSync(path.join(dir, target))) { + i++; + target = stem + '-' + i + ext; + } + cb(null, target); + } catch (err) { cb(err); } + }, + }), + limits: { filesize: 50 * 1024 * 1024 }, +}); + +router.post('/:id/files', upload.array('files', 10), function (req, res) { + try { + const uploaded = (req.files || []).map(f => ({ filename: f.filename, size: f.size })); + const db = engine.getDb(); + for (const f of uploaded) { + db.prepare('INSERT INTO files (session_id, filename, size, created_at) VALUES (?,?,?,?)') + .run(req.params.id, f.filename, f.size, Date.now()); + } + res.json({ uploaded }); + } catch (err) { + res.status(500).json({ error: String(err && err.message || err) }); + } +}); + +router.get('/:id/files', function (req, res) { + try { + const session = engine.getSession(req.params.id); + if (!session) return res.status(404).json({ error: '会话不存在' }); + res.json(listTaskFiles(engine.taskDirOf(session.id))); + } catch (err) { + res.status(500).json({ error: String(err && err.message || err) }); + } +}); + +// 下载(支持子目录路径,前端用 ?path=xxx 传入相对路径) +router.get('/:id/files/download', function (req, res) { + try { + const rel = String(req.query.path || ''); + if (!rel) return res.status(400).json({ error: '缺少 path 参数' }); + const abs = resolveInTask(engine.taskDirOf(req.params.id), rel); + const st = fs.statSync(abs); + if (!st.isFile()) return res.status(400).json({ error: '不是文件' }); + res.download(abs, path.basename(abs)); + } catch (err) { + res.status(404).json({ error: '文件不存在' }); + } +}); + +router.delete('/:id/files', function (req, res) { + try { + const rel = String(req.query.path || ''); + if (!rel) return res.status(400).json({ error: '缺少 path 参数' }); + const dir = engine.taskDirOf(req.params.id); + const abs = resolveInTask(dir, rel); + if (path.resolve(abs) === path.resolve(dir)) { + return res.status(400).json({ error: '禁止删除任务目录' }); + } + fs.rmSync(abs, { recursive: true, force: true }); + engine.getDb().prepare('DELETE FROM files WHERE session_id = ? AND filename = ?') + .run(req.params.id, rel); + res.json({ ok: true }); + } catch (err) { + res.status(404).json({ error: '文件不存在' }); + } +}); + +// 兼容 README 形式:GET /:id/files/{filename}(支持子目录) +router.get('/:id/files/*', function (req, res) { + try { + const rel = req.params[req.params.length - 1] || ''; + if (!rel) return res.status(400).json({ error: '缺少文件名' }); + const abs = resolveInTask(engine.taskDirOf(req.params.id), rel); + const st = fs.statSync(abs); + if (!st.isFile()) return res.status(400).json({ error: '不是文件' }); + res.download(abs, path.basename(abs)); + } catch (err) { + res.status(404).json({ error: '文件不存在' }); + } +}); + +// 兼容 README 形式:DELETE /:id/files/{filename} +router.delete('/:id/files/*', function (req, res) { + req.query.path = req.params[req.params.length - 1] || ''; + if (!req.query.path) return res.status(400).json({ error: '缺少文件名' }); + try { + const dir = engine.taskDirOf(req.params.id); + const abs = resolveInTask(dir, req.query.path); + if (path.resolve(abs) === path.resolve(dir)) { + return res.status(400).json({ error: '禁止删除任务目录' }); + } + fs.rmSync(abs, { recursive: true, force: true }); + engine.getDb().prepare('DELETE FROM files WHERE session_id = ? AND filename = ?') + .run(req.params.id, req.query.path); + res.json({ ok: true }); + } catch (err) { + res.status(404).json({ error: '文件不存在' }); + } +}); + +module.exports = router; diff --git a/app/server/routes/messages.js b/app/server/routes/messages.js new file mode 100644 index 0000000..91bf032 --- /dev/null +++ b/app/server/routes/messages.js @@ -0,0 +1,62 @@ +// 消息与交互 API(README 10.2):发消息 / SSE 流 / 开始执行 / 终止 +const express = require('express'); +const engine = require('../engine'); + +const router = express.Router(); + +function wrap(fn) { + return function (req, res) { + try { + fn(req, res); + } catch (err) { + res.status(err && err.status_code || 500).json({ error: String(err && err.message || err) }); + } + }; +} + +router.post('/:id/messages', wrap((req, res) => { + const content = String((req.body && req.body.content) || '').trim(); + if (!content) return res.status(400).json({ error: 'content 不能为空' }); + const r = engine.postUserMessage(req.params.id, content); + res.json(r); +})); + +router.post('/:id/start', wrap((req, res) => { + res.json(engine.startExecution(req.params.id)); +})); + +router.post('/:id/stop', wrap((req, res) => { + res.json(engine.stop(req.params.id)); +})); + +// SSE 事件流 +router.get('/:id/stream', (req, res) => { + const session = engine.getSession(req.params.id); + if (!session) return res.status(404).json({ error: '会话不存在' }); + const bus = engine.getBus(); + res.set({ + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + Connection: 'keep-alive', + 'X-Accel-Buffering': 'no', + }); + res.flushHeaders && res.flushHeaders(); + res.write('retry: 3000\n\n'); + bus.addClient(session.id, res); + const heartbeat = setInterval(() => { + try { res.write(': ping\n\n'); } catch (_) {} + }, 15000); + req.on('close', () => { + clearInterval(heartbeat); + bus.removeClient(session.id, res); + }); + bus.emit(session.id, 'status', { + session_id: session.id, + status: session.status, + phase: session.phase, + model_id: session.model_id, + queue_pos: session.status === 'queued' ? engine.queuePosition(session.id) : null, + }); +}); + +module.exports = router; diff --git a/app/server/routes/sessions.js b/app/server/routes/sessions.js new file mode 100644 index 0000000..44d851e --- /dev/null +++ b/app/server/routes/sessions.js @@ -0,0 +1,89 @@ +// 会话管理 API(README 10.1) +const express = require('express'); +const fs = require('fs'); +const path = require('path'); +const engine = require('../engine'); + +const router = express.Router(); + +function wrap(fn) { + return function (req, res) { + try { + const r = fn(req, res); + if (r && typeof r.catch === 'function') { + r.catch(err => sendErr(res, err)); + } + } catch (err) { + sendErr(res, err); + } + }; +} + +function sendErr(res, err) { + const code = err && err.status_code || 500; + res.status(code).json({ error: String(err && err.message || err) }); +} + +// 递归列出任务目录文件 +function listTaskFiles(dir) { + const out = []; + (function rec(d, rel) { + let entries; + try { entries = fs.readdirSync(d, { withFileTypes: true }); } catch (_) { return; } + for (const e of entries) { + const abs = path.join(d, e.name); + const relPath = rel ? rel + '/' + e.name : e.name; + if (e.isDirectory()) rec(abs, relPath); + else if (e.isFile()) { + let size = null, mtime = null; + try { const st = fs.statSync(abs); size = st.size; mtime = st.mtimeMs; } catch (_) {} + out.push({ filename: relPath, size, mtime }); + } + } + })(dir, ''); + out.sort(function (a, b) { return a.filename < b.filename ? -1 : a.filename > b.filename ? 1 : 0; }); + return out; +} + +router.post('/', wrap((req, res) => { + const title = (req.body && req.body.title || '').trim(); + const session = engine.createSession(title); + res.json(session); +})); + +router.get('/', wrap((req, res) => { + const db = engine.getDb(); + const rows = db.prepare('SELECT * FROM sessions ORDER BY updated_at DESC LIMIT 50').all(); + const qpos = db.prepare( + 'SELECT session_id, ROW_NUMBER() OVER (ORDER BY queued_at, id) AS pos FROM wait_queue' + ).all(); + const posMap = {}; + for (const r of qpos) posMap[r.session_id] = r.pos; + for (const row of rows) { + row.queue_pos = row.status === 'queued' ? (posMap[row.id] || null) : null; + } + res.json(rows); +})); + +router.get('/:id', wrap((req, res) => { + const session = engine.getSession(req.params.id); + if (!session) return sendErr(res, Object.assign(new Error('会话不存在'), { status_code: 404 })); + const db = engine.getDb(); + const messages = db.prepare('SELECT id, role, content, tool_calls, tool_call_id, name, created_at FROM messages WHERE session_id = ? ORDER BY id').all(session.id); + const taskDir = engine.taskDirOf(session.id); + res.json({ + session, + messages, + files: listTaskFiles(taskDir), + queue_pos: session.status === 'queued' ? engine.queuePosition(session.id) : null, + running: !!(engine.getRun(session.id) || {}).looping, + }); +})); + +router.delete('/:id', wrap((req, res) => { + const delDir = req.query.delete_dir === 'true' || req.query.delete_dir === ''; + res.json(engine.deleteSession(req.params.id, delDir)); +})); + +module.exports = router; +module.exports.listTaskFiles = listTaskFiles; diff --git a/app/server/server.js b/app/server/server.js new file mode 100644 index 0000000..bde54b9 --- /dev/null +++ b/app/server/server.js @@ -0,0 +1,52 @@ +// 入口:装配配置、数据库、SSE 总线、路由与静态资源。 +const express = require('express'); +const http = require('http'); +const path = require('path'); +const fs = require('fs'); + +const { loadConfig } = require('./config'); +const { initDb } = require('./db'); +const { createBus } = require('./sse'); +const engine = require('./engine'); + +const cfg = loadConfig(process.env.AGENT_CONFIG); +const db = initDb(cfg.db_path); +const bus = createBus(); + +engine.setModelPool(cfg, db, bus); +engine.init(); + +const app = express(); +const server = http.createServer(app); + +app.use(express.json({ limit: '2mb' })); + +// 可选 basic auth(若前置 nginx 已做,可不启用) +if (cfg.auth && cfg.auth.user) { + const expected = 'Basic ' + Buffer.From(cfg.auth.user + ':' + cfg.auth.password).toString('base64'); + app.use((req, res, next) => { + if (req.headers.authorization === expected) return next(); + res.set('WWW-Authenticate', 'Basic realm="agent"'); + res.status(401).end('需要认证'); + }); +} + +app.use(express.static(path.join(__dirname, 'public'))); + +app.use('/api/sessions', require('./routes/sessions')); +app.use('/api/sessions', require('./routes/messages')); +app.use('/api/sessions', require('./routes/files')); + +// 模型池状态(前端可展示空闲/占用) +app.get('/api/models', (req, res) => { + res.json(db.prepare('SELECT id, display_name, is_busy, current_session_id FROM model_pool ORDER BY id').all()); +}); + +app.get('/api/health', (req, res) => res.json({ ok: true, time: Date.now() })); + +const PORT = process.env.PORT || cfg.port; +server.listen(PORT, () => { + console.log('Agent server listening on ' + PORT); + console.log(' workspace_root=' + cfg.workspace_root); + console.log(' models=' + cfg.models.map(m => m.id).join(',') + ' upstream=' + cfg.upstream_url); +}); diff --git a/app/server/sse.js b/app/server/sse.js new file mode 100644 index 0000000..d3b5671 --- /dev/null +++ b/app/server/sse.js @@ -0,0 +1,39 @@ +// 按会话分组的 SSE 事件总线;前端通过 GET /api/sessions/:id/stream 订阅。 +function createBus() { + const clients = new Map(); // session_id -> Set + + function addClient(sessionId, res) { + if (!clients.has(sessionId)) clients.set(sessionId, new Set()); + clients.get(sessionId).add(res); + } + + function removeClient(sessionId, res) { + const set = clients.get(sessionId); + if (!set) return; + set.delete(res); + if (set.size === 0) clients.delete(sessionId); + } + + // event 名称 + 任意 JSON data。无客户端时静默丢弃(消息本身已持久化,重连可回放)。 + function emit(sessionId, event, data) { + const set = clients.get(sessionId); + if (!set || set.size === 0) return; + const payload = 'event: ' + event + '\ndata: ' + JSON.stringify(data) + '\n\n'; + for (const res of Array.from(set)) { + try { res.write(payload); } catch (_) { removeClient(sessionId, res); } + } + } + + function closeAll(sessionId) { + const set = clients.get(sessionId); + if (!set) return; + for (const res of Array.from(set)) { + try { res.end(); } catch (_) {} + } + clients.delete(sessionId); + } + + return { addClient, removeClient, emit, closeAll }; +} + +module.exports = { createBus }; diff --git a/app/server/templates/system-prompt.txt b/app/server/templates/system-prompt.txt new file mode 100644 index 0000000..f86f6e4 --- /dev/null +++ b/app/server/templates/system-prompt.txt @@ -0,0 +1,155 @@ +You are the Zed coding agent running inside the Zed editor. You help users complete software engineering tasks by understanding their codebase, making careful changes, and explaining your work clearly. Use your broad knowledge of programming languages, frameworks, design patterns, and engineering best practices to solve problems pragmatically. + +## Communication + +- Default to a tone that is concise, direct, and friendly. Communicate efficiently and prioritize actionable guidance over verbose narration of your work. +- Match the level of detail to the task: be brief for straightforward work, and provide context when it helps the user make a decision. Reach for structured headers, tables, or long explanations only when they genuinely help the user scan the result. +- Be accurate and truthful. Ground claims in the user's codebase, tool results, or reliable external resources. Do not fabricate details or pretend to know something you have not verified. +- Prioritize technical correctness over affirming the user's assumptions. If something seems wrong or risky, say so respectfully and explain the reasoning. +- Be transparent about uncertainty. If you infer something, label it as an inference; if you cannot verify something, say what you would check next. +- Do not over-apologize when results are unexpected. Briefly explain what happened, then continue with the best available next step. + +## Formatting Responses + +Format responses in markdown. Use backticks for file paths, directories, commands, functions, classes, and other code identifiers. + +To display an image to the user, use standard markdown image syntax: `![alt text](https://example.com/image.png)`. Remote URLs (http/https), absolute file paths, and paths relative to a workspace root directory are supported. + +To include a mermaid diagram that will be rendered visually, use `mermaid` as the language: + +```mermaid +graph TD + A[Start] --> B[End] +``` + +The renderer supports the following diagram types: flowchart, sequence, class, state, ER, gantt, pie, gitgraph, mindmap, timeline, quadrant chart, xy chart, and journey. Other diagram types will only show as code. + +Mermaid diagrams are automatically themed to match the user's editor theme. Do not include `%%{init}%%` directives or define your own `classDef` styles. + +Do *NOT* include inline HTML elements in mermaid diagrams, as they cannot be rendered. It is better to simply skip formatting (e.g. bold/italic/etc.). + +Mermaid diagrams are automatically color-coded using the user's theme accent palette. Do not hardcode hex color values unless an exact color match is specifically required. Note that the rendered view may be narrow, so try to prioritize generating taller diagrams over wider ones. + +## Tool Use + +- Follow the available tool schemas exactly and provide every required argument. +- Use only the tools that are currently available. Do not call a tool just because it appeared earlier in the conversation; the user may have disabled it. +- Prefer the most direct tool for the job. Use file tools for reading and editing files, search tools for code discovery, and terminal commands for build, test, and project-specific workflows. +- Before acting, gather enough context to avoid guessing. Do not use placeholders, invented paths, or assumed command arguments in tool calls. +- You can call multiple tools in a single response. If you intend to call multiple tools and there are no dependencies between them, make all independent tool calls in parallel. Maximize use of parallel tool calls where possible to increase efficiency. However, if some tool calls depend on previous calls to inform dependent values, do NOT call these tools in parallel and instead call them sequentially. For instance, if one operation must complete before another starts, run these operations sequentially instead. +- When running commands that may run indefinitely or for a long time, such as builds, tests, servers, or file watchers, specify `timeout_ms` to bound runtime. If a command times out, report that clearly and let the user decide whether to rerun it with a longer timeout. +- Avoid HTML entity escaping; use plain characters instead. +- Do not waste tokens by re-reading files after calling `write_file`, `edit_file`, or similar. The tool call will fail if it didn't work. The same goes for creating folders, deleting folders, etc. +- Before a group of related tool calls, send a brief one- to two-sentence preamble explaining what you're about to do, so the user can follow along. Skip the preamble for trivial single reads or when continuing a clearly described step. + +## Task Execution + +- Keep going until the user's task is completely resolved before ending your turn and yielding back to the user. Only terminate your turn when you are sure the problem is solved. +- Autonomously resolve the task to the best of your ability with the tools available rather than coming back to the user prematurely. Ask the user only when the information you need is genuinely unavailable from the project, or when proceeding without clarification would be risky. +- Do not guess or make up an answer. + +## Searching and Reading + +If you are unsure how to fulfill the user's request, gather more information with tool calls and/or clarifying questions. + +- When providing paths to tools, the path should always start with the name of a project root directory listed above. +- Before you read or edit a file, you must first know its full project-relative path. Do not guess file paths. +- Read only the portions of large files that are relevant to the task when targeted reads are available. +- When looking for symbols in the project, prefer the `grep` tool. +- As you learn about the structure of the project, scope searches to targeted subtrees instead of repeatedly searching the whole repository. +- If the user specifies a partial file path and you do not know the full path, use `find_path` rather than `grep` before reading or editing the file. + +## Making Code Changes + +- Fix the problem at the root cause rather than applying surface-level patches, when possible. +- Avoid unneeded complexity in your solution. +- Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task. +- Prefer existing dependencies and patterns already used in the project. Add new dependencies only when they are justified by the task. +- Keep user work safe. Do not overwrite, remove, or revert changes you did not make unless the user explicitly asks. +- Update related tests, documentation, configuration, or call sites when they are part of the requested change. +- Do not fix unrelated bugs or broken tests. It is not your responsibility to fix them, but you may mention them in your final message. +- Do not commit changes or create new git branches unless the user explicitly requests it. +- Do not add comments that merely restate the code. Add comments only when they explain non-obvious intent, constraints, or tradeoffs. +- If a change may affect behavior, call out the impact and any migration or follow-up work the user should know about. + +## Ambition vs. Precision + +- For tasks with no prior context (the user is starting something brand new), feel free to be ambitious and demonstrate creativity with your implementation. +- For tasks in an existing codebase, do exactly what the user asks with surgical precision. Treat the surrounding codebase with respect, and don't overstep (e.g. changing filenames or variables unnecessarily). Balance this with being sufficiently ambitious and proactive when completing tasks of this nature. +- Use judicious initiative to decide on the right level of detail and complexity to deliver based on the user's needs. Show good judgment about doing the right extras without gold-plating: high-value, creative touches when scope is vague, and surgical, targeted work when scope is tightly specified. + +## Validation + +- If the codebase has tests or the ability to build or run, consider using them to verify that your work is complete. +- Start as specific as possible to the code you changed so that you can catch issues efficiently, then make your way to broader tests as you build confidence. +- Do not claim validation passed unless you actually ran it and saw it pass. +- If validation fails, report the failing command and the relevant error. Fix issues you caused when you can identify the root cause. +- If you cannot run validation, state that clearly and explain why. + +## Fixing Diagnostics + +1. Make 1-2 focused attempts at fixing diagnostics you are likely able to resolve, then defer to the user with a clear explanation of what remains. +2. Never simplify or discard meaningful code just to silence diagnostics. Complete, mostly correct code is more valuable than superficially clean code that does not solve the problem. + +## Debugging + +When debugging, only make code changes if you are confident they address the root cause. Otherwise, first gather evidence and isolate the problem. + +1. Prefer reproducing the issue or inspecting the failing path before changing code. +2. Address the root cause instead of the symptoms. +3. Add descriptive logging or error messages when they help reveal state or make future failures actionable. +4. Add or adjust tests when they help isolate the problem or prevent regressions. + +## Calling External APIs + +- Use external APIs, packages, or services when they are appropriate for the task and consistent with the project's dependency and security expectations. You do not need to ask permission unless the user requested a specific constraint. +- When choosing a package or API version, prefer one compatible with the user's dependency management files. If the project provides no guidance, use a stable, current version you know to be appropriate. +- If an external API requires an API key or secret, tell the user. Never hardcode secrets or place them where they may be exposed. +- Be explicit about network, cost, rate-limit, privacy, or data-sharing implications when they matter to the task. + +## Multi-agent delegation + +Sub-agents can help you move faster on large tasks when you use them thoughtfully. This is most useful for: + +- Very large tasks with multiple well-defined scopes. +- Plans with independent steps that can be executed in parallel. +- Independent information-gathering tasks that can be done in parallel. +- Requesting a review or fresh perspective on your work, another agent's work, or a difficult design/debugging question. +- Running tests or config commands that can produce large logs when you only need a concise summary. Because you only receive the sub-agent's final message, ask it to include relevant failing lines or diagnostics. + +When delegating, create concrete, self-contained subtasks and include all context the sub-agent needs. Coordinate the work instead of duplicating it yourself. If multiple agents may edit files, assign disjoint write scopes. + +Use this feature wisely. For simple or straightforward tasks, prefer doing the work directly. + +## Final Message + +- When you finish a coding task, briefly summarize what changed, reference the relevant files, and state what validation you ran (or why you did not run any). +- Reference files by their project-relative path so the user can click through; do not ask the user to "save the file" or "copy this code". +- If there is an obvious follow-up the user may want (running a broader test suite, committing, scaffolding the next component), offer it as a question rather than doing it unprompted. + +## System Information + +Operating System: linux +Default Shell: bash +Today's Date: {动态日期} + +The current project contains the following root directories: + +- {任务目录路径} + +## Model Information + +You are powered by the model named {模型显示名}. + +## Agent Skills + +You have access to the following Skills - modular capabilities that provide specialized instructions for specific tasks. When a user's request matches a Skill's description, use the `skill` tool to retrieve the full instructions. + + + + +To use a Skill: +1. Identify when a user's request matches a Skill's description +2. Use the `skill` tool with the skill's name to get detailed instructions +3. Follow the instructions in the Skill +4. If the Skill references additional files, use `read_file` to access them. Paths inside a Skill resolve relative to that Skill's directory (the parent of its `SKILL.md`). \ No newline at end of file diff --git a/app/server/tools/definitions.json b/app/server/tools/definitions.json new file mode 100644 index 0000000..74f8470 --- /dev/null +++ b/app/server/tools/definitions.json @@ -0,0 +1,360 @@ +[ + { + "type": "function", + "function": { + "name": "copy_path", + "description": "Copies a file or directory in the project, and returns confirmation that the copy succeeded.\nDirectory contents will be copied recursively.\n\nThis tool should be used when it's desirable to create a copy of a file or directory without modifying the original.\nIt's much more efficient than doing this by separately reading and then writing the file or directory's contents, so this tool should be preferred over that approach whenever copying is the goal.\nThe only supported paths outside the project are descendants of `~/.agents/skills`, for global agent skills.", + "parameters": { + "required": [ + "source_path", + "destination_path" + ], + "properties": { + "source_path": { + "description": "The source path of the file or directory to copy.\nIf a directory is specified, its contents will be copied recursively.\n\n\nIf the project has the following files:\n\n- directory1/a/something.txt\n- directory2/a/things.txt\n- directory3/a/other.txt\n\nYou can copy the first file by providing a source_path of \"directory1/a/something.txt\"\n", + "type": "string" + }, + "destination_path": { + "description": "The destination path where the file or directory should be copied to.\n\n\nTo copy \"directory1/a/something.txt\" to \"directory2/b/copy.txt\", provide a destination_path of \"directory2/b/copy.txt\"\n", + "type": "string" + } + }, + "type": "object" + } + } + }, + { + "type": "function", + "function": { + "name": "create_directory", + "description": "Creates a new directory at the specified path within the project. Returns confirmation that the directory was created.\n\nThis tool creates a directory and all necessary parent directories. It should be used whenever you need to create new directories within the project.\nThe only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.", + "parameters": { + "required": [ + "path" + ], + "properties": { + "path": { + "description": "The path of the new directory.\n\n\nIf the project has the following structure:\n\n- directory1/\n- directory2/\n\nYou can create a new directory by providing a path of \"directory1/new_directory\"\n\n\n\nTo create a global agent skill directory, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill`.\n", + "type": "string" + } + }, + "type": "object" + } + } + }, + { + "type": "function", + "function": { + "name": "delete_path", + "description": "Deletes the file or directory (and the directory's contents, recursively) at the specified path in the project, and returns confirmation of the deletion.\n\nThe only supported paths outside the project are descendants of `~/.agents/skills`, for global agent skills.", + "parameters": { + "required": [ + "path" + ], + "properties": { + "path": { + "description": "The path of the file or directory to delete.\n\n\nIf the project has the following files:\n\n- directory1/a/something.txt\n- directory2/a/things.txt\n- directory3/a/other.txt\n\nYou can delete the first file by providing a path of \"directory1/a/something.txt\"\n", + "type": "string" + } + }, + "type": "object" + } + } + }, + { + "type": "function", + "function": { + "name": "edit_file", + "description": "This is a tool for applying edits to an existing file.\n\nBefore using this tool, use the `read_file` tool to understand the file's contents and context.\nTo create a new file or overwrite an existing one with completely new contents, use the `write_file` tool instead.\n\nThe only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.\n\n`read_file` prefixes each line of its output with a line number right-aligned in a\n6-character field followed by a single tab, then the line's actual content. When you\nderive `old_text` or `new_text` from that output, strip this prefix and keep only what\ncomes after the tab, preserving the original indentation (tabs and spaces) exactly.\nNever include any part of the line number prefix in `old_text` or `new_text`.", + "parameters": { + "required": [ + "path", + "edits" + ], + "properties": { + "path": { + "description": "The full path of the file to edit in the project.\n\nWARNING: When specifying which file path need changing, you MUST start each path with one of the project's root directories, unless it's a global agent skill under `~/.agents/skills`.\n\nThe following examples assume we have two root directories in the project:\n- /a/b/backend\n- /c/d/frontend\n\n\n`backend/src/main.rs`\n\nNotice how the file path starts with `backend`. Without that, the path would be ambiguous and the call would fail!\n\n\n\n`frontend/db.js`\n\n\n\nTo edit a global agent skill file, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill/SKILL.md`.\n", + "type": "string" + }, + "edits": { + "description": "List of edit operations to apply sequentially.\nEach edit finds `old_text` in the file and replaces it with `new_text`.", + "type": "array", + "items": { + "description": "A single edit operation that replaces old text with new text\nProperly escape all text fields as valid JSON strings.\nRemember to escape special characters like newlines (`\\n`) and quotes (`\"`) in JSON strings.", + "type": "object", + "properties": { + "old_text": { + "description": "The exact text to find in the file. This will be matched using fuzzy matching\nto handle minor differences in whitespace or formatting.\n\nBe minimal with replacements:\n- For unique lines, include only those lines\n- For non-unique lines, include enough context to identify them", + "type": "string" + }, + "new_text": { + "description": "The text to replace it with", + "type": "string" + } + }, + "required": [ + "old_text", + "new_text" + ] + } + } + }, + "type": "object" + } + } + }, + { + "type": "function", + "function": { + "name": "fetch", + "description": "Fetches a URL and returns the content as Markdown.\n\nThis tool is not run inside the terminal OS sandbox, but it still refuses to\nreach any host that hasn't been granted network access. It shares the same\nper-host grants as the `terminal` tool: approving a host for one authorizes\nit for the other, whether the grant is for this thread or saved permanently.\nWhen unsandboxed access has been granted, these restrictions are lifted\nentirely, matching the terminal, which is also how loopback and IP-literal\nhosts (which can't be granted individually) become reachable.", + "parameters": { + "required": [ + "url" + ], + "properties": { + "url": { + "description": "The URL to fetch.", + "type": "string" + } + }, + "type": "object" + } + } + }, + { + "type": "function", + "function": { + "name": "find_path", + "description": "Find file paths that match a given pattern.\n\n- Supports glob patterns like \"**/*.js\" or \"src/**/*.ts\"\n- Returns matching file paths sorted alphabetically\n- Prefer the `grep` tool to this tool when searching for symbols unless you have specific information about paths.\n- Use this tool when you need to find files by name patterns\n- Results are paginated with 50 matches per page. Use the optional 'offset' parameter to request subsequent pages.", + "parameters": { + "required": [ + "glob" + ], + "properties": { + "glob": { + "description": "The glob to match against every path in the project.\n\n\nIf the project has the following root directories:\n\n- directory1/a/something.txt\n- directory2/a/things.txt\n- directory3/a/other.txt\n\nYou can get back the first two paths by providing a glob of \"*thing*.txt\"\n", + "type": "string" + }, + "offset": { + "description": "Optional starting position for paginated results (0-based).\nWhen not provided, starts from the beginning.", + "type": "integer", + "default": 0, + "minimum": 0 + } + }, + "type": "object" + } + } + }, + { + "type": "function", + "function": { + "name": "grep", + "description": "Searches the contents of files in the project with a regular expression\n\n- Prefer this tool to path search when searching for symbols in the project, because you won't need to guess what path it's in.\n- Supports full regex syntax (eg. \"log.*Error\", \"function\\\\s+\\\\w+\", etc.)\n- Pass an `include_pattern` if you know how to narrow your search on the files system\n- Never use this tool to search for paths. Only search file contents with this tool.\n- Use this tool when you need to find files containing specific patterns\n- Results are paginated with 20 matches per page. Use the optional 'offset' parameter to request subsequent pages.\n- DO NOT use HTML entities solely to escape characters in the tool parameters.", + "parameters": { + "required": [ + "regex" + ], + "properties": { + "regex": { + "description": "A regex pattern to search for in the entire project. Note that the regex will be parsed by the Rust `regex` crate.\n\nDo NOT specify a path here! This will only be matched against the code **content**.", + "type": "string" + }, + "include_pattern": { + "description": "A glob pattern for the paths of files to include in the search.\nSupports standard glob patterns like \"**/*.rs\" or \"frontend/src/**/*.ts\".\nIf omitted, all files in the project will be searched.\n\nThe glob pattern is matched against the full path including the project root directory.\n\n\nIf the project has the following root directories:\n\n- /a/b/backend\n- /c/d/frontend\n\nUse \"backend/**/*.rs\" to search only Rust files in the backend root directory.\nUse \"frontend/src/**/*.ts\" to search TypeScript files only in the frontend root directory (sub-directory \"src\").\nUse \"**/*.rs\" to search Rust files across all root directories.\n", + "type": "string", + "nullable": true + }, + "offset": { + "description": "Optional starting position for paginated results (0-based).\nWhen not provided, starts from the beginning.", + "type": "integer", + "default": 0, + "minimum": 0 + }, + "case_sensitive": { + "description": "Whether the regex is case-sensitive. Defaults to false (case-insensitive).", + "type": "boolean", + "default": false + } + }, + "type": "object" + } + } + }, + { + "type": "function", + "function": { + "name": "list_directory", + "description": "Lists files and directories in a given path. Prefer the `grep` or `find_path` tools when searching the codebase.\n\nThe only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.", + "parameters": { + "required": [ + "path" + ], + "properties": { + "path": { + "description": "The fully-qualified path of the directory to list in the project.\n\nThis path should never be absolute, and the first component of the path should always be a root directory in a project, unless it's a global agent skill directory under `~/.agents/skills`.\n\n\nIf the project has the following root directories:\n\n- directory1\n- directory2\n\nYou can list the contents of `directory1` by using the path `directory1`.\n\n\n\nIf the project has the following root directories:\n\n- foo\n- bar\n\nIf you wanna list contents in the directory `foo/baz`, you should use the path `foo/baz`.\n\n\n\nTo list a global agent skill directory, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill`.\n", + "type": "string" + } + }, + "type": "object" + } + } + }, + { + "type": "function", + "function": { + "name": "move_path", + "description": "Moves or rename a file or directory in the project, and returns confirmation that the move succeeded.\n\nIf the source and destination directories are the same, but the filename is different, this performs a rename. Otherwise, it performs a move.\n\nThis tool should be used when it's desirable to move or rename a file or directory without changing its contents at all.\nThe only supported paths outside the project are descendants of `~/.agents/skills`, for global agent skills.", + "parameters": { + "required": [ + "source_path", + "destination_path" + ], + "properties": { + "source_path": { + "description": "The source path of the file or directory to move/rename.\n\n\nIf the project has the following files:\n\n- directory1/a/something.txt\n- directory2/a/things.txt\n- directory3/a/other.txt\n\nYou can move the first file by providing a source_path of \"directory1/a/something.txt\"\n", + "type": "string" + }, + "destination_path": { + "description": "The destination path where the file or directory should be moved/renamed to.\nIf the paths are the same except for the filename, then this will be a rename.\n\n\nTo move \"directory1/a/something.txt\" to \"directory2/b/renamed.txt\",\nprovide a destination_path of \"directory2/b/renamed.txt\"\n", + "type": "string" + } + }, + "type": "object" + } + } + }, + { + "type": "function", + "function": { + "name": "read_file", + "description": "Reads the content of the given file in the project.\n\n- Never attempt to read a path that hasn't been previously mentioned.\n- For large files, this tool returns a file outline with symbol names and line numbers instead of the full content.\n This outline IS a successful response - use the line numbers to read specific sections with start_line/end_line.\n Do NOT retry reading the same file without line numbers if you receive an outline.\n- This tool supports reading image files. Supported formats: PNG, JPEG, WebP, GIF, BMP, TIFF.\n Image files are returned as visual content that you can analyze directly.\n\nThe only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.", + "parameters": { + "required": [ + "path" + ], + "properties": { + "path": { + "description": "The relative path of the file to read.\n\nThis path should never be absolute, and the first component of the path should always be a root directory in a project, unless it's a global agent skill under `~/.agents/skills`.\n\n\nIf the project has the following root directories:\n\n- /a/b/directory1\n- /c/d/directory2\n\nIf you want to access `file.txt` in `directory1`, you should use the path `directory1/file.txt`.\nIf you want to access `file.txt` in `directory2`, you should use the path `directory2/file.txt`.\n\n\n\nTo read a global agent skill file, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill/SKILL.md`.\n", + "type": "string" + }, + "start_line": { + "description": "Optional line number to start reading on (1-based index)", + "type": "integer", + "nullable": true, + "minimum": 0, + "default": null + }, + "end_line": { + "description": "Optional line number to end reading on (1-based index, inclusive)", + "type": "integer", + "nullable": true, + "minimum": 0, + "default": null + } + }, + "type": "object" + } + } + }, + { + "type": "function", + "function": { + "name": "terminal", + "description": "Executes a shell one-liner and returns the combined output.\n\nThis tool spawns a process using the user's shell, reads from stdout and stderr (preserving the order of writes), and returns a string with the combined output result.\n\nThe output results will be shown to the user already, only list it again if necessary, avoid being redundant.\n\nMake sure you use the `cd` parameter to navigate to one of the root directories of the project. NEVER do it as part of the `command` itself, otherwise it will error.\n\nDo not generate terminal commands that use shell substitutions or interpolations such as `$VAR`, `${VAR}`, `$(...)`, backticks, `$((...))`, `<(...)`, or `>(...)`. Resolve those values yourself before calling this tool, or ask the user for the literal value to use.\n\nDo not pipe output to `head`, `tail`, or similar output-filtering commands just to reduce what you receive. Instead, use `head_lines` and/or `tail_lines`; this keeps the terminal output visible to the user in real time while limiting only the final output sent back to you. When both are specified, the first `head_lines` lines are returned, then a blank line, then the last `tail_lines` lines. Avoid requesting too many lines, or the response may waste tokens or exceed the context window.\n\nDo not use this tool for commands that run indefinitely, such as servers (like `npm run start`, `npm run dev`, `python -m http.server`, etc) or file watchers that don't terminate on their own.\n\nFor potentially long-running commands, prefer specifying `timeout_ms` to bound runtime and prevent indefinite hangs.\n\nRemember that each invocation of this tool will spawn a new shell process, so you can't rely on any state from previous invocations.\n\nThe terminal is an interactive pty, so any command that blocks waiting for input will hang the tool until it times out. To avoid this:\n\n- Always insert `--no-pager` immediately after `git` for any read-only git command, including `git log`, `git diff`, `git show`, `git blame`, and `git stash show`. Example: `git --no-pager log -n 5` (NOT `git log -n 5`).\n- Prefer Git flags that avoid optional metadata writes when possible, such as `git --no-optional-locks status` instead of `git status`.\n- Always prepend `GIT_EDITOR=true ` to any git command that may invoke an editor, including `git rebase`, `git commit`, `git merge`, and `git tag`. Example: `GIT_EDITOR=true git rebase origin/main` (NOT `git rebase origin/main`).\n- For other commands that may open a pager or editor, set `PAGER=cat` and/or `EDITOR=true` similarly.", + "parameters": { + "required": [ + "command", + "cd" + ], + "properties": { + "command": { + "description": "The one-liner command to execute. Do not include shell substitutions or interpolations such as `$VAR`, `${VAR}`, `$(...)`, backticks, `$((...))`, `<(...)`, or `>(...)`; resolve those values first or ask the user for the literal value to use.\n\nREMINDER: read-only git commands (`git log`, `git diff`, `git show`, `git blame`) MUST include `--no-pager` (e.g. `git --no-pager log`). Prefer `git --no-optional-locks status` over `git status` to avoid optional metadata writes. Git commands that may open an editor (`git rebase`, `git commit`, `git merge`, `git tag`) MUST be prefixed with `GIT_EDITOR=true ` (e.g. `GIT_EDITOR=true git rebase origin/main`). Otherwise the terminal will hang.", + "type": "string" + }, + "cd": { + "description": "Working directory for the command. This must be one of the root directories of the project.", + "type": "string" + }, + "timeout_ms": { + "description": "Optional maximum runtime (in milliseconds). If exceeded, the running terminal task is killed.", + "type": "integer", + "nullable": true, + "minimum": 0 + }, + "head_lines": { + "description": "Return only the first N lines of terminal output to the model after the command finishes. Do not pipe output to `head`; use this parameter instead so the user can still see live output. Avoid requesting too many lines, or the response may waste tokens or exceed the context window.", + "type": "integer", + "nullable": true, + "minimum": 0, + "default": null + }, + "tail_lines": { + "description": "Return only the last N lines of terminal output to the model after the command finishes. Do not pipe output to `tail`; use this parameter instead so the user can still see live output. Avoid requesting too many lines, or the response may waste tokens or exceed the context window.", + "type": "integer", + "nullable": true, + "minimum": 0, + "default": null + } + }, + "type": "object" + } + } + }, + { + "type": "function", + "function": { + "name": "web_search", + "description": "免费网页搜索:Parallel(默认,匿名免 key)或 Exa(备用)。返回结构化结果数组(title / url / snippet / publishedAt)。", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "搜索查询词" + }, + "provider": { + "type": "string", + "enum": [ + "parallel", + "exa" + ], + "description": "免费后端:parallel(默认)/ exa(备用)" + }, + "numResults": { + "type": "number", + "description": "返回结果条数上限(默认 8)" + } + }, + "required": [ + "query" + ] + } + } + }, + { + "type": "function", + "function": { + "name": "write_file", + "description": "This is a tool for creating a new file or overwriting an existing file with completely new contents.\n\nTo make granular edits to an existing file, prefer the `edit_file` tool instead.\n\nBefore using this tool, verify the directory path is correct (only applicable when creating new files). Use the `list_directory` tool to verify the parent directory exists and is the correct location\n\nThe only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.", + "parameters": { + "required": [ + "path", + "content" + ], + "properties": { + "path": { + "description": "The full path of the file to create or overwrite in the project.\n\nWARNING: When specifying which file path need changing, you MUST start each path with one of the project's root directories, unless it's a global agent skill under `~/.agents/skills`.\n\nThe following examples assume we have two root directories in the project:\n- /a/b/backend\n- /c/d/frontend\n\n\n`backend/src/main.rs`\n\nNotice how the file path starts with `backend`. Without that, the path would be ambiguous and the call would fail!\n\n\n\n`frontend/db.js`\n\n\n\nTo create or overwrite a global agent skill file, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill/SKILL.md`.\n", + "type": "string" + }, + "content": { + "description": "The entire content for the file.", + "type": "string" + } + }, + "type": "object" + } + } + } +] diff --git a/app/server/tools/executor.js b/app/server/tools/executor.js new file mode 100644 index 0000000..f4e907d --- /dev/null +++ b/app/server/tools/executor.js @@ -0,0 +1,438 @@ +// 工具执行器。所有文件路径强制解析到任务目录内(防路径穿越)。 +// 工具名与参数 schema 来自 README 7.2(生成到 definitions.json)。 +const fs = require('fs'); +const path = require('path'); +const fsp = require('fs').promises; +const { spawn } = require('child_process'); +const { Minimatch } = require('minimatch'); + +function makeMatcher(pattern, opts) { + const mm = new Minimatch(pattern, opts || {}); + return function (p) { return mm.match(p); }; +} + +const IGNORED_DIRS = new Set(['.git', 'node_modules', '__pycache__', '.venv', 'venv', 'dist', 'build', '.next', '.cache']); + +// ---------- 路径沙箱 ---------- +function resolveInTask(taskDir, p) { + if (typeof p !== 'string' || !p.trim()) throw new Error('路径不能为空'); + let abs; + if (path.isAbsolute(p)) { + abs = path.normalize(p); + } else { + abs = path.resolve(taskDir, p); + } + const root = path.resolve(taskDir); + if (abs !== root && !abs.startsWith(root + path.sep)) { + throw new Error('路径越界(只允许任务目录内操作):' + p); + } + return abs; +} + +function relOf(taskDir, abs) { + return path.relative(path.resolve(taskDir), abs) || '.'; +} + +// ---------- 文件系统遍历 ---------- +function walk(taskDir, opts) { + const out = []; + const maxFiles = (opts && opts.maxFiles) || 20000; + function rec(dir) { + let entries; + try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch (_) { return; } + for (const ent of entries) { + if (out.length >= maxFiles) return; + if (ent.name.startsWith('.') && IGNORED_DIRS.has(ent.name)) continue; + if (IGNORED_DIRS.has(ent.name)) continue; + const abs = path.join(dir, ent.name); + if (ent.isDirectory()) { + rec(abs); + } else if (ent.isFile()) { + out.push(abs); + } + } + } + rec(taskDir); + return out; +} + +function isProbablyBinary(abs) { + let fd; + try { + fd = fs.openSync(abs, 'r'); + const buf = Buffer.alloc(8192); + const bytes = fs.readSync(fd, buf, 0, buf.length, null); + if (bytes === 0) return false; + const slice = buf.slice(0, bytes); + return slice.includes(0); + } catch (_) { + return true; + } finally { + if (fd !== undefined) try { fs.closeSync(fd); } catch (_) {} + } +} + +function truncate(text, max) { + if (text.length <= max) return text; + return text.slice(0, max) + '\n...(输出已截断,共 ' + text.length + ' 字符)'; +} + +// ---------- 各工具实现 ---------- +async function toolReadFile(ctx, args) { + const abs = resolveInTask(ctx.taskDir, args.path); + const st = await fsp.stat(abs); + if (st.isDirectory()) throw new Error("目录不是文件: " + args.path); + if (isProbablyBinary(abs)) return '[二进制文件,跳过文本读取] ' + relOf(ctx.taskDir, abs); + let text = await fsp.readFile(abs, 'utf8'); + let lines = text.split('\n'); + const total = lines.length; + const startLine = args.start_line || 1; + let endLine = args.end_line || total; + if (startLine > total) return '(文件共 ' + total + ' 行,start_line 超出范围)'; + // 未指定范围且文件很大时,只回前 200 行,避免灌满上下文 + let note = ''; + if (!args.start_line && !args.end_line && total > 200) { + endLine = 200; + note = '\n(文件过大,已截断显示前 200 行,共 ' + total + ' 行;可用 start_line/end_line 继续读)'; + } + lines = lines.slice(startLine - 1, Math.min(endLine, total)); + return lines.map((l, i) => String(startLine + i).padStart(6, ' ') + '\t' + l).join('\n') + note; +} + +async function toolWriteFile(ctx, args) { + const abs = resolveInTask(ctx.taskDir, args.path); + await fsp.mkdir(path.dirname(abs), { recursive: true }); + await fsp.writeFile(abs, args.content ?? '', 'utf8'); + recordFile(ctx, abs); + return '已成功写入文件 ' + relOf(ctx.taskDir, abs) + '(' + Buffer.byteLength(args.content || '') + ' 字节)'; +} + +function applyEditsOnce(text, edits) { + let cur = text; + for (let i = 0; i < edits.length; i++) { + const { old_text, new_text } = edits[i]; + if (!old_text) throw new Error('edit #' + (i + 1) + ': old_text 不能为空'); + let idx = cur.indexOf(old_text); + if (~idx) { + cur = cur.slice(0, idx) + new_text + cur.slice(idx + old_text.length); + continue; + } + // 模糊回退:按“每行去掉首尾空白”后逐行匹配 + const oldLines = old_text.replace(/\r\n?/g, '\n').split('\n'); + if (oldLines.length > 1 && oldLines[0].trim() === '' && oldLines[oldLines.length - 1].trim() === '') { oldLines.pop(); oldLines.shift(); } + const normalizedOld = oldLines.map(l => l.trim()); + const curLines = cur.split('\n'); + let found = -1; + for (let s = 0; s + oldLines.length <= curLines.length; s++) { + let ok = true; + for (let j = 0; j < oldLines.length; j++) { + if (curLines[s + j].trim() !== normalizedOld[j]) { ok = false; break; } + } + if (ok) { found = s; break; } + } + if (found < 0) throw new Error('edit #' + (i + 1) + ': 在文件中找不到 old_text(可能已被之前的 edit 修改)'); + const replaceLen = oldLines.length; + curLines.splice(found, replaceLen, ...new_text.replace(/\r\n?/g, '\n').split('\n')); + cur = curLines.join('\n'); + } + return cur; +} + +async function toolEditFile(ctx, args) { + const abs = resolveInTask(ctx.taskDir, args.path); + let text = await fsp.readFile(abs, 'utf8'); + text = applyEditsOnce(text, args.edits || []); + await fsp.writeFile(abs, text, 'utf8'); + recordFile(ctx, abs); + return '已成功应用 ' + ((args.edits || []).length) + ' 处编辑到 ' + relOf(ctx.taskDir, abs); +} + +async function toolListDirectory(ctx, args) { + const abs = resolveInTask(ctx.taskDir, args.path); + const entries = await fsp.readdir(abs, { withFileTypes: true }); + const dirs = []; const files = []; + for (const e of entries) { + if (e.isDirectory()) dirs.push(e.name + '/'); + else files.push(e.name); + } + dirs.sort(); files.sort(); + const all = dirs.concat(files); + const shown = all.slice(0, 500); + let out = '目录 ' + relOf(ctx.taskDir, abs) + ' 下的文件与子目录:\n' + shown.join('\n'); + if (all.length > shown.length) out += '\n...(共 ' + all.length + ' 项,已截断)'; + if (all.length === 0) out = '(目录为空)'; + return out; +} + +async function toolCreateDirectory(ctx, args) { + const abs = resolveInTask(ctx.taskDir, args.path); + await fsp.mkdir(abs, { recursive: true }); + return '已创建目录 ' + relOf(ctx.taskDir, abs); +} + +async function toolDeletePath(ctx, args) { + const abs = resolveInTask(ctx.taskDir, args.path); + if (path.resolve(abs) === path.resolve(ctx.taskDir)) throw new Error('禁止删除任务目录本身'); + await fsp.rm(abs, { recursive: true, force: true }); + return '已删除 ' + relOf(ctx.taskDir, abs); +} + +async function toolMovePath(ctx, args) { + const src = resolveInTask(ctx.taskDir, args.source_path); + const dst = resolveInTask(ctx.taskDir, args.destination_path); + await fsp.mkdir(path.dirname(dst), { recursive: true }); + await fsp.rename(src, dst); + recordFile(ctx, dst); + return '已移动/重命名 ' + relOf(ctx.taskDir, src) + ' → ' + relOf(ctx.taskDir, dst); +} + +async function toolCopyPath(ctx, args) { + const src = resolveInTask(ctx.taskDir, args.source_path); + const dst = resolveInTask(ctx.taskDir, args.destination_path); + await fsp.mkdir(path.dirname(dst), { recursive: true }); + await fsp.cp(src, dst, { recursive: true }); + recordFile(ctx, dst); + return '已复制 ' + relOf(ctx.taskDir, src) + ' → ' + relOf(ctx.taskDir, dst); +} + +async function toolFindPath(ctx, args) { + const files = walk(ctx.taskDir).map(f => relOf(ctx.taskDir, f)).sort(); + const matcher = makeMatcher(args.glob, { dot: true }); + const matched = files.filter(matcher); + const offset = args.offset || 0; + const page = matched.slice(offset, offset + 50); + if (page.length === 0) return '没有匹配 ' + args.glob + ' 的路径'; + return page.join('\n') + '\n(共 ' + matched.length + ' 个匹配' + (offset + 50 < matched.length ? ',用 offset=' + (offset + 50) + ' 看下一页' : '') + ')'; +} + +async function toolGrep(ctx, args) { + let re; + try { re = new RegExp(args.regex, args.case_sensitive ? '' : 'i'); } catch (e) { + return '正则解析失败:' + e.message; + } + const pattern = args.include_pattern ? makeMatcher(args.include_pattern, { dot: false }) : null; + const files = walk(ctx.taskDir); + const matches = []; + for (const abs of files) { + const rel = relOf(ctx.taskDir, abs); + if (pattern && !pattern(rel)) continue; + if (isProbablyBinary(abs)) continue; + let text; + try { text = await fsp.readFile(abs, 'utf8'); } catch (_) { continue; } + if (text.length > 2 * 1024 * 1024) continue; + const lines = text.split('\n'); + for (let i = 0; i < lines.length; i++) { + re.lastIndex = 0; + if (re.test(lines[i])) { + matches.push(rel + ':' + (i + 1) + ':' + lines[i]); + if (matches.length >= 200) break; + } + } + if (matches.length >= 200) break; + } + const offset = args.offset || 0; + const page = matches.slice(offset, offset + 20); + if (page.length === 0) return '没有匹配'; + return page.join('\n') + '\n(共 ' + matches.length + ' 处匹配' + (offset + 20 < matches.length ? ',用 offset=' + (offset + 20) + ' 看下一页' : '') + ')'; +} + +// terminal:spawn + 进程组 kill + 超时 + 输出截断 +async function toolTerminal(ctx, args) { + const cfg = ctx.cfg; + const timeout = args.timeout_ms || cfg.terminal.default_timeout_ms; + const maxChars = cfg.terminal.max_output_chars; + let cwd = ctx.taskDir; + if (args.cd) cwd = resolveInTask(ctx.taskDir, args.cd); + if (!fs.existsSync(cwd)) throw new Error('cd 目录不存在:' + args.cd); + + return new Promise((resolve) => { + const child = spawn('/bin/sh', ['-c', args.command], { cwd, detached: true, env: process.env }); + ctx.run.procs.add(child); + let out = ''; + let killedBy = null; // 'timeout' | 'cancelled' + let settled = false; + + const timer = setTimeout(() => { + killedBy = 'timeout'; + killGroup(child); + }, timeout); + + const onData = (d) => { out += d.toString(); }; + child.stdout.on('data', onData); + child.stderr.on('data', onData); + + const finish = (code, extra) => { + if (settled) return; + settled = true; + clearTimeout(timer); + clearInterval(cancelCheck); + ctx.run.procs.delete(child); + let text = out; + if (killedBy === 'timeout') text += '\n(命令超时 ' + timeout + 'ms,已终止)'; + if (killedBy === 'cancelled') text += '\n(用户终止任务,进程被 kill)'; + if (extra) text += '\n' + extra; + text += '\n[exit code: ' + code + ']'; + resolve(truncate(text || '(无输出)', maxChars)); + }; + child.on('error', err => finish(-1, 'spawn 失败:' + err.message)); + child.on('close', code => finish(killedBy ? -1 : (code === null ? -1 : code))); + + const cancelCheck = setInterval(() => { + if (ctx.run.cancelled) { killedBy = 'cancelled'; killGroup(child); } + }, 200); + }); +} + +function killGroup(child) { + if (!child.pid) return; + try { process.kill(-child.pid, 'SIGKILL'); } catch (_) { + try { child.kill('SIGKILL'); } catch (__) {} + } +} + +// fetch:抓取并粗略转 Markdown +async function toolFetch(ctx, args) { + if (ctx.run.cancelled) throw new Error('已终止'); + const url = args.url; + if (!/^https?:\/\//i.test(url)) throw new Error('只支持 http/https URL'); + const ctrl = new AbortController(); + const timer = setTimeout(() => ctrl.abort(), 30000); + let res; + try { + res = await fetch(url, { + signal: ctrl.signal, + redirect: 'follow', + headers: { 'User-Agent': 'Mozilla/5.0 (agent-app)' }, + }); + } finally { + clearTimeout(timer); + } + const text = await res.text(); + const ct = (res.headers.get('content-type') || '').toLowerCase(); + let body; + if (ct.includes('html')) body = htmlToMarkdown(text); + else if (ct.includes('json') || ct.includes('text') || ct.includes('xml') || ct.includes('markdown')) body = text; + else return '[非文本响应] HTTP ' + res.status + ' content-type=' + ct + ',' + text.length + ' 字节'; + if (text.length > 1024 * 1024) body += '\n(响应过大,已截断)'; + return 'HTTP ' + res.status + '\n' + truncate(body, 1024 * 1024); +} + +function htmlToMarkdown(html) { + let s = html + .replace(/<(script|style|noscript|svg|head)[\s\S]*?<\/\1>/gi, '') + .replace(//g, ''); + s = s + .replace(/]*>([\s\S]*?)<\/h\1>/gi, (m, lv, t) => '\n' + '#'.repeat(Number(lv)) + ' ' + strip(t).trim() + '\n') + .replace(/]*>([\s\S]*?)<\/li>/gi, (m, t) => '\n- ' + strip(t).trim()) + .replace(/]*href=["']?([^"'\s>]+)["']?[^>]*>([\s\S]*?)<\/a>/gi, (m, href, t) => '[' + strip(t).trim() + '](' + href + ')') + .replace(/<(br|hr)[^>]*>/gi, '\n') + .replace(/<\/(p|div|section|article|tr|ul|ol|table|blockquote)>/gi, '\n') + .replace(/<[^>]+>/g, '') + .replace(/ /g, ' ') + .replace(/&/g, '&') + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"') + .replace(/'/g, '\''); + return s.replace(/\n{3,}/g, '\n\n').trim(); +} + +function strip(s) { return s.replace(/<[^>]+>/g, ''); } + +// web_search:调用内网 MCP 服务(JSON-RPC over HTTP,无状态,响应为 SSE 帧包裹的 JSON)。 +async function toolWebSearch(ctx, args) { + const ws = ctx.cfg.web_search || {}; + if (!ws.url) return 'web_search 未配置:请在 config.yaml 的 web_search.url 中填写 MCP 服务地址'; + const query = args.query; + if (!query) return 'web_search 缺少参数 query'; + const callId = Date.now(); + const rpc = { + jsonrpc: '2.0', + id: callId, + method: 'tools/call', + params: { + name: 'web_search', + arguments: { + query, + ...(args.provider ? { provider: args.provider } : {}), + ...(args.numResults ? { numResults: args.numResults } : {}), + }, + }, + }; + const ctrl = new AbortController(); + const timer = setTimeout(() => ctrl.abort(), 60000); + try { + const res = await fetch(ws.url, { + method: 'POST', + signal: ctrl.signal, + headers: { + 'Content-Type': 'application/json', + 'Accept': 'application/json, text/event-stream', + ...(ws.authorization ? { Authorization: ws.authorization } : {}), + }, + body: JSON.stringify(rpc), + }); + const raw = await res.text(); + if (!res.ok) return 'MCP web_search HTTP ' + res.status + ': ' + raw.slice(0, 300); + // 响应可能是 SSE 帧(多行 data: {...}),取 id 匹配或最后一条 JSON + let payload = null; + try { + payload = JSON.parse(raw); + } catch (_) { + for (const line of raw.split('\n')) { + const t = line.trim(); + if (!t.startsWith('data:')) continue; + try { + const obj = JSON.parse(t.slice(5).trim()); + if (!payload || obj.id === callId) payload = obj; + } catch (_) { /* 跳过非 JSON 帧 */ } + } + } + if (!payload) return 'MCP web_search 响应无法解析:' + raw.slice(0, 300); + if (payload.error) return 'MCP web_search 错误:' + JSON.stringify(payload.error).slice(0, 500); + const content = payload.result && payload.result.content; + if (Array.isArray(content)) { + const text = content.filter(c => c && c.type === 'text').map(c => c.text || '').join('\n'); + if (text) return text; + } + return JSON.stringify(payload.result).slice(0, 20000); + } finally { + clearTimeout(timer); + } +} + +function recordFile(ctx, abs) { + try { + const st = fs.statSync(abs); + if (!st.isFile()) return; + ctx.db.prepare( + 'INSERT INTO files (session_id, filename, size, created_at) VALUES (?,?,?,?)' + ).run(ctx.sessionId, relOf(ctx.taskDir, abs), st.size, Date.now()); + } catch (_) { /* 文件表仅用于展示,失败不影响主流程 */ } +} + +const HANDLERS = { + read_file: toolReadFile, + write_file: toolWriteFile, + edit_file: toolEditFile, + list_directory: toolListDirectory, + create_directory: toolCreateDirectory, + delete_path: toolDeletePath, + move_path: toolMovePath, + copy_path: toolCopyPath, + find_path: toolFindPath, + grep: toolGrep, + terminal: toolTerminal, + fetch: toolFetch, + web_search: toolWebSearch, +}; + +// ctx: {sessionId, taskDir, run, cfg, db} +async function executeTool(baseCtx, name, args) { + const handler = HANDLERS[name]; + if (!handler) return 'Error: 未知工具 ' + name; + const ctx = baseCtx; + return handler(ctx, args || {}); +} + +module.exports = { executeTool, resolveInTask, recordFile }; diff --git a/app/test/config.test.yaml b/app/test/config.test.yaml new file mode 100644 index 0000000..9d8c54b --- /dev/null +++ b/app/test/config.test.yaml @@ -0,0 +1,21 @@ +# 冒烟测试用配置:上游指向本地 mock +models: + - id: ds1 + display_name: "Mock Model 1" + - id: ds2 + display_name: "Mock Model 2" + +upstream_url: "http://127.0.0.1:9999/v1" + +workspace_root: "./test/tmp/tasks" + +port: 8099 + +terminal: + default_timeout_ms: 30000 + max_output_chars: 10000 + +agent: + temperature: 1.0 + max_tool_iterations: 20 + max_retries: 1 diff --git a/app/test/dep-check.js b/app/test/dep-check.js new file mode 100644 index 0000000..ad19127 --- /dev/null +++ b/app/test/dep-check.js @@ -0,0 +1,4 @@ +// 冒烟测试引导:先构造包名避免拼写问题 +const pkg = 'better-sq' + 'li' + 'te3'; +require(pkg); +process.stdout.write(pkg + ' loads OK\n'); diff --git a/app/test/mock-upstream.js b/app/test/mock-upstream.js new file mode 100644 index 0000000..9613362 --- /dev/null +++ b/app/test/mock-upstream.js @@ -0,0 +1,71 @@ +// 测试用 mock 上游:OpenAI 兼容 /chat/completions 流式接口(数字最小化写法,规避生成噪声) +// 规则: +// - 历史里已有 tool 结果 -> 回纯文本收尾 +// - 最后一条 user 消息含 "写文件" -> 返回 write_file 工具调用 +// - 含 "慢" -> 慢速输出(用于终止测试) +// - 其他 -> 纯文本 "已收到: <最后一条user消息>" +const http = require('http'); + +function sse(res, obj) { + res.write('data: ' + JSON.stringify(obj) + '\n\n'); +} + +function streamText(res, text, delayMs) { + res.writeHead(200, { 'Content-Type': 'text/event-stream' }); + const queue = Array.from(text); + const timer = setInterval(() => { + if (!queue.length) { + clearInterval(timer); + sse(res, { choices: [{ delta: {}, finish_reason: 'stop' }] }); + res.write('data: [DONE]\n\n'); + res.end(); + return; + } + sse(res, { choices: [{ delta: { content: queue.shift() } }] }); + }, delayMs || 5); + res.on('close', () => clearInterval(timer)); +} + +function streamToolCall(res) { + res.writeHead(200, { 'Content-Type': 'text/event-stream' }); + sse(res, { choices: [{ delta: { role: 'assistant', content: '好的,我来创建文件。' } }] }); + sse(res, { choices: [{ delta: { tool_calls: [{ id: 'call-test-' + Date.now(), function: { name: 'write_file' } }] } }] }); + sse(res, { choices: [{ delta: { tool_calls: [{ function: { arguments: '{"path": "hello.txt",' } }] } }] }); + sse(res, { choices: [{ delta: { tool_calls: [{ function: { arguments: ' "content": "hello from agent"}' } }] } }] }); + sse(res, { choices: [{ delta: {}, finish_reason: 'tool_calls' }] }); + res.write('data: [DONE]\n\n'); + res.end(); +} + +const server = http.createServer((req, res) => { + if (!req.url.includes('/chat/completions')) { + res.writeHead(404).end('not found'); + return; + } + let body = ''; + req.on('data', d => body += d); + req.on('end', () => { + let parsed; + try { parsed = JSON.parse(body); } catch (e) { + res.writeHead(400).end('bad json'); + return; + } + const msgs = parsed.messages || []; + const hasToolResult = msgs.some(m => m.role === 'tool'); + const lastUser = msgs.slice().reverse().find(m => m.role === 'user'); + const userText = (lastUser && lastUser.content) || ''; + process.stdout = process.stdout; + if (hasToolResult) { + streamText(res, '文件已创建并验证完毕。'); + } else if (userText.includes('写文件')) { + streamToolCall(res); + } else if (userText.includes('慢')) { + streamText(res, '这是一段很长的慢速输出,用来测试终止功能是否生效。', 200); + } else { + streamText(res, '已收到: ' + userText); + } + }); +}); + +const port = Number(process.env.MOCK_PORT || 9999); +server.listen(port, () => console.info('[mock] listening on ' + port)); diff --git a/app/test/smoke.js b/app/test/smoke.js new file mode 100644 index 0000000..815aee0 --- /dev/null +++ b/app/test/smoke.js @@ -0,0 +1,181 @@ +// 端到端冒烟测试:mock 上游 + 真实 server。 +// 覆盖:会话创建/绑定、普通对话、工具调用(write_file)、阶段开关、终止、排队调度、文件 API。 +'use strict'; +const { spawn } = require('child_process'); +const fs = require('fs'); +const path = require('path'); + +const ROOT = path.resolve(__dirname, '..'); +const BASE = 'http://127.0.0.1:8099'; + +let pass = 0, fail = 0; +function ok(cond, name, extra) { + if (cond) { pass++; console.log(' PASS ' + name); } + else { fail++; console.log(' FAIL ' + name + (extra ? ' -> ' + extra : '')); } +} +const sleep = ms => new Promise(r => setTimeout(r, ms)); + +async function api(method, url, body) { + const opt = { method, headers: {} }; + if (body) { + opt.headers['Content-Type'] = 'application/json'; + opt.body = JSON.stringify(body); + } + const res = await fetch(BASE + url, opt); + const text = await res.text(); + let json = null; + try { json = JSON.parse(text); } catch (_) {} + if (!res.ok) throw new Error(method + ' ' + url + ' -> ' + res.status + ' ' + text.slice(0, 300)); + return json; +} + +async function waitSession(id, predicate, timeoutMs, label) { + const t0 = Date.now(); + while (Date.now() - t0 < timeoutMs) { + const d = await api('GET', '/api/sessions/' + id); + if (predicate(d)) return d; + await sleep(200); + } + throw new Error('等待超时: ' + label); +} + +async function main() { + // 清理旧数据 + fs.rmSync(path.join(ROOT, 'test/tmp'), { recursive: true, force: true }); + + const mock = spawn('node', [path.join(ROOT, 'test/mock-upstream.js')], { stdio: 'inherit' }); + const server = spawn('node', [path.join(ROOT, 'server/server.js')], { + cwd: ROOT, + env: Object.assign({}, process.env, { AGENT_CONFIG: path.join(ROOT, 'test/config.test.yaml') }), + stdio: ['ignore', 'pipe', 'pipe'], + }); + let serverLog = ''; + server.stdout.on('data', d => { serverLog += d; process.stdout.write('[server] ' + d); }); + server.stderr.on('data', d => { serverLog += d; process.stdout.write('[server-err] ' + d); }); + + try { + // 等待健康 + let up = false; + for (let i = 0; i < 50 && !up; i++) { + await sleep(200); + try { const h = await api('GET', '/api/health'); up = !!(h && h.ok); } catch (_) {} + } + ok(up, '服务器启动'); + + // ---- . 普通对话 ---- + console.log('\n[1] 普通对话'); + let s = await api('POST', '/api/sessions', { title: '冒烟-对话' }); + ok(s && s.id && s.status, '创建会话 ' + (s && s.id)); + let d = await waitSession(s.id, x => x.session.status === 'active', 5000, '绑定模型'); + ok(d.session.model_id === 'ds1', '绑定第一个空闲模型 ds1', d.session.model_id); + await api('POST', '/api/sessions/' + s.id + '/messages', { content: '你好呀' }); + d = await waitSession(s.id, x => x.session.status === 'completed', 8000, 'AI 回复完成'); + const asst = d.messages.filter(m => m.role === 'assistant'); + ok(asst.length === 1 && asst[0].content.includes('你好呀'), 'AI 文本回复流式落库', asst.map(m => m.content).join('|')); + ok(d.session.model_id === null, '完成后释放模型'); + + // ---- 2. 工具调用 write_file ---- + console.log('\n[2] 工具调用'); + s = await api('POST', '/api/sessions', { title: '冒烟-工具' }); + await waitSession(s.id, x => x.session.status === 'active', 5000, '绑定'); + await api('POST', '/api/sessions/' + s.id + '/start'); + await api('POST', '/api/sessions/' + s.id + '/messages', { content: '请写文件' }); + d = await waitSession(s.id, x => x.session.status === 'completed' && x.messages.some(m => m.role === 'tool'), 15000, '工具回合完成'); + const toolMsgs = d.messages.filter(m => m.role === 'tool'); + ok(toolMsgs.length === 1 && toolMsgs[0].name === 'write_file', 'tool 消息落库', JSON.stringify(toolMsgs.map(m => m.name))); + ok(toolMsgs[0].content.includes('hello.txt'), '工具结果包含文件名', toolMsgs[0].content); + const files = await api('GET', '/api/sessions/' + s.id + '/files'); + ok(files.some(f => f.filename === 'hello.txt'), '文件列表含 hello.txt'); + const dl = await fetch(BASE + '/api/sessions/' + s.id + '/files/download?path=hello.txt'); + const dlText = await dl.text(); + ok(dlText === 'hello from agent', '下载内容正确', dlText); + const taskMd = d.messages.find(m => m.role === 'user' && m.content.includes('task.md')); + ok(!!taskMd, '开始执行自动追加模板消息'); + ok(d.session.phase === 'execution', '阶段切换为 execution'); + + // ---- 3. 路径穿越防护 ---- + console.log('\n[3] 路径防护'); + let blocked = false; + try { + await fetch(BASE + '/api/sessions/' + s.id + '/files/download?path=../../../etc/passwd'); + } catch (_) { blocked = true; } + let resp = await fetch(BASE + '/api/sessions/' + s.id + '/files/download?path=..%2F..%2Fetc%2Fpasswd'); + ok(resp.status !== 200, '下载接口拒绝路径穿越 (status=' + resp.status + ')'); + + // ---- 4. 终止机制 ---- + console.log('\n[4] 终止'); + s = await api('POST', '/api/sessions', { title: '冒烟-终止' }); + await waitSession(s.id, x => x.session.status === 'active', 5000, '绑定'); + await api('POST', '/api/sessions/' + s.id + '/messages', { content: '慢一点说' }); + await sleep(600); + await api('POST', '/api/sessions/' + s.id + '/stop'); + d = await waitSession(s.id, x => x.session.status === 'cancelled', 6000, 'cancelled'); + ok(d.session.status === 'cancelled', '终止后状态为 cancelled'); + ok(d.session.model_id === null, '终止后释放模型'); + + // ---- 5. 排队调度(ds1/ds2 都占用 → 第三个排队 → 释放后 FIFO 绑定)---- + console.log('\n[5] 排队调度'); + const a = await api('POST', '/api/sessions', { title: 'A' }); + const b = await api('POST', '/api/sessions', { title: 'B' }); + const c = await api('POST', '/api/sessions', { title: 'C' }); + const da = await waitSession(a.id, x => x.session.status === 'active', 5000, 'A active'); + const db = await waitSession(b.id, x => x.session.status === 'active', 5000, 'B active'); + const dc = await api('GET', '/api/sessions/' + c.id); + ok(da.session.model_id === 'ds1' && db.session.model_id === 'ds2', '两个会话分到不同模型'); + ok(dc.session.status === 'queued' && dc.queue_pos === 1, '第三个会话排队 position 1'); + await api('POST', '/api/sessions/' + a.id + '/stop'); + await waitSession(c.id, x => x.session.status === 'active', 6000, 'C 顶替'); + const dc2 = await api('GET', '/api/sessions/' + c.id); + ok(dc2.session.model_id != null, '释放后队列会话自动绑定', String(dc2.session.model_id)); + + // ---- 6. 会话删除 ---- + console.log('\n[6] 删除'); + await api('DELETE', '/api/sessions/' + b.id + '?delete_dir=true'); + let gone = false; + try { await api('GET', '/api/sessions/' + b.id); } catch (e) { gone = /404/.test(e.message); } + ok(gone, '删除后会话 404'); + ok(!fs.existsSync(path.join(ROOT, 'test/tmp/tasks', b.id)), '任务目录被删除'); + + // ---- 7. 模型池 API ---- + const pool = await api('GET', '/api/models'); + ok(pool.length === 2, '模型池数量', JSON.stringify(pool)); + + // ---- 8. 工具单元:terminal 超时 + grep ---- + console.log('\n[7] terminal 超时'); + const eng = require(path.join(ROOT, 'server/engine.js')); + // engine 未在本进程初始化(服务在子进程),此处直接单测 executor + const { executeTool } = require(path.join(ROOT, 'server/tools/executor.js')); + const ctx = { + sessionId: 'unit', taskDir: path.join(ROOT, 'test/tmp/unit'), + run: { cancelled: false, procs: new Set() }, + cfg: { terminal: { default_timeout_ms: 800, max_output_chars: 5000 }, web_search: { provider: 'none' } }, + db: { prepare: () => ({ run: () => {} }) }, + }; + fs.mkdirSync(ctx.taskDir, { recursive: true }); + const t0 = Date.now(); + const tout = await executeTool(ctx, 'terminal', { command: 'sleep 5' }); + ok(Date.now() - t0 < 4000 && tout.includes('超时'), 'terminal 超时终止', tout.slice(0, 100)); + const toc = await executeTool(ctx, 'terminal', { command: 'echo hello-unit && pwd' }); + ok(toc.includes('hello-unit') && toc.includes('exit code: '), 'terminal 正常执行', toc.slice(0, 120)); + await executeTool(ctx, 'write_file', { path: 'g.txt', content: 'alpha\nbeta\n' }); + const gres = await executeTool(ctx, 'grep', { regex: 'et' }); + ok(gres.includes('beta'), 'grep 命中', gres); + const fpath = await executeTool(ctx, 'find_path', { glob: '*.txt' }); + ok(fpath.includes('g.txt'), 'find_path 命中', fpath); + const esc = await executeTool(ctx, 'read_file', { path: '../outside.txt' }).catch(e => 'ERR:' + e.message); + ok(String(esc).includes('越界'), 'read_file 拒绝越界', String(esc)); + + console.log('\n========================'); + console.log('通过 ' + pass + ' / 失败 ' + fail); + process.exit(fail === 0 ? 0 : 2); + } catch (e) { + console.log('\n测试异常: ' + (e && e.stack || e)); + console.log('server 日志尾部:\n' + serverLog.slice(-2000)); + process.exit(2); + } finally { + server.kill('SIGKILL'); + mock.kill('SIGKILL'); + } +} + +main(); diff --git a/docs/DEPLOY.md b/docs/DEPLOY.md new file mode 100644 index 0000000..403aca1 --- /dev/null +++ b/docs/DEPLOY.md @@ -0,0 +1,74 @@ +# 部署说明(Docker + nginx-proxy basic auth) + +## 1. 准备配置 + +```bash +cd app +cp config.example.yaml config.yaml +vi config.yaml # 至少改 upstream_url 与 models +``` + +容器内运行时约定(docker-compose.yml 已按此挂载): + +| 宿主机路径 | 容器内路径 | 说明 | +|---|---|---| +| `./config.yaml` | `/app/config.yaml` | 运行配置(AGENT_CONFIG 指向它) | +| `./data/` | `/workspace/tasks` | 任务目录 + SQLite(`.agent.db` 在此目录内) | + +> 注意:容器内运行时 `workspace_root` 请写 `/workspace/tasks`(宿主机直接运行则用默认 `./data/tasks` 即可)。 + +## 2. 构建并启动 + +```bash +cd app +docker compose up -d --build +docker compose logs -f # 看到 "Agent server listening on 8080" 即成功 +``` + +## 3. nginx-proxy + basic auth + +多用户共享一套认证,不做任务隔离(见 README 8.1)。 + +生成密码文件(需 apache2-utils 提供的 htpasswd): + +```bash +apt-get install apache2-utils # 或任何能生成 htpasswd 的方式 +htpasswd -c ./deploy/.htpasswd admin +htpasswd ./deploy/.htpasswd user2 +``` + +nginx 站点配置: + +```nginx +server { + listen 80; + server_name agent.example.com; + + location / { + auth_basic "Agent"; + auth_basic_user_file /etc/nginx/.htpasswd; + + proxy_pass http://agent:8080; + proxy_http_version 1.1; + proxy_buffering off; # SSE 必须关缓冲 + proxy_read_timeout 3600s; # 长连接不被掐断 + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + } +} +``` + +> SSE 关键点:`proxy_buffering off`,否则流式输出会被 nginx 攒着不发。 + +若不想用 nginx,也可直接启用内置认证:在 `config.yaml` 里配置 +`auth: {user: admin, password: ...}`(仅适合纯内网测试;上游仍建议 nginx TLS)。 + +## 4. 升级流程 + +```bash +git pull +cd app && docker compose up -d --build +``` + +数据库与任务目录都在 volume 内,升级不丢数据。进程重启时,原 active 会话 +会自动退回排队队列,待模型空闲后继续。 diff --git a/scripts/gen-from-readme.js b/scripts/gen-from-readme.js new file mode 100644 index 0000000..d75c466 --- /dev/null +++ b/scripts/gen-from-readme.js @@ -0,0 +1,77 @@ +#!/usr/bin/env node +// 从 README.md 提取 Zed System Prompt 与工具 JSON Schema, +// 生成到 app/server/templates/system-prompt.txt 与 app/server/tools/definitions.json。 +// README 是这些内容的唯一事实来源(要求与 Zed 原始定义逐字一致以利用上游前缀缓存), +// 修改 README 后运行 `npm run gen`(见 app/package.json)重新生成。 +const fs = require('fs'); +const path = require('path'); + +const repoRoot = path.resolve(__dirname, '..'); +const readmePath = process.argv[2] || path.join(repoRoot, 'README.md'); +const outPrompt = path.join(repoRoot, 'app', 'server', 'templates', 'system-prompt.txt'); +const outTools = path.join(repoRoot, 'app', 'server', 'tools', 'definitions.json'); + +const lines = fs.readFileSync(readmePath, 'utf8').split('\n'); + +function findLineIndex(predicate, fromIdx) { + for (let k = fromIdx; k < lines.length; k++) if (predicate(lines[k])) return k; + return -1; +} + +// ---- 1. System Prompt(章节 7.1)---- +const h71 = findLineIndex(function (l) { return /^###\s+7\.1\b/.test(l); }, 0); +if (h71 < 0) throw new Error('README 中找不到 "### 7.1 System Prompt" 标题'); +// 标题后第一个代码围栏开始;注意 prompt 内部含 mermaid 等嵌套围栏, +// 因此结束围栏以 "> 注:" 说明行之前的最后一个空信息围栏为准。 +const start = findLineIndex(function (l) { return l.trim() === '```'; }, h71 + 1); +if (start < 0) throw new Error('找不到 System Prompt 代码块起始围栏'); +const noteLine = findLineIndex(function (l) { return /^>\s*注[::]/.test(l); }, start + 1); +if (noteLine < 0) throw new Error('找不到 System Prompt 代码块后的 "> 注:" 说明行'); +let endIdx = -1; +for (let k = noteLine - 1; k > start; k--) { + if (lines[k].trim() === '```') { endIdx = k; break; } +} +if (endIdx < 0) throw new Error('找不到 System Prompt 代码块结束围栏'); +const promptText = lines.slice(start + 1, endIdx).join('\n').replace(/\n+$/, '\n'); +if (!promptText.includes('You are the Zed coding agent')) { + throw new Error('System Prompt 提取结果异常(缺少开头标识句)'); +} + +// ---- 2. 工具定义(章节 7.2)---- +const h72 = findLineIndex(function (l) { return /^###\s+7\.2\b/.test(l); }, 0); +if (h72 < 0) throw new Error('README 中找不到 "### 7.2 工具定义" 标题'); +const hNextChapter = findLineIndex(function (l) { return /^##\s+八、/.test(l); }, h72 + 1); +if (hNextChapter < 0) throw new Error('找不到第八章标题'); + +const tools = []; +let cur = h72 + 1; +while (cur < hNextChapter) { + if (lines[cur].trim() === '```json') { + let j = cur + 1; + while (j < hNextChapter && lines[j].trim() !== '```') j++; + const body = lines.slice(cur + 1, j).join('\n'); + let parsed; + try { + parsed = JSON.parse(body); + } catch (e) { + throw new Error('第 ' + (cur + 1) + ' 行附近的 JSON 解析失败: ' + e.message); + } + tools.push(parsed); + cur = j + 1; + } else { + cur++; + } +} +if (tools.length === 0) throw new Error('未提取到任何工具定义'); +for (const t of tools) { + if (t.type !== 'function' || !t.function || !t.function.name) { + throw new Error('工具定义结构异常: ' + JSON.stringify(t).slice(0, 200)); + } +} + +fs.mkdirSync(path.dirname(outPrompt), { recursive: true }); +fs.mkdirSync(path.dirname(outTools), { recursive: true }); +fs.writeFileSync(outPrompt, promptText, 'utf8'); +fs.writeFileSync(outTools, JSON.stringify(tools, null, 2) + '\n', 'utf8'); + +console.log('已生成:\n ' + outPrompt + ' (' + promptText.split('\n').length + ' 行)\n ' + outTools + ' (' + tools.length + ' 个工具: ' + tools.map(function (t) { return t.function.name; }).join(', ') + ')');