204848 commited on
Commit ·
feccc69
0
Parent(s):
Initial commit: ds2api with HF Spaces support
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .dockerignore +71 -0
- .env.example +20 -0
- .gitattributes +35 -0
- .gitignore +73 -0
- .golangci.yml +73 -0
- .releaserc.json +21 -0
- AGENTS.md +36 -0
- API.en.md +1449 -0
- API.md +1459 -0
- CODE_OF_CONDUCT.md +128 -0
- Dockerfile +73 -0
- LICENSE +661 -0
- README.en.md +441 -0
- README.md +17 -0
- SECURITY.md +65 -0
- VERSION +1 -0
- _fix.py +8 -0
- _fix2.py +7 -0
- api/chat-stream.js +3 -0
- api/index.go +20 -0
- app/handler.go +19 -0
- cf-worker/package-lock.json +1504 -0
- cf-worker/package.json +12 -0
- cf-worker/src/index.js +103 -0
- cf-worker/wrangler.toml +9 -0
- cmd/ds2api-tests/main.go +37 -0
- cmd/ds2api/main.go +111 -0
- config.example.json +72 -0
- docker-compose.dev.yml +33 -0
- docker-compose.yml +17 -0
- entrypoint.sh +22 -0
- go.mod +27 -0
- go.sum +49 -0
- internal/account/pool_acquire.go +99 -0
- internal/account/pool_core.go +132 -0
- internal/account/pool_edge_test.go +232 -0
- internal/account/pool_limits.go +81 -0
- internal/account/pool_test.go +313 -0
- internal/account/pool_waiters.go +43 -0
- internal/assistantturn/stream.go +64 -0
- internal/assistantturn/turn.go +285 -0
- internal/assistantturn/turn_test.go +149 -0
- internal/auth/admin.go +225 -0
- internal/auth/admin_test.go +86 -0
- internal/auth/auth_edge_test.go +442 -0
- internal/auth/request.go +314 -0
- internal/auth/request_test.go +397 -0
- internal/chathistory/store.go +810 -0
- internal/chathistory/store_test.go +635 -0
- internal/claudeconv/convert.go +37 -0
.dockerignore
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Git
|
| 2 |
+
.git
|
| 3 |
+
.gitignore
|
| 4 |
+
|
| 5 |
+
# Python
|
| 6 |
+
__pycache__
|
| 7 |
+
*.py[cod]
|
| 8 |
+
*$py.class
|
| 9 |
+
*.so
|
| 10 |
+
.Python
|
| 11 |
+
build/
|
| 12 |
+
develop-eggs/
|
| 13 |
+
dist/*
|
| 14 |
+
!dist/docker-input/
|
| 15 |
+
!dist/docker-input/*.tar.gz
|
| 16 |
+
downloads/
|
| 17 |
+
eggs/
|
| 18 |
+
.eggs/
|
| 19 |
+
lib/
|
| 20 |
+
lib64/
|
| 21 |
+
parts/
|
| 22 |
+
sdist/
|
| 23 |
+
var/
|
| 24 |
+
wheels/
|
| 25 |
+
*.egg-info/
|
| 26 |
+
.installed.cfg
|
| 27 |
+
*.egg
|
| 28 |
+
|
| 29 |
+
# 虚拟环境
|
| 30 |
+
venv/
|
| 31 |
+
env/
|
| 32 |
+
ENV/
|
| 33 |
+
.venv
|
| 34 |
+
|
| 35 |
+
# 环境配置(通过 docker-compose 挂载或环境变量传递)
|
| 36 |
+
.env
|
| 37 |
+
.env.local
|
| 38 |
+
.env.*.local
|
| 39 |
+
config.json
|
| 40 |
+
|
| 41 |
+
# 开发工具
|
| 42 |
+
.vscode/
|
| 43 |
+
.idea/
|
| 44 |
+
*.swp
|
| 45 |
+
*.swo
|
| 46 |
+
*~
|
| 47 |
+
|
| 48 |
+
# 测试
|
| 49 |
+
tests/
|
| 50 |
+
.pytest_cache/
|
| 51 |
+
.coverage
|
| 52 |
+
htmlcov/
|
| 53 |
+
|
| 54 |
+
# Node.js / WebUI 开发依赖
|
| 55 |
+
node_modules/
|
| 56 |
+
webui/node_modules/
|
| 57 |
+
npm-debug.log*
|
| 58 |
+
yarn-debug.log*
|
| 59 |
+
yarn-error.log*
|
| 60 |
+
|
| 61 |
+
# 文档
|
| 62 |
+
*.md
|
| 63 |
+
!README*.md
|
| 64 |
+
|
| 65 |
+
# CI/CD
|
| 66 |
+
.github/
|
| 67 |
+
.releaserc.json
|
| 68 |
+
|
| 69 |
+
# 其他
|
| 70 |
+
.DS_Store
|
| 71 |
+
Thumbs.db
|
.env.example
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# DS2API runtime
|
| 2 |
+
# Runtime listen port inside the app/container
|
| 3 |
+
PORT=5001
|
| 4 |
+
# Docker Compose host port (compose only; container still listens on PORT)
|
| 5 |
+
DS2API_HOST_PORT=6011
|
| 6 |
+
LOG_LEVEL=INFO
|
| 7 |
+
|
| 8 |
+
# Admin authentication
|
| 9 |
+
DS2API_ADMIN_KEY=change-me
|
| 10 |
+
|
| 11 |
+
# Config loading (choose one)
|
| 12 |
+
# 1) file-based config
|
| 13 |
+
DS2API_CONFIG_PATH=/app/config.json
|
| 14 |
+
# 2) inline JSON or Base64 JSON
|
| 15 |
+
# DS2API_CONFIG_JSON=
|
| 16 |
+
# 3) legacy compatibility alias
|
| 17 |
+
# CONFIG_JSON=
|
| 18 |
+
|
| 19 |
+
# Optional: static admin assets path
|
| 20 |
+
# DS2API_STATIC_ADMIN_DIR=/app/static/admin
|
.gitattributes
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.bak
|
| 2 |
+
config.json
|
| 3 |
+
.env
|
| 4 |
+
|
| 5 |
+
# IDE
|
| 6 |
+
.vscode/
|
| 7 |
+
.idea/
|
| 8 |
+
*.swp
|
| 9 |
+
*.swo
|
| 10 |
+
*~
|
| 11 |
+
.DS_Store
|
| 12 |
+
opencode.json
|
| 13 |
+
|
| 14 |
+
# Logs
|
| 15 |
+
*.log
|
| 16 |
+
logs/
|
| 17 |
+
artifacts/
|
| 18 |
+
|
| 19 |
+
# Vercel
|
| 20 |
+
.vercel
|
| 21 |
+
|
| 22 |
+
# Node.js / Frontend
|
| 23 |
+
node_modules/
|
| 24 |
+
webui/node_modules/
|
| 25 |
+
webui/dist/
|
| 26 |
+
.npm
|
| 27 |
+
.pnpm-store/
|
| 28 |
+
yarn.lock
|
| 29 |
+
pnpm-lock.yaml
|
| 30 |
+
|
| 31 |
+
# Build artifacts
|
| 32 |
+
dist/
|
| 33 |
+
*.tsbuildinfo
|
| 34 |
+
.cache/
|
| 35 |
+
.parcel-cache/
|
| 36 |
+
static/admin/
|
| 37 |
+
internal/webui/assets/admin/
|
| 38 |
+
|
| 39 |
+
# Go compiled binaries
|
| 40 |
+
/ds2api
|
| 41 |
+
//ds2api-tests
|
| 42 |
+
|
| 43 |
+
# Environment
|
| 44 |
+
.env.local
|
| 45 |
+
.env.*.local
|
| 46 |
+
|
| 47 |
+
# Testing
|
| 48 |
+
.coverage
|
| 49 |
+
htmlcov/
|
| 50 |
+
.pytest_cache/
|
| 51 |
+
.tox/
|
| 52 |
+
*.coverprofile
|
| 53 |
+
coverage*.out
|
| 54 |
+
cover/
|
| 55 |
+
|
| 56 |
+
# Misc
|
| 57 |
+
.git/
|
| 58 |
+
Thumbs.db
|
| 59 |
+
|
| 60 |
+
# Claude Code
|
| 61 |
+
.claude/
|
| 62 |
+
CLAUDE.local.md
|
| 63 |
+
|
| 64 |
+
# Local tool bootstrap cache
|
| 65 |
+
.tmp/
|
| 66 |
+
|
| 67 |
+
# Chat history
|
| 68 |
+
data/
|
| 69 |
+
.codex
|
| 70 |
+
.roomodes
|
| 71 |
+
|
| 72 |
+
deepseek2api旧版/
|
| 73 |
+
chat.deepseek.com_2026_05_30_09_34_45.har.txt
|
.golangci.yml
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version: "2"
|
| 2 |
+
|
| 3 |
+
run:
|
| 4 |
+
tests: true
|
| 5 |
+
|
| 6 |
+
linters:
|
| 7 |
+
default: standard
|
| 8 |
+
enable:
|
| 9 |
+
- errcheck
|
| 10 |
+
- govet
|
| 11 |
+
- ineffassign
|
| 12 |
+
- staticcheck
|
| 13 |
+
- unused
|
| 14 |
+
settings:
|
| 15 |
+
dupl:
|
| 16 |
+
threshold: 100
|
| 17 |
+
goconst:
|
| 18 |
+
min-len: 2
|
| 19 |
+
min-occurrences: 2
|
| 20 |
+
gocritic:
|
| 21 |
+
enabled-tags:
|
| 22 |
+
- diagnostic
|
| 23 |
+
- experimental
|
| 24 |
+
- opinionated
|
| 25 |
+
- performance
|
| 26 |
+
- style
|
| 27 |
+
disabled-checks:
|
| 28 |
+
- wrapperFunc
|
| 29 |
+
- rangeValCopy
|
| 30 |
+
- hugeParam
|
| 31 |
+
gocyclo:
|
| 32 |
+
min-complexity: 15
|
| 33 |
+
lll:
|
| 34 |
+
line-length: 140
|
| 35 |
+
misspell:
|
| 36 |
+
locale: US
|
| 37 |
+
nakedret:
|
| 38 |
+
max-func-lines: 30
|
| 39 |
+
prealloc:
|
| 40 |
+
simple: true
|
| 41 |
+
range-loops: true
|
| 42 |
+
for-loops: false
|
| 43 |
+
exclusions:
|
| 44 |
+
generated: lax
|
| 45 |
+
rules:
|
| 46 |
+
- path: (.+)\.go$
|
| 47 |
+
text: "ST1000: at least one file in a package should have a package comment"
|
| 48 |
+
paths:
|
| 49 |
+
- third_party$
|
| 50 |
+
- builtin$
|
| 51 |
+
- examples$
|
| 52 |
+
- vendor$
|
| 53 |
+
- webui/node_modules$
|
| 54 |
+
|
| 55 |
+
issues:
|
| 56 |
+
max-issues-per-linter: 0
|
| 57 |
+
max-same-issues: 0
|
| 58 |
+
|
| 59 |
+
formatters:
|
| 60 |
+
enable:
|
| 61 |
+
- gofmt
|
| 62 |
+
settings:
|
| 63 |
+
goimports:
|
| 64 |
+
local-prefixes:
|
| 65 |
+
- ds2api
|
| 66 |
+
exclusions:
|
| 67 |
+
generated: lax
|
| 68 |
+
paths:
|
| 69 |
+
- third_party$
|
| 70 |
+
- builtin$
|
| 71 |
+
- examples$
|
| 72 |
+
- vendor$
|
| 73 |
+
- webui/node_modules$
|
.releaserc.json
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"branches": [
|
| 3 |
+
{
|
| 4 |
+
"name": "main"
|
| 5 |
+
},
|
| 6 |
+
{
|
| 7 |
+
"name": "dev",
|
| 8 |
+
"prerelease": "beta",
|
| 9 |
+
"channel": "beta"
|
| 10 |
+
}
|
| 11 |
+
],
|
| 12 |
+
"plugins": [
|
| 13 |
+
["@semantic-release/commit-analyzer", {
|
| 14 |
+
"preset": "angular"
|
| 15 |
+
}],
|
| 16 |
+
"@semantic-release/release-notes-generator",
|
| 17 |
+
["@semantic-release/github", {
|
| 18 |
+
"successComment": ":tada: This release is now available as ${nextRelease.version}"
|
| 19 |
+
}]
|
| 20 |
+
]
|
| 21 |
+
}
|
AGENTS.md
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# AGENTS.md
|
| 2 |
+
|
| 3 |
+
These rules apply to all agent-made changes in this repository.
|
| 4 |
+
|
| 5 |
+
## PR Gate
|
| 6 |
+
|
| 7 |
+
- Before opening or updating a PR, run the same local gates as `.github/workflows/quality-gates.yml`.
|
| 8 |
+
- Required commands:
|
| 9 |
+
- `./scripts/lint.sh`
|
| 10 |
+
- `./tests/scripts/check-refactor-line-gate.sh`
|
| 11 |
+
- `./tests/scripts/run-unit-all.sh`
|
| 12 |
+
- `npm run build --prefix webui`
|
| 13 |
+
|
| 14 |
+
## Go Lint Rules
|
| 15 |
+
|
| 16 |
+
- Run `gofmt -w` on every changed Go file before commit or push.
|
| 17 |
+
- Do not ignore error returns from I/O-style cleanup calls such as `Close`, `Flush`, `Sync`, or similar methods.
|
| 18 |
+
- If a cleanup error cannot be returned, log it explicitly.
|
| 19 |
+
|
| 20 |
+
## Change Scope
|
| 21 |
+
|
| 22 |
+
- Keep changes additive and tightly scoped to the requested feature or bugfix.
|
| 23 |
+
- Do not mix unrelated refactors into feature PRs unless they are required to make the change pass gates.
|
| 24 |
+
|
| 25 |
+
## Protocol Adapter Boundary
|
| 26 |
+
|
| 27 |
+
- Do not let OpenAI Chat, OpenAI Responses, Claude, Gemini, or other interface protocol formatting own shared business behavior.
|
| 28 |
+
- Normalize protocol-specific request shapes into the project standard request/turn model first, run shared business logic in one place, then render back to the target protocol at the boundary.
|
| 29 |
+
- Business logic that must stay globally consistent includes empty-output retry, thinking/reasoning handling, tool-call detection and policy, usage accounting, current-input-file injection, history persistence, file/reference handling, and completion payload assembly.
|
| 30 |
+
- If a behavior must differ by protocol, keep the difference as an explicit adapter/rendering concern and document why it cannot live in the shared normalized path.
|
| 31 |
+
|
| 32 |
+
## Documentation Sync
|
| 33 |
+
|
| 34 |
+
- When business logic or user-visible behavior changes, update the corresponding documentation in the same change.
|
| 35 |
+
- `docs/prompt-compatibility.md` is the source-of-truth document for the “API -> pure-text web-chat context” compatibility flow.
|
| 36 |
+
- If a change affects message normalization, tool prompt injection, prompt-visible tool history, file/reference handling, history split, or completion payload assembly, update `docs/prompt-compatibility.md` in the same change.
|
API.en.md
ADDED
|
@@ -0,0 +1,1449 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
| 1 |
+
# DS2API API Reference
|
| 2 |
+
|
| 3 |
+
Language: [中文](API.md) | [English](API.en.md)
|
| 4 |
+
|
| 5 |
+
This document describes the actual behavior of the current Go codebase.
|
| 6 |
+
|
| 7 |
+
Docs: [Overview](README.en.md) / [Architecture](docs/ARCHITECTURE.en.md) / [Deployment](docs/DEPLOY.en.md) / [Testing](docs/TESTING.md)
|
| 8 |
+
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
## Table of Contents
|
| 12 |
+
|
| 13 |
+
- [Basics](#basics)
|
| 14 |
+
- [Configuration Best Practice](#configuration-best-practice)
|
| 15 |
+
- [Authentication](#authentication)
|
| 16 |
+
- [Route Index](#route-index)
|
| 17 |
+
- [Health Endpoints](#health-endpoints)
|
| 18 |
+
- [OpenAI-Compatible API](#openai-compatible-api)
|
| 19 |
+
- [Claude-Compatible API](#claude-compatible-api)
|
| 20 |
+
- [Gemini-Compatible API](#gemini-compatible-api)
|
| 21 |
+
- [Ollama API](#ollama-api)
|
| 22 |
+
- [Admin API](#admin-api)
|
| 23 |
+
- [Error Payloads](#error-payloads)
|
| 24 |
+
- [cURL Examples](#curl-examples)
|
| 25 |
+
|
| 26 |
+
---
|
| 27 |
+
|
| 28 |
+
## Basics
|
| 29 |
+
|
| 30 |
+
| Item | Details |
|
| 31 |
+
| --- | --- |
|
| 32 |
+
| Base URL | `http://localhost:5001` or your deployment domain |
|
| 33 |
+
| Default Content-Type | `application/json` |
|
| 34 |
+
| Health probes | `GET /healthz`, `GET /readyz` |
|
| 35 |
+
| CORS | Enabled (uniformly covers `/v1/*`, `/anthropic/*`, `/v1beta/models/*`, `/api/*`, and `/admin/*`; echoes the browser `Origin` when present, otherwise `*`; default allow-list includes `Content-Type`, `Authorization`, `X-API-Key`, `X-Ds2-Target-Account`, `X-Ds2-Source`, `X-Vercel-Protection-Bypass`, `X-Goog-Api-Key`, `Anthropic-Version`, `Anthropic-Beta`, and also accepts third-party preflight-requested headers such as `x-stainless-*`; `/v1/chat/completions` on Vercel Node Runtime matches the same behavior; internal-only `X-Ds2-Internal-Token` remains blocked) |
|
| 36 |
+
|
| 37 |
+
- All JSON request bodies must be valid UTF-8; malformed byte sequences are rejected on ingress with `400 invalid json`.
|
| 38 |
+
|
| 39 |
+
### 3.0 Adapter-Layer Notes
|
| 40 |
+
|
| 41 |
+
- OpenAI / Claude / Gemini protocols are now mounted on one shared `chi` router tree assembled in `internal/server/router.go`.
|
| 42 |
+
- Adapter responsibilities are streamlined to: **request normalization → DeepSeek invocation → protocol-shaped rendering**, reducing legacy split-logic paths.
|
| 43 |
+
- Tool-calling semantics are aligned between Go and Node runtime: models should output the halfwidth-pipe DSML shell `<|DSML|tool_calls>` → `<|DSML|invoke name="...">` → `<|DSML|parameter name="...">`; DS2API also accepts DSML wrapper aliases such as `<dsml|tool_calls>` and `<|tool_calls>`, common DSML separator drift such as `<|DSML tool_calls>`, collapsed DSML local names such as `<DSMLtool_calls>`, control-separator drift such as `<DSML␂tool_calls>` / raw STX `\x02`, CJK angle bracket, fullwidth-bang / ideographic-comma separator drift, PascalCase local-name drift, and trailing attribute separator drift such as `<DSM|parameter name="command"|>...〈/DSM|parameter〉`, `<!DSML!invoke name=“Bash”>`, `<、DSML、tool_calls>`, `<DSmartToolCalls>`, or `<DSMLtool_calls※>`, arbitrary protocol prefixes such as `<proto💥tool_calls>`, and legacy canonical XML `<tool_calls>` → `<invoke name="...">` → `<parameter name="...">`. The scanner normalizes fixed local names (`tool_calls` / `invoke` / `parameter`) with non-structural separators before or after them back to XML before parsing, and also tolerates CDATA opener drift such as `<![CDATA[` / `<、[CDATA[`; only wrapped tool blocks or the narrow missing-opening-wrapper repair path enter the tool path, while bare `<invoke>` does not count as supported syntax. JSON literal parameter bodies are preserved as structured values, explicit empty or whitespace-only parameters are preserved as empty strings, malformed complete wrappers are released as plain text, and loose CDATA is narrowly repaired at final parse/flush when it can preserve a complete outer tool call.
|
| 44 |
+
- `Admin API` separates static config from runtime policy: `/admin/config*` for configuration state, `/admin/settings*` for runtime behavior.
|
| 45 |
+
- When upstream returns a thinking-only response with no visible text, the Go main path and the Vercel Node streaming path retry once in the same DeepSeek session: it appends the prompt suffix `"Please provide a non-empty final answer or tool call."` and sets `parent_message_id`. If that same-account retry would still end as `429 upstream_empty_output`, managed-account mode switches to the next available account, creates a fresh session, and retries the original payload once before returning 429.
|
| 46 |
+
- Citation/reference marker boundary: streaming output hides upstream `[citation:N]` / `[reference:N]` placeholders by default; non-stream output converts DeepSeek search reference markers into Markdown links.
|
| 47 |
+
|
| 48 |
+
---
|
| 49 |
+
|
| 50 |
+
## Configuration Best Practice
|
| 51 |
+
|
| 52 |
+
Use `config.json` as the single source of truth:
|
| 53 |
+
|
| 54 |
+
```bash
|
| 55 |
+
cp config.example.json config.json
|
| 56 |
+
# Edit config.json (keys/accounts)
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
Use it per deployment mode:
|
| 60 |
+
|
| 61 |
+
- Local run: read `config.json` directly
|
| 62 |
+
- Docker / Vercel: generate Base64 from `config.json`, then set `DS2API_CONFIG_JSON`, or paste raw JSON directly
|
| 63 |
+
|
| 64 |
+
```bash
|
| 65 |
+
DS2API_CONFIG_JSON="$(base64 < config.json | tr -d '\n')"
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
For Vercel one-click bootstrap, you can set only `DS2API_ADMIN_KEY` first, then import config at `/admin` and sync env vars from the "Vercel Sync" page.
|
| 69 |
+
|
| 70 |
+
---
|
| 71 |
+
|
| 72 |
+
## Authentication
|
| 73 |
+
|
| 74 |
+
### Business Endpoints (`/v1/*`, `/anthropic/*`, `/v1beta/models/*`)
|
| 75 |
+
|
| 76 |
+
Two header formats accepted:
|
| 77 |
+
|
| 78 |
+
| Method | Example |
|
| 79 |
+
| --- | --- |
|
| 80 |
+
| Bearer Token | `Authorization: Bearer <token>` |
|
| 81 |
+
| API Key Header | `x-api-key: <token>` (no `Bearer` prefix) |
|
| 82 |
+
| Gemini-compatible | `x-goog-api-key: <token>` or `?key=<token>` / `?api_key=<token>` |
|
| 83 |
+
|
| 84 |
+
**Auth behavior**:
|
| 85 |
+
|
| 86 |
+
- Token is in `config.keys` → **Managed account mode**: DS2API auto-selects an account via rotation
|
| 87 |
+
- Token is not in `config.keys` → **Direct token mode**: treated as a DeepSeek token directly
|
| 88 |
+
|
| 89 |
+
**Optional header**: `X-Ds2-Target-Account: <email_or_mobile>` — Pin a specific managed account; if the target account does not exist or the managed-account queue is exhausted, the request returns `429`, and current responses do not include `Retry-After`. If the account exists but login/refresh fails, the request returns the underlying `401` or upstream error. Without a pinned target, managed-account completion requests try one alternate-account fresh retry before returning an empty-output 429; pinned-target requests and requests with no other available account do not switch.
|
| 90 |
+
Gemini-compatible clients can also send `x-goog-api-key`, `?key=`, or `?api_key=` as the caller credential source.
|
| 91 |
+
|
| 92 |
+
### Admin Endpoints (`/admin/*`)
|
| 93 |
+
|
| 94 |
+
| Endpoint | Auth |
|
| 95 |
+
| --- | --- |
|
| 96 |
+
| `POST /admin/login` | Public |
|
| 97 |
+
| `GET /admin/verify` | `Authorization: Bearer <jwt>` (JWT only) |
|
| 98 |
+
| Other `/admin/*` | `Authorization: Bearer <jwt>` or `Authorization: Bearer <admin_key>` |
|
| 99 |
+
|
| 100 |
+
---
|
| 101 |
+
|
| 102 |
+
## Route Index
|
| 103 |
+
|
| 104 |
+
| Method | Path | Auth | Description |
|
| 105 |
+
| --- | --- | --- | --- |
|
| 106 |
+
| GET | `/healthz` | None | Liveness probe |
|
| 107 |
+
| HEAD | `/healthz` | None | Liveness probe (no body) |
|
| 108 |
+
| GET | `/readyz` | None | Readiness probe |
|
| 109 |
+
| HEAD | `/readyz` | None | Readiness probe (no body) |
|
| 110 |
+
| GET | `/v1/models` | None | OpenAI model list |
|
| 111 |
+
| GET | `/v1/models/{id}` | None | OpenAI single-model query (alias accepted) |
|
| 112 |
+
| POST | `/v1/chat/completions` | Business | OpenAI chat completions |
|
| 113 |
+
| POST | `/v1/responses` | Business | OpenAI Responses API (stream/non-stream) |
|
| 114 |
+
| GET | `/v1/responses/{response_id}` | Business | Query stored response (in-memory TTL) |
|
| 115 |
+
| POST | `/v1/embeddings` | Business | OpenAI Embeddings API |
|
| 116 |
+
| POST | `/v1/files` | Business | OpenAI Files upload (multipart/form-data) |
|
| 117 |
+
| GET | `/v1/files/{file_id}` | Business | Retrieve uploaded file status |
|
| 118 |
+
| GET | `/anthropic/v1/models` | None | Claude model list |
|
| 119 |
+
| POST | `/anthropic/v1/messages` | Business | Claude messages |
|
| 120 |
+
| POST | `/anthropic/v1/messages/count_tokens` | Business | Claude token counting |
|
| 121 |
+
| POST | `/v1/messages` | Business | Claude shortcut path |
|
| 122 |
+
| POST | `/messages` | Business | Claude shortcut path |
|
| 123 |
+
| POST | `/v1/messages/count_tokens` | Business | Claude token counting shortcut |
|
| 124 |
+
| POST | `/messages/count_tokens` | Business | Claude token counting shortcut |
|
| 125 |
+
| POST | `/v1beta/models/{model}:generateContent` | Business | Gemini non-stream |
|
| 126 |
+
| POST | `/v1beta/models/{model}:streamGenerateContent` | Business | Gemini stream |
|
| 127 |
+
| POST | `/v1/models/{model}:generateContent` | Business | Gemini non-stream compat path |
|
| 128 |
+
| POST | `/v1/models/{model}:streamGenerateContent` | Business | Gemini stream compat path |
|
| 129 |
+
| GET | `/api/version` | None | Ollama version endpoint |
|
| 130 |
+
| GET | `/api/tags` | None | Ollama model list |
|
| 131 |
+
| POST | `/api/show` | None | Ollama model capability query (returns `id` + `capabilities`) |
|
| 132 |
+
| POST | `/admin/login` | None | Admin login |
|
| 133 |
+
| GET | `/admin/verify` | JWT | Verify admin JWT |
|
| 134 |
+
| GET | `/admin/vercel/config` | Admin | Read preconfigured Vercel creds |
|
| 135 |
+
| GET | `/admin/config` | Admin | Read sanitized config |
|
| 136 |
+
| POST | `/admin/config` | Admin | Update config |
|
| 137 |
+
| GET | `/admin/settings` | Admin | Read runtime settings |
|
| 138 |
+
| PUT | `/admin/settings` | Admin | Update runtime settings (hot reload) |
|
| 139 |
+
| POST | `/admin/settings/password` | Admin | Update admin password and invalidate old JWTs |
|
| 140 |
+
| POST | `/admin/config/import` | Admin | Import config (merge/replace) |
|
| 141 |
+
| GET | `/admin/config/export` | Admin | Export full config (`config`/`json`/`base64`) |
|
| 142 |
+
| POST | `/admin/keys` | Admin | Add API key (optional `name`/`remark`) |
|
| 143 |
+
| PUT | `/admin/keys/{key}` | Admin | Update API key metadata |
|
| 144 |
+
| DELETE | `/admin/keys/{key}` | Admin | Delete API key |
|
| 145 |
+
| GET | `/admin/proxies` | Admin | List proxies |
|
| 146 |
+
| POST | `/admin/proxies` | Admin | Add proxy |
|
| 147 |
+
| PUT | `/admin/proxies/{proxyID}` | Admin | Update proxy (empty password keeps old secret) |
|
| 148 |
+
| DELETE | `/admin/proxies/{proxyID}` | Admin | Delete proxy (auto-unbind referenced accounts) |
|
| 149 |
+
| POST | `/admin/proxies/test` | Admin | Test proxy connectivity |
|
| 150 |
+
| GET | `/admin/accounts` | Admin | Paginated account list |
|
| 151 |
+
| POST | `/admin/accounts` | Admin | Add account |
|
| 152 |
+
| PUT | `/admin/accounts/{identifier}` | Admin | Update account name/remark |
|
| 153 |
+
| DELETE | `/admin/accounts/{identifier}` | Admin | Delete account |
|
| 154 |
+
| PUT | `/admin/accounts/{identifier}/proxy` | Admin | Bind/unbind proxy for an account |
|
| 155 |
+
| GET | `/admin/queue/status` | Admin | Account queue status |
|
| 156 |
+
| POST | `/admin/accounts/test` | Admin | Test one account |
|
| 157 |
+
| POST | `/admin/accounts/test-all` | Admin | Test all accounts |
|
| 158 |
+
| POST | `/admin/accounts/sessions/delete-all` | Admin | Delete all sessions for one account |
|
| 159 |
+
| POST | `/admin/import` | Admin | Batch import keys/accounts |
|
| 160 |
+
| POST | `/admin/test` | Admin | Test API through service |
|
| 161 |
+
| POST | `/admin/dev/raw-samples/capture` | Admin | Fire one request and persist it as a raw sample |
|
| 162 |
+
| GET | `/admin/dev/raw-samples/query` | Admin | Search current in-memory capture chains by prompt keyword |
|
| 163 |
+
| POST | `/admin/dev/raw-samples/save` | Admin | Persist a selected in-memory capture chain as a raw sample |
|
| 164 |
+
| POST | `/admin/vercel/sync` | Admin | Sync config to Vercel |
|
| 165 |
+
| GET | `/admin/vercel/status` | Admin | Vercel sync status |
|
| 166 |
+
| POST | `/admin/vercel/status` | Admin | Vercel sync status / draft compare |
|
| 167 |
+
| GET | `/admin/export` | Admin | Export config JSON/Base64 |
|
| 168 |
+
| GET | `/admin/dev/captures` | Admin | Read local packet-capture entries |
|
| 169 |
+
| DELETE | `/admin/dev/captures` | Admin | Clear local packet-capture entries |
|
| 170 |
+
| GET | `/admin/chat-history` | Admin | Read server-side conversation history |
|
| 171 |
+
| DELETE | `/admin/chat-history` | Admin | Clear server-side conversation history |
|
| 172 |
+
| GET | `/admin/chat-history/{id}` | Admin | Read one server-side conversation entry |
|
| 173 |
+
| DELETE | `/admin/chat-history/{id}` | Admin | Delete one server-side conversation entry |
|
| 174 |
+
| PUT | `/admin/chat-history/settings` | Admin | Update conversation history retention limit |
|
| 175 |
+
| GET | `/admin/version` | Admin | Check current version and latest Release |
|
| 176 |
+
|
| 177 |
+
OpenAI `/v1/*` paths are canonical. For clients configured with the bare DS2API service URL, the same OpenAI handlers are also exposed through root shortcuts: `/models`, `/models/{id}`, `/chat/completions`, `/responses`, `/responses/{response_id}`, `/embeddings`, `/files`, and `/files/{file_id}`.
|
| 178 |
+
|
| 179 |
+
---
|
| 180 |
+
|
| 181 |
+
## Health Endpoints
|
| 182 |
+
|
| 183 |
+
### `GET /healthz`
|
| 184 |
+
|
| 185 |
+
```json
|
| 186 |
+
{"status": "ok"}
|
| 187 |
+
```
|
| 188 |
+
|
| 189 |
+
### `GET /readyz`
|
| 190 |
+
|
| 191 |
+
```json
|
| 192 |
+
{"status": "ready"}
|
| 193 |
+
```
|
| 194 |
+
|
| 195 |
+
---
|
| 196 |
+
|
| 197 |
+
## OpenAI-Compatible API
|
| 198 |
+
|
| 199 |
+
### `GET /v1/models`
|
| 200 |
+
|
| 201 |
+
No auth required. Returns the currently supported DeepSeek native model list.
|
| 202 |
+
|
| 203 |
+
**Response**:
|
| 204 |
+
|
| 205 |
+
```json
|
| 206 |
+
{
|
| 207 |
+
"object": "list",
|
| 208 |
+
"data": [
|
| 209 |
+
{"id": "deepseek-v4-flash", "object": "model", "created": 1677610602, "owned_by": "deepseek", "permission": []},
|
| 210 |
+
{"id": "deepseek-v4-flash-nothinking", "object": "model", "created": 1677610602, "owned_by": "deepseek", "permission": []},
|
| 211 |
+
{"id": "deepseek-v4-pro", "object": "model", "created": 1677610602, "owned_by": "deepseek", "permission": []},
|
| 212 |
+
{"id": "deepseek-v4-pro-nothinking", "object": "model", "created": 1677610602, "owned_by": "deepseek", "permission": []},
|
| 213 |
+
{"id": "deepseek-v4-flash-search", "object": "model", "created": 1677610602, "owned_by": "deepseek", "permission": []},
|
| 214 |
+
{"id": "deepseek-v4-flash-search-nothinking", "object": "model", "created": 1677610602, "owned_by": "deepseek", "permission": []},
|
| 215 |
+
{"id": "deepseek-v4-pro-search", "object": "model", "created": 1677610602, "owned_by": "deepseek", "permission": []},
|
| 216 |
+
{"id": "deepseek-v4-pro-search-nothinking", "object": "model", "created": 1677610602, "owned_by": "deepseek", "permission": []},
|
| 217 |
+
{"id": "deepseek-v4-vision", "object": "model", "created": 1677610602, "owned_by": "deepseek", "permission": []},
|
| 218 |
+
{"id": "deepseek-v4-vision-nothinking", "object": "model", "created": 1677610602, "owned_by": "deepseek", "permission": []}
|
| 219 |
+
]
|
| 220 |
+
}
|
| 221 |
+
```
|
| 222 |
+
|
| 223 |
+
> Note: `/v1/models` returns normalized DeepSeek native model IDs. Common aliases are accepted only as request input and are not expanded as separate items in this endpoint.
|
| 224 |
+
|
| 225 |
+
### Model Alias Resolution
|
| 226 |
+
|
| 227 |
+
For `chat` / `responses` / `embeddings`, DS2API follows a wide-input/strict-output policy:
|
| 228 |
+
|
| 229 |
+
1. Match DeepSeek native model IDs first.
|
| 230 |
+
2. Then match exact keys in `model_aliases`.
|
| 231 |
+
3. If the request name ends with `-nothinking`, resolve the base alias and append the corresponding no-thinking variant.
|
| 232 |
+
4. If still unmatched, return `invalid_request_error`. Unknown model families are not guessed heuristically; add explicit compatibility names through `model_aliases`.
|
| 233 |
+
|
| 234 |
+
Built-in aliases come from `internal/config/models.go`; `config.model_aliases` can override or add mappings at runtime. Excerpt:
|
| 235 |
+
|
| 236 |
+
- OpenAI / Codex: `gpt-4o`, `gpt-4.1`, `gpt-5`, `gpt-5.5`, `gpt-5-codex`, `gpt-5.3-codex`, `codex-mini-latest`
|
| 237 |
+
- OpenAI reasoning: `o1`, `o3`, `o3-deep-research`, `o4-mini`
|
| 238 |
+
- Claude: `claude-opus-4-6`, `claude-sonnet-4-6`, `claude-haiku-4-5`, `claude-3-5-sonnet-latest`
|
| 239 |
+
- Gemini: `gemini-2.5-pro`, `gemini-2.5-flash`, `gemini-3.1-pro`, `gemini-3-pro`, `gemini-3-flash`, `gemini-3.1-flash-lite`, `gemini-pro-vision`
|
| 240 |
+
- Other exact built-in aliases: `llama-3.1-70b-instruct`, `qwen-max`
|
| 241 |
+
|
| 242 |
+
Aliases with a `-nothinking` suffix also map to the corresponding forced no-thinking DeepSeek model.
|
| 243 |
+
|
| 244 |
+
Current vision support resolves only to `deepseek-v4-vision` and does not expose a separate `vision-search` variant.
|
| 245 |
+
|
| 246 |
+
Retired historical families such as `claude-1.*`, `claude-2.*`, `claude-instant-*`, and `gpt-3.5*` are explicitly rejected.
|
| 247 |
+
|
| 248 |
+
### `POST /v1/chat/completions`
|
| 249 |
+
|
| 250 |
+
> Path note: besides the canonical `/v1/chat/completions`, DS2API also accepts the root shortcut `/chat/completions`. On Vercel Runtime, `vercel.json` rewrites only the canonical `/v1/chat/completions` path to the Node streaming bridge; the root shortcut stays on the Go primary path. Use `/v1/chat/completions` on Vercel when real-time streaming is required.
|
| 251 |
+
|
| 252 |
+
**Headers**:
|
| 253 |
+
|
| 254 |
+
```http
|
| 255 |
+
Authorization: Bearer your-api-key
|
| 256 |
+
Content-Type: application/json
|
| 257 |
+
```
|
| 258 |
+
|
| 259 |
+
**Request body**:
|
| 260 |
+
|
| 261 |
+
| Field | Type | Required | Notes |
|
| 262 |
+
| --- | --- | --- | --- |
|
| 263 |
+
| `model` | string | ✅ | DeepSeek native models + common aliases (`gpt-5.5`, `gpt-5.4-mini`, `gpt-5.3-codex`, `o3`, `claude-opus-4-6`, `gemini-2.5-pro`, `gemini-3.1-pro`, `gemini-3-flash`, etc.); `-nothinking` suffixes force thinking / reasoning off |
|
| 264 |
+
| `messages` | array | ✅ | OpenAI-style messages |
|
| 265 |
+
| `stream` | boolean | ❌ | Default `false` |
|
| 266 |
+
| `tools` | array | ❌ | Function calling schema |
|
| 267 |
+
| `temperature`, etc. | any | ❌ | Accepted but final behavior depends on upstream |
|
| 268 |
+
|
| 269 |
+
#### Non-Stream Response
|
| 270 |
+
|
| 271 |
+
```json
|
| 272 |
+
{
|
| 273 |
+
"id": "<chat_session_id>",
|
| 274 |
+
"object": "chat.completion",
|
| 275 |
+
"created": 1738400000,
|
| 276 |
+
"model": "deepseek-v4-pro",
|
| 277 |
+
"choices": [
|
| 278 |
+
{
|
| 279 |
+
"index": 0,
|
| 280 |
+
"message": {
|
| 281 |
+
"role": "assistant",
|
| 282 |
+
"content": "final response",
|
| 283 |
+
"reasoning_content": "reasoning trace (when thinking is enabled)"
|
| 284 |
+
},
|
| 285 |
+
"finish_reason": "stop"
|
| 286 |
+
}
|
| 287 |
+
],
|
| 288 |
+
"usage": {
|
| 289 |
+
"prompt_tokens": 10,
|
| 290 |
+
"completion_tokens": 20,
|
| 291 |
+
"total_tokens": 30,
|
| 292 |
+
"completion_tokens_details": {
|
| 293 |
+
"reasoning_tokens": 5
|
| 294 |
+
}
|
| 295 |
+
}
|
| 296 |
+
}
|
| 297 |
+
```
|
| 298 |
+
|
| 299 |
+
#### Streaming (`stream=true`)
|
| 300 |
+
|
| 301 |
+
SSE format: each frame is `data: <json>\n\n`, terminated by `data: [DONE]`.
|
| 302 |
+
|
| 303 |
+
```text
|
| 304 |
+
data: {"id":"...","object":"chat.completion.chunk","choices":[{"delta":{"role":"assistant"},"index":0}]}
|
| 305 |
+
|
| 306 |
+
data: {"id":"...","object":"chat.completion.chunk","choices":[{"delta":{"reasoning_content":"..."},"index":0}]}
|
| 307 |
+
|
| 308 |
+
data: {"id":"...","object":"chat.completion.chunk","choices":[{"delta":{"content":"..."},"index":0}]}
|
| 309 |
+
|
| 310 |
+
data: {"id":"...","object":"chat.completion.chunk","choices":[{"delta":{},"index":0,"finish_reason":"stop"}],"usage":{...}}
|
| 311 |
+
|
| 312 |
+
data: [DONE]
|
| 313 |
+
```
|
| 314 |
+
|
| 315 |
+
**Field notes**:
|
| 316 |
+
|
| 317 |
+
- First delta includes `role: assistant`
|
| 318 |
+
- When thinking is enabled, the stream may emit `delta.reasoning_content`
|
| 319 |
+
- Text emits `delta.content`
|
| 320 |
+
- Last chunk includes `finish_reason` and `usage`
|
| 321 |
+
- Token counting prefers pass-through from upstream DeepSeek SSE (`accumulated_token_usage` / `token_usage`), and only falls back to local estimation when upstream usage is absent. Failed/interrupted endings (for example `response.failed`) may not include `usage`
|
| 322 |
+
|
| 323 |
+
#### Tool Calls
|
| 324 |
+
|
| 325 |
+
When `tools` is present, DS2API performs anti-leak handling:
|
| 326 |
+
|
| 327 |
+
**Non-stream**: If detected, returns `message.tool_calls`, `finish_reason=tool_calls`, `message.content=null`.
|
| 328 |
+
|
| 329 |
+
```json
|
| 330 |
+
{
|
| 331 |
+
"choices": [
|
| 332 |
+
{
|
| 333 |
+
"index": 0,
|
| 334 |
+
"message": {
|
| 335 |
+
"role": "assistant",
|
| 336 |
+
"content": null,
|
| 337 |
+
"tool_calls": [
|
| 338 |
+
{
|
| 339 |
+
"id": "call_xxx",
|
| 340 |
+
"type": "function",
|
| 341 |
+
"function": {
|
| 342 |
+
"name": "get_weather",
|
| 343 |
+
"arguments": "{\"city\":\"beijing\"}"
|
| 344 |
+
}
|
| 345 |
+
}
|
| 346 |
+
]
|
| 347 |
+
},
|
| 348 |
+
"finish_reason": "tool_calls"
|
| 349 |
+
}
|
| 350 |
+
]
|
| 351 |
+
}
|
| 352 |
+
```
|
| 353 |
+
|
| 354 |
+
**Stream**: Once high-confidence toolcall features are matched, DS2API emits `delta.tool_calls` immediately (without waiting for full argument closure), then keeps sending argument deltas; confirmed tool-call fragments are not forwarded as `delta.content`.
|
| 355 |
+
|
| 356 |
+
Additional notes:
|
| 357 |
+
|
| 358 |
+
- The parser treats the recommended halfwidth-pipe DSML shell tool blocks (`<|DSML|tool_calls>` / `<|DSML|invoke name="...">` / `<|DSML|parameter name="...">`), DSML wrapper aliases (`<dsml|tool_calls>`, `<|tool_calls>`), common DSML separator drift (`<|DSML tool_calls>` / `<|DSML invoke>` / `<|DSML parameter>`), collapsed DSML local names (`<DSMLtool_calls>` / `<DSMLinvoke>` / `<DSMLparameter>`), control-separator drift (`<DSML␂tool_calls>` / raw STX `\x02`), CJK angle bracket, fullwidth-bang / ideographic-comma separator drift, PascalCase local-name drift, and trailing attribute separator drift (`<DSM|parameter name="command"|>...〈/DSM|parameter〉` / `<!DSML!invoke name=“Bash”>` / `<、DSML、tool_calls>` / `<DSmartToolCalls>` / `<DSMLtool_calls※>`), arbitrary protocol prefixes (`<proto💥tool_calls>`), and legacy canonical XML tool blocks (`<tool_calls>` / `<invoke name="...">` / `<parameter name="...">`) as executable tool calls. These shells normalize non-structural separators back to XML first, while internal parsing remains XML-based; CDATA opener drift such as `<![CDATA[` / `<、[CDATA[` is also normalized for parameter bodies. Legacy `<tools>`, `<tool_call>`, `<tool_name>`, `<param>`, `<function_call>`, `tool_use`, antml variants, and standalone JSON `tool_calls` payloads are treated as plain text; complete but malformed wrappers are also released as plain text.
|
| 359 |
+
- The parser no longer drops tool calls solely because parameter values are empty; explicit empty strings or whitespace-only parameters become empty strings in structured `tool_calls`. Prompting still tells the model not to emit blank parameters, and missing/empty argument rejection belongs in the tool executor or client schema validation.
|
| 360 |
+
- If the final visible response text is empty but the reasoning stream contains an executable tool call, Chat / Responses emits a standard OpenAI `tool_calls` / `function_call` output during finalization. If thinking/reasoning was not enabled by the client, that reasoning text is used only for detection and is not exposed as visible text or `reasoning_content`.
|
| 361 |
+
- `tool_calls` shown inside fenced markdown code blocks (for example, ```json ... ```) are treated as examples, not executable calls.
|
| 362 |
+
|
| 363 |
+
---
|
| 364 |
+
|
| 365 |
+
### `GET /v1/models/{id}`
|
| 366 |
+
|
| 367 |
+
No auth required. Alias values are accepted as path params (for example `gpt-4o`), and the returned object is the mapped DeepSeek model.
|
| 368 |
+
|
| 369 |
+
### `POST /v1/responses`
|
| 370 |
+
|
| 371 |
+
OpenAI Responses-style endpoint, accepting either `input` or `messages`.
|
| 372 |
+
|
| 373 |
+
| Field | Type | Required | Notes |
|
| 374 |
+
| --- | --- | --- | --- |
|
| 375 |
+
| `model` | string | ✅ | Supports native models + alias mapping |
|
| 376 |
+
| `input` | string/array/object | ❌ | One of `input` or `messages` is required |
|
| 377 |
+
| `messages` | array | ❌ | One of `input` or `messages` is required |
|
| 378 |
+
| `instructions` | string | ❌ | Prepended as a system message |
|
| 379 |
+
| `stream` | boolean | ❌ | Default `false` |
|
| 380 |
+
| `tools` | array | ❌ | Same tool detection/translation policy as chat |
|
| 381 |
+
| `tool_choice` | string/object | ❌ | Supports `auto`/`none`/`required` and forced function selection (`{"type":"function","name":"..."}`) |
|
| 382 |
+
|
| 383 |
+
**Non-stream**: Returns a standard `response` object with an ID like `resp_xxx`, and stores it in in-memory TTL cache.
|
| 384 |
+
If `tool_choice=required` and no valid tool call is produced, DS2API returns HTTP `422` (`error.code=tool_choice_violation`).
|
| 385 |
+
|
| 386 |
+
**Stream (SSE)**: minimal event sequence:
|
| 387 |
+
|
| 388 |
+
```text
|
| 389 |
+
event: response.created
|
| 390 |
+
data: {"type":"response.created","id":"resp_xxx","status":"in_progress",...}
|
| 391 |
+
|
| 392 |
+
event: response.output_item.added
|
| 393 |
+
data: {"type":"response.output_item.added","response_id":"resp_xxx","item":{"type":"message|function_call",...},...}
|
| 394 |
+
|
| 395 |
+
event: response.content_part.added
|
| 396 |
+
data: {"type":"response.content_part.added","response_id":"resp_xxx","part":{"type":"output_text",...},...}
|
| 397 |
+
|
| 398 |
+
event: response.output_text.delta
|
| 399 |
+
data: {"type":"response.output_text.delta","response_id":"resp_xxx","item_id":"msg_xxx","output_index":0,"content_index":0,"delta":"..."}
|
| 400 |
+
|
| 401 |
+
event: response.function_call_arguments.delta
|
| 402 |
+
data: {"type":"response.function_call_arguments.delta","response_id":"resp_xxx","call_id":"call_xxx","delta":"..."}
|
| 403 |
+
|
| 404 |
+
event: response.function_call_arguments.done
|
| 405 |
+
data: {"type":"response.function_call_arguments.done","response_id":"resp_xxx","call_id":"call_xxx","name":"tool","arguments":"{...}"}
|
| 406 |
+
|
| 407 |
+
event: response.content_part.done
|
| 408 |
+
data: {"type":"response.content_part.done","response_id":"resp_xxx",...}
|
| 409 |
+
|
| 410 |
+
event: response.output_item.done
|
| 411 |
+
data: {"type":"response.output_item.done","response_id":"resp_xxx","item":{"type":"message|function_call",...},...}
|
| 412 |
+
|
| 413 |
+
event: response.completed
|
| 414 |
+
data: {"type":"response.completed","response":{...}}
|
| 415 |
+
|
| 416 |
+
data: [DONE]
|
| 417 |
+
```
|
| 418 |
+
|
| 419 |
+
If `tool_choice=required` is violated in stream mode, DS2API emits `response.failed` then `[DONE]` (no `response.completed`).
|
| 420 |
+
|
| 421 |
+
> Current behavior: the parser tries to extract structured tool calls and does not enforce a hard allow-list reject; your tool executor should still validate against a whitelist before executing.
|
| 422 |
+
|
| 423 |
+
### `GET /v1/responses/{response_id}`
|
| 424 |
+
|
| 425 |
+
Business auth required. Fetches cached responses created by `POST /v1/responses` (caller-scoped; only the same key/token can read).
|
| 426 |
+
|
| 427 |
+
> Backed by in-memory TTL store. Default TTL is `900s` (configurable via `responses.store_ttl_seconds`).
|
| 428 |
+
|
| 429 |
+
### `POST /v1/embeddings`
|
| 430 |
+
|
| 431 |
+
Business auth required. Returns OpenAI-compatible embeddings shape.
|
| 432 |
+
|
| 433 |
+
| Field | Type | Required | Notes |
|
| 434 |
+
| --- | --- | --- | --- |
|
| 435 |
+
| `model` | string | ✅ | Supports native models + alias mapping |
|
| 436 |
+
| `input` | string/array | ✅ | Supports string, string array, token array |
|
| 437 |
+
|
| 438 |
+
> Requires `embeddings.provider`. Current supported values: `mock` / `deterministic` / `builtin` (all three use the same local deterministic implementation). If missing/unsupported, returns standard error shape with HTTP 501.
|
| 439 |
+
|
| 440 |
+
### `POST /v1/files`
|
| 441 |
+
|
| 442 |
+
Business auth required. OpenAI Files-compatible upload endpoint; currently only `multipart/form-data` is supported.
|
| 443 |
+
|
| 444 |
+
| Field | Type | Required | Notes |
|
| 445 |
+
| --- | --- | --- | --- |
|
| 446 |
+
| `file` | file | ✅ | Binary payload |
|
| 447 |
+
| `purpose` | string | ❌ | Forwarded purpose field |
|
| 448 |
+
|
| 449 |
+
Constraints and behavior:
|
| 450 |
+
|
| 451 |
+
- `Content-Type` must be `multipart/form-data` (otherwise `400`).
|
| 452 |
+
- Total request size limit is **100 MiB** (over-limit returns `413`).
|
| 453 |
+
- Success returns an OpenAI `file` object (`id/object/bytes/filename/purpose/status`, etc.) and includes `account_id` for source-account tracing.
|
| 454 |
+
|
| 455 |
+
### `GET /v1/files/{file_id}`
|
| 456 |
+
|
| 457 |
+
Business auth required. Retrieves the current DeepSeek upload status for a file and returns an OpenAI `file` object. Returns `404` when no matching file is found.
|
| 458 |
+
|
| 459 |
+
---
|
| 460 |
+
|
| 461 |
+
## Claude-Compatible API
|
| 462 |
+
|
| 463 |
+
Besides `/anthropic/v1/*`, DS2API also supports shortcut paths: `/v1/messages`, `/messages`, `/v1/messages/count_tokens`, `/messages/count_tokens`.
|
| 464 |
+
Implementation-wise this path is unified on the OpenAI Chat Completions parse-and-translate pipeline to avoid maintaining divergent parsing chains.
|
| 465 |
+
|
| 466 |
+
### `GET /anthropic/v1/models`
|
| 467 |
+
|
| 468 |
+
No auth required.
|
| 469 |
+
|
| 470 |
+
**Response**:
|
| 471 |
+
|
| 472 |
+
```json
|
| 473 |
+
{
|
| 474 |
+
"object": "list",
|
| 475 |
+
"data": [
|
| 476 |
+
{"id": "claude-sonnet-4-6", "object": "model", "created": 1715635200, "owned_by": "anthropic"},
|
| 477 |
+
{"id": "claude-haiku-4-5", "object": "model", "created": 1715635200, "owned_by": "anthropic"},
|
| 478 |
+
{"id": "claude-opus-4-6", "object": "model", "created": 1715635200, "owned_by": "anthropic"}
|
| 479 |
+
],
|
| 480 |
+
"first_id": "claude-opus-4-6",
|
| 481 |
+
"last_id": "claude-3-haiku-20240307",
|
| 482 |
+
"has_more": false
|
| 483 |
+
}
|
| 484 |
+
```
|
| 485 |
+
|
| 486 |
+
> Note: the example is partial; besides the current primary aliases, the real response also includes Claude 4.x snapshots plus historical 3.x IDs and common aliases.
|
| 487 |
+
|
| 488 |
+
### `POST /anthropic/v1/messages`
|
| 489 |
+
|
| 490 |
+
**Headers**:
|
| 491 |
+
|
| 492 |
+
```http
|
| 493 |
+
x-api-key: your-api-key
|
| 494 |
+
Content-Type: application/json
|
| 495 |
+
anthropic-version: 2023-06-01
|
| 496 |
+
```
|
| 497 |
+
|
| 498 |
+
> `anthropic-version` is optional; DS2API auto-fills `2023-06-01` when absent.
|
| 499 |
+
|
| 500 |
+
**Request body**:
|
| 501 |
+
|
| 502 |
+
| Field | Type | Required | Notes |
|
| 503 |
+
| --- | --- | --- | --- |
|
| 504 |
+
| `model` | string | ✅ | For example `claude-sonnet-4-6` / `claude-opus-4-6` / `claude-haiku-4-5` (compatible with `claude-3-5-haiku-latest`), plus historical Claude model IDs |
|
| 505 |
+
| `messages` | array | ✅ | Claude-style messages |
|
| 506 |
+
| `max_tokens` | number | ❌ | Auto-filled to `8192` when omitted; not strictly enforced by upstream bridge |
|
| 507 |
+
| `stream` | boolean | ❌ | Default `false` |
|
| 508 |
+
| `system` | string | ❌ | Optional system prompt |
|
| 509 |
+
| `tools` | array | ❌ | Claude tool schema |
|
| 510 |
+
| `thinking` | object | ❌ | Anthropic thinking config; translated into downstream reasoning control, and ignored by `-nothinking` models |
|
| 511 |
+
| `temperature` | number | ❌ | Passed through to the downstream bridge; if `temperature` and `top_p` are both present, `temperature` wins |
|
| 512 |
+
| `top_p` | number | ❌ | Passed through when `temperature` is absent |
|
| 513 |
+
| `stop_sequences` | array | ❌ | Passed through as downstream stop sequences |
|
| 514 |
+
| `tool_choice` | string/object | ❌ | Supports `auto` / `none` / `required` / `{"type":"function","name":"..."}` and is translated to downstream tool choice |
|
| 515 |
+
|
| 516 |
+
> Note: `thinking`, `temperature`, `top_p`, `stop_sequences`, and `tool_choice` are translated through the compatibility bridge. Final behavior still depends on the selected model and upstream support. When both `temperature` and `top_p` are present, `temperature` takes precedence.
|
| 517 |
+
|
| 518 |
+
#### Non-Stream Response
|
| 519 |
+
|
| 520 |
+
```json
|
| 521 |
+
{
|
| 522 |
+
"id": "msg_1738400000000000000",
|
| 523 |
+
"type": "message",
|
| 524 |
+
"role": "assistant",
|
| 525 |
+
"model": "claude-sonnet-4-6",
|
| 526 |
+
"content": [
|
| 527 |
+
{"type": "text", "text": "response"}
|
| 528 |
+
],
|
| 529 |
+
"stop_reason": "end_turn",
|
| 530 |
+
"stop_sequence": null,
|
| 531 |
+
"usage": {
|
| 532 |
+
"input_tokens": 12,
|
| 533 |
+
"output_tokens": 34
|
| 534 |
+
}
|
| 535 |
+
}
|
| 536 |
+
```
|
| 537 |
+
|
| 538 |
+
If tool use is detected, `stop_reason` becomes `tool_use` and `content` contains `tool_use` blocks.
|
| 539 |
+
|
| 540 |
+
#### Streaming (`stream=true`)
|
| 541 |
+
|
| 542 |
+
SSE uses paired `event:` + `data:` lines. Event type is also in JSON `type`.
|
| 543 |
+
|
| 544 |
+
```text
|
| 545 |
+
event: message_start
|
| 546 |
+
data: {"type":"message_start","message":{...}}
|
| 547 |
+
|
| 548 |
+
event: content_block_start
|
| 549 |
+
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}
|
| 550 |
+
|
| 551 |
+
event: content_block_delta
|
| 552 |
+
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hello"}}
|
| 553 |
+
|
| 554 |
+
event: ping
|
| 555 |
+
data: {"type":"ping"}
|
| 556 |
+
|
| 557 |
+
event: content_block_stop
|
| 558 |
+
data: {"type":"content_block_stop","index":0}
|
| 559 |
+
|
| 560 |
+
event: message_delta
|
| 561 |
+
data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":12}}
|
| 562 |
+
|
| 563 |
+
event: message_stop
|
| 564 |
+
data: {"type":"message_stop"}
|
| 565 |
+
```
|
| 566 |
+
|
| 567 |
+
**Notes**:
|
| 568 |
+
|
| 569 |
+
- Models that support thinking emit `thinking` blocks / `thinking_delta` by default; explicit thinking disablement or `-nothinking` models suppress them
|
| 570 |
+
- `signature_delta` is not emitted (DeepSeek does not provide verifiable thinking signatures)
|
| 571 |
+
- In `tools` mode, the stream avoids leaking raw tool JSON and does not force `input_json_delta`
|
| 572 |
+
|
| 573 |
+
### `POST /anthropic/v1/messages/count_tokens`
|
| 574 |
+
|
| 575 |
+
**Request**:
|
| 576 |
+
|
| 577 |
+
```json
|
| 578 |
+
{
|
| 579 |
+
"model": "claude-sonnet-4-6",
|
| 580 |
+
"messages": [
|
| 581 |
+
{"role": "user", "content": "Hello"}
|
| 582 |
+
]
|
| 583 |
+
}
|
| 584 |
+
```
|
| 585 |
+
|
| 586 |
+
**Response**:
|
| 587 |
+
|
| 588 |
+
```json
|
| 589 |
+
{
|
| 590 |
+
"input_tokens": 5
|
| 591 |
+
}
|
| 592 |
+
```
|
| 593 |
+
|
| 594 |
+
---
|
| 595 |
+
|
| 596 |
+
## Gemini-Compatible API
|
| 597 |
+
|
| 598 |
+
Supported paths:
|
| 599 |
+
|
| 600 |
+
- `/v1beta/models/{model}:generateContent`
|
| 601 |
+
- `/v1beta/models/{model}:streamGenerateContent`
|
| 602 |
+
- `/v1/models/{model}:generateContent` (compat path)
|
| 603 |
+
- `/v1/models/{model}:streamGenerateContent` (compat path)
|
| 604 |
+
|
| 605 |
+
Authentication is the same as other business routes (`Authorization: Bearer <token>` or `x-api-key`).
|
| 606 |
+
Implementation-wise this path is unified on the OpenAI Chat Completions parse-and-translate pipeline to avoid maintaining divergent parsing chains.
|
| 607 |
+
|
| 608 |
+
### `POST /v1beta/models/{model}:generateContent`
|
| 609 |
+
|
| 610 |
+
Request body accepts Gemini-style `contents` / `tools`. Model names can use aliases and are mapped to DeepSeek models.
|
| 611 |
+
|
| 612 |
+
Response uses Gemini-compatible fields, including:
|
| 613 |
+
|
| 614 |
+
- `candidates[].content.parts[].text`
|
| 615 |
+
- `candidates[].content.parts[].thought=true` for thinking output
|
| 616 |
+
- `candidates[].content.parts[].functionCall` (when tool call is produced)
|
| 617 |
+
- `usageMetadata` (`promptTokenCount` / `candidatesTokenCount` / `totalTokenCount`)
|
| 618 |
+
|
| 619 |
+
### `POST /v1beta/models/{model}:streamGenerateContent`
|
| 620 |
+
|
| 621 |
+
Returns SSE (`text/event-stream`), each chunk as `data: <json>`:
|
| 622 |
+
|
| 623 |
+
- regular text: incremental text chunks
|
| 624 |
+
- thinking: incremental chunks with `parts[].thought=true`
|
| 625 |
+
- `tools` mode: buffered and emitted as `functionCall` at finalize phase
|
| 626 |
+
- final chunk: includes `finishReason: "STOP"` and `usageMetadata`
|
| 627 |
+
- Token counting prefers pass-through from upstream DeepSeek SSE (`accumulated_token_usage` / `token_usage`), and only falls back to local estimation when upstream usage is absent
|
| 628 |
+
|
| 629 |
+
---
|
| 630 |
+
|
| 631 |
+
## Ollama API
|
| 632 |
+
|
| 633 |
+
- `POST /api/show` request body: `{"model":"<model-id>"}`.
|
| 634 |
+
- Response uses lowercase `id` (not `ID`) and includes `capabilities` for Ollama-style clients and strict schemas.
|
| 635 |
+
|
| 636 |
+
Example response:
|
| 637 |
+
|
| 638 |
+
```json
|
| 639 |
+
{
|
| 640 |
+
"id": "deepseek-v4-flash",
|
| 641 |
+
"capabilities": ["tools", "thinking"]
|
| 642 |
+
}
|
| 643 |
+
```
|
| 644 |
+
|
| 645 |
+
## Admin API
|
| 646 |
+
|
| 647 |
+
### `POST /admin/login`
|
| 648 |
+
|
| 649 |
+
Public endpoint.
|
| 650 |
+
|
| 651 |
+
**Request**:
|
| 652 |
+
|
| 653 |
+
```json
|
| 654 |
+
{
|
| 655 |
+
"admin_key": "admin",
|
| 656 |
+
"expire_hours": 24
|
| 657 |
+
}
|
| 658 |
+
```
|
| 659 |
+
|
| 660 |
+
`expire_hours` is optional, default `24`.
|
| 661 |
+
|
| 662 |
+
**Response**:
|
| 663 |
+
|
| 664 |
+
```json
|
| 665 |
+
{
|
| 666 |
+
"success": true,
|
| 667 |
+
"token": "<jwt>",
|
| 668 |
+
"expires_in": 86400
|
| 669 |
+
}
|
| 670 |
+
```
|
| 671 |
+
|
| 672 |
+
### `GET /admin/verify`
|
| 673 |
+
|
| 674 |
+
Requires JWT: `Authorization: Bearer <jwt>`
|
| 675 |
+
|
| 676 |
+
**Response**:
|
| 677 |
+
|
| 678 |
+
```json
|
| 679 |
+
{
|
| 680 |
+
"valid": true,
|
| 681 |
+
"expires_at": 1738400000,
|
| 682 |
+
"remaining_seconds": 72000
|
| 683 |
+
}
|
| 684 |
+
```
|
| 685 |
+
|
| 686 |
+
### `GET /admin/vercel/config`
|
| 687 |
+
|
| 688 |
+
Returns Vercel preconfiguration status. Environment variables are preferred, then the saved `vercel` config block is used as a fallback.
|
| 689 |
+
|
| 690 |
+
```json
|
| 691 |
+
{
|
| 692 |
+
"has_token": true,
|
| 693 |
+
"token_preview": "vc****en",
|
| 694 |
+
"token_source": "config",
|
| 695 |
+
"project_id": "prj_xxx",
|
| 696 |
+
"team_id": null
|
| 697 |
+
}
|
| 698 |
+
```
|
| 699 |
+
|
| 700 |
+
### `GET /admin/config`
|
| 701 |
+
|
| 702 |
+
Returns sanitized config, including both `keys` and `api_keys`.
|
| 703 |
+
|
| 704 |
+
```json
|
| 705 |
+
{
|
| 706 |
+
"keys": ["k1", "k2"],
|
| 707 |
+
"api_keys": [
|
| 708 |
+
{"key": "k1", "name": "Primary", "remark": "Production"},
|
| 709 |
+
{"key": "k2", "name": "Backup", "remark": "Load test"}
|
| 710 |
+
],
|
| 711 |
+
"env_backed": false,
|
| 712 |
+
"env_source_present": true,
|
| 713 |
+
"env_writeback_enabled": true,
|
| 714 |
+
"config_path": "/data/config.json",
|
| 715 |
+
"vercel": {
|
| 716 |
+
"has_token": true,
|
| 717 |
+
"token_preview": "vc****en",
|
| 718 |
+
"project_id": "prj_xxx",
|
| 719 |
+
"team_id": ""
|
| 720 |
+
},
|
| 721 |
+
"accounts": [
|
| 722 |
+
{
|
| 723 |
+
"identifier": "user@example.com",
|
| 724 |
+
"email": "user@example.com",
|
| 725 |
+
"mobile": "",
|
| 726 |
+
"has_password": true,
|
| 727 |
+
"has_token": true,
|
| 728 |
+
"token_preview": "abcde..."
|
| 729 |
+
}
|
| 730 |
+
],
|
| 731 |
+
"model_aliases": {
|
| 732 |
+
"claude-sonnet-4-6": "deepseek-v4-flash",
|
| 733 |
+
"claude-opus-4-6": "deepseek-v4-pro"
|
| 734 |
+
}
|
| 735 |
+
}
|
| 736 |
+
```
|
| 737 |
+
|
| 738 |
+
### `POST /admin/config`
|
| 739 |
+
|
| 740 |
+
Only updates `keys`, `api_keys`, `accounts`, and `model_aliases`.
|
| 741 |
+
If both `api_keys` and `keys` are sent, the structured `api_keys` entries win so `name` / `remark` metadata is preserved; `keys` remains a legacy fallback.
|
| 742 |
+
|
| 743 |
+
**Request**:
|
| 744 |
+
|
| 745 |
+
```json
|
| 746 |
+
{
|
| 747 |
+
"keys": ["k1", "k2"],
|
| 748 |
+
"api_keys": [
|
| 749 |
+
{"key": "k1", "name": "Primary", "remark": "Production"},
|
| 750 |
+
{"key": "k2", "name": "Backup", "remark": "Load test"}
|
| 751 |
+
],
|
| 752 |
+
"accounts": [
|
| 753 |
+
{"email": "user@example.com", "password": "pwd", "token": ""}
|
| 754 |
+
],
|
| 755 |
+
"model_aliases": {
|
| 756 |
+
"claude-sonnet-4-6": "deepseek-v4-flash",
|
| 757 |
+
"claude-opus-4-6": "deepseek-v4-pro"
|
| 758 |
+
}
|
| 759 |
+
}
|
| 760 |
+
```
|
| 761 |
+
|
| 762 |
+
### `GET /admin/settings`
|
| 763 |
+
|
| 764 |
+
Reads runtime settings and status, including:
|
| 765 |
+
|
| 766 |
+
- `success`
|
| 767 |
+
- `admin` (`has_password_hash`, `jwt_expire_hours`, `jwt_valid_after_unix`, `default_password_warning`)
|
| 768 |
+
- `runtime` (`account_max_inflight`, `account_max_queue`, `global_max_inflight`, `token_refresh_interval_hours`)
|
| 769 |
+
- `config_snapshot`: raw config values (`admin` / `runtime` / `responses` / `embeddings` / `auto_delete` / `current_input_file` / `thinking_injection` / `model_aliases`) before env overrides
|
| 770 |
+
- `responses` / `embeddings`
|
| 771 |
+
- `auto_delete` (`mode`: `none` / `single` / `all`; legacy `sessions=true` is still treated as `all`)
|
| 772 |
+
- `current_input_file` (`enabled` defaults to `true`, plus `min_chars`)
|
| 773 |
+
- `thinking_injection` (`enabled` defaults to `true`, `prompt`, and `default_prompt`)
|
| 774 |
+
- `model_aliases`
|
| 775 |
+
- `env_backed`, `needs_vercel_sync`
|
| 776 |
+
- `toolcall` policy is fixed to `feature_match + high` and is no longer returned or editable via settings
|
| 777 |
+
|
| 778 |
+
### `PUT /admin/settings`
|
| 779 |
+
|
| 780 |
+
Hot-updates runtime settings. Supported fields:
|
| 781 |
+
|
| 782 |
+
- `admin.jwt_expire_hours`
|
| 783 |
+
- `runtime.account_max_inflight` / `runtime.account_max_queue` / `runtime.global_max_inflight` / `runtime.token_refresh_interval_hours`
|
| 784 |
+
- `responses.store_ttl_seconds`
|
| 785 |
+
- `embeddings.provider`
|
| 786 |
+
- `auto_delete.mode`
|
| 787 |
+
- `current_input_file.enabled` / `current_input_file.min_chars`
|
| 788 |
+
- `thinking_injection.enabled` / `thinking_injection.prompt`
|
| 789 |
+
- `model_aliases`
|
| 790 |
+
- `toolcall` policy is fixed and is no longer writable through settings
|
| 791 |
+
|
| 792 |
+
### `POST /admin/settings/password`
|
| 793 |
+
|
| 794 |
+
Updates admin password and invalidates existing JWTs.
|
| 795 |
+
|
| 796 |
+
Request example:
|
| 797 |
+
|
| 798 |
+
```json
|
| 799 |
+
{"new_password":"your-new-password"}
|
| 800 |
+
```
|
| 801 |
+
|
| 802 |
+
It also accepts `{"password":"your-new-password"}`.
|
| 803 |
+
|
| 804 |
+
### `POST /admin/config/import`
|
| 805 |
+
|
| 806 |
+
Imports full config with:
|
| 807 |
+
|
| 808 |
+
- `mode=merge` (default)
|
| 809 |
+
- `mode=replace`
|
| 810 |
+
|
| 811 |
+
The request can send config directly, or wrapped as `{"config": {...}, "mode":"merge"}`.
|
| 812 |
+
Query params `?mode=merge` / `?mode=replace` are also supported.
|
| 813 |
+
`replace` mode replaces the full config shape while preserving Vercel sync metadata. `merge` mode merges `keys`, `api_keys`, `accounts`, and `model_aliases`, and overwrites non-empty fields under `admin`, `runtime`, `responses`, and `embeddings`. Manage `auto_delete` and `current_input_file` via `/admin/settings` or the config file; legacy `compat` and `toolcall` fields are ignored.
|
| 814 |
+
|
| 815 |
+
> Note: `merge` mode does not update `auto_delete` or `current_input_file`.
|
| 816 |
+
|
| 817 |
+
### `GET /admin/config/export`
|
| 818 |
+
|
| 819 |
+
Exports full config in three forms: `config`, `json`, and `base64`.
|
| 820 |
+
|
| 821 |
+
### `POST /admin/keys`
|
| 822 |
+
|
| 823 |
+
```json
|
| 824 |
+
{"key": "new-api-key", "name": "Primary", "remark": "Production"}
|
| 825 |
+
```
|
| 826 |
+
|
| 827 |
+
**Response**: `{"success": true, "total_keys": 3}`
|
| 828 |
+
|
| 829 |
+
### `PUT /admin/keys/{key}`
|
| 830 |
+
|
| 831 |
+
Updates the `name` / `remark` of the specified API key. The path `key` is read-only and cannot be changed.
|
| 832 |
+
|
| 833 |
+
```json
|
| 834 |
+
{"name": "Backup", "remark": "Load test"}
|
| 835 |
+
```
|
| 836 |
+
|
| 837 |
+
**Response**: `{"success": true, "total_keys": 3}`
|
| 838 |
+
|
| 839 |
+
### `DELETE /admin/keys/{key}`
|
| 840 |
+
|
| 841 |
+
**Response**: `{"success": true, "total_keys": 2}`
|
| 842 |
+
|
| 843 |
+
### `GET /admin/proxies`
|
| 844 |
+
|
| 845 |
+
Lists proxy configs (password is never returned; use `has_password` as a marker).
|
| 846 |
+
|
| 847 |
+
### `POST /admin/proxies`
|
| 848 |
+
|
| 849 |
+
Adds a proxy. Request accepts `id` (optional; auto-generated when omitted), `name`, `type` (`http` / `socks5`), `host`, `port`, `username`, `password`.
|
| 850 |
+
|
| 851 |
+
### `PUT /admin/proxies/{proxyID}`
|
| 852 |
+
|
| 853 |
+
Updates a proxy. If `password` is an empty string, the existing secret is preserved.
|
| 854 |
+
|
| 855 |
+
### `DELETE /admin/proxies/{proxyID}`
|
| 856 |
+
|
| 857 |
+
Deletes a proxy and automatically clears `proxy_id` on all accounts that reference it.
|
| 858 |
+
|
| 859 |
+
### `POST /admin/proxies/test`
|
| 860 |
+
|
| 861 |
+
Tests proxy connectivity: provide `proxy_id` to test a saved proxy; omit it to run a one-off test using proxy fields in the request body.
|
| 862 |
+
|
| 863 |
+
### `GET /admin/accounts`
|
| 864 |
+
|
| 865 |
+
**Query params**:
|
| 866 |
+
|
| 867 |
+
| Param | Default | Range |
|
| 868 |
+
| --- | --- | --- |
|
| 869 |
+
| `page` | `1` | ≥ 1 |
|
| 870 |
+
| `page_size` | `10` | 1–5000 |
|
| 871 |
+
| `q` | empty | Filter by identifier / email / mobile |
|
| 872 |
+
|
| 873 |
+
**Response**:
|
| 874 |
+
|
| 875 |
+
```json
|
| 876 |
+
{
|
| 877 |
+
"items": [
|
| 878 |
+
{
|
| 879 |
+
"identifier": "user@example.com",
|
| 880 |
+
"email": "user@example.com",
|
| 881 |
+
"mobile": "",
|
| 882 |
+
"has_password": true,
|
| 883 |
+
"has_token": true,
|
| 884 |
+
"token_preview": "abc...",
|
| 885 |
+
"test_status": "ok"
|
| 886 |
+
}
|
| 887 |
+
],
|
| 888 |
+
"total": 25,
|
| 889 |
+
"page": 1,
|
| 890 |
+
"page_size": 10,
|
| 891 |
+
"total_pages": 3
|
| 892 |
+
}
|
| 893 |
+
```
|
| 894 |
+
|
| 895 |
+
Returned items also include `test_status`, usually `ok` or `failed`.
|
| 896 |
+
|
| 897 |
+
### `POST /admin/accounts`
|
| 898 |
+
|
| 899 |
+
```json
|
| 900 |
+
{"email": "user@example.com", "password": "pwd"}
|
| 901 |
+
```
|
| 902 |
+
|
| 903 |
+
**Response**: `{"success": true, "total_accounts": 6}`
|
| 904 |
+
|
| 905 |
+
### `PUT /admin/accounts/{identifier}`
|
| 906 |
+
|
| 907 |
+
Updates the `name` / `remark` of the specified account. The path `identifier` can be email or mobile and cannot be changed.
|
| 908 |
+
|
| 909 |
+
```json
|
| 910 |
+
{"name": "Primary account", "remark": "Shared with the team"}
|
| 911 |
+
```
|
| 912 |
+
|
| 913 |
+
**Response**: `{"success": true, "total_accounts": 6}`
|
| 914 |
+
|
| 915 |
+
### `DELETE /admin/accounts/{identifier}`
|
| 916 |
+
|
| 917 |
+
`identifier` can be email, mobile, or the synthetic id for token-only accounts (`token:<hash>`).
|
| 918 |
+
|
| 919 |
+
**Response**: `{"success": true, "total_accounts": 5}`
|
| 920 |
+
|
| 921 |
+
### `PUT /admin/accounts/{identifier}/proxy`
|
| 922 |
+
|
| 923 |
+
Updates proxy binding for a specific account.
|
| 924 |
+
|
| 925 |
+
- Request body: `{"proxy_id":"..."}`.
|
| 926 |
+
- Use empty `proxy_id` to unbind proxy.
|
| 927 |
+
- `identifier` supports email / mobile / token-only synthetic id.
|
| 928 |
+
|
| 929 |
+
### `GET /admin/queue/status`
|
| 930 |
+
|
| 931 |
+
```json
|
| 932 |
+
{
|
| 933 |
+
"available": 3,
|
| 934 |
+
"in_use": 1,
|
| 935 |
+
"total": 4,
|
| 936 |
+
"available_accounts": ["a@example.com"],
|
| 937 |
+
"in_use_accounts": ["b@example.com"],
|
| 938 |
+
"max_inflight_per_account": 2,
|
| 939 |
+
"global_max_inflight": 8,
|
| 940 |
+
"recommended_concurrency": 8,
|
| 941 |
+
"waiting": 0,
|
| 942 |
+
"max_queue_size": 8
|
| 943 |
+
}
|
| 944 |
+
```
|
| 945 |
+
|
| 946 |
+
| Field | Description |
|
| 947 |
+
| --- | --- |
|
| 948 |
+
| `available` | Accounts that still have spare inflight capacity |
|
| 949 |
+
| `in_use` | Number of occupied in-flight slots |
|
| 950 |
+
| `total` | Total accounts |
|
| 951 |
+
| `available_accounts` | List of account IDs with remaining inflight capacity |
|
| 952 |
+
| `in_use_accounts` | List of account IDs currently in use |
|
| 953 |
+
| `max_inflight_per_account` | Per-account inflight limit |
|
| 954 |
+
| `global_max_inflight` | Global inflight limit |
|
| 955 |
+
| `recommended_concurrency` | Suggested concurrency (`total × max_inflight_per_account`) |
|
| 956 |
+
| `waiting` | Number of queued requests currently waiting |
|
| 957 |
+
| `max_queue_size` | Waiting queue limit |
|
| 958 |
+
|
| 959 |
+
### `POST /admin/accounts/test`
|
| 960 |
+
|
| 961 |
+
| Field | Required | Notes |
|
| 962 |
+
| --- | --- | --- |
|
| 963 |
+
| `identifier` | ✅ | email / mobile / token-only synthetic id |
|
| 964 |
+
| `model` | ❌ | default `deepseek-v4-flash` |
|
| 965 |
+
| `message` | ❌ | if empty, only session creation is tested |
|
| 966 |
+
|
| 967 |
+
**Response**:
|
| 968 |
+
|
| 969 |
+
```json
|
| 970 |
+
{
|
| 971 |
+
"account": "user@example.com",
|
| 972 |
+
"success": true,
|
| 973 |
+
"response_time": 1240,
|
| 974 |
+
"message": "API test successful (session creation only)",
|
| 975 |
+
"model": "deepseek-v4-flash",
|
| 976 |
+
"session_count": 0,
|
| 977 |
+
"config_writable": true,
|
| 978 |
+
"config_warning": ""
|
| 979 |
+
}
|
| 980 |
+
```
|
| 981 |
+
|
| 982 |
+
If a `message` is provided, `thinking` may also be included when the upstream response carries reasoning text.
|
| 983 |
+
|
| 984 |
+
When the configured file path is not writable (for example, read-only `/app/config.json` inside some containers), login/session testing still proceeds; `config_warning` is returned to indicate token persistence failed and the token is memory-only until restart.
|
| 985 |
+
|
| 986 |
+
### `POST /admin/accounts/test-all`
|
| 987 |
+
|
| 988 |
+
Optional request field: `model`.
|
| 989 |
+
|
| 990 |
+
```json
|
| 991 |
+
{
|
| 992 |
+
"total": 5,
|
| 993 |
+
"success": 4,
|
| 994 |
+
"failed": 1,
|
| 995 |
+
"results": [...]
|
| 996 |
+
}
|
| 997 |
+
```
|
| 998 |
+
|
| 999 |
+
The internal concurrency limit is currently fixed at 5.
|
| 1000 |
+
|
| 1001 |
+
### `POST /admin/accounts/sessions/delete-all`
|
| 1002 |
+
|
| 1003 |
+
Deletes all DeepSeek sessions for a specific account. Request example:
|
| 1004 |
+
|
| 1005 |
+
```json
|
| 1006 |
+
{"identifier":"user@example.com"}
|
| 1007 |
+
```
|
| 1008 |
+
|
| 1009 |
+
Response:
|
| 1010 |
+
|
| 1011 |
+
```json
|
| 1012 |
+
{"success": true, "message": "删除成功"}
|
| 1013 |
+
```
|
| 1014 |
+
|
| 1015 |
+
If the account is missing or deletion fails, `success` becomes `false` and `message` contains the error.
|
| 1016 |
+
The current handler returns the Chinese literal `删除成功` on success.
|
| 1017 |
+
|
| 1018 |
+
### `POST /admin/import`
|
| 1019 |
+
|
| 1020 |
+
Batch import keys and accounts.
|
| 1021 |
+
|
| 1022 |
+
**Request**:
|
| 1023 |
+
|
| 1024 |
+
```json
|
| 1025 |
+
{
|
| 1026 |
+
"keys": ["k1", "k2"],
|
| 1027 |
+
"accounts": [
|
| 1028 |
+
{"email": "user@example.com", "password": "pwd", "token": ""}
|
| 1029 |
+
]
|
| 1030 |
+
}
|
| 1031 |
+
```
|
| 1032 |
+
|
| 1033 |
+
**Response**:
|
| 1034 |
+
|
| 1035 |
+
```json
|
| 1036 |
+
{
|
| 1037 |
+
"success": true,
|
| 1038 |
+
"imported_keys": 2,
|
| 1039 |
+
"imported_accounts": 1
|
| 1040 |
+
}
|
| 1041 |
+
```
|
| 1042 |
+
|
| 1043 |
+
### `POST /admin/test`
|
| 1044 |
+
|
| 1045 |
+
Test API availability through the service itself.
|
| 1046 |
+
|
| 1047 |
+
| Field | Required | Default |
|
| 1048 |
+
| --- | --- | --- |
|
| 1049 |
+
| `model` | ❌ | `deepseek-v4-flash` |
|
| 1050 |
+
| `message` | ❌ | `你好` |
|
| 1051 |
+
| `api_key` | ❌ | First key in config |
|
| 1052 |
+
|
| 1053 |
+
**Response**:
|
| 1054 |
+
|
| 1055 |
+
```json
|
| 1056 |
+
{
|
| 1057 |
+
"success": true,
|
| 1058 |
+
"status_code": 200,
|
| 1059 |
+
"response": {"id": "..."}
|
| 1060 |
+
}
|
| 1061 |
+
```
|
| 1062 |
+
|
| 1063 |
+
### `POST /admin/dev/raw-samples/capture`
|
| 1064 |
+
|
| 1065 |
+
Internally issues one `/v1/chat/completions` request through the service, then persists the request metadata and raw upstream SSE into `tests/raw_stream_samples/<sample-id>/`.
|
| 1066 |
+
|
| 1067 |
+
Common request fields:
|
| 1068 |
+
|
| 1069 |
+
| Field | Required | Default | Notes |
|
| 1070 |
+
| --- | --- | --- | --- |
|
| 1071 |
+
| `message` | No | `你好` | Convenience single-turn user message |
|
| 1072 |
+
| `messages` | No | Auto-derived from `message` | OpenAI-style message array |
|
| 1073 |
+
| `model` | No | `deepseek-v4-flash` | Target model |
|
| 1074 |
+
| `stream` | No | `true` | Recommended to keep streaming enabled so raw SSE is recorded |
|
| 1075 |
+
| `api_key` | No | First configured key | Business API key to use |
|
| 1076 |
+
| `sample_id` | No | Auto-generated | Sample directory name |
|
| 1077 |
+
|
| 1078 |
+
On success, the response headers include:
|
| 1079 |
+
|
| 1080 |
+
- `X-Ds2-Sample-Id`
|
| 1081 |
+
- `X-Ds2-Sample-Dir`
|
| 1082 |
+
- `X-Ds2-Sample-Meta`
|
| 1083 |
+
- `X-Ds2-Sample-Upstream`
|
| 1084 |
+
|
| 1085 |
+
If the request itself succeeds but the process did not record a new upstream capture, the endpoint returns:
|
| 1086 |
+
|
| 1087 |
+
```json
|
| 1088 |
+
{"detail":"no upstream capture was recorded"}
|
| 1089 |
+
```
|
| 1090 |
+
|
| 1091 |
+
### `GET /admin/dev/raw-samples/query`
|
| 1092 |
+
|
| 1093 |
+
Searches the current process's in-memory capture entries and groups `completion + continue` rounds by `chat_session_id`.
|
| 1094 |
+
|
| 1095 |
+
**Query parameters**:
|
| 1096 |
+
|
| 1097 |
+
| Param | Default | Notes |
|
| 1098 |
+
| --- | --- | --- |
|
| 1099 |
+
| `q` | empty | Fuzzy match against request/response text |
|
| 1100 |
+
| `limit` | `20` | Max number of chains returned |
|
| 1101 |
+
|
| 1102 |
+
**Response fields** include:
|
| 1103 |
+
|
| 1104 |
+
- `items[].chain_key`
|
| 1105 |
+
- `items[].capture_ids`
|
| 1106 |
+
- `items[].round_count`
|
| 1107 |
+
- `items[].initial_label`
|
| 1108 |
+
- `items[].request_preview`
|
| 1109 |
+
- `items[].response_preview`
|
| 1110 |
+
|
| 1111 |
+
### `POST /admin/dev/raw-samples/save`
|
| 1112 |
+
|
| 1113 |
+
Persists one selected in-memory capture chain into `tests/raw_stream_samples/<sample-id>/`.
|
| 1114 |
+
|
| 1115 |
+
Any one of these selectors is accepted:
|
| 1116 |
+
|
| 1117 |
+
```json
|
| 1118 |
+
{"chain_key":"session:xxxx","sample_id":"tmp-from-memory"}
|
| 1119 |
+
```
|
| 1120 |
+
|
| 1121 |
+
```json
|
| 1122 |
+
{"capture_id":"cap_xxx","sample_id":"tmp-from-memory"}
|
| 1123 |
+
```
|
| 1124 |
+
|
| 1125 |
+
```json
|
| 1126 |
+
{"query":"Guangzhou weather","sample_id":"tmp-from-memory"}
|
| 1127 |
+
```
|
| 1128 |
+
|
| 1129 |
+
The success payload includes `sample_id`, `dir`, `meta_path`, and `upstream_path`.
|
| 1130 |
+
|
| 1131 |
+
### `POST /admin/vercel/sync`
|
| 1132 |
+
|
| 1133 |
+
| Field | Required | Notes |
|
| 1134 |
+
| --- | --- | --- |
|
| 1135 |
+
| `vercel_token` | ❌ | If empty or `__USE_PRECONFIG__`, read env, then saved config |
|
| 1136 |
+
| `project_id` | ❌ | Fallback: `VERCEL_PROJECT_ID`, then saved config |
|
| 1137 |
+
| `team_id` | ❌ | Fallback: `VERCEL_TEAM_ID`, then saved config |
|
| 1138 |
+
| `auto_validate` | ❌ | Default `true` |
|
| 1139 |
+
| `save_credentials` | ❌ | Default `true`; saves explicitly supplied Vercel credentials for the next sync |
|
| 1140 |
+
| `config_override` | ❌ | Provide a full config object to sync instead of the runtime config |
|
| 1141 |
+
|
| 1142 |
+
**Success response**:
|
| 1143 |
+
|
| 1144 |
+
```json
|
| 1145 |
+
{
|
| 1146 |
+
"success": true,
|
| 1147 |
+
"validated_accounts": 3,
|
| 1148 |
+
"message": "Config synced, redeploying...",
|
| 1149 |
+
"deployment_url": "https://..."
|
| 1150 |
+
}
|
| 1151 |
+
```
|
| 1152 |
+
|
| 1153 |
+
Or manual deploy required:
|
| 1154 |
+
|
| 1155 |
+
```json
|
| 1156 |
+
{
|
| 1157 |
+
"success": true,
|
| 1158 |
+
"validated_accounts": 3,
|
| 1159 |
+
"message": "Config synced to Vercel, please trigger redeploy manually",
|
| 1160 |
+
"manual_deploy_required": true
|
| 1161 |
+
}
|
| 1162 |
+
```
|
| 1163 |
+
|
| 1164 |
+
Failed account checks are returned in `failed_accounts`, and any saved Vercel credentials are returned in `saved_credentials`.
|
| 1165 |
+
|
| 1166 |
+
### `GET /admin/vercel/status`
|
| 1167 |
+
|
| 1168 |
+
```json
|
| 1169 |
+
{
|
| 1170 |
+
"synced": true,
|
| 1171 |
+
"last_sync_time": 1738400000,
|
| 1172 |
+
"has_synced_before": true,
|
| 1173 |
+
"env_backed": false,
|
| 1174 |
+
"config_hash": "....",
|
| 1175 |
+
"last_synced_hash": "....",
|
| 1176 |
+
"draft_hash": "....",
|
| 1177 |
+
"draft_differs": false
|
| 1178 |
+
}
|
| 1179 |
+
```
|
| 1180 |
+
|
| 1181 |
+
`POST /admin/vercel/status` can also accept `config_override` to compare a draft config against the current synced config.
|
| 1182 |
+
|
| 1183 |
+
### `GET /admin/export`
|
| 1184 |
+
|
| 1185 |
+
```json
|
| 1186 |
+
{
|
| 1187 |
+
"json": "{...}",
|
| 1188 |
+
"base64": "ey4uLn0="
|
| 1189 |
+
}
|
| 1190 |
+
```
|
| 1191 |
+
|
| 1192 |
+
This is the same payload as `GET /admin/config/export`, just with a shorter path.
|
| 1193 |
+
|
| 1194 |
+
### `GET /admin/version`
|
| 1195 |
+
|
| 1196 |
+
Checks the current build version and the latest GitHub Release:
|
| 1197 |
+
|
| 1198 |
+
```json
|
| 1199 |
+
{
|
| 1200 |
+
"success": true,
|
| 1201 |
+
"current_version": "3.0.0",
|
| 1202 |
+
"current_tag": "v3.0.0",
|
| 1203 |
+
"source": "file:VERSION",
|
| 1204 |
+
"checked_at": "2026-03-29T00:00:00Z",
|
| 1205 |
+
"latest_tag": "v3.0.0",
|
| 1206 |
+
"latest_version": "3.0.0",
|
| 1207 |
+
"release_url": "https://github.com/CJackHwang/ds2api/releases/tag/v3.0.0",
|
| 1208 |
+
"published_at": "2026-03-28T12:00:00Z",
|
| 1209 |
+
"has_update": false
|
| 1210 |
+
}
|
| 1211 |
+
```
|
| 1212 |
+
|
| 1213 |
+
If GitHub API access fails, the response includes `check_error` while still returning HTTP 200.
|
| 1214 |
+
|
| 1215 |
+
### `GET /admin/dev/captures`
|
| 1216 |
+
|
| 1217 |
+
Reads local packet-capture status and recent entries (Admin auth required):
|
| 1218 |
+
|
| 1219 |
+
- `enabled`
|
| 1220 |
+
- `limit`
|
| 1221 |
+
- `max_body_bytes`
|
| 1222 |
+
- `items`
|
| 1223 |
+
|
| 1224 |
+
### `DELETE /admin/dev/captures`
|
| 1225 |
+
|
| 1226 |
+
Clears packet-capture entries:
|
| 1227 |
+
|
| 1228 |
+
```json
|
| 1229 |
+
{"success":true,"detail":"capture logs cleared"}
|
| 1230 |
+
```
|
| 1231 |
+
|
| 1232 |
+
---
|
| 1233 |
+
|
| 1234 |
+
## Error Payloads
|
| 1235 |
+
|
| 1236 |
+
Compatible routes (`/v1/*`, `/anthropic/*`) use the same error envelope:
|
| 1237 |
+
|
| 1238 |
+
```json
|
| 1239 |
+
{
|
| 1240 |
+
"error": {
|
| 1241 |
+
"message": "...",
|
| 1242 |
+
"type": "invalid_request_error",
|
| 1243 |
+
"code": "invalid_request",
|
| 1244 |
+
"param": null
|
| 1245 |
+
}
|
| 1246 |
+
}
|
| 1247 |
+
```
|
| 1248 |
+
|
| 1249 |
+
Admin routes keep `{"detail":"..."}`.
|
| 1250 |
+
|
| 1251 |
+
Gemini routes use Google-style errors:
|
| 1252 |
+
|
| 1253 |
+
```json
|
| 1254 |
+
{
|
| 1255 |
+
"error": {
|
| 1256 |
+
"code": 400,
|
| 1257 |
+
"message": "invalid json",
|
| 1258 |
+
"status": "INVALID_ARGUMENT"
|
| 1259 |
+
}
|
| 1260 |
+
}
|
| 1261 |
+
```
|
| 1262 |
+
|
| 1263 |
+
Clients should handle HTTP status code plus `error` / `detail` fields.
|
| 1264 |
+
|
| 1265 |
+
**Common status codes**:
|
| 1266 |
+
|
| 1267 |
+
| Code | Meaning |
|
| 1268 |
+
| --- | --- |
|
| 1269 |
+
| `401` | Authentication failed (invalid key/token, or expired admin JWT) |
|
| 1270 |
+
| `429` | Too many requests (exceeded inflight + queue capacity, or upstream thinking-only output with no visible answer; managed-account mode first tries one alternate-account fresh retry; current responses do not include `Retry-After`) |
|
| 1271 |
+
| `503` | Model unavailable or upstream error |
|
| 1272 |
+
|
| 1273 |
+
---
|
| 1274 |
+
|
| 1275 |
+
## cURL Examples
|
| 1276 |
+
|
| 1277 |
+
### OpenAI Non-Stream
|
| 1278 |
+
|
| 1279 |
+
```bash
|
| 1280 |
+
curl http://localhost:5001/v1/chat/completions \
|
| 1281 |
+
-H "Authorization: Bearer your-api-key" \
|
| 1282 |
+
-H "Content-Type: application/json" \
|
| 1283 |
+
-d '{
|
| 1284 |
+
"model": "deepseek-v4-flash",
|
| 1285 |
+
"messages": [{"role": "user", "content": "Hello"}],
|
| 1286 |
+
"stream": false
|
| 1287 |
+
}'
|
| 1288 |
+
```
|
| 1289 |
+
|
| 1290 |
+
### OpenAI Stream
|
| 1291 |
+
|
| 1292 |
+
```bash
|
| 1293 |
+
curl http://localhost:5001/v1/chat/completions \
|
| 1294 |
+
-H "Authorization: Bearer your-api-key" \
|
| 1295 |
+
-H "Content-Type: application/json" \
|
| 1296 |
+
-d '{
|
| 1297 |
+
"model": "deepseek-v4-pro",
|
| 1298 |
+
"messages": [{"role": "user", "content": "Explain quantum entanglement"}],
|
| 1299 |
+
"stream": true
|
| 1300 |
+
}'
|
| 1301 |
+
```
|
| 1302 |
+
|
| 1303 |
+
### OpenAI Responses (Stream)
|
| 1304 |
+
|
| 1305 |
+
```bash
|
| 1306 |
+
curl http://localhost:5001/v1/responses \
|
| 1307 |
+
-H "Authorization: Bearer your-api-key" \
|
| 1308 |
+
-H "Content-Type: application/json" \
|
| 1309 |
+
-d '{
|
| 1310 |
+
"model": "gpt-5-codex",
|
| 1311 |
+
"input": "Write a hello world in golang",
|
| 1312 |
+
"stream": true
|
| 1313 |
+
}'
|
| 1314 |
+
```
|
| 1315 |
+
|
| 1316 |
+
### OpenAI Embeddings
|
| 1317 |
+
|
| 1318 |
+
```bash
|
| 1319 |
+
curl http://localhost:5001/v1/embeddings \
|
| 1320 |
+
-H "Authorization: Bearer your-api-key" \
|
| 1321 |
+
-H "Content-Type: application/json" \
|
| 1322 |
+
-d '{
|
| 1323 |
+
"model": "gpt-4o",
|
| 1324 |
+
"input": ["first text", "second text"]
|
| 1325 |
+
}'
|
| 1326 |
+
```
|
| 1327 |
+
|
| 1328 |
+
### OpenAI with Search
|
| 1329 |
+
|
| 1330 |
+
```bash
|
| 1331 |
+
curl http://localhost:5001/v1/chat/completions \
|
| 1332 |
+
-H "Authorization: Bearer your-api-key" \
|
| 1333 |
+
-H "Content-Type: application/json" \
|
| 1334 |
+
-d '{
|
| 1335 |
+
"model": "deepseek-v4-flash-search",
|
| 1336 |
+
"messages": [{"role": "user", "content": "Latest news today"}],
|
| 1337 |
+
"stream": true
|
| 1338 |
+
}'
|
| 1339 |
+
```
|
| 1340 |
+
|
| 1341 |
+
### OpenAI Tool Calling
|
| 1342 |
+
|
| 1343 |
+
```bash
|
| 1344 |
+
curl http://localhost:5001/v1/chat/completions \
|
| 1345 |
+
-H "Authorization: Bearer your-api-key" \
|
| 1346 |
+
-H "Content-Type: application/json" \
|
| 1347 |
+
-d '{
|
| 1348 |
+
"model": "deepseek-v4-flash",
|
| 1349 |
+
"messages": [{"role": "user", "content": "What is the weather in Beijing?"}],
|
| 1350 |
+
"tools": [
|
| 1351 |
+
{
|
| 1352 |
+
"type": "function",
|
| 1353 |
+
"function": {
|
| 1354 |
+
"name": "get_weather",
|
| 1355 |
+
"description": "Get weather for a city",
|
| 1356 |
+
"parameters": {
|
| 1357 |
+
"type": "object",
|
| 1358 |
+
"properties": {
|
| 1359 |
+
"city": {"type": "string", "description": "City name"}
|
| 1360 |
+
},
|
| 1361 |
+
"required": ["city"]
|
| 1362 |
+
}
|
| 1363 |
+
}
|
| 1364 |
+
}
|
| 1365 |
+
]
|
| 1366 |
+
}'
|
| 1367 |
+
```
|
| 1368 |
+
|
| 1369 |
+
### Gemini Non-Stream
|
| 1370 |
+
|
| 1371 |
+
```bash
|
| 1372 |
+
curl "http://localhost:5001/v1beta/models/gemini-2.5-pro:generateContent" \
|
| 1373 |
+
-H "Authorization: Bearer your-api-key" \
|
| 1374 |
+
-H "Content-Type: application/json" \
|
| 1375 |
+
-d '{
|
| 1376 |
+
"contents": [
|
| 1377 |
+
{
|
| 1378 |
+
"role": "user",
|
| 1379 |
+
"parts": [{"text": "Introduce Go in three sentences"}]
|
| 1380 |
+
}
|
| 1381 |
+
]
|
| 1382 |
+
}'
|
| 1383 |
+
```
|
| 1384 |
+
|
| 1385 |
+
### Gemini Stream
|
| 1386 |
+
|
| 1387 |
+
```bash
|
| 1388 |
+
curl "http://localhost:5001/v1beta/models/gemini-2.5-flash:streamGenerateContent" \
|
| 1389 |
+
-H "Authorization: Bearer your-api-key" \
|
| 1390 |
+
-H "Content-Type: application/json" \
|
| 1391 |
+
-d '{
|
| 1392 |
+
"contents": [
|
| 1393 |
+
{
|
| 1394 |
+
"role": "user",
|
| 1395 |
+
"parts": [{"text": "Write a short summary"}]
|
| 1396 |
+
}
|
| 1397 |
+
]
|
| 1398 |
+
}'
|
| 1399 |
+
```
|
| 1400 |
+
|
| 1401 |
+
### Claude Non-Stream
|
| 1402 |
+
|
| 1403 |
+
```bash
|
| 1404 |
+
curl http://localhost:5001/anthropic/v1/messages \
|
| 1405 |
+
-H "x-api-key: your-api-key" \
|
| 1406 |
+
-H "Content-Type: application/json" \
|
| 1407 |
+
-H "anthropic-version: 2023-06-01" \
|
| 1408 |
+
-d '{
|
| 1409 |
+
"model": "claude-sonnet-4-6",
|
| 1410 |
+
"max_tokens": 1024,
|
| 1411 |
+
"messages": [{"role": "user", "content": "Hello"}]
|
| 1412 |
+
}'
|
| 1413 |
+
```
|
| 1414 |
+
|
| 1415 |
+
### Claude Stream
|
| 1416 |
+
|
| 1417 |
+
```bash
|
| 1418 |
+
curl http://localhost:5001/anthropic/v1/messages \
|
| 1419 |
+
-H "x-api-key: your-api-key" \
|
| 1420 |
+
-H "Content-Type: application/json" \
|
| 1421 |
+
-H "anthropic-version: 2023-06-01" \
|
| 1422 |
+
-d '{
|
| 1423 |
+
"model": "claude-opus-4-6",
|
| 1424 |
+
"max_tokens": 1024,
|
| 1425 |
+
"messages": [{"role": "user", "content": "Explain relativity"}],
|
| 1426 |
+
"stream": true
|
| 1427 |
+
}'
|
| 1428 |
+
```
|
| 1429 |
+
|
| 1430 |
+
### Admin Login
|
| 1431 |
+
|
| 1432 |
+
```bash
|
| 1433 |
+
curl http://localhost:5001/admin/login \
|
| 1434 |
+
-H "Content-Type: application/json" \
|
| 1435 |
+
-d '{"admin_key": "admin"}'
|
| 1436 |
+
```
|
| 1437 |
+
|
| 1438 |
+
### Pin Specific Account
|
| 1439 |
+
|
| 1440 |
+
```bash
|
| 1441 |
+
curl http://localhost:5001/v1/chat/completions \
|
| 1442 |
+
-H "Authorization: Bearer your-api-key" \
|
| 1443 |
+
-H "X-Ds2-Target-Account: user@example.com" \
|
| 1444 |
+
-H "Content-Type: application/json" \
|
| 1445 |
+
-d '{
|
| 1446 |
+
"model": "deepseek-v4-flash",
|
| 1447 |
+
"messages": [{"role": "user", "content": "Hello"}]
|
| 1448 |
+
}'
|
| 1449 |
+
```
|
API.md
ADDED
|
@@ -0,0 +1,1459 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# DS2API 接口文档1
|
| 2 |
+
|
| 3 |
+
语言 / Language: [中文](API.md) | [English](API.en.md)
|
| 4 |
+
|
| 5 |
+
本文档描述当前 Go 代码库的实际 API 行为。
|
| 6 |
+
|
| 7 |
+
文档导航:[总览](README.MD) / [架构说明](docs/ARCHITECTURE.md) / [部署指南](docs/DEPLOY.md) / [测试指南](docs/TESTING.md)
|
| 8 |
+
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
## 目录
|
| 12 |
+
|
| 13 |
+
- [基础信息](#基础信息)
|
| 14 |
+
- [配置最佳实践](#配置最佳实践)
|
| 15 |
+
- [鉴权规则](#鉴权规则)
|
| 16 |
+
- [路由总览](#路由总览)
|
| 17 |
+
- [健康检查](#健康检查)
|
| 18 |
+
- [OpenAI 兼容接口](#openai-兼容接口)
|
| 19 |
+
- [Claude 兼容接口](#claude-兼容接口)
|
| 20 |
+
- [Gemini 兼容接口](#gemini-兼容接口)
|
| 21 |
+
- [Ollama 兼容接口](#ollama-兼容接口)
|
| 22 |
+
- [Admin 接口](#admin-接口)
|
| 23 |
+
- [错误响应格式](#错误响应格式)
|
| 24 |
+
- [cURL 示例](#curl-示例)
|
| 25 |
+
|
| 26 |
+
---
|
| 27 |
+
|
| 28 |
+
## 基础信息
|
| 29 |
+
|
| 30 |
+
| 项目 | 说明 |
|
| 31 |
+
| --- | --- |
|
| 32 |
+
| Base URL | `http://localhost:5001` 或你的部署域名 |
|
| 33 |
+
| 默认 Content-Type | `application/json` |
|
| 34 |
+
| 健康检查 | `GET /healthz`、`GET /readyz` |
|
| 35 |
+
| CORS | 已启用(统一覆盖 `/v1/*`、`/anthropic/*`、`/v1beta/models/*`、`/api/*`、`/admin/*`;浏览器有 `Origin` 时回显该 Origin,否则为 `*`;默认允许 `Content-Type`, `Authorization`, `X-API-Key`, `X-Ds2-Target-Account`, `X-Ds2-Source`, `X-Vercel-Protection-Bypass`, `X-Goog-Api-Key`, `Anthropic-Version`, `Anthropic-Beta`,并会放行预检里声明的第三方请求头,如 `x-stainless-*`;Vercel 上 `/v1/chat/completions` 的 Node Runtime 也对齐相同行为;内部专用头 `X-Ds2-Internal-Token` 仍被拦截) |
|
| 36 |
+
|
| 37 |
+
- 所有 JSON 请求体都必须是合法 UTF-8;非法字节序列会在入站阶段被拒绝为 `400 invalid json`。
|
| 38 |
+
|
| 39 |
+
### 3.0 接口适配层说明
|
| 40 |
+
|
| 41 |
+
- OpenAI / Claude / Gemini 三套协议已统一挂在同一 `chi` 路由树上,由 `internal/server/router.go` 负责装配。
|
| 42 |
+
- 适配器层职责收敛为:**请求归一化 → DeepSeek 调用 → 协议形态渲染**,减少历史版本中“同能力多处实现”的分叉。
|
| 43 |
+
- Tool Calling 的解析策略在 Go 与 Node Runtime 间保持一致:推荐模型输出半角管道符 DSML 外壳 `<|DSML|tool_calls>` → `<|DSML|invoke name="...">` → `<|DSML|parameter name="...">`;兼容层也接受 DSML wrapper 别名 `<dsml|tool_calls>`、`<|tool_calls>`、常见 DSML 分隔符漏写形态(如 `<|DSML tool_calls>`)、`DSML` 与工具标签名黏连的常见 typo(如 `<DSMLtool_calls>`)、控制分隔符漂移(如 `<DSML␂tool_calls>` / 原始 STX `\x02`)、CJK 尖括号、全角感叹号、顿号、PascalCase 本地名、弯引号属性值与属性尾部分隔符漂移(如 `<DSM|parameter name="command"|>...〈/DSM|parameter〉` / `<!DSML!invoke name=“Bash”>` / `<、DSML、tool_calls>` / `<DSmartToolCalls>` / `<DSMLtool_calls※>`)、任意协议前缀壳(如 `<proto💥tool_calls>`),以及旧式 canonical XML `<tool_calls>` → `<invoke name="...">` → `<parameter name="...">`。实现上采用结构扫描:只要固定本地标签名是 `tool_calls` / `invoke` / `parameter`,标签名前或标签名后的非结构性分隔符会在解析入口归一化;CDATA 开头也会容错 `<![CDATA[` / `<、[CDATA[` 这类分隔符漂移;只有 `tool_calls` wrapper 或可修复的缺失 opening wrapper 会进入工具路径,裸 `<invoke>` 不计为已支持语法;流式场景继续执行防泄漏筛分。若参数体本身是合法 JSON 字面量(如 `123`、`true`、`null`、数组或对象),会按结构化值输出,不再一律当作字符串;显式空字符串和纯空白参数会结构化保留为空字符串,是否拒绝缺参由工具执行侧决定;完整但 malformed 的 wrapper 会作为普通文本释放,不会吞掉或伪造成工具调用;若 CDATA 偶发漏闭合,则会在最终 parse / flush 恢复阶段做窄修复,尽量保住已完整包裹的外层工具调用。
|
| 44 |
+
- `Admin API` 将配置与运行时策略分开:`/admin/config*` 管静态配置,`/admin/settings*` 管运行时行为。
|
| 45 |
+
- 当上游返回 thinking-only 响应(模型输出了推理链但无可见文本)时,Go 主路径与 Vercel Node 流式路径都会先自动重试一次:以多轮对话 follow-up 方式追加 prompt 后缀 `"Please provide a non-empty final answer or tool call."` 并设置 `parent_message_id` 在同一 DeepSeek session 内让模型重新输出;同账号重试最大 1 次。若同账号重试后仍即将返回 `429 upstream_empty_output`,托管账号模式会在返回 429 前自动切换到下一个可用账号,新建 session,用原始 payload 再 fresh retry 一次。
|
| 46 |
+
- 引用标记处理边界:流式输出默认隐藏 `[citation:N]` / `[reference:N]` 这类上游内部占位符;非流式输出默认把 DeepSeek 搜索引用标记转换为 Markdown 引用链接。
|
| 47 |
+
|
| 48 |
+
---
|
| 49 |
+
|
| 50 |
+
## 配置最佳实践
|
| 51 |
+
|
| 52 |
+
推荐把 `config.json` 作为唯一配置源:
|
| 53 |
+
|
| 54 |
+
```bash
|
| 55 |
+
cp config.example.json config.json
|
| 56 |
+
# 编辑 config.json(keys/accounts)
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
按部署方式使用:
|
| 60 |
+
|
| 61 |
+
- 本地运行:直接读取 `config.json`
|
| 62 |
+
- Docker / Vercel:从 `config.json` 生成 Base64,填入 `DS2API_CONFIG_JSON`,也可以直接填原始 JSON
|
| 63 |
+
|
| 64 |
+
```bash
|
| 65 |
+
DS2API_CONFIG_JSON="$(base64 < config.json | tr -d '\n')"
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
Vercel 一键部署可先只填 `DS2API_ADMIN_KEY`,部署后在 `/admin` 导入配置,再通过 “Vercel 同步” 写回环境变量。
|
| 69 |
+
|
| 70 |
+
---
|
| 71 |
+
|
| 72 |
+
## 鉴权规则
|
| 73 |
+
|
| 74 |
+
### 业务接口(`/v1/*`、`/anthropic/*`、`/v1beta/models/*`)
|
| 75 |
+
|
| 76 |
+
支持两种传参方式:
|
| 77 |
+
|
| 78 |
+
| 方式 | 示例 |
|
| 79 |
+
| --- | --- |
|
| 80 |
+
| Bearer Token | `Authorization: Bearer <token>` |
|
| 81 |
+
| API Key Header | `x-api-key: <token>`(无 `Bearer` 前缀) |
|
| 82 |
+
| Gemini 兼容 | `x-goog-api-key: <token>` 或 `?key=<token>` / `?api_key=<token>` |
|
| 83 |
+
|
| 84 |
+
**鉴权行为**:
|
| 85 |
+
|
| 86 |
+
- token 在 `config.keys` 中 → **托管账号模式**,自动轮询选择账号
|
| 87 |
+
- token 不在 `config.keys` 中 → **直通 token 模式**,直接作为 DeepSeek token 使用
|
| 88 |
+
|
| 89 |
+
**可选请求头**:`X-Ds2-Target-Account: <email_or_mobile>` — 指定使用某个托管账号;如果目标账号不存在,或管理账号队列已耗尽,相关业务请求会返回 `429`,当前不会附带 `Retry-After` 头。若账号存在但登录/刷新失败,则返回对应的 `401` 或上游错误。未指定目标账号时,托管账号模式的 completion 空输出 429 会先尝试切到另一个可用账号 fresh retry 一次;指定目标账号或无其他可用账号时不会切号。
|
| 90 |
+
Gemini 兼容客户端还可以使用 `x-goog-api-key`、`?key=` 或 `?api_key=` 作为凭据来源。
|
| 91 |
+
|
| 92 |
+
### Admin 接口(`/admin/*`)
|
| 93 |
+
|
| 94 |
+
| 端点 | 鉴权 |
|
| 95 |
+
| --- | --- |
|
| 96 |
+
| `POST /admin/login` | 无需鉴权 |
|
| 97 |
+
| `GET /admin/verify` | `Authorization: Bearer <jwt>`(仅 JWT) |
|
| 98 |
+
| 其他 `/admin/*` | `Authorization: Bearer <jwt>` 或 `Authorization: Bearer <admin_key>`(直传管理密钥) |
|
| 99 |
+
|
| 100 |
+
---
|
| 101 |
+
|
| 102 |
+
## 路由总览
|
| 103 |
+
|
| 104 |
+
| 方法 | 路径 | 鉴权 | 说明 |
|
| 105 |
+
| --- | --- | --- | --- |
|
| 106 |
+
| GET | `/healthz` | 无 | 存活探针 |
|
| 107 |
+
| HEAD | `/healthz` | 无 | 存活探针(无响应体) |
|
| 108 |
+
| GET | `/readyz` | 无 | 就绪探针 |
|
| 109 |
+
| HEAD | `/readyz` | 无 | 就绪探针(无响应体) |
|
| 110 |
+
| GET | `/v1/models` | 无 | OpenAI 模型列表 |
|
| 111 |
+
| GET | `/v1/models/{id}` | 无 | OpenAI 单模型查询(支持 alias 入参) |
|
| 112 |
+
| POST | `/v1/chat/completions` | 业务 | OpenAI 对话补全 |
|
| 113 |
+
| POST | `/v1/responses` | 业务 | OpenAI Responses 接口(流式/非流式) |
|
| 114 |
+
| GET | `/v1/responses/{response_id}` | 业务 | 查询已生成 response(内存 TTL) |
|
| 115 |
+
| POST | `/v1/embeddings` | 业务 | OpenAI Embeddings 接口 |
|
| 116 |
+
| POST | `/v1/files` | 业务 | OpenAI Files 上传(multipart/form-data) |
|
| 117 |
+
| GET | `/v1/files/{file_id}` | 业务 | 查询已上传文件状态 |
|
| 118 |
+
| GET | `/anthropic/v1/models` | 无 | Claude 模型列表 |
|
| 119 |
+
| POST | `/anthropic/v1/messages` | 业务 | Claude 消息接口 |
|
| 120 |
+
| POST | `/anthropic/v1/messages/count_tokens` | 业务 | Claude token 计数 |
|
| 121 |
+
| POST | `/v1/messages` | 业务 | Claude 消息快捷路径 |
|
| 122 |
+
| POST | `/messages` | 业务 | Claude 消息快捷路径 |
|
| 123 |
+
| POST | `/v1/messages/count_tokens` | 业务 | Claude token 计数快捷路径 |
|
| 124 |
+
| POST | `/messages/count_tokens` | 业务 | Claude token 计数快捷路径 |
|
| 125 |
+
| POST | `/v1beta/models/{model}:generateContent` | 业务 | Gemini 非流式 |
|
| 126 |
+
| POST | `/v1beta/models/{model}:streamGenerateContent` | 业务 | Gemini 流式 |
|
| 127 |
+
| POST | `/v1/models/{model}:generateContent` | 业务 | Gemini 非流式兼容路径 |
|
| 128 |
+
| POST | `/v1/models/{model}:streamGenerateContent` | 业务 | Gemini 流式兼容路径 |
|
| 129 |
+
| GET | `/api/version` | 无 | Ollama 版本接口 |
|
| 130 |
+
| GET | `/api/tags` | 无 | Ollama 模型列表 |
|
| 131 |
+
| POST | `/api/show` | 无 | Ollama 单模型能力查询(返回 `id` 与 `capabilities`) |
|
| 132 |
+
| POST | `/admin/login` | 无 | 管理登录 |
|
| 133 |
+
| GET | `/admin/verify` | JWT | 校验管理 JWT |
|
| 134 |
+
| GET | `/admin/vercel/config` | Admin | 读取 Vercel 预配置 |
|
| 135 |
+
| GET | `/admin/config` | Admin | 读取配置(脱敏) |
|
| 136 |
+
| POST | `/admin/config` | Admin | 更新配置 |
|
| 137 |
+
| GET | `/admin/settings` | Admin | 读取运行时设置 |
|
| 138 |
+
| PUT | `/admin/settings` | Admin | 更新运行时设置(热更新) |
|
| 139 |
+
| POST | `/admin/settings/password` | Admin | 更新 Admin 密码并使旧 JWT 失效 |
|
| 140 |
+
| POST | `/admin/config/import` | Admin | 导入配置(merge/replace) |
|
| 141 |
+
| GET | `/admin/config/export` | Admin | 导出完整配置(含 `config`/`json`/`base64`) |
|
| 142 |
+
| POST | `/admin/keys` | Admin | 添加 API key(可附 name/remark) |
|
| 143 |
+
| PUT | `/admin/keys/{key}` | Admin | 更新 API key 备注信息 |
|
| 144 |
+
| DELETE | `/admin/keys/{key}` | Admin | 删除 API key |
|
| 145 |
+
| GET | `/admin/proxies` | Admin | 代理列表 |
|
| 146 |
+
| POST | `/admin/proxies` | Admin | 添加代理 |
|
| 147 |
+
| PUT | `/admin/proxies/{proxyID}` | Admin | 更新代理(留空 password 表示保留原密码) |
|
| 148 |
+
| DELETE | `/admin/proxies/{proxyID}` | Admin | 删除代理(自动解绑引用该代理的账号) |
|
| 149 |
+
| POST | `/admin/proxies/test` | Admin | 测试代理连通性 |
|
| 150 |
+
| GET | `/admin/accounts` | Admin | 分页账号列表 |
|
| 151 |
+
| POST | `/admin/accounts` | Admin | 添加账号 |
|
| 152 |
+
| PUT | `/admin/accounts/{identifier}` | Admin | 更新账号 name/remark |
|
| 153 |
+
| DELETE | `/admin/accounts/{identifier}` | Admin | 删除账号 |
|
| 154 |
+
| PUT | `/admin/accounts/{identifier}/proxy` | Admin | 为账号绑定/解绑代理 |
|
| 155 |
+
| GET | `/admin/queue/status` | Admin | 账号队列状态 |
|
| 156 |
+
| POST | `/admin/accounts/test` | Admin | 测试单个账号 |
|
| 157 |
+
| POST | `/admin/accounts/test-all` | Admin | 测试全部账号 |
|
| 158 |
+
| POST | `/admin/accounts/sessions/delete-all` | Admin | 删除某账号的全部会话 |
|
| 159 |
+
| POST | `/admin/import` | Admin | 批量导入 keys/accounts |
|
| 160 |
+
| POST | `/admin/test` | Admin | 测试当前 API 可用性 |
|
| 161 |
+
| POST | `/admin/dev/raw-samples/capture` | Admin | 直接发起一次请求并保存为 raw sample |
|
| 162 |
+
| GET | `/admin/dev/raw-samples/query` | Admin | 按问题关键词查询当前内存抓包链 |
|
| 163 |
+
| POST | `/admin/dev/raw-samples/save` | Admin | 把命中的内存抓包链保存为 raw sample |
|
| 164 |
+
| POST | `/admin/vercel/sync` | Admin | 同步配置到 Vercel |
|
| 165 |
+
| GET | `/admin/vercel/status` | Admin | Vercel 同步状态 |
|
| 166 |
+
| POST | `/admin/vercel/status` | Admin | Vercel 同步状态 / 草稿对比 |
|
| 167 |
+
| GET | `/admin/export` | Admin | 导出配置 JSON/Base64 |
|
| 168 |
+
| GET | `/admin/dev/captures` | Admin | 查看本地抓包记录 |
|
| 169 |
+
| DELETE | `/admin/dev/captures` | Admin | 清空本地抓包记录 |
|
| 170 |
+
| GET | `/admin/chat-history` | Admin | 查看服务器端对话记录 |
|
| 171 |
+
| DELETE | `/admin/chat-history` | Admin | 清空服务器端对话记录 |
|
| 172 |
+
| GET | `/admin/chat-history/{id}` | Admin | 查看单条服务器端对话记录 |
|
| 173 |
+
| DELETE | `/admin/chat-history/{id}` | Admin | 删除单条服务器端对话记录 |
|
| 174 |
+
| PUT | `/admin/chat-history/settings` | Admin | 更新对话记录保留条数 |
|
| 175 |
+
| GET | `/admin/version` | Admin | 查询当前版本与最新 Release |
|
| 176 |
+
|
| 177 |
+
OpenAI `/v1/*` 仍是规范路径。对于只配置 DS2API 根地址的客户端,同一套 OpenAI handler 也通过根路径快捷路由暴露:`/models`、`/models/{id}`、`/chat/completions`、`/responses`、`/responses/{response_id}`、`/embeddings`、`/files`、`/files/{file_id}`。
|
| 178 |
+
|
| 179 |
+
服务器端记录本质上是 DeepSeek 上游响应归档:OpenAI Chat、OpenAI Responses、Claude Messages、Gemini GenerateContent 等直连 DeepSeek 的生成接口,在收到上游响应后会于各协议回译/裁剪前写入记录;列表按请求创建时间倒序展示,流式请求会在生成过程中持续刷新状态与详情。WebUI「API 测试」发出的请求也会进入该记录。
|
| 180 |
+
|
| 181 |
+
---
|
| 182 |
+
|
| 183 |
+
## 健康检查
|
| 184 |
+
|
| 185 |
+
### `GET /healthz`
|
| 186 |
+
|
| 187 |
+
```json
|
| 188 |
+
{"status": "ok"}
|
| 189 |
+
```
|
| 190 |
+
|
| 191 |
+
### `GET /readyz`
|
| 192 |
+
|
| 193 |
+
```json
|
| 194 |
+
{"status": "ready"}
|
| 195 |
+
```
|
| 196 |
+
|
| 197 |
+
---
|
| 198 |
+
|
| 199 |
+
## OpenAI 兼容接口
|
| 200 |
+
|
| 201 |
+
### `GET /v1/models`
|
| 202 |
+
|
| 203 |
+
无需鉴权。返回当前支持的 DeepSeek 原生模型列表。
|
| 204 |
+
|
| 205 |
+
**响应示例**:
|
| 206 |
+
|
| 207 |
+
```json
|
| 208 |
+
{
|
| 209 |
+
"object": "list",
|
| 210 |
+
"data": [
|
| 211 |
+
{"id": "deepseek-v4-flash", "object": "model", "created": 1677610602, "owned_by": "deepseek", "permission": []},
|
| 212 |
+
{"id": "deepseek-v4-flash-nothinking", "object": "model", "created": 1677610602, "owned_by": "deepseek", "permission": []},
|
| 213 |
+
{"id": "deepseek-v4-pro", "object": "model", "created": 1677610602, "owned_by": "deepseek", "permission": []},
|
| 214 |
+
{"id": "deepseek-v4-pro-nothinking", "object": "model", "created": 1677610602, "owned_by": "deepseek", "permission": []},
|
| 215 |
+
{"id": "deepseek-v4-flash-search", "object": "model", "created": 1677610602, "owned_by": "deepseek", "permission": []},
|
| 216 |
+
{"id": "deepseek-v4-flash-search-nothinking", "object": "model", "created": 1677610602, "owned_by": "deepseek", "permission": []},
|
| 217 |
+
{"id": "deepseek-v4-pro-search", "object": "model", "created": 1677610602, "owned_by": "deepseek", "permission": []},
|
| 218 |
+
{"id": "deepseek-v4-pro-search-nothinking", "object": "model", "created": 1677610602, "owned_by": "deepseek", "permission": []},
|
| 219 |
+
{"id": "deepseek-v4-vision", "object": "model", "created": 1677610602, "owned_by": "deepseek", "permission": []},
|
| 220 |
+
{"id": "deepseek-v4-vision-nothinking", "object": "model", "created": 1677610602, "owned_by": "deepseek", "permission": []}
|
| 221 |
+
]
|
| 222 |
+
}
|
| 223 |
+
```
|
| 224 |
+
|
| 225 |
+
> 说明:`/v1/models` 返回的是规范化后的 DeepSeek 原生模型 ID;常见 alias 仅用于请求入参解析,不会在该接口中单独展开返回。带 `-nothinking` 后缀的模型表示无论请求里是否显式开启 thinking / reasoning,都会强制关闭思考输出。
|
| 226 |
+
|
| 227 |
+
### 模型 alias 解析策略
|
| 228 |
+
|
| 229 |
+
对 `chat` / `responses` / `embeddings` 的 `model` 字段采用“宽进严出”:
|
| 230 |
+
|
| 231 |
+
1. 先匹配 DeepSeek 原生模型。
|
| 232 |
+
2. 再匹配 `model_aliases` 精确映射。
|
| 233 |
+
3. 如果请求名以 `-nothinking` 结尾,则在最终解析出的规范模型上追加对应的无思考变体。
|
| 234 |
+
4. 仍未命中则返回 `invalid_request_error`。当前不会按未知模型家族做启发式兜底;需要新增兼容名时请通过 `model_aliases` 明确配置。
|
| 235 |
+
|
| 236 |
+
当前内置默认 alias 来自 `internal/config/models.go`,`config.model_aliases` 会在运行时覆盖或补充同名映射。节选:
|
| 237 |
+
|
| 238 |
+
- OpenAI / Codex:`gpt-4o`、`gpt-4.1`、`gpt-5`、`gpt-5.5`、`gpt-5-codex`、`gpt-5.3-codex`、`codex-mini-latest`
|
| 239 |
+
- OpenAI reasoning:`o1`、`o3`、`o3-deep-research`、`o4-mini`
|
| 240 |
+
- Claude:`claude-opus-4-6`、`claude-sonnet-4-6`、`claude-haiku-4-5`、`claude-3-5-sonnet-latest`
|
| 241 |
+
- Gemini:`gemini-2.5-pro`、`gemini-2.5-flash`、`gemini-3.1-pro`、`gemini-3-pro`、`gemini-3-flash`、`gemini-3.1-flash-lite`、`gemini-pro-vision`
|
| 242 |
+
- 其他内置精确 alias:`llama-3.1-70b-instruct`、`qwen-max`
|
| 243 |
+
|
| 244 |
+
上述 alias 若在请求名后追加 `-nothinking` 后缀,也会映射到对应的强制关闭 thinking 版本。
|
| 245 |
+
当前视觉能力仅对应 `deepseek-v4-vision` / `deepseek-v4-vision-nothinking`,不会解析出独立的 `vision-search` 变体。
|
| 246 |
+
|
| 247 |
+
退役历史模型(如 `claude-1.*`、`claude-2.*`、`claude-instant-*`、`gpt-3.5*`)会被显式拒绝。
|
| 248 |
+
|
| 249 |
+
### `POST /v1/chat/completions`
|
| 250 |
+
|
| 251 |
+
> 路径说明:除规范路径 `/v1/chat/completions` 外,也支持根路径快捷别名 `/chat/completions`。在 Vercel Runtime 上,`vercel.json` 仅把规范路径 `/v1/chat/completions` 重写到 Node 流式桥接;根路径快捷别名仍走 Go 主链路。因此 Vercel 上需要实时流式时请使用 `/v1/chat/completions`。
|
| 252 |
+
|
| 253 |
+
**请求头**:
|
| 254 |
+
|
| 255 |
+
```http
|
| 256 |
+
Authorization: Bearer your-api-key
|
| 257 |
+
Content-Type: application/json
|
| 258 |
+
```
|
| 259 |
+
|
| 260 |
+
**请求体**:
|
| 261 |
+
|
| 262 |
+
| 字段 | 类型 | 必填 | 说明 |
|
| 263 |
+
| --- | --- | --- | --- |
|
| 264 |
+
| `model` | string | ✅ | 支持 DeepSeek 原生模型 + 常见 alias(如 `gpt-5.5`、`gpt-5.4-mini`、`gpt-5.3-codex`、`o3`、`claude-opus-4-6`、`claude-sonnet-4-6`、`gemini-2.5-pro`、`gemini-3.1-pro`、`gemini-3-flash` 等);若模型名带 `-nothinking` 后缀,则强制关闭 thinking / reasoning |
|
| 265 |
+
| `messages` | array | ✅ | OpenAI 风格消息数组 |
|
| 266 |
+
| `stream` | boolean | ❌ | 默认 `false` |
|
| 267 |
+
| `tools` | array | ❌ | Function Calling 定义 |
|
| 268 |
+
| `temperature` 等 | any | ❌ | 兼容透传字段(最终效果由上游决定) |
|
| 269 |
+
|
| 270 |
+
#### 非流式响应
|
| 271 |
+
|
| 272 |
+
```json
|
| 273 |
+
{
|
| 274 |
+
"id": "<chat_session_id>",
|
| 275 |
+
"object": "chat.completion",
|
| 276 |
+
"created": 1738400000,
|
| 277 |
+
"model": "deepseek-v4-pro",
|
| 278 |
+
"choices": [
|
| 279 |
+
{
|
| 280 |
+
"index": 0,
|
| 281 |
+
"message": {
|
| 282 |
+
"role": "assistant",
|
| 283 |
+
"content": "最终回复",
|
| 284 |
+
"reasoning_content": "思考内容(开启 thinking 时)"
|
| 285 |
+
},
|
| 286 |
+
"finish_reason": "stop"
|
| 287 |
+
}
|
| 288 |
+
],
|
| 289 |
+
"usage": {
|
| 290 |
+
"prompt_tokens": 10,
|
| 291 |
+
"completion_tokens": 20,
|
| 292 |
+
"total_tokens": 30,
|
| 293 |
+
"completion_tokens_details": {
|
| 294 |
+
"reasoning_tokens": 5
|
| 295 |
+
}
|
| 296 |
+
}
|
| 297 |
+
}
|
| 298 |
+
```
|
| 299 |
+
|
| 300 |
+
#### 流式响应(`stream=true`)
|
| 301 |
+
|
| 302 |
+
SSE 格式:每段为 `data: <json>\n\n`,结束为 `data: [DONE]`。
|
| 303 |
+
|
| 304 |
+
```text
|
| 305 |
+
data: {"id":"...","object":"chat.completion.chunk","choices":[{"delta":{"role":"assistant"},"index":0}]}
|
| 306 |
+
|
| 307 |
+
data: {"id":"...","object":"chat.completion.chunk","choices":[{"delta":{"reasoning_content":"..."},"index":0}]}
|
| 308 |
+
|
| 309 |
+
data: {"id":"...","object":"chat.completion.chunk","choices":[{"delta":{"content":"..."},"index":0}]}
|
| 310 |
+
|
| 311 |
+
data: {"id":"...","object":"chat.completion.chunk","choices":[{"delta":{},"index":0,"finish_reason":"stop"}],"usage":{...}}
|
| 312 |
+
|
| 313 |
+
data: [DONE]
|
| 314 |
+
```
|
| 315 |
+
|
| 316 |
+
**字段说明**:
|
| 317 |
+
|
| 318 |
+
- 首个 delta 包含 `role: assistant`
|
| 319 |
+
- 开启 thinking 时会输出 `delta.reasoning_content`
|
| 320 |
+
- 普通文本输出 `delta.content`
|
| 321 |
+
- 最后一段包含 `finish_reason` 和 `usage`
|
| 322 |
+
- token 计数优先透传上游 DeepSeek SSE(如 `accumulated_token_usage` / `token_usage`);仅在上游缺失时回退本地估算。失败/中断型结束(例如 `response.failed`)可能不会携带 `usage`
|
| 323 |
+
|
| 324 |
+
#### Tool Calls
|
| 325 |
+
|
| 326 |
+
当请求中含 `tools` 时,DS2API 做防泄漏处理:
|
| 327 |
+
|
| 328 |
+
**非流式**:识别到工具调用时,返回 `message.tool_calls`,设置 `finish_reason=tool_calls`,`message.content=null`。
|
| 329 |
+
|
| 330 |
+
```json
|
| 331 |
+
{
|
| 332 |
+
"choices": [
|
| 333 |
+
{
|
| 334 |
+
"index": 0,
|
| 335 |
+
"message": {
|
| 336 |
+
"role": "assistant",
|
| 337 |
+
"content": null,
|
| 338 |
+
"tool_calls": [
|
| 339 |
+
{
|
| 340 |
+
"id": "call_xxx",
|
| 341 |
+
"type": "function",
|
| 342 |
+
"function": {
|
| 343 |
+
"name": "get_weather",
|
| 344 |
+
"arguments": "{\"city\":\"beijing\"}"
|
| 345 |
+
}
|
| 346 |
+
}
|
| 347 |
+
]
|
| 348 |
+
},
|
| 349 |
+
"finish_reason": "tool_calls"
|
| 350 |
+
}
|
| 351 |
+
]
|
| 352 |
+
}
|
| 353 |
+
```
|
| 354 |
+
|
| 355 |
+
**流式**:命中高置信特征后立即输出 `delta.tool_calls`(不等待完整工具参数闭合),并持续发送 arguments 增量;已确认的工具调用片段不会回流到 `delta.content`。
|
| 356 |
+
|
| 357 |
+
补充说明:
|
| 358 |
+
|
| 359 |
+
- **非代码块上下文**下,工具负载即使与普通文本混合,也会按特征识别并产出可执行 tool call(前后普通文本仍可透传)。
|
| 360 |
+
- 解析器当前把推荐半角管道符 DSML 外壳(`<|DSML|tool_calls>` / `<|DSML|invoke name="...">` / `<|DSML|parameter name="...">`)、DSML wrapper 别名(`<dsml|tool_calls>`、`<|tool_calls>`)、常见 DSML 分隔符漏写形态(如 `<|DSML tool_calls>` / `<|DSML invoke>` / `<|DSML parameter>`)、`DSML` 与工具标签名黏连的常见 typo(如 `<DSMLtool_calls>` / `<DSMLinvoke>` / `<DSMLparameter>`)、控制分隔符漂移(如 `<DSML␂tool_calls>` / 原始 STX `\x02`)、CJK 尖括号、全角感叹号、顿号、PascalCase 本地名、弯引号属性值与属性尾部分隔符漂移(如 `<DSM|parameter name="command"|>...〈/DSM|parameter〉` / `<!DSML!invoke name=“Bash”>` / `<、DSML、tool_calls>` / `<DSmartToolCalls>` / `<DSMLtool_calls※>`)、任意协议前缀壳(如 `<proto💥tool_calls>`)和旧式 canonical XML 工具块(`<tool_calls>` / `<invoke name="...">` / `<parameter name="...">`)作为可执行调用解析;这些非结构性分隔符壳会先归一化回 XML,内部仍以 XML 解析语义为准,CDATA 开头也会容错 `<![CDATA[` / `<、[CDATA[`。旧式 `<tools>`、`<tool_call>`、`<tool_name>`、`<param>`、`<function_call>`、`tool_use`、antml 风格与纯 JSON `tool_calls` 片段默认都会按普通文本处理;完整但 malformed 的 wrapper 同样会作为普通文本释放。
|
| 361 |
+
- 解析层不会因为参数值为空而丢弃工具调用;显式空字符串或纯空白参数会按空字符串进入结构化 `tool_calls`。Prompt 会要求模型不要主动输出空参数,缺参/空命令的拒绝应由工具执行侧或客户端 schema 校验负责。
|
| 362 |
+
- 当最终可见正文为空但思维链里包含可执行工具调用时,Chat / Responses 会在收尾阶段补发标准 OpenAI `tool_calls` / `function_call` 输出;如果客户端未开启 thinking / reasoning,该思维链只用于检测,不会作为可见正文或 `reasoning_content` 暴露。
|
| 363 |
+
- Markdown fenced code block(例如 ```json ... ```)和行内 code span(例如 `` `<tool_calls>...</tool_calls>` ``)中的 `tool_calls` 仅视为示例文本,不会被执行。
|
| 364 |
+
|
| 365 |
+
---
|
| 366 |
+
|
| 367 |
+
### `GET /v1/models/{id}`
|
| 368 |
+
|
| 369 |
+
无需鉴权。入参支持 alias(例如 `gpt-4o`),返回的是映射后的 DeepSeek 模型对象。
|
| 370 |
+
|
| 371 |
+
### `POST /v1/responses`
|
| 372 |
+
|
| 373 |
+
OpenAI Responses 风格接口,兼容 `input` 或 `messages`。
|
| 374 |
+
|
| 375 |
+
| 字段 | 类型 | 必填 | 说明 |
|
| 376 |
+
| --- | --- | --- | --- |
|
| 377 |
+
| `model` | string | ✅ | 支持原生模型 + alias 自动映射 |
|
| 378 |
+
| `input` | string/array/object | ❌ | 与 `messages` 二选一 |
|
| 379 |
+
| `messages` | array | ❌ | 与 `input` 二选一 |
|
| 380 |
+
| `instructions` | string | ❌ | 自动前置为 system 消息 |
|
| 381 |
+
| `stream` | boolean | ❌ | 默认 `false` |
|
| 382 |
+
| `tools` | array | ❌ | 与 chat 同样的工具识别与转译策略(含代码块示例豁免) |
|
| 383 |
+
| `tool_choice` | string/object | ❌ | 支持 `auto`/`none`/`required` 与强制函数(`{"type":"function","name":"..."}`) |
|
| 384 |
+
|
| 385 |
+
**非流式响应**:返回标准 `response` 对象,`id` 形如 `resp_xxx`,并写入内存 TTL 存储。
|
| 386 |
+
当 `tool_choice=required` 且未产出有效工具调用时,返回 HTTP `422`(`error.code=tool_choice_violation`)。
|
| 387 |
+
|
| 388 |
+
**流式响应(SSE)**:最小事件序列如下。
|
| 389 |
+
|
| 390 |
+
```text
|
| 391 |
+
event: response.created
|
| 392 |
+
data: {"type":"response.created","id":"resp_xxx","status":"in_progress",...}
|
| 393 |
+
|
| 394 |
+
event: response.output_item.added
|
| 395 |
+
data: {"type":"response.output_item.added","response_id":"resp_xxx","item":{"type":"message|function_call",...},...}
|
| 396 |
+
|
| 397 |
+
event: response.content_part.added
|
| 398 |
+
data: {"type":"response.content_part.added","response_id":"resp_xxx","part":{"type":"output_text",...},...}
|
| 399 |
+
|
| 400 |
+
event: response.output_text.delta
|
| 401 |
+
data: {"type":"response.output_text.delta","response_id":"resp_xxx","item_id":"msg_xxx","output_index":0,"content_index":0,"delta":"..."}
|
| 402 |
+
|
| 403 |
+
event: response.function_call_arguments.delta
|
| 404 |
+
data: {"type":"response.function_call_arguments.delta","response_id":"resp_xxx","call_id":"call_xxx","delta":"..."}
|
| 405 |
+
|
| 406 |
+
event: response.function_call_arguments.done
|
| 407 |
+
data: {"type":"response.function_call_arguments.done","response_id":"resp_xxx","call_id":"call_xxx","name":"tool","arguments":"{...}"}
|
| 408 |
+
|
| 409 |
+
event: response.content_part.done
|
| 410 |
+
data: {"type":"response.content_part.done","response_id":"resp_xxx",...}
|
| 411 |
+
|
| 412 |
+
event: response.output_item.done
|
| 413 |
+
data: {"type":"response.output_item.done","response_id":"resp_xxx","item":{"type":"message|function_call",...},...}
|
| 414 |
+
|
| 415 |
+
event: response.completed
|
| 416 |
+
data: {"type":"response.completed","response":{...}}
|
| 417 |
+
|
| 418 |
+
data: [DONE]
|
| 419 |
+
```
|
| 420 |
+
|
| 421 |
+
流式场景下若 `tool_choice=required` 违规,会返回 `response.failed` 后结束(不再发送 `response.completed`)。
|
| 422 |
+
|
| 423 |
+
> 当前版本说明:解析层默认“尽量提取结构化 tool call”,未启用基于 `tools` allow-list 的硬拒绝;是否执行仍应由你的工具执行器做白名单校验。
|
| 424 |
+
|
| 425 |
+
### `GET /v1/responses/{response_id}`
|
| 426 |
+
|
| 427 |
+
需要业务鉴权。查询 `POST /v1/responses` 生成并缓存的 response 对象(按调用方鉴权隔离,仅同一 key/token 可读取)。
|
| 428 |
+
|
| 429 |
+
> 当前为内存 TTL 存储,默认过期时间 `900s`(可用 `responses.store_ttl_seconds` 调整)。
|
| 430 |
+
|
| 431 |
+
### `POST /v1/embeddings`
|
| 432 |
+
|
| 433 |
+
需要业务鉴权。返回 OpenAI Embeddings 兼容结构。
|
| 434 |
+
|
| 435 |
+
| 字段 | 类型 | 必填 | 说明 |
|
| 436 |
+
| --- | --- | --- | --- |
|
| 437 |
+
| `model` | string | ✅ | 支持原生模型 + alias 自动映射 |
|
| 438 |
+
| `input` | string/array | ✅ | 支持字符串、字符串数组、token 数组 |
|
| 439 |
+
|
| 440 |
+
> 需配置 `embeddings.provider`。当前支持:`mock` / `deterministic` / `builtin`(三者都走同一套本地确定性实现)。未配置或不支持时返回标准错误结构(HTTP 501)。
|
| 441 |
+
|
| 442 |
+
### `POST /v1/files`
|
| 443 |
+
|
| 444 |
+
需要业务鉴权。兼容 OpenAI Files 上传接口,当前仅支持 `multipart/form-data`。
|
| 445 |
+
|
| 446 |
+
| 字段 | 类型 | 必填 | 说明 |
|
| 447 |
+
| --- | --- | --- | --- |
|
| 448 |
+
| `file` | file | ✅ | 上传文件二进制 |
|
| 449 |
+
| `purpose` | string | ❌ | 透传到上游用途字段 |
|
| 450 |
+
|
| 451 |
+
约束与行为:
|
| 452 |
+
|
| 453 |
+
- 请求必须为 `multipart/form-data`,否则返回 `400`。
|
| 454 |
+
- 请求体总大小上限 **100 MiB**(超限返回 `413`)。
|
| 455 |
+
- 成功返回 OpenAI `file` 对象(`id/object/bytes/filename/purpose/status` 等字段),并附带 `account_id` 便于定位来源账号。
|
| 456 |
+
|
| 457 |
+
### `GET /v1/files/{file_id}`
|
| 458 |
+
|
| 459 |
+
需要业务鉴权。查询 DeepSeek 上传文件的当前状态,并返回 OpenAI `file` 对象;未找到匹配文件时返回 `404`。
|
| 460 |
+
|
| 461 |
+
---
|
| 462 |
+
|
| 463 |
+
## Claude 兼容接口
|
| 464 |
+
|
| 465 |
+
除标准路径 `/anthropic/v1/*` 外,还支持快捷路径 `/v1/messages`、`/messages`、`/v1/messages/count_tokens`、`/messages/count_tokens`。
|
| 466 |
+
实现上统一走 OpenAI Chat Completions 解析与回译链路,避免多套解析逻辑分叉维护。
|
| 467 |
+
|
| 468 |
+
### `GET /anthropic/v1/models`
|
| 469 |
+
|
| 470 |
+
无需鉴权。
|
| 471 |
+
|
| 472 |
+
**响应示例**:
|
| 473 |
+
|
| 474 |
+
```json
|
| 475 |
+
{
|
| 476 |
+
"object": "list",
|
| 477 |
+
"data": [
|
| 478 |
+
{"id": "claude-sonnet-4-6", "object": "model", "created": 1715635200, "owned_by": "anthropic"},
|
| 479 |
+
{"id": "claude-sonnet-4-6-nothinking", "object": "model", "created": 1715635200, "owned_by": "anthropic"},
|
| 480 |
+
{"id": "claude-haiku-4-5", "object": "model", "created": 1715635200, "owned_by": "anthropic"},
|
| 481 |
+
{"id": "claude-haiku-4-5-nothinking", "object": "model", "created": 1715635200, "owned_by": "anthropic"},
|
| 482 |
+
{"id": "claude-opus-4-6", "object": "model", "created": 1715635200, "owned_by": "anthropic"},
|
| 483 |
+
{"id": "claude-opus-4-6-nothinking", "object": "model", "created": 1715635200, "owned_by": "anthropic"}
|
| 484 |
+
],
|
| 485 |
+
"first_id": "claude-opus-4-6",
|
| 486 |
+
"last_id": "claude-3-haiku-20240307-nothinking",
|
| 487 |
+
"has_more": false
|
| 488 |
+
}
|
| 489 |
+
```
|
| 490 |
+
|
| 491 |
+
> 说明:示例仅展示部分模型;实际返回除当前主别名外,还包含 Claude 4.x snapshots、3.x 历史模型 ID 与常见别名,并为这些可映射模型额外提供 `-nothinking` 变体。
|
| 492 |
+
|
| 493 |
+
### `POST /anthropic/v1/messages`
|
| 494 |
+
|
| 495 |
+
**请求头**:
|
| 496 |
+
|
| 497 |
+
```http
|
| 498 |
+
x-api-key: your-api-key
|
| 499 |
+
Content-Type: application/json
|
| 500 |
+
anthropic-version: 2023-06-01
|
| 501 |
+
```
|
| 502 |
+
|
| 503 |
+
> `anthropic-version` 可省略,服务端会自动补为 `2023-06-01`。
|
| 504 |
+
|
| 505 |
+
**请求体**:
|
| 506 |
+
|
| 507 |
+
| 字段 | 类型 | 必填 | 说明 |
|
| 508 |
+
| --- | --- | --- | --- |
|
| 509 |
+
| `model` | string | ✅ | 例如 `claude-sonnet-4-6` / `claude-opus-4-6` / `claude-haiku-4-5`(兼容 `claude-sonnet-4-5`、`claude-3-5-haiku-latest`),并支持历史 Claude 模型 ID;若模型名带 `-nothinking` 后缀,则强制关闭 thinking / reasoning |
|
| 510 |
+
| `messages` | array | ✅ | Claude 风格消息数组 |
|
| 511 |
+
| `max_tokens` | number | ❌ | 缺省自动补 `8192`;当前实现不会硬性截断上游输出 |
|
| 512 |
+
| `stream` | boolean | ❌ | 默认 `false` |
|
| 513 |
+
| `system` | string | ❌ | 可选系统提示 |
|
| 514 |
+
| `tools` | array | ❌ | Claude tool 定义 |
|
| 515 |
+
| `thinking` | object | ❌ | Anthropic thinking 配置;会转译为下游 reasoning 控制,`-nothinking` 模型会忽略 |
|
| 516 |
+
| `temperature` | number | ❌ | 透传到下游;若同时提供 `top_p`,以 `temperature` 为准 |
|
| 517 |
+
| `top_p` | number | ❌ | 当未提供 `temperature` 时透传到下游 |
|
| 518 |
+
| `stop_sequences` | array | ❌ | 透传到下游停用序列 |
|
| 519 |
+
| `tool_choice` | string/object | ❌ | 支持 `auto` / `none` / `required` / `{"type":"function","name":"..."}`,并会转译为下游工具选择 |
|
| 520 |
+
|
| 521 |
+
> 说明:上述 `thinking`、`temperature`、`top_p`、`stop_sequences`、`tool_choice` 都会走兼容层转译;最终是否生效仍取决于当前模型和上游能力。`temperature` 与 `top_p` 同时存在时,`temperature` 优先。
|
| 522 |
+
|
| 523 |
+
#### 非流式响应
|
| 524 |
+
|
| 525 |
+
```json
|
| 526 |
+
{
|
| 527 |
+
"id": "msg_1738400000000000000",
|
| 528 |
+
"type": "message",
|
| 529 |
+
"role": "assistant",
|
| 530 |
+
"model": "claude-sonnet-4-6",
|
| 531 |
+
"content": [
|
| 532 |
+
{"type": "text", "text": "回复内容"}
|
| 533 |
+
],
|
| 534 |
+
"stop_reason": "end_turn",
|
| 535 |
+
"stop_sequence": null,
|
| 536 |
+
"usage": {
|
| 537 |
+
"input_tokens": 12,
|
| 538 |
+
"output_tokens": 34
|
| 539 |
+
}
|
| 540 |
+
}
|
| 541 |
+
```
|
| 542 |
+
|
| 543 |
+
若识别到工具调用,`stop_reason=tool_use`,`content` 中返回 `tool_use` block。
|
| 544 |
+
|
| 545 |
+
#### 流式响应(`stream=true`)
|
| 546 |
+
|
| 547 |
+
SSE 使用 `event:` + `data:` 双行格式,JSON 中保留 `type` 字段。
|
| 548 |
+
|
| 549 |
+
```text
|
| 550 |
+
event: message_start
|
| 551 |
+
data: {"type":"message_start","message":{...}}
|
| 552 |
+
|
| 553 |
+
event: content_block_start
|
| 554 |
+
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}
|
| 555 |
+
|
| 556 |
+
event: content_block_delta
|
| 557 |
+
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hello"}}
|
| 558 |
+
|
| 559 |
+
event: ping
|
| 560 |
+
data: {"type":"ping"}
|
| 561 |
+
|
| 562 |
+
event: content_block_stop
|
| 563 |
+
data: {"type":"content_block_stop","index":0}
|
| 564 |
+
|
| 565 |
+
event: message_delta
|
| 566 |
+
data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":12}}
|
| 567 |
+
|
| 568 |
+
event: message_stop
|
| 569 |
+
data: {"type":"message_stop"}
|
| 570 |
+
```
|
| 571 |
+
|
| 572 |
+
**说明**:
|
| 573 |
+
|
| 574 |
+
- 默认支持 thinking 的模型会输出 `thinking` block / `thinking_delta`;请求显式关闭 thinking 或使用 `-nothinking` 模型时不会输出
|
| 575 |
+
- 带 `-nothinking` 后缀的模型会强制关闭 thinking,即使请求显式传了 `thinking` / `reasoning` / `reasoning_effort` 也不会输出 `thinking_delta`
|
| 576 |
+
- 不会输出 `signature_delta`(上游 DeepSeek 未提供可验证签名)
|
| 577 |
+
- `tools` 场景优先避免泄露原始工具 JSON,不强制发送 `input_json_delta`
|
| 578 |
+
|
| 579 |
+
### `POST /anthropic/v1/messages/count_tokens`
|
| 580 |
+
|
| 581 |
+
**请求**:
|
| 582 |
+
|
| 583 |
+
```json
|
| 584 |
+
{
|
| 585 |
+
"model": "claude-sonnet-4-6",
|
| 586 |
+
"messages": [
|
| 587 |
+
{"role": "user", "content": "你好"}
|
| 588 |
+
]
|
| 589 |
+
}
|
| 590 |
+
```
|
| 591 |
+
|
| 592 |
+
**响应**:
|
| 593 |
+
|
| 594 |
+
```json
|
| 595 |
+
{
|
| 596 |
+
"input_tokens": 5
|
| 597 |
+
}
|
| 598 |
+
```
|
| 599 |
+
|
| 600 |
+
---
|
| 601 |
+
|
| 602 |
+
## Gemini 兼容接口
|
| 603 |
+
|
| 604 |
+
支持路径:
|
| 605 |
+
|
| 606 |
+
- `/v1beta/models/{model}:generateContent`
|
| 607 |
+
- `/v1beta/models/{model}:streamGenerateContent`
|
| 608 |
+
- `/v1/models/{model}:generateContent`(兼容路径)
|
| 609 |
+
- `/v1/models/{model}:streamGenerateContent`(兼容路径)
|
| 610 |
+
|
| 611 |
+
鉴权方式同业务接口(`Authorization: Bearer <token>` 或 `x-api-key`)。
|
| 612 |
+
实现上统一走 OpenAI Chat Completions 解析与回译链路,避免多套解析逻辑分叉维护。
|
| 613 |
+
|
| 614 |
+
### `POST /v1beta/models/{model}:generateContent`
|
| 615 |
+
|
| 616 |
+
请求体兼容 Gemini `contents` / `tools` 字段,模型名可用 alias 自动映射到 DeepSeek 模型;若路径中的模型名带 `-nothinking` 后缀,则最终会映射到对应的无思考模型。
|
| 617 |
+
|
| 618 |
+
响应为 Gemini 兼容结构,核心字段包括:
|
| 619 |
+
|
| 620 |
+
- `candidates[].content.parts[].text`
|
| 621 |
+
- `candidates[].content.parts[].thought=true`(thinking 输出)
|
| 622 |
+
- `candidates[].content.parts[].functionCall`(工具调用时)
|
| 623 |
+
- `usageMetadata`(`promptTokenCount` / `candidatesTokenCount` / `totalTokenCount`)
|
| 624 |
+
|
| 625 |
+
### `POST /v1beta/models/{model}:streamGenerateContent`
|
| 626 |
+
|
| 627 |
+
返回 SSE(`text/event-stream`),每个 chunk 为一条 `data: <json>`:
|
| 628 |
+
|
| 629 |
+
- 常规文本:持续返回增量文本 chunk
|
| 630 |
+
- thinking:持续返回 `parts[].thought=true` 的增量 chunk
|
| 631 |
+
- `tools` 场景:会缓冲并在结束时输出 `functionCall` 结构
|
| 632 |
+
- 结束 chunk:包含 `finishReason: "STOP"` 与 `usageMetadata`
|
| 633 |
+
- token 计数优先透传上游 DeepSeek SSE(如 `accumulated_token_usage` / `token_usage`);仅在上游缺失时回退本地估算
|
| 634 |
+
|
| 635 |
+
---
|
| 636 |
+
|
| 637 |
+
## Ollama 兼容接口
|
| 638 |
+
|
| 639 |
+
- `POST /api/show` 请求体:`{"model":"<model-id>"}`。
|
| 640 |
+
- 响应字段使用小写 `id`(不是 `ID`),并返回 `capabilities` 数组,便于与 Ollama 风格客户端/严格 schema 对齐。
|
| 641 |
+
|
| 642 |
+
示例响应:
|
| 643 |
+
|
| 644 |
+
```json
|
| 645 |
+
{
|
| 646 |
+
"id": "deepseek-v4-flash",
|
| 647 |
+
"capabilities": ["tools", "thinking"]
|
| 648 |
+
}
|
| 649 |
+
```
|
| 650 |
+
|
| 651 |
+
## Admin 接口
|
| 652 |
+
|
| 653 |
+
### `POST /admin/login`
|
| 654 |
+
|
| 655 |
+
无需鉴权。
|
| 656 |
+
|
| 657 |
+
**请求**:
|
| 658 |
+
|
| 659 |
+
```json
|
| 660 |
+
{
|
| 661 |
+
"admin_key": "admin",
|
| 662 |
+
"expire_hours": 24
|
| 663 |
+
}
|
| 664 |
+
```
|
| 665 |
+
|
| 666 |
+
`expire_hours` 可省略,默认 `24`。
|
| 667 |
+
|
| 668 |
+
**响应**:
|
| 669 |
+
|
| 670 |
+
```json
|
| 671 |
+
{
|
| 672 |
+
"success": true,
|
| 673 |
+
"token": "<jwt>",
|
| 674 |
+
"expires_in": 86400
|
| 675 |
+
}
|
| 676 |
+
```
|
| 677 |
+
|
| 678 |
+
### `GET /admin/verify`
|
| 679 |
+
|
| 680 |
+
需要 JWT:`Authorization: Bearer <jwt>`
|
| 681 |
+
|
| 682 |
+
**响应**:
|
| 683 |
+
|
| 684 |
+
```json
|
| 685 |
+
{
|
| 686 |
+
"valid": true,
|
| 687 |
+
"expires_at": 1738400000,
|
| 688 |
+
"remaining_seconds": 72000
|
| 689 |
+
}
|
| 690 |
+
```
|
| 691 |
+
|
| 692 |
+
### `GET /admin/vercel/config`
|
| 693 |
+
|
| 694 |
+
返回 Vercel 预配置状态。优先读取环境变量,其次回退到已保存的 `vercel` 配置块。
|
| 695 |
+
|
| 696 |
+
```json
|
| 697 |
+
{
|
| 698 |
+
"has_token": true,
|
| 699 |
+
"token_preview": "vc****en",
|
| 700 |
+
"token_source": "config",
|
| 701 |
+
"project_id": "prj_xxx",
|
| 702 |
+
"team_id": null
|
| 703 |
+
}
|
| 704 |
+
```
|
| 705 |
+
|
| 706 |
+
### `GET /admin/config`
|
| 707 |
+
|
| 708 |
+
返回脱敏后的配置,包含 `keys` 与 `api_keys`。
|
| 709 |
+
|
| 710 |
+
```json
|
| 711 |
+
{
|
| 712 |
+
"keys": ["k1", "k2"],
|
| 713 |
+
"api_keys": [
|
| 714 |
+
{"key": "k1", "name": "主 Key", "remark": "生产流量"},
|
| 715 |
+
{"key": "k2", "name": "备用 Key", "remark": "压测"}
|
| 716 |
+
],
|
| 717 |
+
"env_backed": false,
|
| 718 |
+
"env_source_present": true,
|
| 719 |
+
"env_writeback_enabled": true,
|
| 720 |
+
"config_path": "/data/config.json",
|
| 721 |
+
"vercel": {
|
| 722 |
+
"has_token": true,
|
| 723 |
+
"token_preview": "vc****en",
|
| 724 |
+
"project_id": "prj_xxx",
|
| 725 |
+
"team_id": ""
|
| 726 |
+
},
|
| 727 |
+
"accounts": [
|
| 728 |
+
{
|
| 729 |
+
"identifier": "user@example.com",
|
| 730 |
+
"email": "user@example.com",
|
| 731 |
+
"mobile": "",
|
| 732 |
+
"has_password": true,
|
| 733 |
+
"has_token": true,
|
| 734 |
+
"token_preview": "abcde..."
|
| 735 |
+
}
|
| 736 |
+
],
|
| 737 |
+
"model_aliases": {
|
| 738 |
+
"claude-sonnet-4-6": "deepseek-v4-flash",
|
| 739 |
+
"claude-opus-4-6": "deepseek-v4-pro"
|
| 740 |
+
}
|
| 741 |
+
}
|
| 742 |
+
```
|
| 743 |
+
|
| 744 |
+
### `POST /admin/config`
|
| 745 |
+
|
| 746 |
+
只更新 `keys`、`api_keys`、`accounts`、`model_aliases`。
|
| 747 |
+
如果同时发送 `api_keys` 与 `keys`,优先保留 `api_keys` 中的结构化 `name` / `remark`;`keys` 仅作为旧格式兼容回退。
|
| 748 |
+
|
| 749 |
+
**请求**:
|
| 750 |
+
|
| 751 |
+
```json
|
| 752 |
+
{
|
| 753 |
+
"keys": ["k1", "k2"],
|
| 754 |
+
"api_keys": [
|
| 755 |
+
{"key": "k1", "name": "主 Key", "remark": "生产流量"},
|
| 756 |
+
{"key": "k2", "name": "备用 Key", "remark": "压测"}
|
| 757 |
+
],
|
| 758 |
+
"accounts": [
|
| 759 |
+
{"email": "user@example.com", "password": "pwd", "token": ""}
|
| 760 |
+
],
|
| 761 |
+
"model_aliases": {
|
| 762 |
+
"claude-sonnet-4-6": "deepseek-v4-flash",
|
| 763 |
+
"claude-opus-4-6": "deepseek-v4-pro"
|
| 764 |
+
}
|
| 765 |
+
}
|
| 766 |
+
```
|
| 767 |
+
|
| 768 |
+
### `GET /admin/settings`
|
| 769 |
+
|
| 770 |
+
读取运行时设置与状态,返回:
|
| 771 |
+
|
| 772 |
+
- `success`
|
| 773 |
+
- `admin`(`has_password_hash`、`jwt_expire_hours`、`jwt_valid_after_unix`、`default_password_warning`)
|
| 774 |
+
- `runtime`(`account_max_inflight`、`account_max_queue`、`global_max_inflight`、`token_refresh_interval_hours`)
|
| 775 |
+
- `config_snapshot`:原始配置快照(`admin` / `runtime` / `responses` / `embeddings` / `auto_delete` / `current_input_file` / `thinking_injection` / `model_aliases`),用于区分环境变量覆盖前的配置
|
| 776 |
+
- `responses` / `embeddings`
|
| 777 |
+
- `auto_delete`(`mode`:`none` / `single` / `all`;旧配置 `sessions=true` 仍按 `all` 处理)
|
| 778 |
+
- `current_input_file`(`enabled` 默认返回 `true`、`min_chars`)
|
| 779 |
+
- `thinking_injection`(`enabled` 默认返回 `true`、`prompt`、`default_prompt`)
|
| 780 |
+
- `model_aliases`
|
| 781 |
+
- `env_backed`、`needs_vercel_sync`
|
| 782 |
+
- `toolcall` 策略已固定为 `feature_match + high`,不再通过 settings 返回或修改
|
| 783 |
+
|
| 784 |
+
### `PUT /admin/settings`
|
| 785 |
+
|
| 786 |
+
热更新运行时设置。支持更新:
|
| 787 |
+
|
| 788 |
+
- `admin.jwt_expire_hours`
|
| 789 |
+
- `runtime.account_max_inflight` / `runtime.account_max_queue` / `runtime.global_max_inflight` / `runtime.token_refresh_interval_hours`
|
| 790 |
+
- `responses.store_ttl_seconds`
|
| 791 |
+
- `embeddings.provider`
|
| 792 |
+
- `auto_delete.mode`
|
| 793 |
+
- `current_input_file.enabled` / `current_input_file.min_chars`
|
| 794 |
+
- `thinking_injection.enabled` / `thinking_injection.prompt`
|
| 795 |
+
- `model_aliases`
|
| 796 |
+
- `toolcall` 策略已固定,不再作为可写入字段
|
| 797 |
+
|
| 798 |
+
### `POST /admin/settings/password`
|
| 799 |
+
|
| 800 |
+
更新管理密码并使旧 JWT 失效。
|
| 801 |
+
|
| 802 |
+
请求示例:
|
| 803 |
+
|
| 804 |
+
```json
|
| 805 |
+
{"new_password":"your-new-password"}
|
| 806 |
+
```
|
| 807 |
+
|
| 808 |
+
也兼容 `{"password":"your-new-password"}`。
|
| 809 |
+
|
| 810 |
+
### `POST /admin/config/import`
|
| 811 |
+
|
| 812 |
+
导入完整配置,支持:
|
| 813 |
+
|
| 814 |
+
- `mode=merge`(默认)
|
| 815 |
+
- `mode=replace`
|
| 816 |
+
|
| 817 |
+
请求可直接传配置对象,或使用 `{"config": {...}, "mode":"merge"}` 包裹格式。
|
| 818 |
+
也支持在查询参数里传 `?mode=merge` / `?mode=replace`。
|
| 819 |
+
`replace` 模式会按完整配置结构替换(保留 Vercel 同步元信息);`merge` 模式会合并 `keys`、`api_keys`、`accounts`、`model_aliases`,并覆盖 `admin`、`runtime`、`responses`、`embeddings` 中的非空字段。`auto_delete`、`current_input_file` 建议通过 `/admin/settings` 或配置文件管理;`compat` 与 `toolcall` 相关字段会被忽略。
|
| 820 |
+
|
| 821 |
+
> 注意:`merge` 模式不会更新 `auto_delete`、`current_input_file`。
|
| 822 |
+
|
| 823 |
+
### `GET /admin/config/export`
|
| 824 |
+
|
| 825 |
+
导出完整配置,返回 `config`、`json`、`base64` 三种格式。
|
| 826 |
+
|
| 827 |
+
响应示例:
|
| 828 |
+
|
| 829 |
+
|
| 830 |
+
> 注:`_vercel_sync_hash` 和 `_vercel_sync_time` 为内部同步元数据字段,用于 Vercel 配置漂移检测。
|
| 831 |
+
|
| 832 |
+
### `POST /admin/keys`
|
| 833 |
+
|
| 834 |
+
```json
|
| 835 |
+
{"key": "new-api-key", "name": "主 Key", "remark": "生产流量"}
|
| 836 |
+
```
|
| 837 |
+
|
| 838 |
+
**响应**:`{"success": true, "total_keys": 3}`
|
| 839 |
+
|
| 840 |
+
### `PUT /admin/keys/{key}`
|
| 841 |
+
|
| 842 |
+
更新指定 API key 的 `name` / `remark`,路径参数中的 `key` 为只读标识,不可修改。
|
| 843 |
+
|
| 844 |
+
```json
|
| 845 |
+
{"name": "备用 Key", "remark": "压测"}
|
| 846 |
+
```
|
| 847 |
+
|
| 848 |
+
**响应**:`{"success": true, "total_keys": 3}`
|
| 849 |
+
|
| 850 |
+
### `DELETE /admin/keys/{key}`
|
| 851 |
+
|
| 852 |
+
**响应**:`{"success": true, "total_keys": 2}`
|
| 853 |
+
|
| 854 |
+
### `GET /admin/proxies`
|
| 855 |
+
|
| 856 |
+
列出代理配置(密码不回传,仅返回 `has_password` 标记)。
|
| 857 |
+
|
| 858 |
+
### `POST /admin/proxies`
|
| 859 |
+
|
| 860 |
+
新增代理。请求体支持 `id`(可选,未传则自动生成)、`name`、`type`(`http` / `socks5`)、`host`、`port`、`username`、`password`。
|
| 861 |
+
|
| 862 |
+
### `PUT /admin/proxies/{proxyID}`
|
| 863 |
+
|
| 864 |
+
更新指定代理。若请求中 `password` 为空字符串,则保留原密码。
|
| 865 |
+
|
| 866 |
+
### `DELETE /admin/proxies/{proxyID}`
|
| 867 |
+
|
| 868 |
+
删除代理,并自动清空所有引用该代理账号的 `proxy_id`。
|
| 869 |
+
|
| 870 |
+
### `POST /admin/proxies/test`
|
| 871 |
+
|
| 872 |
+
测试代理连通性:传 `proxy_id` 时测试已保存代理;不传时按请求体代理字段做临时连通性测试。
|
| 873 |
+
|
| 874 |
+
### `GET /admin/accounts`
|
| 875 |
+
|
| 876 |
+
**查询参数**:
|
| 877 |
+
|
| 878 |
+
| 参数 | 默认 | 范围 |
|
| 879 |
+
| --- | --- | --- |
|
| 880 |
+
| `page` | `1` | ≥ 1 |
|
| 881 |
+
| `page_size` | `10` | 1–5000 |
|
| 882 |
+
| `q` | 空 | 按 identifier / email / mobile 过滤 |
|
| 883 |
+
|
| 884 |
+
**响应**:
|
| 885 |
+
|
| 886 |
+
```json
|
| 887 |
+
{
|
| 888 |
+
"items": [
|
| 889 |
+
{
|
| 890 |
+
"identifier": "user@example.com",
|
| 891 |
+
"email": "user@example.com",
|
| 892 |
+
"mobile": "",
|
| 893 |
+
"has_password": true,
|
| 894 |
+
"has_token": true,
|
| 895 |
+
"token_preview": "abc...",
|
| 896 |
+
"test_status": "ok"
|
| 897 |
+
}
|
| 898 |
+
],
|
| 899 |
+
"total": 25,
|
| 900 |
+
"page": 1,
|
| 901 |
+
"page_size": 10,
|
| 902 |
+
"total_pages": 3
|
| 903 |
+
}
|
| 904 |
+
```
|
| 905 |
+
|
| 906 |
+
### `POST /admin/accounts`
|
| 907 |
+
|
| 908 |
+
```json
|
| 909 |
+
{"email": "user@example.com", "password": "pwd"}
|
| 910 |
+
```
|
| 911 |
+
|
| 912 |
+
**响应**:`{"success": true, "total_accounts": 6}`
|
| 913 |
+
|
| 914 |
+
### `PUT /admin/accounts/{identifier}`
|
| 915 |
+
|
| 916 |
+
更新指定账号的 `name` / `remark`。路径参数中的 `identifier` 可以是 email 或 mobile,且不可修改。
|
| 917 |
+
|
| 918 |
+
```json
|
| 919 |
+
{"name": "主账号", "remark": "团队共享"}
|
| 920 |
+
```
|
| 921 |
+
|
| 922 |
+
**响应**:`{"success": true, "total_accounts": 6}`
|
| 923 |
+
|
| 924 |
+
### `DELETE /admin/accounts/{identifier}`
|
| 925 |
+
|
| 926 |
+
`identifier` 可为 email、mobile,或 token-only 账号的合成标识(`token:<hash>`)。
|
| 927 |
+
|
| 928 |
+
**响应**:`{"success": true, "total_accounts": 5}`
|
| 929 |
+
|
| 930 |
+
### `PUT /admin/accounts/{identifier}/proxy`
|
| 931 |
+
|
| 932 |
+
更新指定账号绑定代理。
|
| 933 |
+
|
| 934 |
+
- 请求体:`{"proxy_id":"..."}`;
|
| 935 |
+
- `proxy_id` 传空字符串时表示解绑代理;
|
| 936 |
+
- `identifier` 支持 email / mobile / token-only 合成标识。
|
| 937 |
+
|
| 938 |
+
### `GET /admin/queue/status`
|
| 939 |
+
|
| 940 |
+
```json
|
| 941 |
+
{
|
| 942 |
+
"available": 3,
|
| 943 |
+
"in_use": 1,
|
| 944 |
+
"total": 4,
|
| 945 |
+
"available_accounts": ["a@example.com"],
|
| 946 |
+
"in_use_accounts": ["b@example.com"],
|
| 947 |
+
"max_inflight_per_account": 2,
|
| 948 |
+
"global_max_inflight": 8,
|
| 949 |
+
"recommended_concurrency": 8,
|
| 950 |
+
"waiting": 0,
|
| 951 |
+
"max_queue_size": 8
|
| 952 |
+
}
|
| 953 |
+
```
|
| 954 |
+
|
| 955 |
+
| 字段 | 说明 |
|
| 956 |
+
| --- | --- |
|
| 957 |
+
| `available` | 仍有剩余并发槽位的账号数 |
|
| 958 |
+
| `in_use` | 当前已占用的 in-flight 槽位数 |
|
| 959 |
+
| `total` | 总账号数 |
|
| 960 |
+
| `available_accounts` | 仍有剩余并发槽位的账号 ID 列表 |
|
| 961 |
+
| `in_use_accounts` | 当前处于使用中的账号 ID 列表 |
|
| 962 |
+
| `max_inflight_per_account` | 每账号并发上限 |
|
| 963 |
+
| `global_max_inflight` | 全局并发上限 |
|
| 964 |
+
| `recommended_concurrency` | 建议并发值(`total × max_inflight_per_account`) |
|
| 965 |
+
| `waiting` | 当前等待中的请求数 |
|
| 966 |
+
| `max_queue_size` | 等待队列上限 |
|
| 967 |
+
|
| 968 |
+
### `POST /admin/accounts/test`
|
| 969 |
+
|
| 970 |
+
| 字段 | 必填 | 说明 |
|
| 971 |
+
| --- | --- | --- |
|
| 972 |
+
| `identifier` | ✅ | email / mobile / token-only 合成标识 |
|
| 973 |
+
| `model` | ❌ | 默认 `deepseek-v4-flash` |
|
| 974 |
+
| `message` | ❌ | 空字符串时仅测试会话创建 |
|
| 975 |
+
|
| 976 |
+
**响应**:
|
| 977 |
+
|
| 978 |
+
```json
|
| 979 |
+
{
|
| 980 |
+
"account": "user@example.com",
|
| 981 |
+
"success": true,
|
| 982 |
+
"response_time": 1240,
|
| 983 |
+
"message": "API 测试成功(仅会话创建)",
|
| 984 |
+
"model": "deepseek-v4-flash",
|
| 985 |
+
"session_count": 0,
|
| 986 |
+
"config_writable": true,
|
| 987 |
+
"config_warning": ""
|
| 988 |
+
}
|
| 989 |
+
```
|
| 990 |
+
|
| 991 |
+
如果传入 `message`,还会附带 `thinking`(当上游返回思考内容时)。
|
| 992 |
+
|
| 993 |
+
当部署环境配置文件路径不可写(例如容器内默认 `/app/config.json` 只读)时,登录与会话测试仍可继续;此时会返回 `config_warning` 提示 token 仅保存在内存、重启后丢失。
|
| 994 |
+
|
| 995 |
+
### `POST /admin/accounts/test-all`
|
| 996 |
+
|
| 997 |
+
可选请求字段:`model`
|
| 998 |
+
|
| 999 |
+
```json
|
| 1000 |
+
{
|
| 1001 |
+
"total": 5,
|
| 1002 |
+
"success": 4,
|
| 1003 |
+
"failed": 1,
|
| 1004 |
+
"results": [...]
|
| 1005 |
+
}
|
| 1006 |
+
```
|
| 1007 |
+
|
| 1008 |
+
内部并发上限当前固定为 5。
|
| 1009 |
+
|
| 1010 |
+
### `POST /admin/accounts/sessions/delete-all`
|
| 1011 |
+
|
| 1012 |
+
清空指定账号的所有 DeepSeek 会话。请求体示例:
|
| 1013 |
+
|
| 1014 |
+
```json
|
| 1015 |
+
{"identifier":"user@example.com"}
|
| 1016 |
+
```
|
| 1017 |
+
|
| 1018 |
+
响应:
|
| 1019 |
+
|
| 1020 |
+
```json
|
| 1021 |
+
{"success": true, "message": "删除成功"}
|
| 1022 |
+
```
|
| 1023 |
+
|
| 1024 |
+
如果账号不存在或删除失败,`success` 会是 `false`,`message` 会返回错误原因。
|
| 1025 |
+
|
| 1026 |
+
### `POST /admin/import`
|
| 1027 |
+
|
| 1028 |
+
批量导入 keys 与 accounts。
|
| 1029 |
+
|
| 1030 |
+
**请求**:
|
| 1031 |
+
|
| 1032 |
+
```json
|
| 1033 |
+
{
|
| 1034 |
+
"keys": ["k1", "k2"],
|
| 1035 |
+
"accounts": [
|
| 1036 |
+
{"email": "user@example.com", "password": "pwd", "token": ""}
|
| 1037 |
+
]
|
| 1038 |
+
}
|
| 1039 |
+
```
|
| 1040 |
+
|
| 1041 |
+
**响应**:
|
| 1042 |
+
|
| 1043 |
+
```json
|
| 1044 |
+
{
|
| 1045 |
+
"success": true,
|
| 1046 |
+
"imported_keys": 2,
|
| 1047 |
+
"imported_accounts": 1
|
| 1048 |
+
}
|
| 1049 |
+
```
|
| 1050 |
+
|
| 1051 |
+
### `POST /admin/test`
|
| 1052 |
+
|
| 1053 |
+
测试当前 API 可用性(通过自身接口调用)。
|
| 1054 |
+
|
| 1055 |
+
| 字段 | 必填 | 默认值 |
|
| 1056 |
+
| --- | --- | --- |
|
| 1057 |
+
| `model` | ❌ | `deepseek-v4-flash` |
|
| 1058 |
+
| `message` | ❌ | `你好` |
|
| 1059 |
+
| `api_key` | ❌ | 配置中第一个 key |
|
| 1060 |
+
|
| 1061 |
+
**响应**:
|
| 1062 |
+
|
| 1063 |
+
```json
|
| 1064 |
+
{
|
| 1065 |
+
"success": true,
|
| 1066 |
+
"status_code": 200,
|
| 1067 |
+
"response": {"id": "..."}
|
| 1068 |
+
}
|
| 1069 |
+
```
|
| 1070 |
+
|
| 1071 |
+
### `POST /admin/dev/raw-samples/capture`
|
| 1072 |
+
|
| 1073 |
+
直接通过服务自身发起一次 `/v1/chat/completions` 请求,并把请求元信息和上游原始 SSE 保存到 `tests/raw_stream_samples/<sample-id>/`。
|
| 1074 |
+
|
| 1075 |
+
常用请求字段:
|
| 1076 |
+
|
| 1077 |
+
| 字段 | 必填 | 默认值 | 说明 |
|
| 1078 |
+
| --- | --- | --- | --- |
|
| 1079 |
+
| `message` | 否 | `你好` | 便捷单轮用户消息 |
|
| 1080 |
+
| `messages` | 否 | 自动由 `message` 生成 | OpenAI 风格消息数组 |
|
| 1081 |
+
| `model` | 否 | `deepseek-v4-flash` | 目标模型 |
|
| 1082 |
+
| `stream` | 否 | `true` | 建议保留流式,以记录原始 SSE |
|
| 1083 |
+
| `api_key` | 否 | 配置中第一个 key | 调用业务接口使用的 key |
|
| 1084 |
+
| `sample_id` | 否 | 自动生成 | 样本目录名 |
|
| 1085 |
+
|
| 1086 |
+
成功时会在响应头里附带:
|
| 1087 |
+
|
| 1088 |
+
- `X-Ds2-Sample-Id`
|
| 1089 |
+
- `X-Ds2-Sample-Dir`
|
| 1090 |
+
- `X-Ds2-Sample-Meta`
|
| 1091 |
+
- `X-Ds2-Sample-Upstream`
|
| 1092 |
+
|
| 1093 |
+
如果请求本身成功,但当前进程没有记录到新的上游抓包,会返回:
|
| 1094 |
+
|
| 1095 |
+
```json
|
| 1096 |
+
{"detail":"no upstream capture was recorded"}
|
| 1097 |
+
```
|
| 1098 |
+
|
| 1099 |
+
### `GET /admin/dev/raw-samples/query`
|
| 1100 |
+
|
| 1101 |
+
按关键词查询当前进程内存里的抓包记录,并按 `chat_session_id` 归并 `completion + continue` 链。
|
| 1102 |
+
|
| 1103 |
+
**查询参数**:
|
| 1104 |
+
|
| 1105 |
+
| 参数 | 默认值 | 说明 |
|
| 1106 |
+
| --- | --- | --- |
|
| 1107 |
+
| `q` | 空 | 按请求体/响应体关键词模糊匹配 |
|
| 1108 |
+
| `limit` | `20` | 返回链条数上限 |
|
| 1109 |
+
|
| 1110 |
+
**响应字段**包含:
|
| 1111 |
+
|
| 1112 |
+
- `items[].chain_key`
|
| 1113 |
+
- `items[].capture_ids`
|
| 1114 |
+
- `items[].round_count`
|
| 1115 |
+
- `items[].initial_label`
|
| 1116 |
+
- `items[].request_preview`
|
| 1117 |
+
- `items[].response_preview`
|
| 1118 |
+
|
| 1119 |
+
### `POST /admin/dev/raw-samples/save`
|
| 1120 |
+
|
| 1121 |
+
把当前内存中的某条抓包链落盘为 `tests/raw_stream_samples/<sample-id>/`。
|
| 1122 |
+
|
| 1123 |
+
支持���下任一种选中方式:
|
| 1124 |
+
|
| 1125 |
+
```json
|
| 1126 |
+
{"chain_key":"session:xxxx","sample_id":"tmp-from-memory"}
|
| 1127 |
+
```
|
| 1128 |
+
|
| 1129 |
+
```json
|
| 1130 |
+
{"capture_id":"cap_xxx","sample_id":"tmp-from-memory"}
|
| 1131 |
+
```
|
| 1132 |
+
|
| 1133 |
+
```json
|
| 1134 |
+
{"query":"广州天气","sample_id":"tmp-from-memory"}
|
| 1135 |
+
```
|
| 1136 |
+
|
| 1137 |
+
成功响应会返回 `sample_id`、`dir`、`meta_path`、`upstream_path`。
|
| 1138 |
+
|
| 1139 |
+
### `POST /admin/vercel/sync`
|
| 1140 |
+
|
| 1141 |
+
| 字段 | 必填 | 说明 |
|
| 1142 |
+
| --- | --- | --- |
|
| 1143 |
+
| `vercel_token` | ❌ | 空或 `__USE_PRECONFIG__` 则读环境变量,再回退到已保存配置 |
|
| 1144 |
+
| `project_id` | ❌ | 空则读 `VERCEL_PROJECT_ID`,再回退到已保存配置 |
|
| 1145 |
+
| `team_id` | ❌ | 空则读 `VERCEL_TEAM_ID`,再回退到已保存配置 |
|
| 1146 |
+
| `auto_validate` | ❌ | 默认 `true` |
|
| 1147 |
+
| `save_credentials` | ❌ | 默认 `true`;保存本次显式填写的 Vercel 凭据,供下次同步复用 |
|
| 1148 |
+
| `config_override` | ❌ | 传入完整配置对象,覆盖当前内存配置用于同步 |
|
| 1149 |
+
|
| 1150 |
+
**成功响应**:
|
| 1151 |
+
|
| 1152 |
+
```json
|
| 1153 |
+
{
|
| 1154 |
+
"success": true,
|
| 1155 |
+
"validated_accounts": 3,
|
| 1156 |
+
"message": "配置已同步,正在重新部署...",
|
| 1157 |
+
"deployment_url": "https://..."
|
| 1158 |
+
}
|
| 1159 |
+
```
|
| 1160 |
+
|
| 1161 |
+
或需要手动部署:
|
| 1162 |
+
|
| 1163 |
+
```json
|
| 1164 |
+
{
|
| 1165 |
+
"success": true,
|
| 1166 |
+
"validated_accounts": 3,
|
| 1167 |
+
"message": "配置已同步到 Vercel,请手动触发重新部署",
|
| 1168 |
+
"manual_deploy_required": true
|
| 1169 |
+
}
|
| 1170 |
+
```
|
| 1171 |
+
|
| 1172 |
+
失败校验的账号会通过 `failed_accounts` 返回;成功保存到 Vercel 的凭据会通过 `saved_credentials` 返回。
|
| 1173 |
+
|
| 1174 |
+
### `GET /admin/vercel/status`
|
| 1175 |
+
|
| 1176 |
+
也支持 `POST /admin/vercel/status`,可提交 `config_override` 用于比对草稿是否与已同步配置一致。
|
| 1177 |
+
|
| 1178 |
+
```json
|
| 1179 |
+
{
|
| 1180 |
+
"synced": true,
|
| 1181 |
+
"last_sync_time": 1738400000,
|
| 1182 |
+
"has_synced_before": true,
|
| 1183 |
+
"env_backed": false,
|
| 1184 |
+
"config_hash": "....",
|
| 1185 |
+
"last_synced_hash": "....",
|
| 1186 |
+
"draft_hash": "....",
|
| 1187 |
+
"draft_differs": false
|
| 1188 |
+
}
|
| 1189 |
+
```
|
| 1190 |
+
|
| 1191 |
+
`POST /admin/vercel/status` 还可以携带 `config_override`,用于对比“草稿配置”和当前已同步配置。
|
| 1192 |
+
|
| 1193 |
+
### `GET /admin/export`
|
| 1194 |
+
|
| 1195 |
+
```json
|
| 1196 |
+
{
|
| 1197 |
+
"json": "{...}",
|
| 1198 |
+
"base64": "ey4uLn0="
|
| 1199 |
+
}
|
| 1200 |
+
```
|
| 1201 |
+
|
| 1202 |
+
该接口与 `GET /admin/config/export` 返回相同内容,只是路径更短。
|
| 1203 |
+
|
| 1204 |
+
### `GET /admin/version`
|
| 1205 |
+
|
| 1206 |
+
查询当前构建版本与 GitHub 最新 Release:
|
| 1207 |
+
|
| 1208 |
+
```json
|
| 1209 |
+
{
|
| 1210 |
+
"success": true,
|
| 1211 |
+
"current_version": "3.0.0",
|
| 1212 |
+
"current_tag": "v3.0.0",
|
| 1213 |
+
"source": "file:VERSION",
|
| 1214 |
+
"checked_at": "2026-03-29T00:00:00Z",
|
| 1215 |
+
"latest_tag": "v3.0.0",
|
| 1216 |
+
"latest_version": "3.0.0",
|
| 1217 |
+
"release_url": "https://github.com/CJackHwang/ds2api/releases/tag/v3.0.0",
|
| 1218 |
+
"published_at": "2026-03-28T12:00:00Z",
|
| 1219 |
+
"has_update": false
|
| 1220 |
+
}
|
| 1221 |
+
```
|
| 1222 |
+
|
| 1223 |
+
如果 GitHub API 不可用,响应里会额外包含 `check_error`,但 HTTP 状态仍为 200。
|
| 1224 |
+
|
| 1225 |
+
### `GET /admin/dev/captures`
|
| 1226 |
+
|
| 1227 |
+
查看本地抓包状态与最近记录(需 Admin 鉴权):
|
| 1228 |
+
|
| 1229 |
+
- `enabled`
|
| 1230 |
+
- `limit`
|
| 1231 |
+
- `max_body_bytes`
|
| 1232 |
+
- `items`
|
| 1233 |
+
|
| 1234 |
+
### `DELETE /admin/dev/captures`
|
| 1235 |
+
|
| 1236 |
+
清空抓包记录,返回:
|
| 1237 |
+
|
| 1238 |
+
```json
|
| 1239 |
+
{"success":true,"detail":"capture logs cleared"}
|
| 1240 |
+
```
|
| 1241 |
+
|
| 1242 |
+
---
|
| 1243 |
+
|
| 1244 |
+
## 错误响应格式
|
| 1245 |
+
|
| 1246 |
+
兼容路由(`/v1/*`、`/anthropic/*`)统一使用以下结构:
|
| 1247 |
+
|
| 1248 |
+
```json
|
| 1249 |
+
{
|
| 1250 |
+
"error": {
|
| 1251 |
+
"message": "...",
|
| 1252 |
+
"type": "invalid_request_error",
|
| 1253 |
+
"code": "invalid_request",
|
| 1254 |
+
"param": null
|
| 1255 |
+
}
|
| 1256 |
+
}
|
| 1257 |
+
```
|
| 1258 |
+
|
| 1259 |
+
Admin 接口保持 `{"detail":"..."}`。
|
| 1260 |
+
|
| 1261 |
+
Gemini 路由使用 Google 风格错误结构:
|
| 1262 |
+
|
| 1263 |
+
```json
|
| 1264 |
+
{
|
| 1265 |
+
"error": {
|
| 1266 |
+
"code": 400,
|
| 1267 |
+
"message": "invalid json",
|
| 1268 |
+
"status": "INVALID_ARGUMENT"
|
| 1269 |
+
}
|
| 1270 |
+
}
|
| 1271 |
+
```
|
| 1272 |
+
|
| 1273 |
+
建议客户端处理逻辑:检查 HTTP 状态码 + 解析 `error` 或 `detail` 字段。
|
| 1274 |
+
|
| 1275 |
+
**常见状态码**:
|
| 1276 |
+
|
| 1277 |
+
| 状态码 | 说明 |
|
| 1278 |
+
| --- | --- |
|
| 1279 |
+
| `401` | 鉴权失败(key/token 无效,或 Admin JWT 过期) |
|
| 1280 |
+
| `429` | 请求过多(超出并发上限 + 等待队列,或上游账号 thinking-only 后仍无可见输出;托管账号模式会先尝试一次切号 fresh retry;当前不附带 `Retry-After` 头) |
|
| 1281 |
+
| `503` | 模型不可用或上游服务异常 |
|
| 1282 |
+
|
| 1283 |
+
---
|
| 1284 |
+
|
| 1285 |
+
## cURL 示例
|
| 1286 |
+
|
| 1287 |
+
### OpenAI 非流式
|
| 1288 |
+
|
| 1289 |
+
```bash
|
| 1290 |
+
curl http://localhost:5001/v1/chat/completions \
|
| 1291 |
+
-H "Authorization: Bearer your-api-key" \
|
| 1292 |
+
-H "Content-Type: application/json" \
|
| 1293 |
+
-d '{
|
| 1294 |
+
"model": "deepseek-v4-flash",
|
| 1295 |
+
"messages": [{"role": "user", "content": "你好"}],
|
| 1296 |
+
"stream": false
|
| 1297 |
+
}'
|
| 1298 |
+
```
|
| 1299 |
+
|
| 1300 |
+
### OpenAI 流式
|
| 1301 |
+
|
| 1302 |
+
```bash
|
| 1303 |
+
curl http://localhost:5001/v1/chat/completions \
|
| 1304 |
+
-H "Authorization: Bearer your-api-key" \
|
| 1305 |
+
-H "Content-Type: application/json" \
|
| 1306 |
+
-d '{
|
| 1307 |
+
"model": "deepseek-v4-pro",
|
| 1308 |
+
"messages": [{"role": "user", "content": "解释一下量子纠缠"}],
|
| 1309 |
+
"stream": true
|
| 1310 |
+
}'
|
| 1311 |
+
```
|
| 1312 |
+
|
| 1313 |
+
### OpenAI Responses(流式)
|
| 1314 |
+
|
| 1315 |
+
```bash
|
| 1316 |
+
curl http://localhost:5001/v1/responses \
|
| 1317 |
+
-H "Authorization: Bearer your-api-key" \
|
| 1318 |
+
-H "Content-Type: application/json" \
|
| 1319 |
+
-d '{
|
| 1320 |
+
"model": "gpt-5.3-codex",
|
| 1321 |
+
"input": "写一个 golang 的 hello world",
|
| 1322 |
+
"stream": true
|
| 1323 |
+
}'
|
| 1324 |
+
```
|
| 1325 |
+
|
| 1326 |
+
### OpenAI Embeddings
|
| 1327 |
+
|
| 1328 |
+
```bash
|
| 1329 |
+
curl http://localhost:5001/v1/embeddings \
|
| 1330 |
+
-H "Authorization: Bearer your-api-key" \
|
| 1331 |
+
-H "Content-Type: application/json" \
|
| 1332 |
+
-d '{
|
| 1333 |
+
"model": "gpt-4o",
|
| 1334 |
+
"input": ["第一段文本", "第二段文本"]
|
| 1335 |
+
}'
|
| 1336 |
+
```
|
| 1337 |
+
|
| 1338 |
+
### OpenAI 带搜索
|
| 1339 |
+
|
| 1340 |
+
```bash
|
| 1341 |
+
curl http://localhost:5001/v1/chat/completions \
|
| 1342 |
+
-H "Authorization: Bearer your-api-key" \
|
| 1343 |
+
-H "Content-Type: application/json" \
|
| 1344 |
+
-d '{
|
| 1345 |
+
"model": "deepseek-v4-flash-search",
|
| 1346 |
+
"messages": [{"role": "user", "content": "今天的新闻"}],
|
| 1347 |
+
"stream": true
|
| 1348 |
+
}'
|
| 1349 |
+
```
|
| 1350 |
+
|
| 1351 |
+
### OpenAI Tool Calling
|
| 1352 |
+
|
| 1353 |
+
```bash
|
| 1354 |
+
curl http://localhost:5001/v1/chat/completions \
|
| 1355 |
+
-H "Authorization: Bearer your-api-key" \
|
| 1356 |
+
-H "Content-Type: application/json" \
|
| 1357 |
+
-d '{
|
| 1358 |
+
"model": "deepseek-v4-flash",
|
| 1359 |
+
"messages": [{"role": "user", "content": "北京今天天气怎么样?"}],
|
| 1360 |
+
"tools": [
|
| 1361 |
+
{
|
| 1362 |
+
"type": "function",
|
| 1363 |
+
"function": {
|
| 1364 |
+
"name": "get_weather",
|
| 1365 |
+
"description": "获取指定城市的天气",
|
| 1366 |
+
"parameters": {
|
| 1367 |
+
"type": "object",
|
| 1368 |
+
"properties": {
|
| 1369 |
+
"city": {"type": "string", "description": "城市名"}
|
| 1370 |
+
},
|
| 1371 |
+
"required": ["city"]
|
| 1372 |
+
}
|
| 1373 |
+
}
|
| 1374 |
+
}
|
| 1375 |
+
]
|
| 1376 |
+
}'
|
| 1377 |
+
```
|
| 1378 |
+
|
| 1379 |
+
### Gemini 非流式
|
| 1380 |
+
|
| 1381 |
+
```bash
|
| 1382 |
+
curl "http://localhost:5001/v1beta/models/gemini-2.5-pro:generateContent" \
|
| 1383 |
+
-H "Authorization: Bearer your-api-key" \
|
| 1384 |
+
-H "Content-Type: application/json" \
|
| 1385 |
+
-d '{
|
| 1386 |
+
"contents": [
|
| 1387 |
+
{
|
| 1388 |
+
"role": "user",
|
| 1389 |
+
"parts": [{"text": "用三句话介绍 Go 语言"}]
|
| 1390 |
+
}
|
| 1391 |
+
]
|
| 1392 |
+
}'
|
| 1393 |
+
```
|
| 1394 |
+
|
| 1395 |
+
### Gemini 流式
|
| 1396 |
+
|
| 1397 |
+
```bash
|
| 1398 |
+
curl "http://localhost:5001/v1beta/models/gemini-2.5-flash:streamGenerateContent" \
|
| 1399 |
+
-H "Authorization: Bearer your-api-key" \
|
| 1400 |
+
-H "Content-Type: application/json" \
|
| 1401 |
+
-d '{
|
| 1402 |
+
"contents": [
|
| 1403 |
+
{
|
| 1404 |
+
"role": "user",
|
| 1405 |
+
"parts": [{"text": "写一个简短摘要"}]
|
| 1406 |
+
}
|
| 1407 |
+
]
|
| 1408 |
+
}'
|
| 1409 |
+
```
|
| 1410 |
+
|
| 1411 |
+
### Claude 非流式
|
| 1412 |
+
|
| 1413 |
+
```bash
|
| 1414 |
+
curl http://localhost:5001/anthropic/v1/messages \
|
| 1415 |
+
-H "x-api-key: your-api-key" \
|
| 1416 |
+
-H "Content-Type: application/json" \
|
| 1417 |
+
-H "anthropic-version: 2023-06-01" \
|
| 1418 |
+
-d '{
|
| 1419 |
+
"model": "claude-sonnet-4-6",
|
| 1420 |
+
"max_tokens": 1024,
|
| 1421 |
+
"messages": [{"role": "user", "content": "你好"}]
|
| 1422 |
+
}'
|
| 1423 |
+
```
|
| 1424 |
+
|
| 1425 |
+
### Claude 流式
|
| 1426 |
+
|
| 1427 |
+
```bash
|
| 1428 |
+
curl http://localhost:5001/anthropic/v1/messages \
|
| 1429 |
+
-H "x-api-key: your-api-key" \
|
| 1430 |
+
-H "Content-Type: application/json" \
|
| 1431 |
+
-H "anthropic-version: 2023-06-01" \
|
| 1432 |
+
-d '{
|
| 1433 |
+
"model": "claude-opus-4-6",
|
| 1434 |
+
"max_tokens": 1024,
|
| 1435 |
+
"messages": [{"role": "user", "content": "解释相对论"}],
|
| 1436 |
+
"stream": true
|
| 1437 |
+
}'
|
| 1438 |
+
```
|
| 1439 |
+
|
| 1440 |
+
### Admin 登录
|
| 1441 |
+
|
| 1442 |
+
```bash
|
| 1443 |
+
curl http://localhost:5001/admin/login \
|
| 1444 |
+
-H "Content-Type: application/json" \
|
| 1445 |
+
-d '{"admin_key": "admin"}'
|
| 1446 |
+
```
|
| 1447 |
+
|
| 1448 |
+
### 指定账号请求
|
| 1449 |
+
|
| 1450 |
+
```bash
|
| 1451 |
+
curl http://localhost:5001/v1/chat/completions \
|
| 1452 |
+
-H "Authorization: Bearer your-api-key" \
|
| 1453 |
+
-H "X-Ds2-Target-Account: user@example.com" \
|
| 1454 |
+
-H "Content-Type: application/json" \
|
| 1455 |
+
-d '{
|
| 1456 |
+
"model": "deepseek-v4-flash",
|
| 1457 |
+
"messages": [{"role": "user", "content": "你好"}]
|
| 1458 |
+
}'
|
| 1459 |
+
```
|
CODE_OF_CONDUCT.md
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Contributor Covenant Code of Conduct
|
| 2 |
+
|
| 3 |
+
## Our Pledge
|
| 4 |
+
|
| 5 |
+
We as members, contributors, and leaders pledge to make participation in our
|
| 6 |
+
community a harassment-free experience for everyone, regardless of age, body
|
| 7 |
+
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
| 8 |
+
identity and expression, level of experience, education, socio-economic status,
|
| 9 |
+
nationality, personal appearance, race, religion, or sexual identity
|
| 10 |
+
and orientation.
|
| 11 |
+
|
| 12 |
+
We pledge to act and interact in ways that contribute to an open, welcoming,
|
| 13 |
+
diverse, inclusive, and healthy community.
|
| 14 |
+
|
| 15 |
+
## Our Standards
|
| 16 |
+
|
| 17 |
+
Examples of behavior that contributes to a positive environment for our
|
| 18 |
+
community include:
|
| 19 |
+
|
| 20 |
+
* Demonstrating empathy and kindness toward other people
|
| 21 |
+
* Being respectful of differing opinions, viewpoints, and experiences
|
| 22 |
+
* Giving and gracefully accepting constructive feedback
|
| 23 |
+
* Accepting responsibility and apologizing to those affected by our mistakes,
|
| 24 |
+
and learning from the experience
|
| 25 |
+
* Focusing on what is best not just for us as individuals, but for the
|
| 26 |
+
overall community
|
| 27 |
+
|
| 28 |
+
Examples of unacceptable behavior include:
|
| 29 |
+
|
| 30 |
+
* The use of sexualized language or imagery, and sexual attention or
|
| 31 |
+
advances of any kind
|
| 32 |
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
| 33 |
+
* Public or private harassment
|
| 34 |
+
* Publishing others' private information, such as a physical or email
|
| 35 |
+
address, without their explicit permission
|
| 36 |
+
* Other conduct which could reasonably be considered inappropriate in a
|
| 37 |
+
professional setting
|
| 38 |
+
|
| 39 |
+
## Enforcement Responsibilities
|
| 40 |
+
|
| 41 |
+
Community leaders are responsible for clarifying and enforcing our standards of
|
| 42 |
+
acceptable behavior and will take appropriate and fair corrective action in
|
| 43 |
+
response to any behavior that they deem inappropriate, threatening, offensive,
|
| 44 |
+
or harmful.
|
| 45 |
+
|
| 46 |
+
Community leaders have the right and responsibility to remove, edit, or reject
|
| 47 |
+
comments, commits, code, wiki edits, issues, and other contributions that are
|
| 48 |
+
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
| 49 |
+
decisions when appropriate.
|
| 50 |
+
|
| 51 |
+
## Scope
|
| 52 |
+
|
| 53 |
+
This Code of Conduct applies within all community spaces, and also applies when
|
| 54 |
+
an individual is officially representing the community in public spaces.
|
| 55 |
+
Examples of representing our community include using an official e-mail address,
|
| 56 |
+
posting via an official social media account, or acting as an appointed
|
| 57 |
+
representative at an online or offline event.
|
| 58 |
+
|
| 59 |
+
## Enforcement
|
| 60 |
+
|
| 61 |
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
| 62 |
+
reported to the community leaders responsible for enforcement at
|
| 63 |
+
cjackhwang@qq.com.
|
| 64 |
+
All complaints will be reviewed and investigated promptly and fairly.
|
| 65 |
+
|
| 66 |
+
All community leaders are obligated to respect the privacy and security of the
|
| 67 |
+
reporter of any incident.
|
| 68 |
+
|
| 69 |
+
## Enforcement Guidelines
|
| 70 |
+
|
| 71 |
+
Community leaders will follow these Community Impact Guidelines in determining
|
| 72 |
+
the consequences for any action they deem in violation of this Code of Conduct:
|
| 73 |
+
|
| 74 |
+
### 1. Correction
|
| 75 |
+
|
| 76 |
+
**Community Impact**: Use of inappropriate language or other behavior deemed
|
| 77 |
+
unprofessional or unwelcome in the community.
|
| 78 |
+
|
| 79 |
+
**Consequence**: A private, written warning from community leaders, providing
|
| 80 |
+
clarity around the nature of the violation and an explanation of why the
|
| 81 |
+
behavior was inappropriate. A public apology may be requested.
|
| 82 |
+
|
| 83 |
+
### 2. Warning
|
| 84 |
+
|
| 85 |
+
**Community Impact**: A violation through a single incident or series
|
| 86 |
+
of actions.
|
| 87 |
+
|
| 88 |
+
**Consequence**: A warning with consequences for continued behavior. No
|
| 89 |
+
interaction with the people involved, including unsolicited interaction with
|
| 90 |
+
those enforcing the Code of Conduct, for a specified period of time. This
|
| 91 |
+
includes avoiding interactions in community spaces as well as external channels
|
| 92 |
+
like social media. Violating these terms may lead to a temporary or
|
| 93 |
+
permanent ban.
|
| 94 |
+
|
| 95 |
+
### 3. Temporary Ban
|
| 96 |
+
|
| 97 |
+
**Community Impact**: A serious violation of community standards, including
|
| 98 |
+
sustained inappropriate behavior.
|
| 99 |
+
|
| 100 |
+
**Consequence**: A temporary ban from any sort of interaction or public
|
| 101 |
+
communication with the community for a specified period of time. No public or
|
| 102 |
+
private interaction with the people involved, including unsolicited interaction
|
| 103 |
+
with those enforcing the Code of Conduct, is allowed during this period.
|
| 104 |
+
Violating these terms may lead to a permanent ban.
|
| 105 |
+
|
| 106 |
+
### 4. Permanent Ban
|
| 107 |
+
|
| 108 |
+
**Community Impact**: Demonstrating a pattern of violation of community
|
| 109 |
+
standards, including sustained inappropriate behavior, harassment of an
|
| 110 |
+
individual, or aggression toward or disparagement of classes of individuals.
|
| 111 |
+
|
| 112 |
+
**Consequence**: A permanent ban from any sort of public interaction within
|
| 113 |
+
the community.
|
| 114 |
+
|
| 115 |
+
## Attribution
|
| 116 |
+
|
| 117 |
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
| 118 |
+
version 2.0, available at
|
| 119 |
+
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
| 120 |
+
|
| 121 |
+
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
| 122 |
+
enforcement ladder](https://github.com/mozilla/diversity).
|
| 123 |
+
|
| 124 |
+
[homepage]: https://www.contributor-covenant.org
|
| 125 |
+
|
| 126 |
+
For answers to common questions about this code of conduct, see the FAQ at
|
| 127 |
+
https://www.contributor-covenant.org/faq. Translations are available at
|
| 128 |
+
https://www.contributor-covenant.org/translations.
|
Dockerfile
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM node:24 AS webui-builder
|
| 2 |
+
|
| 3 |
+
WORKDIR /app/webui
|
| 4 |
+
COPY webui/package.json webui/package-lock.json ./
|
| 5 |
+
RUN npm ci
|
| 6 |
+
COPY config.example.json /app/config.example.json
|
| 7 |
+
COPY webui ./
|
| 8 |
+
RUN npm run build
|
| 9 |
+
|
| 10 |
+
FROM golang:1.26 AS go-builder
|
| 11 |
+
WORKDIR /app
|
| 12 |
+
ARG TARGETOS
|
| 13 |
+
ARG TARGETARCH
|
| 14 |
+
ARG BUILD_VERSION
|
| 15 |
+
COPY go.mod go.sum* ./
|
| 16 |
+
RUN go mod download
|
| 17 |
+
COPY . .
|
| 18 |
+
RUN set -eux; \
|
| 19 |
+
GOOS="${TARGETOS:-$(go env GOOS)}"; \
|
| 20 |
+
GOARCH="${TARGETARCH:-$(go env GOARCH)}"; \
|
| 21 |
+
BUILD_VERSION_RESOLVED="${BUILD_VERSION:-}"; \
|
| 22 |
+
if [ -z "${BUILD_VERSION_RESOLVED}" ] && [ -f VERSION ]; then BUILD_VERSION_RESOLVED="$(cat VERSION | tr -d "[:space:]")"; fi; \
|
| 23 |
+
CGO_ENABLED=0 GOOS="${GOOS}" GOARCH="${GOARCH}" go build -buildvcs=false -ldflags="-s -w -X ds2api/internal/version.BuildVersion=${BUILD_VERSION_RESOLVED}" -o /out/ds2api ./cmd/ds2api
|
| 24 |
+
|
| 25 |
+
FROM busybox:1.36.1-musl AS busybox-tools
|
| 26 |
+
|
| 27 |
+
FROM debian:bookworm-slim AS runtime-base
|
| 28 |
+
WORKDIR /app
|
| 29 |
+
RUN apt-get update \
|
| 30 |
+
&& apt-get install -y --no-install-recommends ca-certificates gosu \
|
| 31 |
+
&& groupadd -r ds2api && useradd -r -g ds2api -d /app -s /sbin/nologin ds2api \
|
| 32 |
+
&& mkdir -p /app/data /data && chown -R ds2api:ds2api /app /data \
|
| 33 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 34 |
+
COPY --from=busybox-tools /bin/busybox /usr/local/bin/busybox
|
| 35 |
+
EXPOSE 7860
|
| 36 |
+
ENV PORT=7860
|
| 37 |
+
ENV DS2API_CONFIG_PATH=/data/config.json
|
| 38 |
+
ENV DS2API_CHAT_HISTORY_PATH=/data/chat_history.json
|
| 39 |
+
COPY entrypoint.sh /usr/local/bin/entrypoint.sh
|
| 40 |
+
RUN chmod +x /usr/local/bin/entrypoint.sh
|
| 41 |
+
CMD ["/usr/local/bin/entrypoint.sh"]
|
| 42 |
+
|
| 43 |
+
FROM runtime-base AS runtime-from-source
|
| 44 |
+
COPY --from=go-builder /out/ds2api /usr/local/bin/ds2api
|
| 45 |
+
|
| 46 |
+
COPY --from=go-builder --chown=ds2api:ds2api /app/config.example.json /app/config.example.json
|
| 47 |
+
COPY --from=webui-builder --chown=ds2api:ds2api /app/static/admin /app/static/admin
|
| 48 |
+
|
| 49 |
+
FROM busybox-tools AS dist-extract
|
| 50 |
+
ARG TARGETARCH
|
| 51 |
+
COPY dist/docker-input/linux_amd64.tar.gz /tmp/ds2api_linux_amd64.tar.gz
|
| 52 |
+
COPY dist/docker-input/linux_arm64.tar.gz /tmp/ds2api_linux_arm64.tar.gz
|
| 53 |
+
RUN set -eux; \
|
| 54 |
+
case "${TARGETARCH}" in \
|
| 55 |
+
amd64) ARCHIVE="/tmp/ds2api_linux_amd64.tar.gz" ;; \
|
| 56 |
+
arm64) ARCHIVE="/tmp/ds2api_linux_arm64.tar.gz" ;; \
|
| 57 |
+
*) echo "unsupported TARGETARCH: ${TARGETARCH}" >&2; exit 1 ;; \
|
| 58 |
+
esac; \
|
| 59 |
+
tar -xzf "${ARCHIVE}" -C /tmp; \
|
| 60 |
+
PKG_DIR="$(find /tmp -maxdepth 1 -type d -name "ds2api_*_linux_${TARGETARCH}" | head -n1)"; \
|
| 61 |
+
test -n "${PKG_DIR}"; \
|
| 62 |
+
mkdir -p /out/static; \
|
| 63 |
+
cp "${PKG_DIR}/ds2api" /out/ds2api; \
|
| 64 |
+
cp "${PKG_DIR}/config.example.json" /out/config.example.json; \
|
| 65 |
+
cp -R "${PKG_DIR}/static/admin" /out/static/admin
|
| 66 |
+
|
| 67 |
+
FROM runtime-base AS runtime-from-dist
|
| 68 |
+
COPY --from=dist-extract /out/ds2api /usr/local/bin/ds2api
|
| 69 |
+
|
| 70 |
+
COPY --from=dist-extract --chown=ds2api:ds2api /out/config.example.json /app/config.example.json
|
| 71 |
+
COPY --from=dist-extract --chown=ds2api:ds2api /out/static/admin /app/static/admin
|
| 72 |
+
|
| 73 |
+
FROM runtime-from-source AS final
|
LICENSE
ADDED
|
@@ -0,0 +1,661 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
GNU AFFERO GENERAL PUBLIC LICENSE
|
| 2 |
+
Version 3, 19 November 2007
|
| 3 |
+
|
| 4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
| 5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
| 6 |
+
of this license document, but changing it is not allowed.
|
| 7 |
+
|
| 8 |
+
Preamble
|
| 9 |
+
|
| 10 |
+
The GNU Affero General Public License is a free, copyleft license for
|
| 11 |
+
software and other kinds of works, specifically designed to ensure
|
| 12 |
+
cooperation with the community in the case of network server software.
|
| 13 |
+
|
| 14 |
+
The licenses for most software and other practical works are designed
|
| 15 |
+
to take away your freedom to share and change the works. By contrast,
|
| 16 |
+
our General Public Licenses are intended to guarantee your freedom to
|
| 17 |
+
share and change all versions of a program--to make sure it remains free
|
| 18 |
+
software for all its users.
|
| 19 |
+
|
| 20 |
+
When we speak of free software, we are referring to freedom, not
|
| 21 |
+
price. Our General Public Licenses are designed to make sure that you
|
| 22 |
+
have the freedom to distribute copies of free software (and charge for
|
| 23 |
+
them if you wish), that you receive source code or can get it if you
|
| 24 |
+
want it, that you can change the software or use pieces of it in new
|
| 25 |
+
free programs, and that you know you can do these things.
|
| 26 |
+
|
| 27 |
+
Developers that use our General Public Licenses protect your rights
|
| 28 |
+
with two steps: (1) assert copyright on the software, and (2) offer
|
| 29 |
+
you this License which gives you legal permission to copy, distribute
|
| 30 |
+
and/or modify the software.
|
| 31 |
+
|
| 32 |
+
A secondary benefit of defending all users' freedom is that
|
| 33 |
+
improvements made in alternate versions of the program, if they
|
| 34 |
+
receive widespread use, become available for other developers to
|
| 35 |
+
incorporate. Many developers of free software are heartened and
|
| 36 |
+
encouraged by the resulting cooperation. However, in the case of
|
| 37 |
+
software used on network servers, this result may fail to come about.
|
| 38 |
+
The GNU General Public License permits making a modified version and
|
| 39 |
+
letting the public access it on a server without ever releasing its
|
| 40 |
+
source code to the public.
|
| 41 |
+
|
| 42 |
+
The GNU Affero General Public License is designed specifically to
|
| 43 |
+
ensure that, in such cases, the modified source code becomes available
|
| 44 |
+
to the community. It requires the operator of a network server to
|
| 45 |
+
provide the source code of the modified version running there to the
|
| 46 |
+
users of that server. Therefore, public use of a modified version, on
|
| 47 |
+
a publicly accessible server, gives the public access to the source
|
| 48 |
+
code of the modified version.
|
| 49 |
+
|
| 50 |
+
An older license, called the Affero General Public License and
|
| 51 |
+
published by Affero, was designed to accomplish similar goals. This is
|
| 52 |
+
a different license, not a version of the Affero GPL, but Affero has
|
| 53 |
+
released a new version of the Affero GPL which permits relicensing under
|
| 54 |
+
this license.
|
| 55 |
+
|
| 56 |
+
The precise terms and conditions for copying, distribution and
|
| 57 |
+
modification follow.
|
| 58 |
+
|
| 59 |
+
TERMS AND CONDITIONS
|
| 60 |
+
|
| 61 |
+
0. Definitions.
|
| 62 |
+
|
| 63 |
+
"This License" refers to version 3 of the GNU Affero General Public License.
|
| 64 |
+
|
| 65 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
| 66 |
+
works, such as semiconductor masks.
|
| 67 |
+
|
| 68 |
+
"The Program" refers to any copyrightable work licensed under this
|
| 69 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
| 70 |
+
"recipients" may be individuals or organizations.
|
| 71 |
+
|
| 72 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
| 73 |
+
in a fashion requiring copyright permission, other than the making of an
|
| 74 |
+
exact copy. The resulting work is called a "modified version" of the
|
| 75 |
+
earlier work or a work "based on" the earlier work.
|
| 76 |
+
|
| 77 |
+
A "covered work" means either the unmodified Program or a work based
|
| 78 |
+
on the Program.
|
| 79 |
+
|
| 80 |
+
To "propagate" a work means to do anything with it that, without
|
| 81 |
+
permission, would make you directly or secondarily liable for
|
| 82 |
+
infringement under applicable copyright law, except executing it on a
|
| 83 |
+
computer or modifying a private copy. Propagation includes copying,
|
| 84 |
+
distribution (with or without modification), making available to the
|
| 85 |
+
public, and in some countries other activities as well.
|
| 86 |
+
|
| 87 |
+
To "convey" a work means any kind of propagation that enables other
|
| 88 |
+
parties to make or receive copies. Mere interaction with a user through
|
| 89 |
+
a computer network, with no transfer of a copy, is not conveying.
|
| 90 |
+
|
| 91 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
| 92 |
+
to the extent that it includes a convenient and prominently visible
|
| 93 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
| 94 |
+
tells the user that there is no warranty for the work (except to the
|
| 95 |
+
extent that warranties are provided), that licensees may convey the
|
| 96 |
+
work under this License, and how to view a copy of this License. If
|
| 97 |
+
the interface presents a list of user commands or options, such as a
|
| 98 |
+
menu, a prominent item in the list meets this criterion.
|
| 99 |
+
|
| 100 |
+
1. Source Code.
|
| 101 |
+
|
| 102 |
+
The "source code" for a work means the preferred form of the work
|
| 103 |
+
for making modifications to it. "Object code" means any non-source
|
| 104 |
+
form of a work.
|
| 105 |
+
|
| 106 |
+
A "Standard Interface" means an interface that either is an official
|
| 107 |
+
standard defined by a recognized standards body, or, in the case of
|
| 108 |
+
interfaces specified for a particular programming language, one that
|
| 109 |
+
is widely used among developers working in that language.
|
| 110 |
+
|
| 111 |
+
The "System Libraries" of an executable work include anything, other
|
| 112 |
+
than the work as a whole, that (a) is included in the normal form of
|
| 113 |
+
packaging a Major Component, but which is not part of that Major
|
| 114 |
+
Component, and (b) serves only to enable use of the work with that
|
| 115 |
+
Major Component, or to implement a Standard Interface for which an
|
| 116 |
+
implementation is available to the public in source code form. A
|
| 117 |
+
"Major Component", in this context, means a major essential component
|
| 118 |
+
(kernel, window system, and so on) of the specific operating system
|
| 119 |
+
(if any) on which the executable work runs, or a compiler used to
|
| 120 |
+
produce the work, or an object code interpreter used to run it.
|
| 121 |
+
|
| 122 |
+
The "Corresponding Source" for a work in object code form means all
|
| 123 |
+
the source code needed to generate, install, and (for an executable
|
| 124 |
+
work) run the object code and to modify the work, including scripts to
|
| 125 |
+
control those activities. However, it does not include the work's
|
| 126 |
+
System Libraries, or general-purpose tools or generally available free
|
| 127 |
+
programs which are used unmodified in performing those activities but
|
| 128 |
+
which are not part of the work. For example, Corresponding Source
|
| 129 |
+
includes interface definition files associated with source files for
|
| 130 |
+
the work, and the source code for shared libraries and dynamically
|
| 131 |
+
linked subprograms that the work is specifically designed to require,
|
| 132 |
+
such as by intimate data communication or control flow between those
|
| 133 |
+
subprograms and other parts of the work.
|
| 134 |
+
|
| 135 |
+
The Corresponding Source need not include anything that users
|
| 136 |
+
can regenerate automatically from other parts of the Corresponding
|
| 137 |
+
Source.
|
| 138 |
+
|
| 139 |
+
The Corresponding Source for a work in source code form is that
|
| 140 |
+
same work.
|
| 141 |
+
|
| 142 |
+
2. Basic Permissions.
|
| 143 |
+
|
| 144 |
+
All rights granted under this License are granted for the term of
|
| 145 |
+
copyright on the Program, and are irrevocable provided the stated
|
| 146 |
+
conditions are met. This License explicitly affirms your unlimited
|
| 147 |
+
permission to run the unmodified Program. The output from running a
|
| 148 |
+
covered work is covered by this License only if the output, given its
|
| 149 |
+
content, constitutes a covered work. This License acknowledges your
|
| 150 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
| 151 |
+
|
| 152 |
+
You may make, run and propagate covered works that you do not
|
| 153 |
+
convey, without conditions so long as your license otherwise remains
|
| 154 |
+
in force. You may convey covered works to others for the sole purpose
|
| 155 |
+
of having them make modifications exclusively for you, or provide you
|
| 156 |
+
with facilities for running those works, provided that you comply with
|
| 157 |
+
the terms of this License in conveying all material for which you do
|
| 158 |
+
not control copyright. Those thus making or running the covered works
|
| 159 |
+
for you must do so exclusively on your behalf, under your direction
|
| 160 |
+
and control, on terms that prohibit them from making any copies of
|
| 161 |
+
your copyrighted material outside their relationship with you.
|
| 162 |
+
|
| 163 |
+
Conveying under any other circumstances is permitted solely under
|
| 164 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
| 165 |
+
makes it unnecessary.
|
| 166 |
+
|
| 167 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
| 168 |
+
|
| 169 |
+
No covered work shall be deemed part of an effective technological
|
| 170 |
+
measure under any applicable law fulfilling obligations under article
|
| 171 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
| 172 |
+
similar laws prohibiting or restricting circumvention of such
|
| 173 |
+
measures.
|
| 174 |
+
|
| 175 |
+
When you convey a covered work, you waive any legal power to forbid
|
| 176 |
+
circumvention of technological measures to the extent such circumvention
|
| 177 |
+
is effected by exercising rights under this License with respect to
|
| 178 |
+
the covered work, and you disclaim any intention to limit operation or
|
| 179 |
+
modification of the work as a means of enforcing, against the work's
|
| 180 |
+
users, your or third parties' legal rights to forbid circumvention of
|
| 181 |
+
technological measures.
|
| 182 |
+
|
| 183 |
+
4. Conveying Verbatim Copies.
|
| 184 |
+
|
| 185 |
+
You may convey verbatim copies of the Program's source code as you
|
| 186 |
+
receive it, in any medium, provided that you conspicuously and
|
| 187 |
+
appropriately publish on each copy an appropriate copyright notice;
|
| 188 |
+
keep intact all notices stating that this License and any
|
| 189 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
| 190 |
+
keep intact all notices of the absence of any warranty; and give all
|
| 191 |
+
recipients a copy of this License along with the Program.
|
| 192 |
+
|
| 193 |
+
You may charge any price or no price for each copy that you convey,
|
| 194 |
+
and you may offer support or warranty protection for a fee.
|
| 195 |
+
|
| 196 |
+
5. Conveying Modified Source Versions.
|
| 197 |
+
|
| 198 |
+
You may convey a work based on the Program, or the modifications to
|
| 199 |
+
produce it from the Program, in the form of source code under the
|
| 200 |
+
terms of section 4, provided that you also meet all of these conditions:
|
| 201 |
+
|
| 202 |
+
a) The work must carry prominent notices stating that you modified
|
| 203 |
+
it, and giving a relevant date.
|
| 204 |
+
|
| 205 |
+
b) The work must carry prominent notices stating that it is
|
| 206 |
+
released under this License and any conditions added under section
|
| 207 |
+
7. This requirement modifies the requirement in section 4 to
|
| 208 |
+
"keep intact all notices".
|
| 209 |
+
|
| 210 |
+
c) You must license the entire work, as a whole, under this
|
| 211 |
+
License to anyone who comes into possession of a copy. This
|
| 212 |
+
License will therefore apply, along with any applicable section 7
|
| 213 |
+
additional terms, to the whole of the work, and all its parts,
|
| 214 |
+
regardless of how they are packaged. This License gives no
|
| 215 |
+
permission to license the work in any other way, but it does not
|
| 216 |
+
invalidate such permission if you have separately received it.
|
| 217 |
+
|
| 218 |
+
d) If the work has interactive user interfaces, each must display
|
| 219 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
| 220 |
+
interfaces that do not display Appropriate Legal Notices, your
|
| 221 |
+
work need not make them do so.
|
| 222 |
+
|
| 223 |
+
A compilation of a covered work with other separate and independent
|
| 224 |
+
works, which are not by their nature extensions of the covered work,
|
| 225 |
+
and which are not combined with it such as to form a larger program,
|
| 226 |
+
in or on a volume of a storage or distribution medium, is called an
|
| 227 |
+
"aggregate" if the compilation and its resulting copyright are not
|
| 228 |
+
used to limit the access or legal rights of the compilation's users
|
| 229 |
+
beyond what the individual works permit. Inclusion of a covered work
|
| 230 |
+
in an aggregate does not cause this License to apply to the other
|
| 231 |
+
parts of the aggregate.
|
| 232 |
+
|
| 233 |
+
6. Conveying Non-Source Forms.
|
| 234 |
+
|
| 235 |
+
You may convey a covered work in object code form under the terms
|
| 236 |
+
of sections 4 and 5, provided that you also convey the
|
| 237 |
+
machine-readable Corresponding Source under the terms of this License,
|
| 238 |
+
in one of these ways:
|
| 239 |
+
|
| 240 |
+
a) Convey the object code in, or embodied in, a physical product
|
| 241 |
+
(including a physical distribution medium), accompanied by the
|
| 242 |
+
Corresponding Source fixed on a durable physical medium
|
| 243 |
+
customarily used for software interchange.
|
| 244 |
+
|
| 245 |
+
b) Convey the object code in, or embodied in, a physical product
|
| 246 |
+
(including a physical distribution medium), accompanied by a
|
| 247 |
+
written offer, valid for at least three years and valid for as
|
| 248 |
+
long as you offer spare parts or customer support for that product
|
| 249 |
+
model, to give anyone who possesses the object code either (1) a
|
| 250 |
+
copy of the Corresponding Source for all the software in the
|
| 251 |
+
product that is covered by this License, on a durable physical
|
| 252 |
+
medium customarily used for software interchange, for a price no
|
| 253 |
+
more than your reasonable cost of physically performing this
|
| 254 |
+
conveying of source, or (2) access to copy the
|
| 255 |
+
Corresponding Source from a network server at no charge.
|
| 256 |
+
|
| 257 |
+
c) Convey individual copies of the object code with a copy of the
|
| 258 |
+
written offer to provide the Corresponding Source. This
|
| 259 |
+
alternative is allowed only occasionally and noncommercially, and
|
| 260 |
+
only if you received the object code with such an offer, in accord
|
| 261 |
+
with subsection 6b.
|
| 262 |
+
|
| 263 |
+
d) Convey the object code by offering access from a designated
|
| 264 |
+
place (gratis or for a charge), and offer equivalent access to the
|
| 265 |
+
Corresponding Source in the same way through the same place at no
|
| 266 |
+
further charge. You need not require recipients to copy the
|
| 267 |
+
Corresponding Source along with the object code. If the place to
|
| 268 |
+
copy the object code is a network server, the Corresponding Source
|
| 269 |
+
may be on a different server (operated by you or a third party)
|
| 270 |
+
that supports equivalent copying facilities, provided you maintain
|
| 271 |
+
clear directions next to the object code saying where to find the
|
| 272 |
+
Corresponding Source. Regardless of what server hosts the
|
| 273 |
+
Corresponding Source, you remain obligated to ensure that it is
|
| 274 |
+
available for as long as needed to satisfy these requirements.
|
| 275 |
+
|
| 276 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
| 277 |
+
you inform other peers where the object code and Corresponding
|
| 278 |
+
Source of the work are being offered to the general public at no
|
| 279 |
+
charge under subsection 6d.
|
| 280 |
+
|
| 281 |
+
A separable portion of the object code, whose source code is excluded
|
| 282 |
+
from the Corresponding Source as a System Library, need not be
|
| 283 |
+
included in conveying the object code work.
|
| 284 |
+
|
| 285 |
+
A "User Product" is either (1) a "consumer product", which means any
|
| 286 |
+
tangible personal property which is normally used for personal, family,
|
| 287 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
| 288 |
+
into a dwelling. In determining whether a product is a consumer product,
|
| 289 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
| 290 |
+
product received by a particular user, "normally used" refers to a
|
| 291 |
+
typical or common use of that class of product, regardless of the status
|
| 292 |
+
of the particular user or of the way in which the particular user
|
| 293 |
+
actually uses, or expects or is expected to use, the product. A product
|
| 294 |
+
is a consumer product regardless of whether the product has substantial
|
| 295 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
| 296 |
+
the only significant mode of use of the product.
|
| 297 |
+
|
| 298 |
+
"Installation Information" for a User Product means any methods,
|
| 299 |
+
procedures, authorization keys, or other information required to install
|
| 300 |
+
and execute modified versions of a covered work in that User Product from
|
| 301 |
+
a modified version of its Corresponding Source. The information must
|
| 302 |
+
suffice to ensure that the continued functioning of the modified object
|
| 303 |
+
code is in no case prevented or interfered with solely because
|
| 304 |
+
modification has been made.
|
| 305 |
+
|
| 306 |
+
If you convey an object code work under this section in, or with, or
|
| 307 |
+
specifically for use in, a User Product, and the conveying occurs as
|
| 308 |
+
part of a transaction in which the right of possession and use of the
|
| 309 |
+
User Product is transferred to the recipient in perpetuity or for a
|
| 310 |
+
fixed term (regardless of how the transaction is characterized), the
|
| 311 |
+
Corresponding Source conveyed under this section must be accompanied
|
| 312 |
+
by the Installation Information. But this requirement does not apply
|
| 313 |
+
if neither you nor any third party retains the ability to install
|
| 314 |
+
modified object code on the User Product (for example, the work has
|
| 315 |
+
been installed in ROM).
|
| 316 |
+
|
| 317 |
+
The requirement to provide Installation Information does not include a
|
| 318 |
+
requirement to continue to provide support service, warranty, or updates
|
| 319 |
+
for a work that has been modified or installed by the recipient, or for
|
| 320 |
+
the User Product in which it has been modified or installed. Access to a
|
| 321 |
+
network may be denied when the modification itself materially and
|
| 322 |
+
adversely affects the operation of the network or violates the rules and
|
| 323 |
+
protocols for communication across the network.
|
| 324 |
+
|
| 325 |
+
Corresponding Source conveyed, and Installation Information provided,
|
| 326 |
+
in accord with this section must be in a format that is publicly
|
| 327 |
+
documented (and with an implementation available to the public in
|
| 328 |
+
source code form), and must require no special password or key for
|
| 329 |
+
unpacking, reading or copying.
|
| 330 |
+
|
| 331 |
+
7. Additional Terms.
|
| 332 |
+
|
| 333 |
+
"Additional permissions" are terms that supplement the terms of this
|
| 334 |
+
License by making exceptions from one or more of its conditions.
|
| 335 |
+
Additional permissions that are applicable to the entire Program shall
|
| 336 |
+
be treated as though they were included in this License, to the extent
|
| 337 |
+
that they are valid under applicable law. If additional permissions
|
| 338 |
+
apply only to part of the Program, that part may be used separately
|
| 339 |
+
under those permissions, but the entire Program remains governed by
|
| 340 |
+
this License without regard to the additional permissions.
|
| 341 |
+
|
| 342 |
+
When you convey a copy of a covered work, you may at your option
|
| 343 |
+
remove any additional permissions from that copy, or from any part of
|
| 344 |
+
it. (Additional permissions may be written to require their own
|
| 345 |
+
removal in certain cases when you modify the work.) You may place
|
| 346 |
+
additional permissions on material, added by you to a covered work,
|
| 347 |
+
for which you have or can give appropriate copyright permission.
|
| 348 |
+
|
| 349 |
+
Notwithstanding any other provision of this License, for material you
|
| 350 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
| 351 |
+
that material) supplement the terms of this License with terms:
|
| 352 |
+
|
| 353 |
+
a) Disclaiming warranty or limiting liability differently from the
|
| 354 |
+
terms of sections 15 and 16 of this License; or
|
| 355 |
+
|
| 356 |
+
b) Requiring preservation of specified reasonable legal notices or
|
| 357 |
+
author attributions in that material or in the Appropriate Legal
|
| 358 |
+
Notices displayed by works containing it; or
|
| 359 |
+
|
| 360 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
| 361 |
+
requiring that modified versions of such material be marked in
|
| 362 |
+
reasonable ways as different from the original version; or
|
| 363 |
+
|
| 364 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
| 365 |
+
authors of the material; or
|
| 366 |
+
|
| 367 |
+
e) Declining to grant rights under trademark law for use of some
|
| 368 |
+
trade names, trademarks, or service marks; or
|
| 369 |
+
|
| 370 |
+
f) Requiring indemnification of licensors and authors of that
|
| 371 |
+
material by anyone who conveys the material (or modified versions of
|
| 372 |
+
it) with contractual assumptions of liability to the recipient, for
|
| 373 |
+
any liability that these contractual assumptions directly impose on
|
| 374 |
+
those licensors and authors.
|
| 375 |
+
|
| 376 |
+
All other non-permissive additional terms are considered "further
|
| 377 |
+
restrictions" within the meaning of section 10. If the Program as you
|
| 378 |
+
received it, or any part of it, contains a notice stating that it is
|
| 379 |
+
governed by this License along with a term that is a further
|
| 380 |
+
restriction, you may remove that term. If a license document contains
|
| 381 |
+
a further restriction but permits relicensing or conveying under this
|
| 382 |
+
License, you may add to a covered work material governed by the terms
|
| 383 |
+
of that license document, provided that the further restriction does
|
| 384 |
+
not survive such relicensing or conveying.
|
| 385 |
+
|
| 386 |
+
If you add terms to a covered work in accord with this section, you
|
| 387 |
+
must place, in the relevant source files, a statement of the
|
| 388 |
+
additional terms that apply to those files, or a notice indicating
|
| 389 |
+
where to find the applicable terms.
|
| 390 |
+
|
| 391 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
| 392 |
+
form of a separately written license, or stated as exceptions;
|
| 393 |
+
the above requirements apply either way.
|
| 394 |
+
|
| 395 |
+
8. Termination.
|
| 396 |
+
|
| 397 |
+
You may not propagate or modify a covered work except as expressly
|
| 398 |
+
provided under this License. Any attempt otherwise to propagate or
|
| 399 |
+
modify it is void, and will automatically terminate your rights under
|
| 400 |
+
this License (including any patent licenses granted under the third
|
| 401 |
+
paragraph of section 11).
|
| 402 |
+
|
| 403 |
+
However, if you cease all violation of this License, then your
|
| 404 |
+
license from a particular copyright holder is reinstated (a)
|
| 405 |
+
provisionally, unless and until the copyright holder explicitly and
|
| 406 |
+
finally terminates your license, and (b) permanently, if the copyright
|
| 407 |
+
holder fails to notify you of the violation by some reasonable means
|
| 408 |
+
prior to 60 days after the cessation.
|
| 409 |
+
|
| 410 |
+
Moreover, your license from a particular copyright holder is
|
| 411 |
+
reinstated permanently if the copyright holder notifies you of the
|
| 412 |
+
violation by some reasonable means, this is the first time you have
|
| 413 |
+
received notice of violation of this License (for any work) from that
|
| 414 |
+
copyright holder, and you cure the violation prior to 30 days after
|
| 415 |
+
your receipt of the notice.
|
| 416 |
+
|
| 417 |
+
Termination of your rights under this section does not terminate the
|
| 418 |
+
licenses of parties who have received copies or rights from you under
|
| 419 |
+
this License. If your rights have been terminated and not permanently
|
| 420 |
+
reinstated, you do not qualify to receive new licenses for the same
|
| 421 |
+
material under section 10.
|
| 422 |
+
|
| 423 |
+
9. Acceptance Not Required for Having Copies.
|
| 424 |
+
|
| 425 |
+
You are not required to accept this License in order to receive or
|
| 426 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
| 427 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
| 428 |
+
to receive a copy likewise does not require acceptance. However,
|
| 429 |
+
nothing other than this License grants you permission to propagate or
|
| 430 |
+
modify any covered work. These actions infringe copyright if you do
|
| 431 |
+
not accept this License. Therefore, by modifying or propagating a
|
| 432 |
+
covered work, you indicate your acceptance of this License to do so.
|
| 433 |
+
|
| 434 |
+
10. Automatic Licensing of Downstream Recipients.
|
| 435 |
+
|
| 436 |
+
Each time you convey a covered work, the recipient automatically
|
| 437 |
+
receives a license from the original licensors, to run, modify and
|
| 438 |
+
propagate that work, subject to this License. You are not responsible
|
| 439 |
+
for enforcing compliance by third parties with this License.
|
| 440 |
+
|
| 441 |
+
An "entity transaction" is a transaction transferring control of an
|
| 442 |
+
organization, or substantially all assets of one, or subdividing an
|
| 443 |
+
organization, or merging organizations. If propagation of a covered
|
| 444 |
+
work results from an entity transaction, each party to that
|
| 445 |
+
transaction who receives a copy of the work also receives whatever
|
| 446 |
+
licenses to the work the party's predecessor in interest had or could
|
| 447 |
+
give under the previous paragraph, plus a right to possession of the
|
| 448 |
+
Corresponding Source of the work from the predecessor in interest, if
|
| 449 |
+
the predecessor has it or can get it with reasonable efforts.
|
| 450 |
+
|
| 451 |
+
You may not impose any further restrictions on the exercise of the
|
| 452 |
+
rights granted or affirmed under this License. For example, you may
|
| 453 |
+
not impose a license fee, royalty, or other charge for exercise of
|
| 454 |
+
rights granted under this License, and you may not initiate litigation
|
| 455 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
| 456 |
+
any patent claim is infringed by making, using, selling, offering for
|
| 457 |
+
sale, or importing the Program or any portion of it.
|
| 458 |
+
|
| 459 |
+
11. Patents.
|
| 460 |
+
|
| 461 |
+
A "contributor" is a copyright holder who authorizes use under this
|
| 462 |
+
License of the Program or a work on which the Program is based. The
|
| 463 |
+
work thus licensed is called the contributor's "contributor version".
|
| 464 |
+
|
| 465 |
+
A contributor's "essential patent claims" are all patent claims
|
| 466 |
+
owned or controlled by the contributor, whether already acquired or
|
| 467 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
| 468 |
+
by this License, of making, using, or selling its contributor version,
|
| 469 |
+
but do not include claims that would be infringed only as a
|
| 470 |
+
consequence of further modification of the contributor version. For
|
| 471 |
+
purposes of this definition, "control" includes the right to grant
|
| 472 |
+
patent sublicenses in a manner consistent with the requirements of
|
| 473 |
+
this License.
|
| 474 |
+
|
| 475 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
| 476 |
+
patent license under the contributor's essential patent claims, to
|
| 477 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
| 478 |
+
propagate the contents of its contributor version.
|
| 479 |
+
|
| 480 |
+
In the following three paragraphs, a "patent license" is any express
|
| 481 |
+
agreement or commitment, however denominated, not to enforce a patent
|
| 482 |
+
(such as an express permission to practice a patent or covenant not to
|
| 483 |
+
sue for patent infringement). To "grant" such a patent license to a
|
| 484 |
+
party means to make such an agreement or commitment not to enforce a
|
| 485 |
+
patent against the party.
|
| 486 |
+
|
| 487 |
+
If you convey a covered work, knowingly relying on a patent license,
|
| 488 |
+
and the Corresponding Source of the work is not available for anyone
|
| 489 |
+
to copy, free of charge and under the terms of this License, through a
|
| 490 |
+
publicly available network server or other readily accessible means,
|
| 491 |
+
then you must either (1) cause the Corresponding Source to be so
|
| 492 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
| 493 |
+
patent license for this particular work, or (3) arrange, in a manner
|
| 494 |
+
consistent with the requirements of this License, to extend the patent
|
| 495 |
+
license to downstream recipients. "Knowingly relying" means you have
|
| 496 |
+
actual knowledge that, but for the patent license, your conveying the
|
| 497 |
+
covered work in a country, or your recipient's use of the covered work
|
| 498 |
+
in a country, would infringe one or more identifiable patents in that
|
| 499 |
+
country that you have reason to believe are valid.
|
| 500 |
+
|
| 501 |
+
If, pursuant to or in connection with a single transaction or
|
| 502 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
| 503 |
+
covered work, and grant a patent license to some of the parties
|
| 504 |
+
receiving the covered work authorizing them to use, propagate, modify
|
| 505 |
+
or convey a specific copy of the covered work, then the patent license
|
| 506 |
+
you grant is automatically extended to all recipients of the covered
|
| 507 |
+
work and works based on it.
|
| 508 |
+
|
| 509 |
+
A patent license is "discriminatory" if it does not include within
|
| 510 |
+
the scope of its coverage, prohibits the exercise of, or is
|
| 511 |
+
conditioned on the non-exercise of one or more of the rights that are
|
| 512 |
+
specifically granted under this License. You may not convey a covered
|
| 513 |
+
work if you are a party to an arrangement with a third party that is
|
| 514 |
+
in the business of distributing software, under which you make payment
|
| 515 |
+
to the third party based on the extent of your activity of conveying
|
| 516 |
+
the work, and under which the third party grants, to any of the
|
| 517 |
+
parties who would receive the covered work from you, a discriminatory
|
| 518 |
+
patent license (a) in connection with copies of the covered work
|
| 519 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
| 520 |
+
for and in connection with specific products or compilations that
|
| 521 |
+
contain the covered work, unless you entered into that arrangement,
|
| 522 |
+
or that patent license was granted, prior to 28 March 2007.
|
| 523 |
+
|
| 524 |
+
Nothing in this License shall be construed as excluding or limiting
|
| 525 |
+
any implied license or other defenses to infringement that may
|
| 526 |
+
otherwise be available to you under applicable patent law.
|
| 527 |
+
|
| 528 |
+
12. No Surrender of Others' Freedom.
|
| 529 |
+
|
| 530 |
+
If conditions are imposed on you (whether by court order, agreement or
|
| 531 |
+
otherwise) that contradict the conditions of this License, they do not
|
| 532 |
+
excuse you from the conditions of this License. If you cannot convey a
|
| 533 |
+
covered work so as to satisfy simultaneously your obligations under this
|
| 534 |
+
License and any other pertinent obligations, then as a consequence you may
|
| 535 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
| 536 |
+
to collect a royalty for further conveying from those to whom you convey
|
| 537 |
+
the Program, the only way you could satisfy both those terms and this
|
| 538 |
+
License would be to refrain entirely from conveying the Program.
|
| 539 |
+
|
| 540 |
+
13. Remote Network Interaction; Use with the GNU General Public License.
|
| 541 |
+
|
| 542 |
+
Notwithstanding any other provision of this License, if you modify the
|
| 543 |
+
Program, your modified version must prominently offer all users
|
| 544 |
+
interacting with it remotely through a computer network (if your version
|
| 545 |
+
supports such interaction) an opportunity to receive the Corresponding
|
| 546 |
+
Source of your version by providing access to the Corresponding Source
|
| 547 |
+
from a network server at no charge, through some standard or customary
|
| 548 |
+
means of facilitating copying of software. This Corresponding Source
|
| 549 |
+
shall include the Corresponding Source for any work covered by version 3
|
| 550 |
+
of the GNU General Public License that is incorporated pursuant to the
|
| 551 |
+
following paragraph.
|
| 552 |
+
|
| 553 |
+
Notwithstanding any other provision of this License, you have
|
| 554 |
+
permission to link or combine any covered work with a work licensed
|
| 555 |
+
under version 3 of the GNU General Public License into a single
|
| 556 |
+
combined work, and to convey the resulting work. The terms of this
|
| 557 |
+
License will continue to apply to the part which is the covered work,
|
| 558 |
+
but the work with which it is combined will remain governed by version
|
| 559 |
+
3 of the GNU General Public License.
|
| 560 |
+
|
| 561 |
+
14. Revised Versions of this License.
|
| 562 |
+
|
| 563 |
+
The Free Software Foundation may publish revised and/or new versions of
|
| 564 |
+
the GNU Affero General Public License from time to time. Such new versions
|
| 565 |
+
will be similar in spirit to the present version, but may differ in detail to
|
| 566 |
+
address new problems or concerns.
|
| 567 |
+
|
| 568 |
+
Each version is given a distinguishing version number. If the
|
| 569 |
+
Program specifies that a certain numbered version of the GNU Affero General
|
| 570 |
+
Public License "or any later version" applies to it, you have the
|
| 571 |
+
option of following the terms and conditions either of that numbered
|
| 572 |
+
version or of any later version published by the Free Software
|
| 573 |
+
Foundation. If the Program does not specify a version number of the
|
| 574 |
+
GNU Affero General Public License, you may choose any version ever published
|
| 575 |
+
by the Free Software Foundation.
|
| 576 |
+
|
| 577 |
+
If the Program specifies that a proxy can decide which future
|
| 578 |
+
versions of the GNU Affero General Public License can be used, that proxy's
|
| 579 |
+
public statement of acceptance of a version permanently authorizes you
|
| 580 |
+
to choose that version for the Program.
|
| 581 |
+
|
| 582 |
+
Later license versions may give you additional or different
|
| 583 |
+
permissions. However, no additional obligations are imposed on any
|
| 584 |
+
author or copyright holder as a result of your choosing to follow a
|
| 585 |
+
later version.
|
| 586 |
+
|
| 587 |
+
15. Disclaimer of Warranty.
|
| 588 |
+
|
| 589 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
| 590 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
| 591 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
| 592 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
| 593 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
| 594 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
| 595 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
| 596 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
| 597 |
+
|
| 598 |
+
16. Limitation of Liability.
|
| 599 |
+
|
| 600 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
| 601 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
| 602 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
| 603 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
| 604 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
| 605 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
| 606 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
| 607 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
| 608 |
+
SUCH DAMAGES.
|
| 609 |
+
|
| 610 |
+
17. Interpretation of Sections 15 and 16.
|
| 611 |
+
|
| 612 |
+
If the disclaimer of warranty and limitation of liability provided
|
| 613 |
+
above cannot be given local legal effect according to their terms,
|
| 614 |
+
reviewing courts shall apply local law that most closely approximates
|
| 615 |
+
an absolute waiver of all civil liability in connection with the
|
| 616 |
+
Program, unless a warranty or assumption of liability accompanies a
|
| 617 |
+
copy of the Program in return for a fee.
|
| 618 |
+
|
| 619 |
+
END OF TERMS AND CONDITIONS
|
| 620 |
+
|
| 621 |
+
How to Apply These Terms to Your New Programs
|
| 622 |
+
|
| 623 |
+
If you develop a new program, and you want it to be of the greatest
|
| 624 |
+
possible use to the public, the best way to achieve this is to make it
|
| 625 |
+
free software which everyone can redistribute and change under these terms.
|
| 626 |
+
|
| 627 |
+
To do so, attach the following notices to the program. It is safest
|
| 628 |
+
to attach them to the start of each source file to most effectively
|
| 629 |
+
state the exclusion of warranty; and each file should have at least
|
| 630 |
+
the "copyright" line and a pointer to where the full notice is found.
|
| 631 |
+
|
| 632 |
+
<one line to give the program's name and a brief idea of what it does.>
|
| 633 |
+
Copyright (C) <year> <name of author>
|
| 634 |
+
|
| 635 |
+
This program is free software: you can redistribute it and/or modify
|
| 636 |
+
it under the terms of the GNU Affero General Public License as published
|
| 637 |
+
by the Free Software Foundation, either version 3 of the License, or
|
| 638 |
+
(at your option) any later version.
|
| 639 |
+
|
| 640 |
+
This program is distributed in the hope that it will be useful,
|
| 641 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 642 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 643 |
+
GNU Affero General Public License for more details.
|
| 644 |
+
|
| 645 |
+
You should have received a copy of the GNU Affero General Public License
|
| 646 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
| 647 |
+
|
| 648 |
+
Also add information on how to contact you by electronic and paper mail.
|
| 649 |
+
|
| 650 |
+
If your software can interact with users remotely through a computer
|
| 651 |
+
network, you should also make sure that it provides a way for users to
|
| 652 |
+
get its source. For example, if your program is a web application, its
|
| 653 |
+
interface could display a "Source" link that leads users to an archive
|
| 654 |
+
of the code. There are many ways you could offer source, and different
|
| 655 |
+
solutions will be better for different programs; see section 13 for the
|
| 656 |
+
specific requirements.
|
| 657 |
+
|
| 658 |
+
You should also get your employer (if you work as a programmer) or school,
|
| 659 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
| 660 |
+
For more information on this, and how to apply and follow the GNU AGPL, see
|
| 661 |
+
<https://www.gnu.org/licenses/>.
|
README.en.md
ADDED
|
@@ -0,0 +1,441 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<p align="center">
|
| 2 |
+
<img src="webui/public/ds2api-favicon.svg" width="128" height="128" alt="DS2API icon" />
|
| 3 |
+
</p>
|
| 4 |
+
|
| 5 |
+
# DS2API
|
| 6 |
+
|
| 7 |
+
<a href="https://trendshift.io/repositories/24508" target="_blank"><img src="https://trendshift.io/api/badge/repositories/24508" alt="CJackHwang%2Fds2api | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
| 8 |
+
|
| 9 |
+
[](LICENSE)
|
| 10 |
+

|
| 11 |
+

|
| 12 |
+
[](https://github.com/CJackHwang/ds2api/releases)
|
| 13 |
+
[](docs/DEPLOY.en.md)
|
| 14 |
+
[](https://zeabur.com/templates/L4CFHP)
|
| 15 |
+
[](https://vercel.com/new/clone?repository-url=https://github.com/CJackHwang/ds2api)
|
| 16 |
+
|
| 17 |
+
Language: [中文](README.MD) | [English](README.en.md)
|
| 18 |
+
|
| 19 |
+
DS2API converts DeepSeek Web chat capability into OpenAI-compatible, Claude-compatible, and Gemini-compatible APIs. The core backend is Go-based, with a small Node Runtime bridge used for Vercel streaming, and the React WebUI admin panel lives in `webui/` (build output auto-generated to `static/admin` during deployment).
|
| 20 |
+
|
| 21 |
+
Documentation entry: [Docs Index](docs/README.md) / [Architecture](docs/ARCHITECTURE.en.md) / [API Reference](API.en.md)
|
| 22 |
+
|
| 23 |
+
## Star History
|
| 24 |
+
|
| 25 |
+
<a href="https://www.star-history.com/?repos=cjackhwang%2Fds2api&type=date&legend=top-left">
|
| 26 |
+
<picture>
|
| 27 |
+
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=cjackhwang/ds2api&type=date&theme=dark&legend=top-left" />
|
| 28 |
+
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=cjackhwang/ds2api&type=date&legend=top-left" />
|
| 29 |
+
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=cjackhwang/ds2api&type=date&legend=top-left" />
|
| 30 |
+
</picture>
|
| 31 |
+
</a>
|
| 32 |
+
|
| 33 |
+
> **Important Disclaimer**
|
| 34 |
+
>
|
| 35 |
+
> This repository is provided for learning, research, personal experimentation, and internal validation only. It does not grant any commercial authorization and comes with no warranty of fitness, stability, or results.
|
| 36 |
+
>
|
| 37 |
+
> The author and repository maintainers are not responsible for any direct or indirect loss, account suspension, data loss, legal risk, or third-party claims arising from use, modification, distribution, deployment, or reliance on this project.
|
| 38 |
+
>
|
| 39 |
+
> Do not use this project in ways that violate service terms, agreements, laws, or platform rules. Before any commercial use, review the `LICENSE`, the relevant terms, and confirm that you have the author's written permission.
|
| 40 |
+
|
| 41 |
+
## Table of Contents
|
| 42 |
+
|
| 43 |
+
- [Architecture Overview (Summary)](#architecture-overview-summary)
|
| 44 |
+
- [Key Capabilities](#key-capabilities)
|
| 45 |
+
- [Platform Compatibility Matrix](#platform-compatibility-matrix)
|
| 46 |
+
- [Model Support](#model-support)
|
| 47 |
+
- [OpenAI Endpoint](#openai-endpoint-get-v1models)
|
| 48 |
+
- [Claude Endpoint](#claude-endpoint-get-anthropicv1models)
|
| 49 |
+
- [Gemini Endpoint](#gemini-endpoint)
|
| 50 |
+
- [Quick Start](#quick-start)
|
| 51 |
+
- [Option 1: Download Release Binaries](#option-1-download-release-binaries)
|
| 52 |
+
- [Option 2: Docker / GHCR](#option-2-docker--ghcr)
|
| 53 |
+
- [Option 3: Vercel](#option-3-vercel)
|
| 54 |
+
- [Option 4: Local Run](#option-4-local-run)
|
| 55 |
+
- [Configuration](#configuration)
|
| 56 |
+
- [Authentication Modes](#authentication-modes)
|
| 57 |
+
- [Concurrency Model](#concurrency-model)
|
| 58 |
+
- [Tool Call Adaptation](#tool-call-adaptation)
|
| 59 |
+
- [Local Dev Packet Capture](#local-dev-packet-capture)
|
| 60 |
+
- [Documentation Index](#documentation-index)
|
| 61 |
+
- [Testing](#testing)
|
| 62 |
+
- [Release Artifact Automation (GitHub Actions)](#release-artifact-automation-github-actions)
|
| 63 |
+
- [Disclaimer](#disclaimer)
|
| 64 |
+
|
| 65 |
+
## Architecture Overview (Summary)
|
| 66 |
+
|
| 67 |
+
```mermaid
|
| 68 |
+
flowchart LR
|
| 69 |
+
Client["🖥️ Clients / SDKs\n(OpenAI / Claude / Gemini)"]
|
| 70 |
+
Upstream["☁️ DeepSeek API"]
|
| 71 |
+
|
| 72 |
+
subgraph DS2API["DS2API 4.x (Modular HTTP Surface + PromptCompat Core)"]
|
| 73 |
+
Router["chi Router + Middleware\n(RequestID / RealIP / Logger / Recoverer / CORS)"]
|
| 74 |
+
|
| 75 |
+
subgraph HTTP["HTTP API Surface"]
|
| 76 |
+
OA["OpenAI\nchat / responses / files / embeddings"]
|
| 77 |
+
CA["Claude\n/anthropic/* + /v1/messages"]
|
| 78 |
+
GA["Gemini\n/v1beta/models/* + /v1/models/*"]
|
| 79 |
+
Admin["Admin API\nresource packages"]
|
| 80 |
+
WebUI["WebUI\n/admin (static hosting)"]
|
| 81 |
+
Vercel["Vercel Node Stream\n/v1/chat/completions"]
|
| 82 |
+
end
|
| 83 |
+
|
| 84 |
+
subgraph Runtime["Runtime + Core Capabilities"]
|
| 85 |
+
Compat["PromptCompat\n(API -> web-chat plain text context)"]
|
| 86 |
+
Completion["Completion Runtime\n(session / PoW / completion)"]
|
| 87 |
+
Turn["AssistantTurn\n(output semantic normalization)"]
|
| 88 |
+
Auth["Auth Resolver\n(API key / bearer / x-goog-api-key)"]
|
| 89 |
+
Pool["Account Pool + Queue\n(in-flight slots + wait queue)"]
|
| 90 |
+
DSClient["DeepSeek Client\n(session / auth / completion / files)"]
|
| 91 |
+
Pow["PoW Solver\n(Pure Go)"]
|
| 92 |
+
Tool["Tool Sieve\n(Go/Node semantic parity)"]
|
| 93 |
+
History["Current Input File\n(random context file)"]
|
| 94 |
+
end
|
| 95 |
+
end
|
| 96 |
+
|
| 97 |
+
Client --> Router
|
| 98 |
+
Router --> OA & CA & GA
|
| 99 |
+
Router --> Admin
|
| 100 |
+
Router --> WebUI
|
| 101 |
+
Router --> Vercel
|
| 102 |
+
|
| 103 |
+
OA --> Compat
|
| 104 |
+
CA & GA --> Compat
|
| 105 |
+
Compat --> Completion
|
| 106 |
+
Completion -.full context.-> History
|
| 107 |
+
Completion --> Turn
|
| 108 |
+
Vercel -.Go prepare.-> Completion
|
| 109 |
+
Vercel -.Node SSE.-> Tool
|
| 110 |
+
Completion --> Auth
|
| 111 |
+
Completion -.account rotation.-> Pool
|
| 112 |
+
Completion -.tool-call parsing.-> Tool
|
| 113 |
+
Completion -.PoW solving.-> Pow
|
| 114 |
+
Auth --> DSClient
|
| 115 |
+
DSClient --> Upstream
|
| 116 |
+
Upstream --> DSClient
|
| 117 |
+
Turn --> Client
|
| 118 |
+
Vercel --> Client
|
| 119 |
+
```
|
| 120 |
+
|
| 121 |
+
For the full module-by-module architecture and directory responsibilities, see [docs/ARCHITECTURE.en.md](docs/ARCHITECTURE.en.md).
|
| 122 |
+
|
| 123 |
+
- **Backend**: Go (`cmd/ds2api/`, `api/`, `internal/`), no Python runtime
|
| 124 |
+
- **Frontend**: React admin panel (`webui/`), served as static build at runtime
|
| 125 |
+
- **Deployment**: local run, Docker, Vercel serverless, Linux systemd
|
| 126 |
+
|
| 127 |
+
## Key Capabilities
|
| 128 |
+
|
| 129 |
+
| Capability | Details |
|
| 130 |
+
| --- | --- |
|
| 131 |
+
| OpenAI compatible | `GET /v1/models`, `GET /v1/models/{id}`, `POST /v1/chat/completions`, `POST /v1/responses`, `GET /v1/responses/{response_id}`, `POST /v1/embeddings`, `POST /v1/files`, `GET /v1/files/{file_id}` |
|
| 132 |
+
| Claude compatible | `GET /anthropic/v1/models`, `POST /anthropic/v1/messages`, `POST /anthropic/v1/messages/count_tokens` (plus shortcut paths `/v1/messages`, `/messages`) |
|
| 133 |
+
| Gemini compatible | `POST /v1beta/models/{model}:generateContent`, `POST /v1beta/models/{model}:streamGenerateContent` (plus `/v1/models/{model}:*` paths) |
|
| 134 |
+
| Ollama compatible | `GET /api/version`, `GET /api/tags`, `POST /api/show` |
|
| 135 |
+
| Unified CORS compatibility | `/v1/*`, `/anthropic/*`, `/v1beta/models/*`, `/api/*`, and `/admin/*` share one CORS policy; on Vercel, the Node Runtime for `/v1/chat/completions` mirrors the same relaxed preflight behavior for third-party clients |
|
| 136 |
+
| Multi-account rotation | Auto token refresh, email/mobile dual login |
|
| 137 |
+
| Concurrency control | Per-account in-flight limit + waiting queue, dynamic recommended concurrency |
|
| 138 |
+
| DeepSeek PoW | Pure Go high-performance solver (DeepSeekHashV1), ms-level response |
|
| 139 |
+
| Tool Calling | Anti-leak handling: non-code-block feature match, early `delta.tool_calls`, structured incremental output |
|
| 140 |
+
| Admin API | Config management, runtime settings hot-reload, proxy management, account testing/batch test, session cleanup, import/export, Vercel sync, version check |
|
| 141 |
+
| WebUI Admin Panel | SPA at `/admin` (bilingual Chinese/English, dark mode, with server-side conversation history) |
|
| 142 |
+
| Health Probes | `GET /healthz` (liveness), `GET /readyz` (readiness) |
|
| 143 |
+
|
| 144 |
+
OpenAI `/v1/*` routes remain canonical, and DS2API also accepts root shortcuts such as `/models`, `/chat/completions`, `/responses`, `/embeddings`, `/files`, and `/files/{file_id}` for clients configured with the bare service URL.
|
| 145 |
+
|
| 146 |
+
## Platform Compatibility Matrix
|
| 147 |
+
|
| 148 |
+
| Tier | Platform | Status |
|
| 149 |
+
| --- | --- | --- |
|
| 150 |
+
| P0 | Codex CLI/SDK (`wire_api=chat` / `wire_api=responses`) | ✅ |
|
| 151 |
+
| P0 | OpenAI SDK (JS/Python, chat + responses) | ✅ |
|
| 152 |
+
| P0 | Vercel AI SDK (openai-compatible) | ✅ |
|
| 153 |
+
| P0 | Anthropic SDK (messages) | ✅ |
|
| 154 |
+
| P0 | Google Gemini SDK (generateContent) | ✅ |
|
| 155 |
+
| P1 | LangChain / LlamaIndex / OpenWebUI (OpenAI-compatible integration) | ✅ |
|
| 156 |
+
|
| 157 |
+
## Model Support
|
| 158 |
+
|
| 159 |
+
### OpenAI Endpoint (`GET /v1/models`)
|
| 160 |
+
|
| 161 |
+
| Family | Model ID | thinking | search |
|
| 162 |
+
| --- | --- | --- | --- |
|
| 163 |
+
| default | `deepseek-v4-flash` | enabled by default, request-controlled | ❌ |
|
| 164 |
+
| expert | `deepseek-v4-pro` | enabled by default, request-controlled | ❌ |
|
| 165 |
+
| default | `deepseek-v4-flash-search` | enabled by default, request-controlled | ✅ |
|
| 166 |
+
| expert | `deepseek-v4-pro-search` | enabled by default, request-controlled | ✅ |
|
| 167 |
+
| vision | `deepseek-v4-vision` | enabled by default, request-controlled | ❌ |
|
| 168 |
+
|
| 169 |
+
Besides native IDs, DS2API also accepts common aliases as input (for example `gpt-4.1`, `gpt-5`, `gpt-5-codex`, `o3`, `claude-*`, `gemini-*`), but `/v1/models` returns normalized DeepSeek native model IDs. The complete alias behavior is documented in [API.en.md](API.en.md#model-alias-resolution) and `config.example.json`.
|
| 170 |
+
Current upstream vision support exposes only the `vision` lane and does not provide a separate search-enabled vision variant.
|
| 171 |
+
|
| 172 |
+
### Claude Endpoint (`GET /anthropic/v1/models`)
|
| 173 |
+
|
| 174 |
+
| Current common model | Default Mapping |
|
| 175 |
+
| --- | --- |
|
| 176 |
+
| `claude-sonnet-4-6` | `deepseek-v4-flash` |
|
| 177 |
+
| `claude-haiku-4-5` (compatible with `claude-3-5-haiku-latest`) | `deepseek-v4-flash` |
|
| 178 |
+
| `claude-opus-4-6` | `deepseek-v4-pro` |
|
| 179 |
+
|
| 180 |
+
Override mapping via the global `model_aliases` config.
|
| 181 |
+
Besides the primary aliases above, `/anthropic/v1/models` also returns Claude 4.x snapshots plus historical 3.x IDs and common aliases for legacy client compatibility.
|
| 182 |
+
|
| 183 |
+
#### Claude Code integration pitfalls (validated)
|
| 184 |
+
|
| 185 |
+
- Set `ANTHROPIC_BASE_URL` to the DS2API root URL (for example `http://127.0.0.1:5001`). Claude Code sends requests to `/v1/messages?beta=true`.
|
| 186 |
+
- `ANTHROPIC_API_KEY` must match an entry in `keys` from `config.json`. Keeping both a regular key and an `sk-ant-*` style key improves client compatibility.
|
| 187 |
+
- If your environment has proxy variables, set `NO_PROXY=127.0.0.1,localhost,<your_host_ip>` for DS2API to avoid proxy interception of local traffic.
|
| 188 |
+
- If tool calls are rendered as plain text and not executed, first verify the model output uses the recommended halfwidth-pipe DSML block: `<|DSML|tool_calls><|DSML|invoke name="..."><|DSML|parameter name="...">...`. DS2API also accepts legacy canonical XML: `<tool_calls><invoke name="..."><parameter name="...">...`; legacy `<tools>` / `<tool_call>` / `<tool_name>` / `<param>`, `<function_call>`, `tool_use`, or standalone JSON `tool_calls` are not executed and stay plain text.
|
| 189 |
+
|
| 190 |
+
### Gemini Endpoint
|
| 191 |
+
|
| 192 |
+
The Gemini adapter maps model names to DeepSeek native models via `model_aliases` or exact built-in aliases (covering common `gemini-2.5-*`, `gemini-3*`, and `gemini-pro-vision` names), supporting both `generateContent` and `streamGenerateContent` call patterns with full Tool Calling support (`functionDeclarations` → `functionCall` output). If the Gemini model name has a `-nothinking` suffix, such as `gemini-2.5-pro-nothinking`, it maps to the corresponding forced no-thinking model.
|
| 193 |
+
|
| 194 |
+
## Quick Start
|
| 195 |
+
|
| 196 |
+
### Recommended deployment priority
|
| 197 |
+
|
| 198 |
+
Recommended order when choosing a deployment method:
|
| 199 |
+
|
| 200 |
+
1. **Download and run release binaries**: the easiest path for most users because the artifacts are already built.
|
| 201 |
+
2. **Docker / GHCR image deployment**: suitable for containerized, orchestrated, or cloud environments.
|
| 202 |
+
3. **Vercel deployment**: suitable if you already use Vercel and accept its platform constraints.
|
| 203 |
+
4. **Run from source / build locally**: suitable for development, debugging, or when you need to modify the code yourself.
|
| 204 |
+
|
| 205 |
+
### Universal First Step (all deployment modes)
|
| 206 |
+
|
| 207 |
+
Use `config.json` as the single source of truth (recommended):
|
| 208 |
+
|
| 209 |
+
```bash
|
| 210 |
+
cp config.example.json config.json
|
| 211 |
+
# Edit config.json
|
| 212 |
+
```
|
| 213 |
+
|
| 214 |
+
Recommended per deployment mode:
|
| 215 |
+
- Local run: read `config.json` directly
|
| 216 |
+
- Docker / Vercel: generate Base64 from `config.json` and inject as `DS2API_CONFIG_JSON`, or paste raw JSON directly
|
| 217 |
+
|
| 218 |
+
The WebUI admin panel’s “Full configuration template” is loaded from the same `config.example.json`, so updating that file keeps the frontend template in sync.
|
| 219 |
+
|
| 220 |
+
### Option 1: Download Release Binaries
|
| 221 |
+
|
| 222 |
+
GitHub Actions automatically builds multi-platform archives on each Release:
|
| 223 |
+
|
| 224 |
+
```bash
|
| 225 |
+
# After downloading the archive for your platform
|
| 226 |
+
tar -xzf ds2api_<tag>_linux_amd64.tar.gz
|
| 227 |
+
cd ds2api_<tag>_linux_amd64
|
| 228 |
+
cp config.example.json config.json
|
| 229 |
+
# Edit config.json
|
| 230 |
+
./ds2api
|
| 231 |
+
```
|
| 232 |
+
|
| 233 |
+
### Option 2: Docker / GHCR
|
| 234 |
+
|
| 235 |
+
```bash
|
| 236 |
+
# Pull prebuilt image
|
| 237 |
+
docker pull ghcr.io/cjackhwang/ds2api:latest
|
| 238 |
+
|
| 239 |
+
# Or run a pinned version
|
| 240 |
+
# docker pull ghcr.io/cjackhwang/ds2api:v3.0.0
|
| 241 |
+
|
| 242 |
+
# Prepare env file and config file
|
| 243 |
+
cp .env.example .env
|
| 244 |
+
cp config.example.json config.json
|
| 245 |
+
|
| 246 |
+
# Start with compose
|
| 247 |
+
docker-compose up -d
|
| 248 |
+
```
|
| 249 |
+
|
| 250 |
+
The default `docker-compose.yml` uses `ghcr.io/cjackhwang/ds2api:latest` and maps host port `6011` to container port `5001`. If you want `5001` exposed directly, set `DS2API_HOST_PORT=5001` (or adjust the `ports` mapping).
|
| 251 |
+
It also mounts `./config.json` to `/data/config.json` and sets `DS2API_CONFIG_PATH=/data/config.json` by default, which avoids runtime token persistence failures caused by read-only `/app`.
|
| 252 |
+
|
| 253 |
+
Rebuild after updates: `docker-compose up -d --build`
|
| 254 |
+
|
| 255 |
+
#### Zeabur One-Click (Dockerfile)
|
| 256 |
+
|
| 257 |
+
1. Click the “Deploy on Zeabur” button above to deploy.
|
| 258 |
+
2. After deployment, open `/admin` and login with `DS2API_ADMIN_KEY` shown in Zeabur env/template instructions.
|
| 259 |
+
3. Import / edit config in Admin UI (it will be written and persisted to `/data/config.json`).
|
| 260 |
+
|
| 261 |
+
Fresh Zeabur volumes can start without `/data/config.json`; DS2API will boot with an empty file-backed config and create the file on the first Admin UI save.
|
| 262 |
+
|
| 263 |
+
For manual deployment without the template, create a Zeabur GitHub service, keep Root Directory as `/`, build with the repo-root `Dockerfile`, mount a persistent volume at `/data`, set `PORT=5001`, `DS2API_ADMIN_KEY=your-strong-secret`, and `DS2API_CONFIG_PATH=/data/config.json`, then expose HTTP port `5001`. See [docs/DEPLOY.en.md](docs/DEPLOY.en.md#manual-deployment-without-the-template) for the full guide.
|
| 264 |
+
|
| 265 |
+
Note: when Zeabur builds directly from the repo `Dockerfile`, you do not need to pass `BUILD_VERSION`. The image prefers that build arg when provided, and automatically falls back to the repo-root `VERSION` file when it is absent.
|
| 266 |
+
|
| 267 |
+
### Option 3: Vercel
|
| 268 |
+
|
| 269 |
+
1. Fork this repo to your GitHub account
|
| 270 |
+
2. Import the project on Vercel
|
| 271 |
+
3. Set environment variables (minimum: `DS2API_ADMIN_KEY`; recommended to also set `DS2API_CONFIG_JSON`)
|
| 272 |
+
4. Deploy
|
| 273 |
+
|
| 274 |
+
Recommended first step in repo root:
|
| 275 |
+
|
| 276 |
+
```bash
|
| 277 |
+
cp config.example.json config.json
|
| 278 |
+
# Edit config.json
|
| 279 |
+
```
|
| 280 |
+
|
| 281 |
+
Recommended: convert `config.json` to Base64 locally, then paste into `DS2API_CONFIG_JSON` to avoid JSON formatting mistakes:
|
| 282 |
+
|
| 283 |
+
```bash
|
| 284 |
+
base64 < config.json | tr -d '\n'
|
| 285 |
+
```
|
| 286 |
+
|
| 287 |
+
> **Streaming note**: OpenAI Chat streaming on Vercel is routed to `api/chat-stream.js` (Node Runtime), but `vercel.json` rewrites only the canonical `/v1/chat/completions` path to Node; the root shortcut `/chat/completions` stays on the Go main path. Auth, account selection, and session/PoW preparation are still handled by the Go internal prepare endpoint; streaming output (including `tools`) is assembled on Node with Go-aligned anti-leak handling. Use `/v1/chat/completions` on Vercel when real-time streaming is required.
|
| 288 |
+
|
| 289 |
+
For detailed deployment instructions, see the [Deployment Guide](docs/DEPLOY.en.md).
|
| 290 |
+
|
| 291 |
+
### Option 4: Local Run
|
| 292 |
+
|
| 293 |
+
**Prerequisites**: Go 1.26+, Node.js `20.19+` or `22.12+` (only if building WebUI locally; CI / Docker builds use Node 24), and npm available; npm 10+ is recommended
|
| 294 |
+
|
| 295 |
+
```bash
|
| 296 |
+
# 1. Clone
|
| 297 |
+
git clone https://github.com/CJackHwang/ds2api.git
|
| 298 |
+
cd ds2api
|
| 299 |
+
|
| 300 |
+
# 2. Configure
|
| 301 |
+
cp config.example.json config.json
|
| 302 |
+
# Edit config.json with your DeepSeek account info and API keys
|
| 303 |
+
|
| 304 |
+
# 3. Start
|
| 305 |
+
go run ./cmd/ds2api
|
| 306 |
+
```
|
| 307 |
+
|
| 308 |
+
Default local URL: `http://127.0.0.1:5001`
|
| 309 |
+
|
| 310 |
+
The server actually binds to `0.0.0.0:5001`, so devices on the same LAN can usually reach it through your private IP as well.
|
| 311 |
+
|
| 312 |
+
> **WebUI auto-build**: On first local startup, if the WebUI static directory is missing, DS2API auto-runs `npm ci --prefix webui` (only when dependencies are missing) and `npm run build --prefix webui -- --outDir static/admin --emptyOutDir` (requires Node.js; `DS2API_STATIC_ADMIN_DIR` can override the static directory). You can also build manually: `./scripts/build-webui.sh`
|
| 313 |
+
|
| 314 |
+
## Configuration
|
| 315 |
+
|
| 316 |
+
`README` keeps only the onboarding path. Use [config.example.json](config.example.json) as the field template, and see the [deployment guide](docs/DEPLOY.en.md#0-prerequisites) plus [API configuration notes](API.en.md#configuration-best-practice) for full details.
|
| 317 |
+
|
| 318 |
+
Common fields:
|
| 319 |
+
|
| 320 |
+
- `keys` / `api_keys`: client API keys; `api_keys` adds `name` and `remark` metadata while `keys` remains compatible.
|
| 321 |
+
- `accounts`: managed DeepSeek accounts, supporting `email` or `mobile` login plus proxy/name/remark metadata.
|
| 322 |
+
- `model_aliases`: one shared alias map for OpenAI / Claude / Gemini model names.
|
| 323 |
+
- `runtime`: account concurrency, queueing, and token refresh behavior, hot-reloadable via Admin Settings.
|
| 324 |
+
- `auto_delete.mode`: remote session cleanup after each request, supporting `none` / `single` / `all`.
|
| 325 |
+
- `current_input_file`: the global context split/upload mode; it is enabled by default and uploads the full context as a randomly named context file (filename never includes "history") once the character threshold is reached.
|
| 326 |
+
- If you turn off `current_input_file`, requests pass through directly without uploading any split context file.
|
| 327 |
+
|
| 328 |
+
For the full environment variable list, see [docs/DEPLOY.en.md](docs/DEPLOY.en.md). For auth behavior, see [API.en.md](API.en.md#authentication).
|
| 329 |
+
|
| 330 |
+
## Authentication Modes
|
| 331 |
+
|
| 332 |
+
For business endpoints (`/v1/*`, `/anthropic/*`, Gemini routes), DS2API supports two modes:
|
| 333 |
+
|
| 334 |
+
| Mode | Description |
|
| 335 |
+
| --- | --- |
|
| 336 |
+
| **Managed account** | Use a key from `config.keys` via `Authorization: Bearer ...` or `x-api-key`; DS2API auto-selects an account |
|
| 337 |
+
| **Direct token** | If the token is not in `config.keys`, DS2API treats it as a DeepSeek token directly |
|
| 338 |
+
|
| 339 |
+
Optional header `X-Ds2-Target-Account`: Pin a specific managed account (value is email or mobile).
|
| 340 |
+
When no target account is pinned, if a completion would end as `429 upstream_empty_output` after the same-account empty-output retry, managed-account mode switches to the next available account, creates a fresh session, and retries the original payload once.
|
| 341 |
+
Gemini routes also accept `x-goog-api-key`, or `?key=` / `?api_key=` when no auth header is present.
|
| 342 |
+
|
| 343 |
+
## Concurrency Model
|
| 344 |
+
|
| 345 |
+
```
|
| 346 |
+
Per-account inflight = DS2API_ACCOUNT_MAX_INFLIGHT (default 2)
|
| 347 |
+
Recommended concurrency = account_count × per_account_inflight
|
| 348 |
+
Queue limit = DS2API_ACCOUNT_MAX_QUEUE (default = recommended concurrency)
|
| 349 |
+
429 threshold = inflight + queue ≈ account_count × 4
|
| 350 |
+
```
|
| 351 |
+
|
| 352 |
+
- When inflight slots are full, requests enter a waiting queue — **no immediate 429**
|
| 353 |
+
- 429 is returned only when total load exceeds inflight + queue capacity; current responses do not include `Retry-After`
|
| 354 |
+
- Completion empty-output 429s first get the same-account compensation retry; managed-account mode also tries one alternate-account fresh retry before returning the final 429
|
| 355 |
+
- `GET /admin/queue/status` returns real-time concurrency state
|
| 356 |
+
|
| 357 |
+
## Tool Call Adaptation
|
| 358 |
+
|
| 359 |
+
When `tools` is present in the request, DS2API performs anti-leak handling:
|
| 360 |
+
|
| 361 |
+
1. Toolcall feature matching is enabled only in **non-code-block context** (fenced examples are ignored)
|
| 362 |
+
2. The parser treats the halfwidth-pipe DSML shell as the recommended executable tool-calling syntax: `<|DSML|tool_calls>` → `<|DSML|invoke name="...">` → `<|DSML|parameter name="...">`; it also accepts legacy canonical XML `<tool_calls>` → `<invoke name="...">` → `<parameter name="...">`, plus common DSML prefix/separator drift. DSML is a shell alias and internal parsing remains XML-based; legacy `<tools>` / `<tool_call>` / `<tool_name>` / `<param>`, `<function_call>`, `tool_use`, antml variants, and standalone JSON `tool_calls` payloads are treated as plain text, and complete but malformed wrappers are released as plain text too
|
| 363 |
+
3. `responses` streaming strictly uses official item lifecycle events (`response.output_item.*`, `response.content_part.*`, `response.function_call_arguments.*`)
|
| 364 |
+
4. `responses` supports and enforces `tool_choice` (`auto`/`none`/`required`/forced function); `required` violations return `422` for non-stream and `response.failed` for stream
|
| 365 |
+
5. The output protocol follows the client request (OpenAI / Claude / Gemini native shapes); model-side prompting can prefer XML, and the compatibility layer handles the protocol-specific translation
|
| 366 |
+
|
| 367 |
+
> Note: the current parser still prioritizes “parse successfully whenever possible”; hard allow-list rejection for undeclared tool names is not enabled yet.
|
| 368 |
+
> Explicit empty strings or whitespace-only parameters are preserved by the parser; prompting tells the model not to emit blank parameters, and missing/empty argument rejection belongs in the tool executor or client schema validation.
|
| 369 |
+
|
| 370 |
+
## Local Dev Packet Capture
|
| 371 |
+
|
| 372 |
+
This is for debugging issues such as Responses reasoning streaming and tool-call handoff. When enabled, DS2API stores the latest N DeepSeek conversation payload pairs (request body + upstream response body), defaulting to 20 entries with auto-eviction; each response body is capped at 5 MB by default.
|
| 373 |
+
|
| 374 |
+
Enable example:
|
| 375 |
+
|
| 376 |
+
```bash
|
| 377 |
+
DS2API_DEV_PACKET_CAPTURE=true \
|
| 378 |
+
DS2API_DEV_PACKET_CAPTURE_LIMIT=20 \
|
| 379 |
+
go run ./cmd/ds2api
|
| 380 |
+
```
|
| 381 |
+
|
| 382 |
+
Inspect/clear (Admin JWT required):
|
| 383 |
+
|
| 384 |
+
- `GET /admin/dev/captures`: list captured items (newest first)
|
| 385 |
+
- `DELETE /admin/dev/captures`: clear captured items
|
| 386 |
+
- `GET /admin/dev/raw-samples/query?q=keyword&limit=20`: search current in-memory captures by prompt keyword and group `completion + continue` by `chat_session_id`
|
| 387 |
+
- `POST /admin/dev/raw-samples/save`: persist a selected capture chain as `tests/raw_stream_samples/<sample-id>/`
|
| 388 |
+
|
| 389 |
+
Response fields include:
|
| 390 |
+
|
| 391 |
+
- `request_body`: full payload sent to DeepSeek
|
| 392 |
+
- `response_body`: concatenated raw upstream stream body text
|
| 393 |
+
- `response_truncated`: whether body-size truncation happened
|
| 394 |
+
|
| 395 |
+
The save endpoint can target a chain by `query`, `chain_key`, or `capture_id`. Example:
|
| 396 |
+
|
| 397 |
+
```json
|
| 398 |
+
{"query":"Guangzhou weather","sample_id":"gz-weather-from-memory"}
|
| 399 |
+
```
|
| 400 |
+
|
| 401 |
+
## Documentation Index
|
| 402 |
+
|
| 403 |
+
| Document | Description |
|
| 404 |
+
| --- | --- |
|
| 405 |
+
| [API.md](API.md) / [API.en.md](API.en.md) | API reference with request/response examples |
|
| 406 |
+
| [DEPLOY.md](docs/DEPLOY.md) / [DEPLOY.en.md](docs/DEPLOY.en.md) | Deployment guide (local/Docker/Vercel/systemd) |
|
| 407 |
+
| [CONTRIBUTING.md](docs/CONTRIBUTING.md) / [CONTRIBUTING.en.md](docs/CONTRIBUTING.en.md) | Contributing guide |
|
| 408 |
+
| [TESTING.md](docs/TESTING.md) | Testsuite guide |
|
| 409 |
+
|
| 410 |
+
## Testing
|
| 411 |
+
|
| 412 |
+
For the full testing guide, see [docs/TESTING.md](docs/TESTING.md).
|
| 413 |
+
|
| 414 |
+
Quick commands:
|
| 415 |
+
|
| 416 |
+
```bash
|
| 417 |
+
# Local PR gates
|
| 418 |
+
./scripts/lint.sh
|
| 419 |
+
./tests/scripts/check-refactor-line-gate.sh
|
| 420 |
+
./tests/scripts/run-unit-all.sh
|
| 421 |
+
npm run build --prefix webui
|
| 422 |
+
|
| 423 |
+
# Live end-to-end tests (real accounts, full request/response logs)
|
| 424 |
+
./tests/scripts/run-live.sh
|
| 425 |
+
```
|
| 426 |
+
|
| 427 |
+
## Release Artifact Automation (GitHub Actions)
|
| 428 |
+
|
| 429 |
+
Workflow: `.github/workflows/release-artifacts.yml`
|
| 430 |
+
|
| 431 |
+
- **Trigger**: by default only on GitHub Release `published`; you can also run it manually via `workflow_dispatch` and pass `release_tag` to rerun / backfill
|
| 432 |
+
- **Outputs**: multi-platform binary archives (`linux/amd64`, `linux/arm64`, `linux/armv7`, `darwin/amd64`, `darwin/arm64`, `windows/amd64`, `windows/arm64`), Linux Docker image export tarballs, and `sha256sums.txt`
|
| 433 |
+
- **Container publishing**: GHCR only (`ghcr.io/cjackhwang/ds2api`)
|
| 434 |
+
- **Each binary archive includes**: the `ds2api` executable, `static/admin`, `config.example.json`, `.env.example`, `README.MD`, `README.en.md`, and `LICENSE`
|
| 435 |
+
|
| 436 |
+
## Disclaimer
|
| 437 |
+
|
| 438 |
+
This project is built through reverse engineering and is provided for learning, research, personal experimentation, and internal validation only. No commercial authorization is granted, and no warranty of stability, fitness, or results is provided.
|
| 439 |
+
The author and repository maintainers are not responsible for any direct or indirect loss, account suspension, data loss, legal risk, or third-party claims arising from use, modification, distribution, deployment, or reliance on this project.
|
| 440 |
+
|
| 441 |
+
Do not use this project in ways that violate service terms, agreements, laws, or platform rules. Before any commercial use, review the `LICENSE`, the relevant terms, and confirm that you have the author's written permission.
|
README.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: DS2API
|
| 3 |
+
emoji: 🚀
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: purple
|
| 6 |
+
sdk: docker
|
| 7 |
+
pinned: false
|
| 8 |
+
---
|
| 9 |
+
|
| 10 |
+
# DS2API - DeepSeek to OpenAI API Adapter
|
| 11 |
+
|
| 12 |
+
DeepSeek web chat to OpenAI-compatible API adapter with multi-protocol support (OpenAI, Claude, Gemini).
|
| 13 |
+
|
| 14 |
+
## Quick Start
|
| 15 |
+
|
| 16 |
+
1. Visit /admin to configure your DeepSeek accounts and API keys
|
| 17 |
+
2. Use the OpenAI-compatible API at /v1/chat/completions
|
SECURITY.md
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Security Policy
|
| 2 |
+
|
| 3 |
+
## Supported Versions
|
| 4 |
+
|
| 5 |
+
**Only the latest version** receives security updates.
|
| 6 |
+
If you are using an older version, please upgrade to the latest release.
|
| 7 |
+
|
| 8 |
+
| Version | Supported |
|
| 9 |
+
| -------------- | ------------------ |
|
| 10 |
+
| latest | :white_check_mark: |
|
| 11 |
+
| < latest | :x: |
|
| 12 |
+
|
| 13 |
+
> **Why?** This project is maintained by a single developer. Keeping only one active version ensures fast response times and avoids legacy maintenance overhead.
|
| 14 |
+
|
| 15 |
+
## What is a Security Vulnerability?
|
| 16 |
+
|
| 17 |
+
A **security vulnerability** is a bug that can be exploited to compromise:
|
| 18 |
+
- Data confidentiality (e.g., leaking secrets, user data)
|
| 19 |
+
- Data integrity (e.g., unauthorized modification)
|
| 20 |
+
- System availability (e.g., remote crash, denial of service)
|
| 21 |
+
- Privilege escalation (e.g., normal user gains admin rights)
|
| 22 |
+
|
| 23 |
+
**Examples**: SQL injection, command injection, path traversal, authentication bypass, insecure deserialization, sensitive data exposure.
|
| 24 |
+
|
| 25 |
+
**What is NOT a security vulnerability?**
|
| 26 |
+
Regular bugs like crashes (without exploit potential), incorrect return values, performance issues, missing features, or documentation typos. Please report those via **GitHub Issues** publicly.
|
| 27 |
+
|
| 28 |
+
## Reporting a Vulnerability
|
| 29 |
+
|
| 30 |
+
If you believe you have found a security vulnerability, **please do NOT open a public issue**.
|
| 31 |
+
|
| 32 |
+
Instead, send an email to: **cjackhwang@qq.com**
|
| 33 |
+
|
| 34 |
+
Please include as much as possible:
|
| 35 |
+
- A clear description of the issue
|
| 36 |
+
- Steps to reproduce (code / input / environment)
|
| 37 |
+
- Potential impact (what could an attacker do?)
|
| 38 |
+
- Suggested fix (if any)
|
| 39 |
+
|
| 40 |
+
You can expect:
|
| 41 |
+
- **Initial response** within 3 business days (acknowledgment)
|
| 42 |
+
- **Confirmation or clarification** within 7 days
|
| 43 |
+
- **Fix or decision** within 14 days (depending on complexity)
|
| 44 |
+
|
| 45 |
+
## What to Expect After Reporting
|
| 46 |
+
|
| 47 |
+
| Outcome | What happens |
|
| 48 |
+
| ------------------ | ------------- |
|
| 49 |
+
| **Accepted** | I will develop a fix, release a patch version, and may credit you in the release notes (unless you prefer anonymity). |
|
| 50 |
+
| **Declined** | I will explain why (e.g., not a security issue, already fixed, out of scope, or requires a larger redesign). |
|
| 51 |
+
| **Need more info** | I will ask follow-up questions. If no response within 14 days, the report may be considered stale. |
|
| 52 |
+
|
| 53 |
+
## Disclosure Policy
|
| 54 |
+
|
| 55 |
+
- Vulnerabilities will be **fixed privately** and then released as a new version.
|
| 56 |
+
- After the fix is released, I will typically publish a short security advisory (via GitHub Security Advisories) without revealing exploit details.
|
| 57 |
+
- Public disclosure can be coordinated if you request it.
|
| 58 |
+
|
| 59 |
+
## Recognition
|
| 60 |
+
|
| 61 |
+
I appreciate security researchers who follow responsible disclosure. Contributors who report valid, previously unknown vulnerabilities may be acknowledged in the project's README or release notes (unless they prefer to stay anonymous).
|
| 62 |
+
|
| 63 |
+
---
|
| 64 |
+
|
| 65 |
+
*Thank you for helping keep this project safe!*
|
VERSION
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
4.6.1
|
_fix.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pathlib
|
| 2 |
+
p = pathlib.Path("Dockerfile")
|
| 3 |
+
t = p.read_text()
|
| 4 |
+
old = 'CMD["/usr/local/bin/ds2api"]'
|
| 5 |
+
new = 'COPY entrypoint.sh /usr/local/bin/entrypoint.sh\nRUN chmod +x /usr/local/bin/entrypoint.sh\nCMD["/usr/local/bin/entrypoint.sh"]'
|
| 6 |
+
t = t.replace(old, new)
|
| 7 |
+
p.write_text(t)
|
| 8 |
+
print("Done")
|
_fix2.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pathlib
|
| 2 |
+
p=pathlib.Path(chr(68)+chr(111)+chr(99)+chr(107)+chr(101)+chr(114)+chr(102)+chr(105)+chr(108)+chr(101))
|
| 3 |
+
t=p.read_text()
|
| 4 |
+
old=CMD [/usr/local/bin/ds2api]
|
| 5 |
+
new=CMD [/usr/local/bin/entrypoint.sh]
|
| 6 |
+
print(repr(old))
|
| 7 |
+
print(repr(new))
|
api/chat-stream.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use strict';
|
| 2 |
+
|
| 3 |
+
module.exports = require('../internal/js/chat-stream/index.js');
|
api/index.go
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package handler
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"net/http"
|
| 5 |
+
"sync"
|
| 6 |
+
|
| 7 |
+
"ds2api/app"
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
var (
|
| 11 |
+
once sync.Once
|
| 12 |
+
h http.Handler
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
func Handler(w http.ResponseWriter, r *http.Request) {
|
| 16 |
+
once.Do(func() {
|
| 17 |
+
h = app.NewHandler()
|
| 18 |
+
})
|
| 19 |
+
h.ServeHTTP(w, r)
|
| 20 |
+
}
|
app/handler.go
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package app
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"net/http"
|
| 5 |
+
|
| 6 |
+
"ds2api/internal/config"
|
| 7 |
+
"ds2api/internal/server"
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
func NewHandler() http.Handler {
|
| 11 |
+
app, err := server.NewApp()
|
| 12 |
+
if err != nil {
|
| 13 |
+
config.Logger.Error("[app] init failed", "error", err)
|
| 14 |
+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
| 15 |
+
server.WriteUnhandledError(w, err)
|
| 16 |
+
})
|
| 17 |
+
}
|
| 18 |
+
return app.Router
|
| 19 |
+
}
|
cf-worker/package-lock.json
ADDED
|
@@ -0,0 +1,1504 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "ds2api-health-check",
|
| 3 |
+
"version": "1.0.0",
|
| 4 |
+
"lockfileVersion": 3,
|
| 5 |
+
"requires": true,
|
| 6 |
+
"packages": {
|
| 7 |
+
"": {
|
| 8 |
+
"name": "ds2api-health-check",
|
| 9 |
+
"version": "1.0.0",
|
| 10 |
+
"devDependencies": {
|
| 11 |
+
"wrangler": "^4"
|
| 12 |
+
}
|
| 13 |
+
},
|
| 14 |
+
"node_modules/@cloudflare/kv-asset-handler": {
|
| 15 |
+
"version": "0.5.0",
|
| 16 |
+
"resolved": "https://registry.npmjs.org/@cloudflare/kv-asset-handler/-/kv-asset-handler-0.5.0.tgz",
|
| 17 |
+
"integrity": "sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg==",
|
| 18 |
+
"dev": true,
|
| 19 |
+
"license": "MIT OR Apache-2.0",
|
| 20 |
+
"engines": {
|
| 21 |
+
"node": ">=22.0.0"
|
| 22 |
+
}
|
| 23 |
+
},
|
| 24 |
+
"node_modules/@cloudflare/unenv-preset": {
|
| 25 |
+
"version": "2.16.1",
|
| 26 |
+
"resolved": "https://registry.npmjs.org/@cloudflare/unenv-preset/-/unenv-preset-2.16.1.tgz",
|
| 27 |
+
"integrity": "sha512-ECxObrMfyTl5bhQf/lZCXwo5G6xX9IAUo+nDMKK4SZ8m4Jvvxp52vilxyySSWh2YTZz8+HQ07qGH/2rEom1vDw==",
|
| 28 |
+
"dev": true,
|
| 29 |
+
"license": "MIT OR Apache-2.0",
|
| 30 |
+
"peerDependencies": {
|
| 31 |
+
"unenv": "2.0.0-rc.24",
|
| 32 |
+
"workerd": ">1.20260305.0 <2.0.0-0"
|
| 33 |
+
},
|
| 34 |
+
"peerDependenciesMeta": {
|
| 35 |
+
"workerd": {
|
| 36 |
+
"optional": true
|
| 37 |
+
}
|
| 38 |
+
}
|
| 39 |
+
},
|
| 40 |
+
"node_modules/@cloudflare/workerd-darwin-64": {
|
| 41 |
+
"version": "1.20260603.1",
|
| 42 |
+
"resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20260603.1.tgz",
|
| 43 |
+
"integrity": "sha512-cEXDWu6V3ZrpmwWkM4OJE9AeXjdAgOY5rh8EHhcBVCuP5rxnzUbPzLtrVOHx0UUUAcCrFq0Xsa6mZKL1VUZsKQ==",
|
| 44 |
+
"cpu": [
|
| 45 |
+
"x64"
|
| 46 |
+
],
|
| 47 |
+
"dev": true,
|
| 48 |
+
"license": "Apache-2.0",
|
| 49 |
+
"optional": true,
|
| 50 |
+
"os": [
|
| 51 |
+
"darwin"
|
| 52 |
+
],
|
| 53 |
+
"engines": {
|
| 54 |
+
"node": ">=16"
|
| 55 |
+
}
|
| 56 |
+
},
|
| 57 |
+
"node_modules/@cloudflare/workerd-darwin-arm64": {
|
| 58 |
+
"version": "1.20260603.1",
|
| 59 |
+
"resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-arm64/-/workerd-darwin-arm64-1.20260603.1.tgz",
|
| 60 |
+
"integrity": "sha512-uBPK4LaWJNbbCYwPnUAehlHbbVulhVZPZsdcAhBPfZhHb3QAuAEPAQepO/P67R3V6Cni4YGx1fLbL8A5wwoaNA==",
|
| 61 |
+
"cpu": [
|
| 62 |
+
"arm64"
|
| 63 |
+
],
|
| 64 |
+
"dev": true,
|
| 65 |
+
"license": "Apache-2.0",
|
| 66 |
+
"optional": true,
|
| 67 |
+
"os": [
|
| 68 |
+
"darwin"
|
| 69 |
+
],
|
| 70 |
+
"engines": {
|
| 71 |
+
"node": ">=16"
|
| 72 |
+
}
|
| 73 |
+
},
|
| 74 |
+
"node_modules/@cloudflare/workerd-linux-64": {
|
| 75 |
+
"version": "1.20260603.1",
|
| 76 |
+
"resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-64/-/workerd-linux-64-1.20260603.1.tgz",
|
| 77 |
+
"integrity": "sha512-ht9l6/8Tk7Rp6kA4S9oFZ4X8u0VjnnFdmU/6B3fnABYKREYTKh2RdOqXqXxcp5eNJseireKnWik/hQOPK1CutQ==",
|
| 78 |
+
"cpu": [
|
| 79 |
+
"x64"
|
| 80 |
+
],
|
| 81 |
+
"dev": true,
|
| 82 |
+
"license": "Apache-2.0",
|
| 83 |
+
"optional": true,
|
| 84 |
+
"os": [
|
| 85 |
+
"linux"
|
| 86 |
+
],
|
| 87 |
+
"engines": {
|
| 88 |
+
"node": ">=16"
|
| 89 |
+
}
|
| 90 |
+
},
|
| 91 |
+
"node_modules/@cloudflare/workerd-linux-arm64": {
|
| 92 |
+
"version": "1.20260603.1",
|
| 93 |
+
"resolved": "https://registry.npmjs.org/@cloudflare/workerd-linux-arm64/-/workerd-linux-arm64-1.20260603.1.tgz",
|
| 94 |
+
"integrity": "sha512-LJZ6x00rAjSrobV4m0ZW0TpH5ilBbKcWBzlH+y+KOUsIE/CpTuhAzKV43TbSnFLRX5+jrWKiz2v0hO91lPXy6A==",
|
| 95 |
+
"cpu": [
|
| 96 |
+
"arm64"
|
| 97 |
+
],
|
| 98 |
+
"dev": true,
|
| 99 |
+
"license": "Apache-2.0",
|
| 100 |
+
"optional": true,
|
| 101 |
+
"os": [
|
| 102 |
+
"linux"
|
| 103 |
+
],
|
| 104 |
+
"engines": {
|
| 105 |
+
"node": ">=16"
|
| 106 |
+
}
|
| 107 |
+
},
|
| 108 |
+
"node_modules/@cloudflare/workerd-windows-64": {
|
| 109 |
+
"version": "1.20260603.1",
|
| 110 |
+
"resolved": "https://registry.npmjs.org/@cloudflare/workerd-windows-64/-/workerd-windows-64-1.20260603.1.tgz",
|
| 111 |
+
"integrity": "sha512-DvwqkXMAJRPoDN4PxapAwhlz/6ouD+6R1ttbAEK3cWD/QBvFF5STx7Ds/9Irf+rBly3np3uHWkeX+wZnNFEuzA==",
|
| 112 |
+
"cpu": [
|
| 113 |
+
"x64"
|
| 114 |
+
],
|
| 115 |
+
"dev": true,
|
| 116 |
+
"license": "Apache-2.0",
|
| 117 |
+
"optional": true,
|
| 118 |
+
"os": [
|
| 119 |
+
"win32"
|
| 120 |
+
],
|
| 121 |
+
"engines": {
|
| 122 |
+
"node": ">=16"
|
| 123 |
+
}
|
| 124 |
+
},
|
| 125 |
+
"node_modules/@cspotcode/source-map-support": {
|
| 126 |
+
"version": "0.8.1",
|
| 127 |
+
"resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz",
|
| 128 |
+
"integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==",
|
| 129 |
+
"dev": true,
|
| 130 |
+
"license": "MIT",
|
| 131 |
+
"dependencies": {
|
| 132 |
+
"@jridgewell/trace-mapping": "0.3.9"
|
| 133 |
+
},
|
| 134 |
+
"engines": {
|
| 135 |
+
"node": ">=12"
|
| 136 |
+
}
|
| 137 |
+
},
|
| 138 |
+
"node_modules/@emnapi/runtime": {
|
| 139 |
+
"version": "1.10.0",
|
| 140 |
+
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz",
|
| 141 |
+
"integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==",
|
| 142 |
+
"dev": true,
|
| 143 |
+
"license": "MIT",
|
| 144 |
+
"optional": true,
|
| 145 |
+
"dependencies": {
|
| 146 |
+
"tslib": "^2.4.0"
|
| 147 |
+
}
|
| 148 |
+
},
|
| 149 |
+
"node_modules/@esbuild/aix-ppc64": {
|
| 150 |
+
"version": "0.27.3",
|
| 151 |
+
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.3.tgz",
|
| 152 |
+
"integrity": "sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg==",
|
| 153 |
+
"cpu": [
|
| 154 |
+
"ppc64"
|
| 155 |
+
],
|
| 156 |
+
"dev": true,
|
| 157 |
+
"license": "MIT",
|
| 158 |
+
"optional": true,
|
| 159 |
+
"os": [
|
| 160 |
+
"aix"
|
| 161 |
+
],
|
| 162 |
+
"engines": {
|
| 163 |
+
"node": ">=18"
|
| 164 |
+
}
|
| 165 |
+
},
|
| 166 |
+
"node_modules/@esbuild/android-arm": {
|
| 167 |
+
"version": "0.27.3",
|
| 168 |
+
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.3.tgz",
|
| 169 |
+
"integrity": "sha512-i5D1hPY7GIQmXlXhs2w8AWHhenb00+GxjxRncS2ZM7YNVGNfaMxgzSGuO8o8SJzRc/oZwU2bcScvVERk03QhzA==",
|
| 170 |
+
"cpu": [
|
| 171 |
+
"arm"
|
| 172 |
+
],
|
| 173 |
+
"dev": true,
|
| 174 |
+
"license": "MIT",
|
| 175 |
+
"optional": true,
|
| 176 |
+
"os": [
|
| 177 |
+
"android"
|
| 178 |
+
],
|
| 179 |
+
"engines": {
|
| 180 |
+
"node": ">=18"
|
| 181 |
+
}
|
| 182 |
+
},
|
| 183 |
+
"node_modules/@esbuild/android-arm64": {
|
| 184 |
+
"version": "0.27.3",
|
| 185 |
+
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.3.tgz",
|
| 186 |
+
"integrity": "sha512-YdghPYUmj/FX2SYKJ0OZxf+iaKgMsKHVPF1MAq/P8WirnSpCStzKJFjOjzsW0QQ7oIAiccHdcqjbHmJxRb/dmg==",
|
| 187 |
+
"cpu": [
|
| 188 |
+
"arm64"
|
| 189 |
+
],
|
| 190 |
+
"dev": true,
|
| 191 |
+
"license": "MIT",
|
| 192 |
+
"optional": true,
|
| 193 |
+
"os": [
|
| 194 |
+
"android"
|
| 195 |
+
],
|
| 196 |
+
"engines": {
|
| 197 |
+
"node": ">=18"
|
| 198 |
+
}
|
| 199 |
+
},
|
| 200 |
+
"node_modules/@esbuild/android-x64": {
|
| 201 |
+
"version": "0.27.3",
|
| 202 |
+
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.3.tgz",
|
| 203 |
+
"integrity": "sha512-IN/0BNTkHtk8lkOM8JWAYFg4ORxBkZQf9zXiEOfERX/CzxW3Vg1ewAhU7QSWQpVIzTW+b8Xy+lGzdYXV6UZObQ==",
|
| 204 |
+
"cpu": [
|
| 205 |
+
"x64"
|
| 206 |
+
],
|
| 207 |
+
"dev": true,
|
| 208 |
+
"license": "MIT",
|
| 209 |
+
"optional": true,
|
| 210 |
+
"os": [
|
| 211 |
+
"android"
|
| 212 |
+
],
|
| 213 |
+
"engines": {
|
| 214 |
+
"node": ">=18"
|
| 215 |
+
}
|
| 216 |
+
},
|
| 217 |
+
"node_modules/@esbuild/darwin-arm64": {
|
| 218 |
+
"version": "0.27.3",
|
| 219 |
+
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.3.tgz",
|
| 220 |
+
"integrity": "sha512-Re491k7ByTVRy0t3EKWajdLIr0gz2kKKfzafkth4Q8A5n1xTHrkqZgLLjFEHVD+AXdUGgQMq+Godfq45mGpCKg==",
|
| 221 |
+
"cpu": [
|
| 222 |
+
"arm64"
|
| 223 |
+
],
|
| 224 |
+
"dev": true,
|
| 225 |
+
"license": "MIT",
|
| 226 |
+
"optional": true,
|
| 227 |
+
"os": [
|
| 228 |
+
"darwin"
|
| 229 |
+
],
|
| 230 |
+
"engines": {
|
| 231 |
+
"node": ">=18"
|
| 232 |
+
}
|
| 233 |
+
},
|
| 234 |
+
"node_modules/@esbuild/darwin-x64": {
|
| 235 |
+
"version": "0.27.3",
|
| 236 |
+
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.3.tgz",
|
| 237 |
+
"integrity": "sha512-vHk/hA7/1AckjGzRqi6wbo+jaShzRowYip6rt6q7VYEDX4LEy1pZfDpdxCBnGtl+A5zq8iXDcyuxwtv3hNtHFg==",
|
| 238 |
+
"cpu": [
|
| 239 |
+
"x64"
|
| 240 |
+
],
|
| 241 |
+
"dev": true,
|
| 242 |
+
"license": "MIT",
|
| 243 |
+
"optional": true,
|
| 244 |
+
"os": [
|
| 245 |
+
"darwin"
|
| 246 |
+
],
|
| 247 |
+
"engines": {
|
| 248 |
+
"node": ">=18"
|
| 249 |
+
}
|
| 250 |
+
},
|
| 251 |
+
"node_modules/@esbuild/freebsd-arm64": {
|
| 252 |
+
"version": "0.27.3",
|
| 253 |
+
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.3.tgz",
|
| 254 |
+
"integrity": "sha512-ipTYM2fjt3kQAYOvo6vcxJx3nBYAzPjgTCk7QEgZG8AUO3ydUhvelmhrbOheMnGOlaSFUoHXB6un+A7q4ygY9w==",
|
| 255 |
+
"cpu": [
|
| 256 |
+
"arm64"
|
| 257 |
+
],
|
| 258 |
+
"dev": true,
|
| 259 |
+
"license": "MIT",
|
| 260 |
+
"optional": true,
|
| 261 |
+
"os": [
|
| 262 |
+
"freebsd"
|
| 263 |
+
],
|
| 264 |
+
"engines": {
|
| 265 |
+
"node": ">=18"
|
| 266 |
+
}
|
| 267 |
+
},
|
| 268 |
+
"node_modules/@esbuild/freebsd-x64": {
|
| 269 |
+
"version": "0.27.3",
|
| 270 |
+
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.3.tgz",
|
| 271 |
+
"integrity": "sha512-dDk0X87T7mI6U3K9VjWtHOXqwAMJBNN2r7bejDsc+j03SEjtD9HrOl8gVFByeM0aJksoUuUVU9TBaZa2rgj0oA==",
|
| 272 |
+
"cpu": [
|
| 273 |
+
"x64"
|
| 274 |
+
],
|
| 275 |
+
"dev": true,
|
| 276 |
+
"license": "MIT",
|
| 277 |
+
"optional": true,
|
| 278 |
+
"os": [
|
| 279 |
+
"freebsd"
|
| 280 |
+
],
|
| 281 |
+
"engines": {
|
| 282 |
+
"node": ">=18"
|
| 283 |
+
}
|
| 284 |
+
},
|
| 285 |
+
"node_modules/@esbuild/linux-arm": {
|
| 286 |
+
"version": "0.27.3",
|
| 287 |
+
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.3.tgz",
|
| 288 |
+
"integrity": "sha512-s6nPv2QkSupJwLYyfS+gwdirm0ukyTFNl3KTgZEAiJDd+iHZcbTPPcWCcRYH+WlNbwChgH2QkE9NSlNrMT8Gfw==",
|
| 289 |
+
"cpu": [
|
| 290 |
+
"arm"
|
| 291 |
+
],
|
| 292 |
+
"dev": true,
|
| 293 |
+
"license": "MIT",
|
| 294 |
+
"optional": true,
|
| 295 |
+
"os": [
|
| 296 |
+
"linux"
|
| 297 |
+
],
|
| 298 |
+
"engines": {
|
| 299 |
+
"node": ">=18"
|
| 300 |
+
}
|
| 301 |
+
},
|
| 302 |
+
"node_modules/@esbuild/linux-arm64": {
|
| 303 |
+
"version": "0.27.3",
|
| 304 |
+
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.3.tgz",
|
| 305 |
+
"integrity": "sha512-sZOuFz/xWnZ4KH3YfFrKCf1WyPZHakVzTiqji3WDc0BCl2kBwiJLCXpzLzUBLgmp4veFZdvN5ChW4Eq/8Fc2Fg==",
|
| 306 |
+
"cpu": [
|
| 307 |
+
"arm64"
|
| 308 |
+
],
|
| 309 |
+
"dev": true,
|
| 310 |
+
"license": "MIT",
|
| 311 |
+
"optional": true,
|
| 312 |
+
"os": [
|
| 313 |
+
"linux"
|
| 314 |
+
],
|
| 315 |
+
"engines": {
|
| 316 |
+
"node": ">=18"
|
| 317 |
+
}
|
| 318 |
+
},
|
| 319 |
+
"node_modules/@esbuild/linux-ia32": {
|
| 320 |
+
"version": "0.27.3",
|
| 321 |
+
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.3.tgz",
|
| 322 |
+
"integrity": "sha512-yGlQYjdxtLdh0a3jHjuwOrxQjOZYD/C9PfdbgJJF3TIZWnm/tMd/RcNiLngiu4iwcBAOezdnSLAwQDPqTmtTYg==",
|
| 323 |
+
"cpu": [
|
| 324 |
+
"ia32"
|
| 325 |
+
],
|
| 326 |
+
"dev": true,
|
| 327 |
+
"license": "MIT",
|
| 328 |
+
"optional": true,
|
| 329 |
+
"os": [
|
| 330 |
+
"linux"
|
| 331 |
+
],
|
| 332 |
+
"engines": {
|
| 333 |
+
"node": ">=18"
|
| 334 |
+
}
|
| 335 |
+
},
|
| 336 |
+
"node_modules/@esbuild/linux-loong64": {
|
| 337 |
+
"version": "0.27.3",
|
| 338 |
+
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.3.tgz",
|
| 339 |
+
"integrity": "sha512-WO60Sn8ly3gtzhyjATDgieJNet/KqsDlX5nRC5Y3oTFcS1l0KWba+SEa9Ja1GfDqSF1z6hif/SkpQJbL63cgOA==",
|
| 340 |
+
"cpu": [
|
| 341 |
+
"loong64"
|
| 342 |
+
],
|
| 343 |
+
"dev": true,
|
| 344 |
+
"license": "MIT",
|
| 345 |
+
"optional": true,
|
| 346 |
+
"os": [
|
| 347 |
+
"linux"
|
| 348 |
+
],
|
| 349 |
+
"engines": {
|
| 350 |
+
"node": ">=18"
|
| 351 |
+
}
|
| 352 |
+
},
|
| 353 |
+
"node_modules/@esbuild/linux-mips64el": {
|
| 354 |
+
"version": "0.27.3",
|
| 355 |
+
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.3.tgz",
|
| 356 |
+
"integrity": "sha512-APsymYA6sGcZ4pD6k+UxbDjOFSvPWyZhjaiPyl/f79xKxwTnrn5QUnXR5prvetuaSMsb4jgeHewIDCIWljrSxw==",
|
| 357 |
+
"cpu": [
|
| 358 |
+
"mips64el"
|
| 359 |
+
],
|
| 360 |
+
"dev": true,
|
| 361 |
+
"license": "MIT",
|
| 362 |
+
"optional": true,
|
| 363 |
+
"os": [
|
| 364 |
+
"linux"
|
| 365 |
+
],
|
| 366 |
+
"engines": {
|
| 367 |
+
"node": ">=18"
|
| 368 |
+
}
|
| 369 |
+
},
|
| 370 |
+
"node_modules/@esbuild/linux-ppc64": {
|
| 371 |
+
"version": "0.27.3",
|
| 372 |
+
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.3.tgz",
|
| 373 |
+
"integrity": "sha512-eizBnTeBefojtDb9nSh4vvVQ3V9Qf9Df01PfawPcRzJH4gFSgrObw+LveUyDoKU3kxi5+9RJTCWlj4FjYXVPEA==",
|
| 374 |
+
"cpu": [
|
| 375 |
+
"ppc64"
|
| 376 |
+
],
|
| 377 |
+
"dev": true,
|
| 378 |
+
"license": "MIT",
|
| 379 |
+
"optional": true,
|
| 380 |
+
"os": [
|
| 381 |
+
"linux"
|
| 382 |
+
],
|
| 383 |
+
"engines": {
|
| 384 |
+
"node": ">=18"
|
| 385 |
+
}
|
| 386 |
+
},
|
| 387 |
+
"node_modules/@esbuild/linux-riscv64": {
|
| 388 |
+
"version": "0.27.3",
|
| 389 |
+
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.3.tgz",
|
| 390 |
+
"integrity": "sha512-3Emwh0r5wmfm3ssTWRQSyVhbOHvqegUDRd0WhmXKX2mkHJe1SFCMJhagUleMq+Uci34wLSipf8Lagt4LlpRFWQ==",
|
| 391 |
+
"cpu": [
|
| 392 |
+
"riscv64"
|
| 393 |
+
],
|
| 394 |
+
"dev": true,
|
| 395 |
+
"license": "MIT",
|
| 396 |
+
"optional": true,
|
| 397 |
+
"os": [
|
| 398 |
+
"linux"
|
| 399 |
+
],
|
| 400 |
+
"engines": {
|
| 401 |
+
"node": ">=18"
|
| 402 |
+
}
|
| 403 |
+
},
|
| 404 |
+
"node_modules/@esbuild/linux-s390x": {
|
| 405 |
+
"version": "0.27.3",
|
| 406 |
+
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.3.tgz",
|
| 407 |
+
"integrity": "sha512-pBHUx9LzXWBc7MFIEEL0yD/ZVtNgLytvx60gES28GcWMqil8ElCYR4kvbV2BDqsHOvVDRrOxGySBM9Fcv744hw==",
|
| 408 |
+
"cpu": [
|
| 409 |
+
"s390x"
|
| 410 |
+
],
|
| 411 |
+
"dev": true,
|
| 412 |
+
"license": "MIT",
|
| 413 |
+
"optional": true,
|
| 414 |
+
"os": [
|
| 415 |
+
"linux"
|
| 416 |
+
],
|
| 417 |
+
"engines": {
|
| 418 |
+
"node": ">=18"
|
| 419 |
+
}
|
| 420 |
+
},
|
| 421 |
+
"node_modules/@esbuild/linux-x64": {
|
| 422 |
+
"version": "0.27.3",
|
| 423 |
+
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.3.tgz",
|
| 424 |
+
"integrity": "sha512-Czi8yzXUWIQYAtL/2y6vogER8pvcsOsk5cpwL4Gk5nJqH5UZiVByIY8Eorm5R13gq+DQKYg0+JyQoytLQas4dA==",
|
| 425 |
+
"cpu": [
|
| 426 |
+
"x64"
|
| 427 |
+
],
|
| 428 |
+
"dev": true,
|
| 429 |
+
"license": "MIT",
|
| 430 |
+
"optional": true,
|
| 431 |
+
"os": [
|
| 432 |
+
"linux"
|
| 433 |
+
],
|
| 434 |
+
"engines": {
|
| 435 |
+
"node": ">=18"
|
| 436 |
+
}
|
| 437 |
+
},
|
| 438 |
+
"node_modules/@esbuild/netbsd-arm64": {
|
| 439 |
+
"version": "0.27.3",
|
| 440 |
+
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.3.tgz",
|
| 441 |
+
"integrity": "sha512-sDpk0RgmTCR/5HguIZa9n9u+HVKf40fbEUt+iTzSnCaGvY9kFP0YKBWZtJaraonFnqef5SlJ8/TiPAxzyS+UoA==",
|
| 442 |
+
"cpu": [
|
| 443 |
+
"arm64"
|
| 444 |
+
],
|
| 445 |
+
"dev": true,
|
| 446 |
+
"license": "MIT",
|
| 447 |
+
"optional": true,
|
| 448 |
+
"os": [
|
| 449 |
+
"netbsd"
|
| 450 |
+
],
|
| 451 |
+
"engines": {
|
| 452 |
+
"node": ">=18"
|
| 453 |
+
}
|
| 454 |
+
},
|
| 455 |
+
"node_modules/@esbuild/netbsd-x64": {
|
| 456 |
+
"version": "0.27.3",
|
| 457 |
+
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.3.tgz",
|
| 458 |
+
"integrity": "sha512-P14lFKJl/DdaE00LItAukUdZO5iqNH7+PjoBm+fLQjtxfcfFE20Xf5CrLsmZdq5LFFZzb5JMZ9grUwvtVYzjiA==",
|
| 459 |
+
"cpu": [
|
| 460 |
+
"x64"
|
| 461 |
+
],
|
| 462 |
+
"dev": true,
|
| 463 |
+
"license": "MIT",
|
| 464 |
+
"optional": true,
|
| 465 |
+
"os": [
|
| 466 |
+
"netbsd"
|
| 467 |
+
],
|
| 468 |
+
"engines": {
|
| 469 |
+
"node": ">=18"
|
| 470 |
+
}
|
| 471 |
+
},
|
| 472 |
+
"node_modules/@esbuild/openbsd-arm64": {
|
| 473 |
+
"version": "0.27.3",
|
| 474 |
+
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.3.tgz",
|
| 475 |
+
"integrity": "sha512-AIcMP77AvirGbRl/UZFTq5hjXK+2wC7qFRGoHSDrZ5v5b8DK/GYpXW3CPRL53NkvDqb9D+alBiC/dV0Fb7eJcw==",
|
| 476 |
+
"cpu": [
|
| 477 |
+
"arm64"
|
| 478 |
+
],
|
| 479 |
+
"dev": true,
|
| 480 |
+
"license": "MIT",
|
| 481 |
+
"optional": true,
|
| 482 |
+
"os": [
|
| 483 |
+
"openbsd"
|
| 484 |
+
],
|
| 485 |
+
"engines": {
|
| 486 |
+
"node": ">=18"
|
| 487 |
+
}
|
| 488 |
+
},
|
| 489 |
+
"node_modules/@esbuild/openbsd-x64": {
|
| 490 |
+
"version": "0.27.3",
|
| 491 |
+
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.3.tgz",
|
| 492 |
+
"integrity": "sha512-DnW2sRrBzA+YnE70LKqnM3P+z8vehfJWHXECbwBmH/CU51z6FiqTQTHFenPlHmo3a8UgpLyH3PT+87OViOh1AQ==",
|
| 493 |
+
"cpu": [
|
| 494 |
+
"x64"
|
| 495 |
+
],
|
| 496 |
+
"dev": true,
|
| 497 |
+
"license": "MIT",
|
| 498 |
+
"optional": true,
|
| 499 |
+
"os": [
|
| 500 |
+
"openbsd"
|
| 501 |
+
],
|
| 502 |
+
"engines": {
|
| 503 |
+
"node": ">=18"
|
| 504 |
+
}
|
| 505 |
+
},
|
| 506 |
+
"node_modules/@esbuild/openharmony-arm64": {
|
| 507 |
+
"version": "0.27.3",
|
| 508 |
+
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.3.tgz",
|
| 509 |
+
"integrity": "sha512-NinAEgr/etERPTsZJ7aEZQvvg/A6IsZG/LgZy+81wON2huV7SrK3e63dU0XhyZP4RKGyTm7aOgmQk0bGp0fy2g==",
|
| 510 |
+
"cpu": [
|
| 511 |
+
"arm64"
|
| 512 |
+
],
|
| 513 |
+
"dev": true,
|
| 514 |
+
"license": "MIT",
|
| 515 |
+
"optional": true,
|
| 516 |
+
"os": [
|
| 517 |
+
"openharmony"
|
| 518 |
+
],
|
| 519 |
+
"engines": {
|
| 520 |
+
"node": ">=18"
|
| 521 |
+
}
|
| 522 |
+
},
|
| 523 |
+
"node_modules/@esbuild/sunos-x64": {
|
| 524 |
+
"version": "0.27.3",
|
| 525 |
+
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.3.tgz",
|
| 526 |
+
"integrity": "sha512-PanZ+nEz+eWoBJ8/f8HKxTTD172SKwdXebZ0ndd953gt1HRBbhMsaNqjTyYLGLPdoWHy4zLU7bDVJztF5f3BHA==",
|
| 527 |
+
"cpu": [
|
| 528 |
+
"x64"
|
| 529 |
+
],
|
| 530 |
+
"dev": true,
|
| 531 |
+
"license": "MIT",
|
| 532 |
+
"optional": true,
|
| 533 |
+
"os": [
|
| 534 |
+
"sunos"
|
| 535 |
+
],
|
| 536 |
+
"engines": {
|
| 537 |
+
"node": ">=18"
|
| 538 |
+
}
|
| 539 |
+
},
|
| 540 |
+
"node_modules/@esbuild/win32-arm64": {
|
| 541 |
+
"version": "0.27.3",
|
| 542 |
+
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.3.tgz",
|
| 543 |
+
"integrity": "sha512-B2t59lWWYrbRDw/tjiWOuzSsFh1Y/E95ofKz7rIVYSQkUYBjfSgf6oeYPNWHToFRr2zx52JKApIcAS/D5TUBnA==",
|
| 544 |
+
"cpu": [
|
| 545 |
+
"arm64"
|
| 546 |
+
],
|
| 547 |
+
"dev": true,
|
| 548 |
+
"license": "MIT",
|
| 549 |
+
"optional": true,
|
| 550 |
+
"os": [
|
| 551 |
+
"win32"
|
| 552 |
+
],
|
| 553 |
+
"engines": {
|
| 554 |
+
"node": ">=18"
|
| 555 |
+
}
|
| 556 |
+
},
|
| 557 |
+
"node_modules/@esbuild/win32-ia32": {
|
| 558 |
+
"version": "0.27.3",
|
| 559 |
+
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.3.tgz",
|
| 560 |
+
"integrity": "sha512-QLKSFeXNS8+tHW7tZpMtjlNb7HKau0QDpwm49u0vUp9y1WOF+PEzkU84y9GqYaAVW8aH8f3GcBck26jh54cX4Q==",
|
| 561 |
+
"cpu": [
|
| 562 |
+
"ia32"
|
| 563 |
+
],
|
| 564 |
+
"dev": true,
|
| 565 |
+
"license": "MIT",
|
| 566 |
+
"optional": true,
|
| 567 |
+
"os": [
|
| 568 |
+
"win32"
|
| 569 |
+
],
|
| 570 |
+
"engines": {
|
| 571 |
+
"node": ">=18"
|
| 572 |
+
}
|
| 573 |
+
},
|
| 574 |
+
"node_modules/@esbuild/win32-x64": {
|
| 575 |
+
"version": "0.27.3",
|
| 576 |
+
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.3.tgz",
|
| 577 |
+
"integrity": "sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA==",
|
| 578 |
+
"cpu": [
|
| 579 |
+
"x64"
|
| 580 |
+
],
|
| 581 |
+
"dev": true,
|
| 582 |
+
"license": "MIT",
|
| 583 |
+
"optional": true,
|
| 584 |
+
"os": [
|
| 585 |
+
"win32"
|
| 586 |
+
],
|
| 587 |
+
"engines": {
|
| 588 |
+
"node": ">=18"
|
| 589 |
+
}
|
| 590 |
+
},
|
| 591 |
+
"node_modules/@img/colour": {
|
| 592 |
+
"version": "1.1.0",
|
| 593 |
+
"resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",
|
| 594 |
+
"integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",
|
| 595 |
+
"dev": true,
|
| 596 |
+
"license": "MIT",
|
| 597 |
+
"engines": {
|
| 598 |
+
"node": ">=18"
|
| 599 |
+
}
|
| 600 |
+
},
|
| 601 |
+
"node_modules/@img/sharp-darwin-arm64": {
|
| 602 |
+
"version": "0.34.5",
|
| 603 |
+
"resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.5.tgz",
|
| 604 |
+
"integrity": "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==",
|
| 605 |
+
"cpu": [
|
| 606 |
+
"arm64"
|
| 607 |
+
],
|
| 608 |
+
"dev": true,
|
| 609 |
+
"license": "Apache-2.0",
|
| 610 |
+
"optional": true,
|
| 611 |
+
"os": [
|
| 612 |
+
"darwin"
|
| 613 |
+
],
|
| 614 |
+
"engines": {
|
| 615 |
+
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
| 616 |
+
},
|
| 617 |
+
"funding": {
|
| 618 |
+
"url": "https://opencollective.com/libvips"
|
| 619 |
+
},
|
| 620 |
+
"optionalDependencies": {
|
| 621 |
+
"@img/sharp-libvips-darwin-arm64": "1.2.4"
|
| 622 |
+
}
|
| 623 |
+
},
|
| 624 |
+
"node_modules/@img/sharp-darwin-x64": {
|
| 625 |
+
"version": "0.34.5",
|
| 626 |
+
"resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.5.tgz",
|
| 627 |
+
"integrity": "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==",
|
| 628 |
+
"cpu": [
|
| 629 |
+
"x64"
|
| 630 |
+
],
|
| 631 |
+
"dev": true,
|
| 632 |
+
"license": "Apache-2.0",
|
| 633 |
+
"optional": true,
|
| 634 |
+
"os": [
|
| 635 |
+
"darwin"
|
| 636 |
+
],
|
| 637 |
+
"engines": {
|
| 638 |
+
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
| 639 |
+
},
|
| 640 |
+
"funding": {
|
| 641 |
+
"url": "https://opencollective.com/libvips"
|
| 642 |
+
},
|
| 643 |
+
"optionalDependencies": {
|
| 644 |
+
"@img/sharp-libvips-darwin-x64": "1.2.4"
|
| 645 |
+
}
|
| 646 |
+
},
|
| 647 |
+
"node_modules/@img/sharp-libvips-darwin-arm64": {
|
| 648 |
+
"version": "1.2.4",
|
| 649 |
+
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.4.tgz",
|
| 650 |
+
"integrity": "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==",
|
| 651 |
+
"cpu": [
|
| 652 |
+
"arm64"
|
| 653 |
+
],
|
| 654 |
+
"dev": true,
|
| 655 |
+
"license": "LGPL-3.0-or-later",
|
| 656 |
+
"optional": true,
|
| 657 |
+
"os": [
|
| 658 |
+
"darwin"
|
| 659 |
+
],
|
| 660 |
+
"funding": {
|
| 661 |
+
"url": "https://opencollective.com/libvips"
|
| 662 |
+
}
|
| 663 |
+
},
|
| 664 |
+
"node_modules/@img/sharp-libvips-darwin-x64": {
|
| 665 |
+
"version": "1.2.4",
|
| 666 |
+
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.4.tgz",
|
| 667 |
+
"integrity": "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==",
|
| 668 |
+
"cpu": [
|
| 669 |
+
"x64"
|
| 670 |
+
],
|
| 671 |
+
"dev": true,
|
| 672 |
+
"license": "LGPL-3.0-or-later",
|
| 673 |
+
"optional": true,
|
| 674 |
+
"os": [
|
| 675 |
+
"darwin"
|
| 676 |
+
],
|
| 677 |
+
"funding": {
|
| 678 |
+
"url": "https://opencollective.com/libvips"
|
| 679 |
+
}
|
| 680 |
+
},
|
| 681 |
+
"node_modules/@img/sharp-libvips-linux-arm": {
|
| 682 |
+
"version": "1.2.4",
|
| 683 |
+
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.4.tgz",
|
| 684 |
+
"integrity": "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==",
|
| 685 |
+
"cpu": [
|
| 686 |
+
"arm"
|
| 687 |
+
],
|
| 688 |
+
"dev": true,
|
| 689 |
+
"license": "LGPL-3.0-or-later",
|
| 690 |
+
"optional": true,
|
| 691 |
+
"os": [
|
| 692 |
+
"linux"
|
| 693 |
+
],
|
| 694 |
+
"funding": {
|
| 695 |
+
"url": "https://opencollective.com/libvips"
|
| 696 |
+
}
|
| 697 |
+
},
|
| 698 |
+
"node_modules/@img/sharp-libvips-linux-arm64": {
|
| 699 |
+
"version": "1.2.4",
|
| 700 |
+
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.4.tgz",
|
| 701 |
+
"integrity": "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==",
|
| 702 |
+
"cpu": [
|
| 703 |
+
"arm64"
|
| 704 |
+
],
|
| 705 |
+
"dev": true,
|
| 706 |
+
"license": "LGPL-3.0-or-later",
|
| 707 |
+
"optional": true,
|
| 708 |
+
"os": [
|
| 709 |
+
"linux"
|
| 710 |
+
],
|
| 711 |
+
"funding": {
|
| 712 |
+
"url": "https://opencollective.com/libvips"
|
| 713 |
+
}
|
| 714 |
+
},
|
| 715 |
+
"node_modules/@img/sharp-libvips-linux-ppc64": {
|
| 716 |
+
"version": "1.2.4",
|
| 717 |
+
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.2.4.tgz",
|
| 718 |
+
"integrity": "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==",
|
| 719 |
+
"cpu": [
|
| 720 |
+
"ppc64"
|
| 721 |
+
],
|
| 722 |
+
"dev": true,
|
| 723 |
+
"license": "LGPL-3.0-or-later",
|
| 724 |
+
"optional": true,
|
| 725 |
+
"os": [
|
| 726 |
+
"linux"
|
| 727 |
+
],
|
| 728 |
+
"funding": {
|
| 729 |
+
"url": "https://opencollective.com/libvips"
|
| 730 |
+
}
|
| 731 |
+
},
|
| 732 |
+
"node_modules/@img/sharp-libvips-linux-riscv64": {
|
| 733 |
+
"version": "1.2.4",
|
| 734 |
+
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.2.4.tgz",
|
| 735 |
+
"integrity": "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==",
|
| 736 |
+
"cpu": [
|
| 737 |
+
"riscv64"
|
| 738 |
+
],
|
| 739 |
+
"dev": true,
|
| 740 |
+
"license": "LGPL-3.0-or-later",
|
| 741 |
+
"optional": true,
|
| 742 |
+
"os": [
|
| 743 |
+
"linux"
|
| 744 |
+
],
|
| 745 |
+
"funding": {
|
| 746 |
+
"url": "https://opencollective.com/libvips"
|
| 747 |
+
}
|
| 748 |
+
},
|
| 749 |
+
"node_modules/@img/sharp-libvips-linux-s390x": {
|
| 750 |
+
"version": "1.2.4",
|
| 751 |
+
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.2.4.tgz",
|
| 752 |
+
"integrity": "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==",
|
| 753 |
+
"cpu": [
|
| 754 |
+
"s390x"
|
| 755 |
+
],
|
| 756 |
+
"dev": true,
|
| 757 |
+
"license": "LGPL-3.0-or-later",
|
| 758 |
+
"optional": true,
|
| 759 |
+
"os": [
|
| 760 |
+
"linux"
|
| 761 |
+
],
|
| 762 |
+
"funding": {
|
| 763 |
+
"url": "https://opencollective.com/libvips"
|
| 764 |
+
}
|
| 765 |
+
},
|
| 766 |
+
"node_modules/@img/sharp-libvips-linux-x64": {
|
| 767 |
+
"version": "1.2.4",
|
| 768 |
+
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.4.tgz",
|
| 769 |
+
"integrity": "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==",
|
| 770 |
+
"cpu": [
|
| 771 |
+
"x64"
|
| 772 |
+
],
|
| 773 |
+
"dev": true,
|
| 774 |
+
"license": "LGPL-3.0-or-later",
|
| 775 |
+
"optional": true,
|
| 776 |
+
"os": [
|
| 777 |
+
"linux"
|
| 778 |
+
],
|
| 779 |
+
"funding": {
|
| 780 |
+
"url": "https://opencollective.com/libvips"
|
| 781 |
+
}
|
| 782 |
+
},
|
| 783 |
+
"node_modules/@img/sharp-libvips-linuxmusl-arm64": {
|
| 784 |
+
"version": "1.2.4",
|
| 785 |
+
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.4.tgz",
|
| 786 |
+
"integrity": "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==",
|
| 787 |
+
"cpu": [
|
| 788 |
+
"arm64"
|
| 789 |
+
],
|
| 790 |
+
"dev": true,
|
| 791 |
+
"license": "LGPL-3.0-or-later",
|
| 792 |
+
"optional": true,
|
| 793 |
+
"os": [
|
| 794 |
+
"linux"
|
| 795 |
+
],
|
| 796 |
+
"funding": {
|
| 797 |
+
"url": "https://opencollective.com/libvips"
|
| 798 |
+
}
|
| 799 |
+
},
|
| 800 |
+
"node_modules/@img/sharp-libvips-linuxmusl-x64": {
|
| 801 |
+
"version": "1.2.4",
|
| 802 |
+
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.4.tgz",
|
| 803 |
+
"integrity": "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==",
|
| 804 |
+
"cpu": [
|
| 805 |
+
"x64"
|
| 806 |
+
],
|
| 807 |
+
"dev": true,
|
| 808 |
+
"license": "LGPL-3.0-or-later",
|
| 809 |
+
"optional": true,
|
| 810 |
+
"os": [
|
| 811 |
+
"linux"
|
| 812 |
+
],
|
| 813 |
+
"funding": {
|
| 814 |
+
"url": "https://opencollective.com/libvips"
|
| 815 |
+
}
|
| 816 |
+
},
|
| 817 |
+
"node_modules/@img/sharp-linux-arm": {
|
| 818 |
+
"version": "0.34.5",
|
| 819 |
+
"resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.5.tgz",
|
| 820 |
+
"integrity": "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==",
|
| 821 |
+
"cpu": [
|
| 822 |
+
"arm"
|
| 823 |
+
],
|
| 824 |
+
"dev": true,
|
| 825 |
+
"license": "Apache-2.0",
|
| 826 |
+
"optional": true,
|
| 827 |
+
"os": [
|
| 828 |
+
"linux"
|
| 829 |
+
],
|
| 830 |
+
"engines": {
|
| 831 |
+
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
| 832 |
+
},
|
| 833 |
+
"funding": {
|
| 834 |
+
"url": "https://opencollective.com/libvips"
|
| 835 |
+
},
|
| 836 |
+
"optionalDependencies": {
|
| 837 |
+
"@img/sharp-libvips-linux-arm": "1.2.4"
|
| 838 |
+
}
|
| 839 |
+
},
|
| 840 |
+
"node_modules/@img/sharp-linux-arm64": {
|
| 841 |
+
"version": "0.34.5",
|
| 842 |
+
"resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.5.tgz",
|
| 843 |
+
"integrity": "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==",
|
| 844 |
+
"cpu": [
|
| 845 |
+
"arm64"
|
| 846 |
+
],
|
| 847 |
+
"dev": true,
|
| 848 |
+
"license": "Apache-2.0",
|
| 849 |
+
"optional": true,
|
| 850 |
+
"os": [
|
| 851 |
+
"linux"
|
| 852 |
+
],
|
| 853 |
+
"engines": {
|
| 854 |
+
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
| 855 |
+
},
|
| 856 |
+
"funding": {
|
| 857 |
+
"url": "https://opencollective.com/libvips"
|
| 858 |
+
},
|
| 859 |
+
"optionalDependencies": {
|
| 860 |
+
"@img/sharp-libvips-linux-arm64": "1.2.4"
|
| 861 |
+
}
|
| 862 |
+
},
|
| 863 |
+
"node_modules/@img/sharp-linux-ppc64": {
|
| 864 |
+
"version": "0.34.5",
|
| 865 |
+
"resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.34.5.tgz",
|
| 866 |
+
"integrity": "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==",
|
| 867 |
+
"cpu": [
|
| 868 |
+
"ppc64"
|
| 869 |
+
],
|
| 870 |
+
"dev": true,
|
| 871 |
+
"license": "Apache-2.0",
|
| 872 |
+
"optional": true,
|
| 873 |
+
"os": [
|
| 874 |
+
"linux"
|
| 875 |
+
],
|
| 876 |
+
"engines": {
|
| 877 |
+
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
| 878 |
+
},
|
| 879 |
+
"funding": {
|
| 880 |
+
"url": "https://opencollective.com/libvips"
|
| 881 |
+
},
|
| 882 |
+
"optionalDependencies": {
|
| 883 |
+
"@img/sharp-libvips-linux-ppc64": "1.2.4"
|
| 884 |
+
}
|
| 885 |
+
},
|
| 886 |
+
"node_modules/@img/sharp-linux-riscv64": {
|
| 887 |
+
"version": "0.34.5",
|
| 888 |
+
"resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.34.5.tgz",
|
| 889 |
+
"integrity": "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==",
|
| 890 |
+
"cpu": [
|
| 891 |
+
"riscv64"
|
| 892 |
+
],
|
| 893 |
+
"dev": true,
|
| 894 |
+
"license": "Apache-2.0",
|
| 895 |
+
"optional": true,
|
| 896 |
+
"os": [
|
| 897 |
+
"linux"
|
| 898 |
+
],
|
| 899 |
+
"engines": {
|
| 900 |
+
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
| 901 |
+
},
|
| 902 |
+
"funding": {
|
| 903 |
+
"url": "https://opencollective.com/libvips"
|
| 904 |
+
},
|
| 905 |
+
"optionalDependencies": {
|
| 906 |
+
"@img/sharp-libvips-linux-riscv64": "1.2.4"
|
| 907 |
+
}
|
| 908 |
+
},
|
| 909 |
+
"node_modules/@img/sharp-linux-s390x": {
|
| 910 |
+
"version": "0.34.5",
|
| 911 |
+
"resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.5.tgz",
|
| 912 |
+
"integrity": "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==",
|
| 913 |
+
"cpu": [
|
| 914 |
+
"s390x"
|
| 915 |
+
],
|
| 916 |
+
"dev": true,
|
| 917 |
+
"license": "Apache-2.0",
|
| 918 |
+
"optional": true,
|
| 919 |
+
"os": [
|
| 920 |
+
"linux"
|
| 921 |
+
],
|
| 922 |
+
"engines": {
|
| 923 |
+
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
| 924 |
+
},
|
| 925 |
+
"funding": {
|
| 926 |
+
"url": "https://opencollective.com/libvips"
|
| 927 |
+
},
|
| 928 |
+
"optionalDependencies": {
|
| 929 |
+
"@img/sharp-libvips-linux-s390x": "1.2.4"
|
| 930 |
+
}
|
| 931 |
+
},
|
| 932 |
+
"node_modules/@img/sharp-linux-x64": {
|
| 933 |
+
"version": "0.34.5",
|
| 934 |
+
"resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.5.tgz",
|
| 935 |
+
"integrity": "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==",
|
| 936 |
+
"cpu": [
|
| 937 |
+
"x64"
|
| 938 |
+
],
|
| 939 |
+
"dev": true,
|
| 940 |
+
"license": "Apache-2.0",
|
| 941 |
+
"optional": true,
|
| 942 |
+
"os": [
|
| 943 |
+
"linux"
|
| 944 |
+
],
|
| 945 |
+
"engines": {
|
| 946 |
+
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
| 947 |
+
},
|
| 948 |
+
"funding": {
|
| 949 |
+
"url": "https://opencollective.com/libvips"
|
| 950 |
+
},
|
| 951 |
+
"optionalDependencies": {
|
| 952 |
+
"@img/sharp-libvips-linux-x64": "1.2.4"
|
| 953 |
+
}
|
| 954 |
+
},
|
| 955 |
+
"node_modules/@img/sharp-linuxmusl-arm64": {
|
| 956 |
+
"version": "0.34.5",
|
| 957 |
+
"resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.5.tgz",
|
| 958 |
+
"integrity": "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==",
|
| 959 |
+
"cpu": [
|
| 960 |
+
"arm64"
|
| 961 |
+
],
|
| 962 |
+
"dev": true,
|
| 963 |
+
"license": "Apache-2.0",
|
| 964 |
+
"optional": true,
|
| 965 |
+
"os": [
|
| 966 |
+
"linux"
|
| 967 |
+
],
|
| 968 |
+
"engines": {
|
| 969 |
+
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
| 970 |
+
},
|
| 971 |
+
"funding": {
|
| 972 |
+
"url": "https://opencollective.com/libvips"
|
| 973 |
+
},
|
| 974 |
+
"optionalDependencies": {
|
| 975 |
+
"@img/sharp-libvips-linuxmusl-arm64": "1.2.4"
|
| 976 |
+
}
|
| 977 |
+
},
|
| 978 |
+
"node_modules/@img/sharp-linuxmusl-x64": {
|
| 979 |
+
"version": "0.34.5",
|
| 980 |
+
"resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.5.tgz",
|
| 981 |
+
"integrity": "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==",
|
| 982 |
+
"cpu": [
|
| 983 |
+
"x64"
|
| 984 |
+
],
|
| 985 |
+
"dev": true,
|
| 986 |
+
"license": "Apache-2.0",
|
| 987 |
+
"optional": true,
|
| 988 |
+
"os": [
|
| 989 |
+
"linux"
|
| 990 |
+
],
|
| 991 |
+
"engines": {
|
| 992 |
+
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
| 993 |
+
},
|
| 994 |
+
"funding": {
|
| 995 |
+
"url": "https://opencollective.com/libvips"
|
| 996 |
+
},
|
| 997 |
+
"optionalDependencies": {
|
| 998 |
+
"@img/sharp-libvips-linuxmusl-x64": "1.2.4"
|
| 999 |
+
}
|
| 1000 |
+
},
|
| 1001 |
+
"node_modules/@img/sharp-wasm32": {
|
| 1002 |
+
"version": "0.34.5",
|
| 1003 |
+
"resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.5.tgz",
|
| 1004 |
+
"integrity": "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==",
|
| 1005 |
+
"cpu": [
|
| 1006 |
+
"wasm32"
|
| 1007 |
+
],
|
| 1008 |
+
"dev": true,
|
| 1009 |
+
"license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",
|
| 1010 |
+
"optional": true,
|
| 1011 |
+
"dependencies": {
|
| 1012 |
+
"@emnapi/runtime": "^1.7.0"
|
| 1013 |
+
},
|
| 1014 |
+
"engines": {
|
| 1015 |
+
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
| 1016 |
+
},
|
| 1017 |
+
"funding": {
|
| 1018 |
+
"url": "https://opencollective.com/libvips"
|
| 1019 |
+
}
|
| 1020 |
+
},
|
| 1021 |
+
"node_modules/@img/sharp-win32-arm64": {
|
| 1022 |
+
"version": "0.34.5",
|
| 1023 |
+
"resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.5.tgz",
|
| 1024 |
+
"integrity": "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==",
|
| 1025 |
+
"cpu": [
|
| 1026 |
+
"arm64"
|
| 1027 |
+
],
|
| 1028 |
+
"dev": true,
|
| 1029 |
+
"license": "Apache-2.0 AND LGPL-3.0-or-later",
|
| 1030 |
+
"optional": true,
|
| 1031 |
+
"os": [
|
| 1032 |
+
"win32"
|
| 1033 |
+
],
|
| 1034 |
+
"engines": {
|
| 1035 |
+
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
| 1036 |
+
},
|
| 1037 |
+
"funding": {
|
| 1038 |
+
"url": "https://opencollective.com/libvips"
|
| 1039 |
+
}
|
| 1040 |
+
},
|
| 1041 |
+
"node_modules/@img/sharp-win32-ia32": {
|
| 1042 |
+
"version": "0.34.5",
|
| 1043 |
+
"resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.5.tgz",
|
| 1044 |
+
"integrity": "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==",
|
| 1045 |
+
"cpu": [
|
| 1046 |
+
"ia32"
|
| 1047 |
+
],
|
| 1048 |
+
"dev": true,
|
| 1049 |
+
"license": "Apache-2.0 AND LGPL-3.0-or-later",
|
| 1050 |
+
"optional": true,
|
| 1051 |
+
"os": [
|
| 1052 |
+
"win32"
|
| 1053 |
+
],
|
| 1054 |
+
"engines": {
|
| 1055 |
+
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
| 1056 |
+
},
|
| 1057 |
+
"funding": {
|
| 1058 |
+
"url": "https://opencollective.com/libvips"
|
| 1059 |
+
}
|
| 1060 |
+
},
|
| 1061 |
+
"node_modules/@img/sharp-win32-x64": {
|
| 1062 |
+
"version": "0.34.5",
|
| 1063 |
+
"resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.5.tgz",
|
| 1064 |
+
"integrity": "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==",
|
| 1065 |
+
"cpu": [
|
| 1066 |
+
"x64"
|
| 1067 |
+
],
|
| 1068 |
+
"dev": true,
|
| 1069 |
+
"license": "Apache-2.0 AND LGPL-3.0-or-later",
|
| 1070 |
+
"optional": true,
|
| 1071 |
+
"os": [
|
| 1072 |
+
"win32"
|
| 1073 |
+
],
|
| 1074 |
+
"engines": {
|
| 1075 |
+
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
| 1076 |
+
},
|
| 1077 |
+
"funding": {
|
| 1078 |
+
"url": "https://opencollective.com/libvips"
|
| 1079 |
+
}
|
| 1080 |
+
},
|
| 1081 |
+
"node_modules/@jridgewell/resolve-uri": {
|
| 1082 |
+
"version": "3.1.2",
|
| 1083 |
+
"resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
|
| 1084 |
+
"integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
|
| 1085 |
+
"dev": true,
|
| 1086 |
+
"license": "MIT",
|
| 1087 |
+
"engines": {
|
| 1088 |
+
"node": ">=6.0.0"
|
| 1089 |
+
}
|
| 1090 |
+
},
|
| 1091 |
+
"node_modules/@jridgewell/sourcemap-codec": {
|
| 1092 |
+
"version": "1.5.5",
|
| 1093 |
+
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
|
| 1094 |
+
"integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
|
| 1095 |
+
"dev": true,
|
| 1096 |
+
"license": "MIT"
|
| 1097 |
+
},
|
| 1098 |
+
"node_modules/@jridgewell/trace-mapping": {
|
| 1099 |
+
"version": "0.3.9",
|
| 1100 |
+
"resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz",
|
| 1101 |
+
"integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==",
|
| 1102 |
+
"dev": true,
|
| 1103 |
+
"license": "MIT",
|
| 1104 |
+
"dependencies": {
|
| 1105 |
+
"@jridgewell/resolve-uri": "^3.0.3",
|
| 1106 |
+
"@jridgewell/sourcemap-codec": "^1.4.10"
|
| 1107 |
+
}
|
| 1108 |
+
},
|
| 1109 |
+
"node_modules/@poppinss/colors": {
|
| 1110 |
+
"version": "4.1.6",
|
| 1111 |
+
"resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.6.tgz",
|
| 1112 |
+
"integrity": "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==",
|
| 1113 |
+
"dev": true,
|
| 1114 |
+
"license": "MIT",
|
| 1115 |
+
"dependencies": {
|
| 1116 |
+
"kleur": "^4.1.5"
|
| 1117 |
+
}
|
| 1118 |
+
},
|
| 1119 |
+
"node_modules/@poppinss/dumper": {
|
| 1120 |
+
"version": "0.6.5",
|
| 1121 |
+
"resolved": "https://registry.npmjs.org/@poppinss/dumper/-/dumper-0.6.5.tgz",
|
| 1122 |
+
"integrity": "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==",
|
| 1123 |
+
"dev": true,
|
| 1124 |
+
"license": "MIT",
|
| 1125 |
+
"dependencies": {
|
| 1126 |
+
"@poppinss/colors": "^4.1.5",
|
| 1127 |
+
"@sindresorhus/is": "^7.0.2",
|
| 1128 |
+
"supports-color": "^10.0.0"
|
| 1129 |
+
}
|
| 1130 |
+
},
|
| 1131 |
+
"node_modules/@poppinss/exception": {
|
| 1132 |
+
"version": "1.2.3",
|
| 1133 |
+
"resolved": "https://registry.npmjs.org/@poppinss/exception/-/exception-1.2.3.tgz",
|
| 1134 |
+
"integrity": "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==",
|
| 1135 |
+
"dev": true,
|
| 1136 |
+
"license": "MIT"
|
| 1137 |
+
},
|
| 1138 |
+
"node_modules/@sindresorhus/is": {
|
| 1139 |
+
"version": "7.2.0",
|
| 1140 |
+
"resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-7.2.0.tgz",
|
| 1141 |
+
"integrity": "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==",
|
| 1142 |
+
"dev": true,
|
| 1143 |
+
"license": "MIT",
|
| 1144 |
+
"engines": {
|
| 1145 |
+
"node": ">=18"
|
| 1146 |
+
},
|
| 1147 |
+
"funding": {
|
| 1148 |
+
"url": "https://github.com/sindresorhus/is?sponsor=1"
|
| 1149 |
+
}
|
| 1150 |
+
},
|
| 1151 |
+
"node_modules/@speed-highlight/core": {
|
| 1152 |
+
"version": "1.2.15",
|
| 1153 |
+
"resolved": "https://registry.npmjs.org/@speed-highlight/core/-/core-1.2.15.tgz",
|
| 1154 |
+
"integrity": "sha512-BMq1K3DsElxDWawkX6eLg9+CKJrTVGCBAWVuHXVUV2u0s2711qiChLSId6ikYPfxhdYocLNt3wWwSvDiTvFabw==",
|
| 1155 |
+
"dev": true,
|
| 1156 |
+
"license": "CC0-1.0"
|
| 1157 |
+
},
|
| 1158 |
+
"node_modules/blake3-wasm": {
|
| 1159 |
+
"version": "2.1.5",
|
| 1160 |
+
"resolved": "https://registry.npmjs.org/blake3-wasm/-/blake3-wasm-2.1.5.tgz",
|
| 1161 |
+
"integrity": "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==",
|
| 1162 |
+
"dev": true,
|
| 1163 |
+
"license": "MIT"
|
| 1164 |
+
},
|
| 1165 |
+
"node_modules/cookie": {
|
| 1166 |
+
"version": "1.1.1",
|
| 1167 |
+
"resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz",
|
| 1168 |
+
"integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==",
|
| 1169 |
+
"dev": true,
|
| 1170 |
+
"license": "MIT",
|
| 1171 |
+
"engines": {
|
| 1172 |
+
"node": ">=18"
|
| 1173 |
+
},
|
| 1174 |
+
"funding": {
|
| 1175 |
+
"type": "opencollective",
|
| 1176 |
+
"url": "https://opencollective.com/express"
|
| 1177 |
+
}
|
| 1178 |
+
},
|
| 1179 |
+
"node_modules/detect-libc": {
|
| 1180 |
+
"version": "2.1.2",
|
| 1181 |
+
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
|
| 1182 |
+
"integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
|
| 1183 |
+
"dev": true,
|
| 1184 |
+
"license": "Apache-2.0",
|
| 1185 |
+
"engines": {
|
| 1186 |
+
"node": ">=8"
|
| 1187 |
+
}
|
| 1188 |
+
},
|
| 1189 |
+
"node_modules/error-stack-parser-es": {
|
| 1190 |
+
"version": "1.0.5",
|
| 1191 |
+
"resolved": "https://registry.npmjs.org/error-stack-parser-es/-/error-stack-parser-es-1.0.5.tgz",
|
| 1192 |
+
"integrity": "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==",
|
| 1193 |
+
"dev": true,
|
| 1194 |
+
"license": "MIT",
|
| 1195 |
+
"funding": {
|
| 1196 |
+
"url": "https://github.com/sponsors/antfu"
|
| 1197 |
+
}
|
| 1198 |
+
},
|
| 1199 |
+
"node_modules/esbuild": {
|
| 1200 |
+
"version": "0.27.3",
|
| 1201 |
+
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.3.tgz",
|
| 1202 |
+
"integrity": "sha512-8VwMnyGCONIs6cWue2IdpHxHnAjzxnw2Zr7MkVxB2vjmQ2ivqGFb4LEG3SMnv0Gb2F/G/2yA8zUaiL1gywDCCg==",
|
| 1203 |
+
"dev": true,
|
| 1204 |
+
"hasInstallScript": true,
|
| 1205 |
+
"license": "MIT",
|
| 1206 |
+
"bin": {
|
| 1207 |
+
"esbuild": "bin/esbuild"
|
| 1208 |
+
},
|
| 1209 |
+
"engines": {
|
| 1210 |
+
"node": ">=18"
|
| 1211 |
+
},
|
| 1212 |
+
"optionalDependencies": {
|
| 1213 |
+
"@esbuild/aix-ppc64": "0.27.3",
|
| 1214 |
+
"@esbuild/android-arm": "0.27.3",
|
| 1215 |
+
"@esbuild/android-arm64": "0.27.3",
|
| 1216 |
+
"@esbuild/android-x64": "0.27.3",
|
| 1217 |
+
"@esbuild/darwin-arm64": "0.27.3",
|
| 1218 |
+
"@esbuild/darwin-x64": "0.27.3",
|
| 1219 |
+
"@esbuild/freebsd-arm64": "0.27.3",
|
| 1220 |
+
"@esbuild/freebsd-x64": "0.27.3",
|
| 1221 |
+
"@esbuild/linux-arm": "0.27.3",
|
| 1222 |
+
"@esbuild/linux-arm64": "0.27.3",
|
| 1223 |
+
"@esbuild/linux-ia32": "0.27.3",
|
| 1224 |
+
"@esbuild/linux-loong64": "0.27.3",
|
| 1225 |
+
"@esbuild/linux-mips64el": "0.27.3",
|
| 1226 |
+
"@esbuild/linux-ppc64": "0.27.3",
|
| 1227 |
+
"@esbuild/linux-riscv64": "0.27.3",
|
| 1228 |
+
"@esbuild/linux-s390x": "0.27.3",
|
| 1229 |
+
"@esbuild/linux-x64": "0.27.3",
|
| 1230 |
+
"@esbuild/netbsd-arm64": "0.27.3",
|
| 1231 |
+
"@esbuild/netbsd-x64": "0.27.3",
|
| 1232 |
+
"@esbuild/openbsd-arm64": "0.27.3",
|
| 1233 |
+
"@esbuild/openbsd-x64": "0.27.3",
|
| 1234 |
+
"@esbuild/openharmony-arm64": "0.27.3",
|
| 1235 |
+
"@esbuild/sunos-x64": "0.27.3",
|
| 1236 |
+
"@esbuild/win32-arm64": "0.27.3",
|
| 1237 |
+
"@esbuild/win32-ia32": "0.27.3",
|
| 1238 |
+
"@esbuild/win32-x64": "0.27.3"
|
| 1239 |
+
}
|
| 1240 |
+
},
|
| 1241 |
+
"node_modules/fsevents": {
|
| 1242 |
+
"version": "2.3.3",
|
| 1243 |
+
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
|
| 1244 |
+
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
|
| 1245 |
+
"dev": true,
|
| 1246 |
+
"hasInstallScript": true,
|
| 1247 |
+
"license": "MIT",
|
| 1248 |
+
"optional": true,
|
| 1249 |
+
"os": [
|
| 1250 |
+
"darwin"
|
| 1251 |
+
],
|
| 1252 |
+
"engines": {
|
| 1253 |
+
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
| 1254 |
+
}
|
| 1255 |
+
},
|
| 1256 |
+
"node_modules/kleur": {
|
| 1257 |
+
"version": "4.1.5",
|
| 1258 |
+
"resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz",
|
| 1259 |
+
"integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==",
|
| 1260 |
+
"dev": true,
|
| 1261 |
+
"license": "MIT",
|
| 1262 |
+
"engines": {
|
| 1263 |
+
"node": ">=6"
|
| 1264 |
+
}
|
| 1265 |
+
},
|
| 1266 |
+
"node_modules/miniflare": {
|
| 1267 |
+
"version": "4.20260603.0",
|
| 1268 |
+
"resolved": "https://registry.npmjs.org/miniflare/-/miniflare-4.20260603.0.tgz",
|
| 1269 |
+
"integrity": "sha512-+kMQYB82gC8MPOuojHur3icQsUeZUEJ+Sphuo5rVC3Ri9txBLAW/mH33b9OVrpmkogQeaaqPS4tPtugJZhk5Kw==",
|
| 1270 |
+
"dev": true,
|
| 1271 |
+
"license": "MIT",
|
| 1272 |
+
"dependencies": {
|
| 1273 |
+
"@cspotcode/source-map-support": "0.8.1",
|
| 1274 |
+
"sharp": "0.34.5",
|
| 1275 |
+
"undici": "7.24.8",
|
| 1276 |
+
"workerd": "1.20260603.1",
|
| 1277 |
+
"ws": "8.20.1",
|
| 1278 |
+
"youch": "4.1.0-beta.10"
|
| 1279 |
+
},
|
| 1280 |
+
"bin": {
|
| 1281 |
+
"miniflare": "bootstrap.js"
|
| 1282 |
+
},
|
| 1283 |
+
"engines": {
|
| 1284 |
+
"node": ">=22.0.0"
|
| 1285 |
+
}
|
| 1286 |
+
},
|
| 1287 |
+
"node_modules/path-to-regexp": {
|
| 1288 |
+
"version": "6.3.0",
|
| 1289 |
+
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-6.3.0.tgz",
|
| 1290 |
+
"integrity": "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==",
|
| 1291 |
+
"dev": true,
|
| 1292 |
+
"license": "MIT"
|
| 1293 |
+
},
|
| 1294 |
+
"node_modules/pathe": {
|
| 1295 |
+
"version": "2.0.3",
|
| 1296 |
+
"resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
|
| 1297 |
+
"integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
|
| 1298 |
+
"dev": true,
|
| 1299 |
+
"license": "MIT"
|
| 1300 |
+
},
|
| 1301 |
+
"node_modules/semver": {
|
| 1302 |
+
"version": "7.8.2",
|
| 1303 |
+
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.2.tgz",
|
| 1304 |
+
"integrity": "sha512-c8jsqUZm3omBOI66G90z1Dyw5z622G8oLG+omfsHBJf3CWQTlOcwOjvOG6wtiNfW6anKm/eA39LMwMtMez2TiQ==",
|
| 1305 |
+
"dev": true,
|
| 1306 |
+
"license": "ISC",
|
| 1307 |
+
"bin": {
|
| 1308 |
+
"semver": "bin/semver.js"
|
| 1309 |
+
},
|
| 1310 |
+
"engines": {
|
| 1311 |
+
"node": ">=10"
|
| 1312 |
+
}
|
| 1313 |
+
},
|
| 1314 |
+
"node_modules/sharp": {
|
| 1315 |
+
"version": "0.34.5",
|
| 1316 |
+
"resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.5.tgz",
|
| 1317 |
+
"integrity": "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==",
|
| 1318 |
+
"dev": true,
|
| 1319 |
+
"hasInstallScript": true,
|
| 1320 |
+
"license": "Apache-2.0",
|
| 1321 |
+
"dependencies": {
|
| 1322 |
+
"@img/colour": "^1.0.0",
|
| 1323 |
+
"detect-libc": "^2.1.2",
|
| 1324 |
+
"semver": "^7.7.3"
|
| 1325 |
+
},
|
| 1326 |
+
"engines": {
|
| 1327 |
+
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
|
| 1328 |
+
},
|
| 1329 |
+
"funding": {
|
| 1330 |
+
"url": "https://opencollective.com/libvips"
|
| 1331 |
+
},
|
| 1332 |
+
"optionalDependencies": {
|
| 1333 |
+
"@img/sharp-darwin-arm64": "0.34.5",
|
| 1334 |
+
"@img/sharp-darwin-x64": "0.34.5",
|
| 1335 |
+
"@img/sharp-libvips-darwin-arm64": "1.2.4",
|
| 1336 |
+
"@img/sharp-libvips-darwin-x64": "1.2.4",
|
| 1337 |
+
"@img/sharp-libvips-linux-arm": "1.2.4",
|
| 1338 |
+
"@img/sharp-libvips-linux-arm64": "1.2.4",
|
| 1339 |
+
"@img/sharp-libvips-linux-ppc64": "1.2.4",
|
| 1340 |
+
"@img/sharp-libvips-linux-riscv64": "1.2.4",
|
| 1341 |
+
"@img/sharp-libvips-linux-s390x": "1.2.4",
|
| 1342 |
+
"@img/sharp-libvips-linux-x64": "1.2.4",
|
| 1343 |
+
"@img/sharp-libvips-linuxmusl-arm64": "1.2.4",
|
| 1344 |
+
"@img/sharp-libvips-linuxmusl-x64": "1.2.4",
|
| 1345 |
+
"@img/sharp-linux-arm": "0.34.5",
|
| 1346 |
+
"@img/sharp-linux-arm64": "0.34.5",
|
| 1347 |
+
"@img/sharp-linux-ppc64": "0.34.5",
|
| 1348 |
+
"@img/sharp-linux-riscv64": "0.34.5",
|
| 1349 |
+
"@img/sharp-linux-s390x": "0.34.5",
|
| 1350 |
+
"@img/sharp-linux-x64": "0.34.5",
|
| 1351 |
+
"@img/sharp-linuxmusl-arm64": "0.34.5",
|
| 1352 |
+
"@img/sharp-linuxmusl-x64": "0.34.5",
|
| 1353 |
+
"@img/sharp-wasm32": "0.34.5",
|
| 1354 |
+
"@img/sharp-win32-arm64": "0.34.5",
|
| 1355 |
+
"@img/sharp-win32-ia32": "0.34.5",
|
| 1356 |
+
"@img/sharp-win32-x64": "0.34.5"
|
| 1357 |
+
}
|
| 1358 |
+
},
|
| 1359 |
+
"node_modules/supports-color": {
|
| 1360 |
+
"version": "10.2.2",
|
| 1361 |
+
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz",
|
| 1362 |
+
"integrity": "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==",
|
| 1363 |
+
"dev": true,
|
| 1364 |
+
"license": "MIT",
|
| 1365 |
+
"engines": {
|
| 1366 |
+
"node": ">=18"
|
| 1367 |
+
},
|
| 1368 |
+
"funding": {
|
| 1369 |
+
"url": "https://github.com/chalk/supports-color?sponsor=1"
|
| 1370 |
+
}
|
| 1371 |
+
},
|
| 1372 |
+
"node_modules/tslib": {
|
| 1373 |
+
"version": "2.8.1",
|
| 1374 |
+
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
|
| 1375 |
+
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
| 1376 |
+
"dev": true,
|
| 1377 |
+
"license": "0BSD",
|
| 1378 |
+
"optional": true
|
| 1379 |
+
},
|
| 1380 |
+
"node_modules/undici": {
|
| 1381 |
+
"version": "7.24.8",
|
| 1382 |
+
"resolved": "https://registry.npmjs.org/undici/-/undici-7.24.8.tgz",
|
| 1383 |
+
"integrity": "sha512-6KQ/+QxK49Z/p3HO6E5ZCZWNnCasyZLa5ExaVYyvPxUwKtbCPMKELJOqh7EqOle0t9cH/7d2TaaTRRa6Nhs4YQ==",
|
| 1384 |
+
"dev": true,
|
| 1385 |
+
"license": "MIT",
|
| 1386 |
+
"engines": {
|
| 1387 |
+
"node": ">=20.18.1"
|
| 1388 |
+
}
|
| 1389 |
+
},
|
| 1390 |
+
"node_modules/unenv": {
|
| 1391 |
+
"version": "2.0.0-rc.24",
|
| 1392 |
+
"resolved": "https://registry.npmjs.org/unenv/-/unenv-2.0.0-rc.24.tgz",
|
| 1393 |
+
"integrity": "sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==",
|
| 1394 |
+
"dev": true,
|
| 1395 |
+
"license": "MIT",
|
| 1396 |
+
"dependencies": {
|
| 1397 |
+
"pathe": "^2.0.3"
|
| 1398 |
+
}
|
| 1399 |
+
},
|
| 1400 |
+
"node_modules/workerd": {
|
| 1401 |
+
"version": "1.20260603.1",
|
| 1402 |
+
"resolved": "https://registry.npmjs.org/workerd/-/workerd-1.20260603.1.tgz",
|
| 1403 |
+
"integrity": "sha512-NPcbhI1++CS+fnELyXtsIR52en+5kwr/OrKeiQeYXGy10HxmPdsQBv9N+DU7hJIOOmBHhOGAAsoGDjyiQ2YCaA==",
|
| 1404 |
+
"dev": true,
|
| 1405 |
+
"hasInstallScript": true,
|
| 1406 |
+
"license": "Apache-2.0",
|
| 1407 |
+
"bin": {
|
| 1408 |
+
"workerd": "bin/workerd"
|
| 1409 |
+
},
|
| 1410 |
+
"engines": {
|
| 1411 |
+
"node": ">=16"
|
| 1412 |
+
},
|
| 1413 |
+
"optionalDependencies": {
|
| 1414 |
+
"@cloudflare/workerd-darwin-64": "1.20260603.1",
|
| 1415 |
+
"@cloudflare/workerd-darwin-arm64": "1.20260603.1",
|
| 1416 |
+
"@cloudflare/workerd-linux-64": "1.20260603.1",
|
| 1417 |
+
"@cloudflare/workerd-linux-arm64": "1.20260603.1",
|
| 1418 |
+
"@cloudflare/workerd-windows-64": "1.20260603.1"
|
| 1419 |
+
}
|
| 1420 |
+
},
|
| 1421 |
+
"node_modules/wrangler": {
|
| 1422 |
+
"version": "4.98.0",
|
| 1423 |
+
"resolved": "https://registry.npmjs.org/wrangler/-/wrangler-4.98.0.tgz",
|
| 1424 |
+
"integrity": "sha512-cXfFUuF4rMIvE0hiMnXjEAB27ERryaCgquBJdUoPIjFzYYE1rbRdMUkEdQ18qDPUtsPvhJdqxLntixT9OfSzQw==",
|
| 1425 |
+
"dev": true,
|
| 1426 |
+
"license": "MIT OR Apache-2.0",
|
| 1427 |
+
"dependencies": {
|
| 1428 |
+
"@cloudflare/kv-asset-handler": "0.5.0",
|
| 1429 |
+
"@cloudflare/unenv-preset": "2.16.1",
|
| 1430 |
+
"blake3-wasm": "2.1.5",
|
| 1431 |
+
"esbuild": "0.27.3",
|
| 1432 |
+
"miniflare": "4.20260603.0",
|
| 1433 |
+
"path-to-regexp": "6.3.0",
|
| 1434 |
+
"unenv": "2.0.0-rc.24",
|
| 1435 |
+
"workerd": "1.20260603.1"
|
| 1436 |
+
},
|
| 1437 |
+
"bin": {
|
| 1438 |
+
"wrangler": "bin/wrangler.js",
|
| 1439 |
+
"wrangler2": "bin/wrangler.js"
|
| 1440 |
+
},
|
| 1441 |
+
"engines": {
|
| 1442 |
+
"node": ">=22.0.0"
|
| 1443 |
+
},
|
| 1444 |
+
"optionalDependencies": {
|
| 1445 |
+
"fsevents": "2.3.3"
|
| 1446 |
+
},
|
| 1447 |
+
"peerDependencies": {
|
| 1448 |
+
"@cloudflare/workers-types": "^4.20260603.1"
|
| 1449 |
+
},
|
| 1450 |
+
"peerDependenciesMeta": {
|
| 1451 |
+
"@cloudflare/workers-types": {
|
| 1452 |
+
"optional": true
|
| 1453 |
+
}
|
| 1454 |
+
}
|
| 1455 |
+
},
|
| 1456 |
+
"node_modules/ws": {
|
| 1457 |
+
"version": "8.20.1",
|
| 1458 |
+
"resolved": "https://registry.npmjs.org/ws/-/ws-8.20.1.tgz",
|
| 1459 |
+
"integrity": "sha512-It4dO0K5v//JtTXuPkfEOaI3uUN87iYPnqo/ZzqCoG3g8uhA66QUMs/SrM0YK7/NAu+r4LMh/9dq2A7k+rHs+w==",
|
| 1460 |
+
"dev": true,
|
| 1461 |
+
"license": "MIT",
|
| 1462 |
+
"engines": {
|
| 1463 |
+
"node": ">=10.0.0"
|
| 1464 |
+
},
|
| 1465 |
+
"peerDependencies": {
|
| 1466 |
+
"bufferutil": "^4.0.1",
|
| 1467 |
+
"utf-8-validate": ">=5.0.2"
|
| 1468 |
+
},
|
| 1469 |
+
"peerDependenciesMeta": {
|
| 1470 |
+
"bufferutil": {
|
| 1471 |
+
"optional": true
|
| 1472 |
+
},
|
| 1473 |
+
"utf-8-validate": {
|
| 1474 |
+
"optional": true
|
| 1475 |
+
}
|
| 1476 |
+
}
|
| 1477 |
+
},
|
| 1478 |
+
"node_modules/youch": {
|
| 1479 |
+
"version": "4.1.0-beta.10",
|
| 1480 |
+
"resolved": "https://registry.npmjs.org/youch/-/youch-4.1.0-beta.10.tgz",
|
| 1481 |
+
"integrity": "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==",
|
| 1482 |
+
"dev": true,
|
| 1483 |
+
"license": "MIT",
|
| 1484 |
+
"dependencies": {
|
| 1485 |
+
"@poppinss/colors": "^4.1.5",
|
| 1486 |
+
"@poppinss/dumper": "^0.6.4",
|
| 1487 |
+
"@speed-highlight/core": "^1.2.7",
|
| 1488 |
+
"cookie": "^1.0.2",
|
| 1489 |
+
"youch-core": "^0.3.3"
|
| 1490 |
+
}
|
| 1491 |
+
},
|
| 1492 |
+
"node_modules/youch-core": {
|
| 1493 |
+
"version": "0.3.3",
|
| 1494 |
+
"resolved": "https://registry.npmjs.org/youch-core/-/youch-core-0.3.3.tgz",
|
| 1495 |
+
"integrity": "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==",
|
| 1496 |
+
"dev": true,
|
| 1497 |
+
"license": "MIT",
|
| 1498 |
+
"dependencies": {
|
| 1499 |
+
"@poppinss/exception": "^1.2.2",
|
| 1500 |
+
"error-stack-parser-es": "^1.0.5"
|
| 1501 |
+
}
|
| 1502 |
+
}
|
| 1503 |
+
}
|
| 1504 |
+
}
|
cf-worker/package.json
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "ds2api-health-check",
|
| 3 |
+
"version": "1.0.0",
|
| 4 |
+
"private": true,
|
| 5 |
+
"scripts": {
|
| 6 |
+
"dev": "wrangler dev",
|
| 7 |
+
"deploy": "wrangler deploy"
|
| 8 |
+
},
|
| 9 |
+
"devDependencies": {
|
| 10 |
+
"wrangler": "^4"
|
| 11 |
+
}
|
| 12 |
+
}
|
cf-worker/src/index.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Cloudflare Worker — 定时刷新 ds2api 代理健康状态
|
| 3 |
+
*
|
| 4 |
+
* 部署步骤:
|
| 5 |
+
* 1. cd cf-worker && npm install
|
| 6 |
+
* 2. 设置 secrets:
|
| 7 |
+
* wrangler secret put DS2API_BASE_URL
|
| 8 |
+
* wrangler secret put ADMIN_KEY
|
| 9 |
+
* wrangler secret put VERCEL_BYPASS_TOKEN (如果开了 Vercel Deployment Protection)
|
| 10 |
+
* 3. wrangler deploy
|
| 11 |
+
*
|
| 12 |
+
* Cron 每 5 小时触发一次 (与 wrangler.toml 中的 crons 对应)。
|
| 13 |
+
* 也可以手动 GET/POST https://<worker>/check 触发。
|
| 14 |
+
*/
|
| 15 |
+
|
| 16 |
+
const LOGIN_PATH = "/admin/login"
|
| 17 |
+
const CHECK_ALL_PATH = "/admin/proxies/check-all"
|
| 18 |
+
|
| 19 |
+
function vercelHeaders(env) {
|
| 20 |
+
const headers = {}
|
| 21 |
+
const bypass = env.VERCEL_BYPASS_TOKEN
|
| 22 |
+
if (bypass) {
|
| 23 |
+
headers["x-vercel-protection-bypass"] = bypass
|
| 24 |
+
}
|
| 25 |
+
return headers
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
async function login(baseURL, adminKey, extraHeaders) {
|
| 29 |
+
const res = await fetch(`${baseURL}${LOGIN_PATH}`, {
|
| 30 |
+
method: "POST",
|
| 31 |
+
headers: { "Content-Type": "application/json", ...extraHeaders },
|
| 32 |
+
body: JSON.stringify({ admin_key: adminKey, expire_hours: 1 }),
|
| 33 |
+
})
|
| 34 |
+
if (!res.ok) {
|
| 35 |
+
const text = await res.text()
|
| 36 |
+
throw new Error(`login failed (${res.status}): ${text}`)
|
| 37 |
+
}
|
| 38 |
+
const data = await res.json()
|
| 39 |
+
return data.token
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
async function checkAll(baseURL, token, extraHeaders) {
|
| 43 |
+
const res = await fetch(`${baseURL}${CHECK_ALL_PATH}`, {
|
| 44 |
+
method: "POST",
|
| 45 |
+
headers: {
|
| 46 |
+
"Content-Type": "application/json",
|
| 47 |
+
Authorization: `Bearer ${token}`,
|
| 48 |
+
...extraHeaders,
|
| 49 |
+
},
|
| 50 |
+
})
|
| 51 |
+
if (!res.ok) {
|
| 52 |
+
const text = await res.text()
|
| 53 |
+
throw new Error(`check-all failed (${res.status}): ${text}`)
|
| 54 |
+
}
|
| 55 |
+
return res.json()
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
async function runCheck(env) {
|
| 59 |
+
const baseURL = (env.DS2API_BASE_URL || "").replace(/\/+$/, "")
|
| 60 |
+
const adminKey = env.ADMIN_KEY || ""
|
| 61 |
+
|
| 62 |
+
if (!baseURL || !adminKey) {
|
| 63 |
+
throw new Error("DS2API_BASE_URL and ADMIN_KEY secrets must be set")
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
const extraHeaders = vercelHeaders(env)
|
| 67 |
+
const token = await login(baseURL, adminKey, extraHeaders)
|
| 68 |
+
const result = await checkAll(baseURL, token, extraHeaders)
|
| 69 |
+
return result
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
export default {
|
| 73 |
+
async scheduled(event, env, ctx) {
|
| 74 |
+
ctx.waitUntil(
|
| 75 |
+
runCheck(env)
|
| 76 |
+
.then((result) => {
|
| 77 |
+
const items = result.items || []
|
| 78 |
+
const healthy = items.filter((i) => i.healthy && !i.disabled).length
|
| 79 |
+
const banned = items.filter((i) => i.disabled).length
|
| 80 |
+
console.log(
|
| 81 |
+
`proxy health check done: ${healthy}/${items.length} healthy, ${banned} banned`
|
| 82 |
+
)
|
| 83 |
+
})
|
| 84 |
+
.catch((err) => {
|
| 85 |
+
console.error(`proxy health check failed: ${err.message}`)
|
| 86 |
+
})
|
| 87 |
+
)
|
| 88 |
+
},
|
| 89 |
+
|
| 90 |
+
async fetch(request, env) {
|
| 91 |
+
const url = new URL(request.url)
|
| 92 |
+
if (url.pathname !== "/check") {
|
| 93 |
+
return new Response("not found", { status: 404 })
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
try {
|
| 97 |
+
const result = await runCheck(env)
|
| 98 |
+
return Response.json(result)
|
| 99 |
+
} catch (err) {
|
| 100 |
+
return Response.json({ error: err.message }, { status: 500 })
|
| 101 |
+
}
|
| 102 |
+
},
|
| 103 |
+
}
|
cf-worker/wrangler.toml
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name = "ds2api-health-check"
|
| 2 |
+
main = "src/index.js"
|
| 3 |
+
compatibility_date = "2024-12-01"
|
| 4 |
+
|
| 5 |
+
[triggers]
|
| 6 |
+
crons = ["0 */5 * * *"]
|
| 7 |
+
|
| 8 |
+
[vars]
|
| 9 |
+
# DS2API_BASE_URL = "https://your-app.vercel.app"
|
cmd/ds2api-tests/main.go
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package main
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"flag"
|
| 6 |
+
"fmt"
|
| 7 |
+
"os"
|
| 8 |
+
"time"
|
| 9 |
+
|
| 10 |
+
"ds2api/internal/testsuite"
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
func main() {
|
| 14 |
+
opts := testsuite.DefaultOptions()
|
| 15 |
+
var timeoutSeconds int
|
| 16 |
+
|
| 17 |
+
flag.StringVar(&opts.ConfigPath, "config", opts.ConfigPath, "Path to config file (default: config.json)")
|
| 18 |
+
flag.StringVar(&opts.AdminKey, "admin-key", opts.AdminKey, "Admin key (default: DS2API_ADMIN_KEY or admin)")
|
| 19 |
+
flag.StringVar(&opts.OutputDir, "out", opts.OutputDir, "Output artifact directory")
|
| 20 |
+
flag.IntVar(&opts.Port, "port", opts.Port, "Server port (0 means auto-select free port)")
|
| 21 |
+
flag.IntVar(&timeoutSeconds, "timeout", int(opts.Timeout.Seconds()), "Per-request timeout in seconds")
|
| 22 |
+
flag.IntVar(&opts.Retries, "retries", opts.Retries, "Retry count for network/5xx requests")
|
| 23 |
+
flag.BoolVar(&opts.NoPreflight, "no-preflight", opts.NoPreflight, "Skip preflight checks")
|
| 24 |
+
flag.IntVar(&opts.MaxKeepRuns, "keep", opts.MaxKeepRuns, "Max test runs to keep (0 = keep all)")
|
| 25 |
+
flag.Parse()
|
| 26 |
+
|
| 27 |
+
if timeoutSeconds <= 0 {
|
| 28 |
+
timeoutSeconds = 120
|
| 29 |
+
}
|
| 30 |
+
opts.Timeout = time.Duration(timeoutSeconds) * time.Second
|
| 31 |
+
|
| 32 |
+
if err := testsuite.Run(context.Background(), opts); err != nil {
|
| 33 |
+
_, _ = fmt.Fprintln(os.Stderr, err.Error())
|
| 34 |
+
os.Exit(1)
|
| 35 |
+
}
|
| 36 |
+
_, _ = fmt.Fprintln(os.Stdout, "testsuite completed successfully")
|
| 37 |
+
}
|
cmd/ds2api/main.go
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package main
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"fmt"
|
| 6 |
+
"net"
|
| 7 |
+
"net/http"
|
| 8 |
+
"os"
|
| 9 |
+
"os/signal"
|
| 10 |
+
"strings"
|
| 11 |
+
"syscall"
|
| 12 |
+
"time"
|
| 13 |
+
|
| 14 |
+
"ds2api/internal/auth"
|
| 15 |
+
"ds2api/internal/config"
|
| 16 |
+
"ds2api/internal/server"
|
| 17 |
+
"ds2api/internal/webui"
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
func main() {
|
| 21 |
+
if err := config.LoadDotEnv(); err != nil {
|
| 22 |
+
config.Logger.Warn("[dotenv] load failed", "error", err)
|
| 23 |
+
}
|
| 24 |
+
config.RefreshLogger()
|
| 25 |
+
webui.EnsureBuiltOnStartup()
|
| 26 |
+
_ = auth.AdminKey()
|
| 27 |
+
app, err := server.NewApp()
|
| 28 |
+
if err != nil {
|
| 29 |
+
config.Logger.Error("server initialization failed", "error", err)
|
| 30 |
+
os.Exit(1)
|
| 31 |
+
}
|
| 32 |
+
port := strings.TrimSpace(os.Getenv("PORT"))
|
| 33 |
+
if port == "" {
|
| 34 |
+
port = "5001"
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
srv := &http.Server{
|
| 38 |
+
Addr: "0.0.0.0:" + port,
|
| 39 |
+
Handler: app.Router,
|
| 40 |
+
ReadHeaderTimeout: 5 * time.Second,
|
| 41 |
+
}
|
| 42 |
+
localURL := fmt.Sprintf("http://127.0.0.1:%s", port)
|
| 43 |
+
lanIP := detectLANIPv4()
|
| 44 |
+
lanURL := ""
|
| 45 |
+
if lanIP != "" {
|
| 46 |
+
lanURL = fmt.Sprintf("http://%s:%s", lanIP, port)
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
// Start server in a goroutine so we can listen for shutdown signals.
|
| 50 |
+
go func() {
|
| 51 |
+
if lanURL != "" {
|
| 52 |
+
config.Logger.Info("starting ds2api", "bind", srv.Addr, "port", port, "local_url", localURL, "lan_url", lanURL, "lan_ip", lanIP)
|
| 53 |
+
} else {
|
| 54 |
+
config.Logger.Info("starting ds2api", "bind", srv.Addr, "port", port, "local_url", localURL)
|
| 55 |
+
config.Logger.Warn("lan ip not detected; check active network interfaces")
|
| 56 |
+
}
|
| 57 |
+
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
| 58 |
+
config.Logger.Error("server stopped unexpectedly", "error", err)
|
| 59 |
+
os.Exit(1)
|
| 60 |
+
}
|
| 61 |
+
}()
|
| 62 |
+
|
| 63 |
+
// Wait for interrupt signal (Ctrl+C / SIGTERM).
|
| 64 |
+
quit := make(chan os.Signal, 1)
|
| 65 |
+
signal.Notify(quit, os.Interrupt, syscall.SIGTERM)
|
| 66 |
+
sig := <-quit
|
| 67 |
+
config.Logger.Info("shutdown signal received", "signal", sig.String())
|
| 68 |
+
|
| 69 |
+
// Graceful shutdown: allow up to 10 seconds for in-flight requests to complete.
|
| 70 |
+
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
| 71 |
+
defer cancel()
|
| 72 |
+
|
| 73 |
+
if err := srv.Shutdown(ctx); err != nil {
|
| 74 |
+
config.Logger.Error("graceful shutdown failed, forcing exit", "error", err)
|
| 75 |
+
os.Exit(1)
|
| 76 |
+
}
|
| 77 |
+
config.Logger.Info("server gracefully stopped")
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
func detectLANIPv4() string {
|
| 81 |
+
ifaces, err := net.Interfaces()
|
| 82 |
+
if err != nil {
|
| 83 |
+
return ""
|
| 84 |
+
}
|
| 85 |
+
for _, iface := range ifaces {
|
| 86 |
+
if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {
|
| 87 |
+
continue
|
| 88 |
+
}
|
| 89 |
+
addrs, err := iface.Addrs()
|
| 90 |
+
if err != nil {
|
| 91 |
+
continue
|
| 92 |
+
}
|
| 93 |
+
for _, addr := range addrs {
|
| 94 |
+
var ip net.IP
|
| 95 |
+
switch v := addr.(type) {
|
| 96 |
+
case *net.IPNet:
|
| 97 |
+
ip = v.IP
|
| 98 |
+
case *net.IPAddr:
|
| 99 |
+
ip = v.IP
|
| 100 |
+
default:
|
| 101 |
+
continue
|
| 102 |
+
}
|
| 103 |
+
ip = ip.To4()
|
| 104 |
+
if ip == nil || !ip.IsPrivate() {
|
| 105 |
+
continue
|
| 106 |
+
}
|
| 107 |
+
return ip.String()
|
| 108 |
+
}
|
| 109 |
+
}
|
| 110 |
+
return ""
|
| 111 |
+
}
|
config.example.json
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_comment": "DS2API 配置文件示例 - 复制为 config.json 使用",
|
| 3 |
+
"_doc": "详细文档: https://github.com/CJackHwang/ds2api",
|
| 4 |
+
"keys": [
|
| 5 |
+
"your-api-key-1",
|
| 6 |
+
"your-api-key-2"
|
| 7 |
+
],
|
| 8 |
+
"api_keys": [
|
| 9 |
+
{
|
| 10 |
+
"key": "your-api-key-1",
|
| 11 |
+
"name": "主 API Key",
|
| 12 |
+
"remark": "给 OpenAI 客户端使用"
|
| 13 |
+
},
|
| 14 |
+
{
|
| 15 |
+
"key": "your-api-key-2",
|
| 16 |
+
"name": "备用 API Key",
|
| 17 |
+
"remark": "压测或临时调试"
|
| 18 |
+
}
|
| 19 |
+
],
|
| 20 |
+
"accounts": [
|
| 21 |
+
{
|
| 22 |
+
"_comment": "邮箱登录方式",
|
| 23 |
+
"name": "主账号",
|
| 24 |
+
"remark": "优先用于生产流量",
|
| 25 |
+
"email": "example1@example.com",
|
| 26 |
+
"password": "your-password-1"
|
| 27 |
+
},
|
| 28 |
+
{
|
| 29 |
+
"_comment": "邮箱登录方式 - 账号2",
|
| 30 |
+
"name": "备用账号",
|
| 31 |
+
"email": "example2@example.com",
|
| 32 |
+
"password": "your-password-2"
|
| 33 |
+
},
|
| 34 |
+
{
|
| 35 |
+
"_comment": "手机号登录方式(中国大陆)",
|
| 36 |
+
"mobile": "12345678901",
|
| 37 |
+
"password": "your-password-3"
|
| 38 |
+
}
|
| 39 |
+
],
|
| 40 |
+
"model_aliases": {
|
| 41 |
+
"gpt-4o": "deepseek-v4-flash",
|
| 42 |
+
"gpt-5.5": "deepseek-v4-flash",
|
| 43 |
+
"gpt-5.3-codex": "deepseek-v4-pro",
|
| 44 |
+
"o3": "deepseek-v4-pro"
|
| 45 |
+
},
|
| 46 |
+
"responses": {
|
| 47 |
+
"store_ttl_seconds": 900
|
| 48 |
+
},
|
| 49 |
+
"current_input_file": {
|
| 50 |
+
"enabled": true,
|
| 51 |
+
"min_chars": 0
|
| 52 |
+
},
|
| 53 |
+
"thinking_injection": {
|
| 54 |
+
"enabled": false,
|
| 55 |
+
"prompt": ""
|
| 56 |
+
},
|
| 57 |
+
"embeddings": {
|
| 58 |
+
"provider": "deterministic"
|
| 59 |
+
},
|
| 60 |
+
"admin": {
|
| 61 |
+
"jwt_expire_hours": 24
|
| 62 |
+
},
|
| 63 |
+
"runtime": {
|
| 64 |
+
"account_max_inflight": 2,
|
| 65 |
+
"account_max_queue": 0,
|
| 66 |
+
"global_max_inflight": 0,
|
| 67 |
+
"token_refresh_interval_hours": 6
|
| 68 |
+
},
|
| 69 |
+
"auto_delete": {
|
| 70 |
+
"mode": "none"
|
| 71 |
+
}
|
| 72 |
+
}
|
docker-compose.dev.yml
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# DS2API 开发环境配置
|
| 2 |
+
# 特性:
|
| 3 |
+
# - 源代码挂载(热重载)
|
| 4 |
+
# - 调试日志级别
|
| 5 |
+
# - 自动重启
|
| 6 |
+
#
|
| 7 |
+
# 使用说明:
|
| 8 |
+
# docker-compose -f docker-compose.dev.yml up
|
| 9 |
+
|
| 10 |
+
services:
|
| 11 |
+
ds2api:
|
| 12 |
+
build:
|
| 13 |
+
context: .
|
| 14 |
+
target: go-builder
|
| 15 |
+
image: ds2api:dev
|
| 16 |
+
container_name: ds2api-dev
|
| 17 |
+
command: ["go", "run", "./cmd/ds2api"]
|
| 18 |
+
ports:
|
| 19 |
+
# Host port is configurable via DS2API_HOST_PORT; container port stays fixed at 5001.
|
| 20 |
+
- "${DS2API_HOST_PORT:-6011}:5001"
|
| 21 |
+
env_file:
|
| 22 |
+
- .env
|
| 23 |
+
environment:
|
| 24 |
+
- HOST=0.0.0.0
|
| 25 |
+
- LOG_LEVEL=DEBUG
|
| 26 |
+
volumes:
|
| 27 |
+
# 源代码挂载(开发时实时生效)
|
| 28 |
+
- ./:/app
|
| 29 |
+
# 配置文件挂载(便于本地修改)
|
| 30 |
+
- ./config.json:/app/config.json
|
| 31 |
+
restart: "no"
|
| 32 |
+
stdin_open: true
|
| 33 |
+
tty: true
|
docker-compose.yml
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
ds2api:
|
| 3 |
+
image: ghcr.io/cjackhwang/ds2api:latest
|
| 4 |
+
container_name: ds2api
|
| 5 |
+
restart: always
|
| 6 |
+
env_file:
|
| 7 |
+
- .env
|
| 8 |
+
ports:
|
| 9 |
+
# Host port is configurable via DS2API_HOST_PORT; container port stays fixed at 5001.
|
| 10 |
+
- "${DS2API_HOST_PORT:-6011}:5001"
|
| 11 |
+
volumes:
|
| 12 |
+
- ./config.json:/data/config.json # 配置文件(持久化推荐路径)
|
| 13 |
+
environment:
|
| 14 |
+
- TZ=Asia/Shanghai
|
| 15 |
+
- LOG_LEVEL=INFO
|
| 16 |
+
- DS2API_ADMIN_KEY=${DS2API_ADMIN_KEY:-ds2api}
|
| 17 |
+
- DS2API_CONFIG_PATH=/data/config.json
|
entrypoint.sh
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -e
|
| 3 |
+
|
| 4 |
+
# Fix /data permissions for HF Spaces Persistent Storage
|
| 5 |
+
if [ -d /data ]; then
|
| 6 |
+
chown -R ds2api:ds2api /data 2>/dev/null || true
|
| 7 |
+
fi
|
| 8 |
+
|
| 9 |
+
# Create config file if not exists or is empty (with empty JSON object)
|
| 10 |
+
if [ ! -f /data/config.json ] || [ ! -s /data/config.json ]; then
|
| 11 |
+
echo {} > /data/config.json
|
| 12 |
+
chown ds2api:ds2api /data/config.json 2>/dev/null || true
|
| 13 |
+
fi
|
| 14 |
+
|
| 15 |
+
# Create chat history file if not exists or is empty
|
| 16 |
+
if [ ! -f /data/chat_history.json ] || [ ! -s /data/chat_history.json ]; then
|
| 17 |
+
echo {} > /data/chat_history.json
|
| 18 |
+
chown ds2api:ds2api /data/chat_history.json 2>/dev/null || true
|
| 19 |
+
fi
|
| 20 |
+
|
| 21 |
+
# Start the application as ds2api user
|
| 22 |
+
exec gosu ds2api /usr/local/bin/ds2api
|
go.mod
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
module ds2api
|
| 2 |
+
|
| 3 |
+
go 1.26.0
|
| 4 |
+
|
| 5 |
+
require (
|
| 6 |
+
github.com/andybalholm/brotli v1.2.1
|
| 7 |
+
github.com/go-chi/chi/v5 v5.2.5
|
| 8 |
+
github.com/google/uuid v1.6.0
|
| 9 |
+
github.com/hupe1980/go-tiktoken v0.0.10
|
| 10 |
+
github.com/refraction-networking/utls v1.8.2
|
| 11 |
+
github.com/router-for-me/CLIProxyAPI/v6 v6.9.14
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
require github.com/dlclark/regexp2 v1.11.5 // indirect
|
| 15 |
+
|
| 16 |
+
require (
|
| 17 |
+
github.com/klauspost/compress v1.18.5 // indirect
|
| 18 |
+
github.com/sirupsen/logrus v1.9.4 // indirect
|
| 19 |
+
github.com/tidwall/gjson v1.18.0 // indirect
|
| 20 |
+
github.com/tidwall/match v1.2.0 // indirect
|
| 21 |
+
github.com/tidwall/pretty v1.2.1 // indirect
|
| 22 |
+
github.com/tidwall/sjson v1.2.5 // indirect
|
| 23 |
+
golang.org/x/crypto v0.49.0 // indirect
|
| 24 |
+
golang.org/x/net v0.52.0
|
| 25 |
+
golang.org/x/sys v0.42.0 // indirect
|
| 26 |
+
gopkg.in/yaml.v3 v3.0.1 // indirect
|
| 27 |
+
)
|
go.sum
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
github.com/andybalholm/brotli v1.2.1 h1:R+f5xP285VArJDRgowrfb9DqL18yVK0gKAW/F+eTWro=
|
| 2 |
+
github.com/andybalholm/brotli v1.2.1/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
| 3 |
+
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
| 4 |
+
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
| 5 |
+
github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=
|
| 6 |
+
github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
|
| 7 |
+
github.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug=
|
| 8 |
+
github.com/go-chi/chi/v5 v5.2.5/go.mod h1:X7Gx4mteadT3eDOMTsXzmI4/rwUpOwBHLpAfupzFJP0=
|
| 9 |
+
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
| 10 |
+
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
| 11 |
+
github.com/hupe1980/go-tiktoken v0.0.10 h1:m6phOJaGyctqWdGIgwn9X8AfJvaG74tnQoDL+ntOUEQ=
|
| 12 |
+
github.com/hupe1980/go-tiktoken v0.0.10/go.mod h1:NME6d8hrE+Jo+kLUZHhXShYV8e40hYkm4BbSLQKtvAo=
|
| 13 |
+
github.com/klauspost/compress v1.18.5 h1:/h1gH5Ce+VWNLSWqPzOVn6XBO+vJbCNGvjoaGBFW2IE=
|
| 14 |
+
github.com/klauspost/compress v1.18.5/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
| 15 |
+
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
| 16 |
+
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
| 17 |
+
github.com/refraction-networking/utls v1.8.2 h1:j4Q1gJj0xngdeH+Ox/qND11aEfhpgoEvV+S9iJ2IdQo=
|
| 18 |
+
github.com/refraction-networking/utls v1.8.2/go.mod h1:jkSOEkLqn+S/jtpEHPOsVv/4V4EVnelwbMQl4vCWXAM=
|
| 19 |
+
github.com/router-for-me/CLIProxyAPI/v6 v6.9.14 h1:XItUHrPGE9E5xTeZIPjKGmKqfEs1AZbxl1RPfO5xtrc=
|
| 20 |
+
github.com/router-for-me/CLIProxyAPI/v6 v6.9.14/go.mod h1:P1jsIPFXorYGuS2N/3BlZYkpRKi/z7+oR3+1tdG0u4k=
|
| 21 |
+
github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
|
| 22 |
+
github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=
|
| 23 |
+
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
| 24 |
+
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
| 25 |
+
github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
| 26 |
+
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
|
| 27 |
+
github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
| 28 |
+
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
|
| 29 |
+
github.com/tidwall/match v1.2.0 h1:0pt8FlkOwjN2fPt4bIl4BoNxb98gGHN2ObFEDkrfZnM=
|
| 30 |
+
github.com/tidwall/match v1.2.0/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
|
| 31 |
+
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
| 32 |
+
github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
|
| 33 |
+
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
| 34 |
+
github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
|
| 35 |
+
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
|
| 36 |
+
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
|
| 37 |
+
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
|
| 38 |
+
golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
|
| 39 |
+
golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
|
| 40 |
+
golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=
|
| 41 |
+
golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=
|
| 42 |
+
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
| 43 |
+
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
| 44 |
+
golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
|
| 45 |
+
golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
|
| 46 |
+
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
| 47 |
+
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
| 48 |
+
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
| 49 |
+
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
internal/account/pool_acquire.go
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package account
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
|
| 6 |
+
"ds2api/internal/config"
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
func (p *Pool) Acquire(target string, exclude map[string]bool) (config.Account, bool) {
|
| 10 |
+
p.mu.Lock()
|
| 11 |
+
defer p.mu.Unlock()
|
| 12 |
+
return p.acquireLocked(target, normalizeExclude(exclude))
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
func (p *Pool) AcquireWait(ctx context.Context, target string, exclude map[string]bool) (config.Account, bool) {
|
| 16 |
+
if ctx == nil {
|
| 17 |
+
ctx = context.Background()
|
| 18 |
+
}
|
| 19 |
+
exclude = normalizeExclude(exclude)
|
| 20 |
+
for {
|
| 21 |
+
if ctx.Err() != nil {
|
| 22 |
+
return config.Account{}, false
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
p.mu.Lock()
|
| 26 |
+
if acc, ok := p.acquireLocked(target, exclude); ok {
|
| 27 |
+
p.mu.Unlock()
|
| 28 |
+
return acc, true
|
| 29 |
+
}
|
| 30 |
+
if !p.canQueueLocked(target, exclude) {
|
| 31 |
+
p.mu.Unlock()
|
| 32 |
+
return config.Account{}, false
|
| 33 |
+
}
|
| 34 |
+
waiter := make(chan struct{})
|
| 35 |
+
p.waiters = append(p.waiters, waiter)
|
| 36 |
+
p.mu.Unlock()
|
| 37 |
+
|
| 38 |
+
select {
|
| 39 |
+
case <-ctx.Done():
|
| 40 |
+
p.mu.Lock()
|
| 41 |
+
p.removeWaiterLocked(waiter)
|
| 42 |
+
p.mu.Unlock()
|
| 43 |
+
return config.Account{}, false
|
| 44 |
+
case <-waiter:
|
| 45 |
+
}
|
| 46 |
+
}
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
func (p *Pool) acquireLocked(target string, exclude map[string]bool) (config.Account, bool) {
|
| 50 |
+
if target != "" {
|
| 51 |
+
if exclude[target] || !p.canAcquireIDLocked(target) {
|
| 52 |
+
return config.Account{}, false
|
| 53 |
+
}
|
| 54 |
+
acc, ok := p.store.FindAccount(target)
|
| 55 |
+
if !ok {
|
| 56 |
+
return config.Account{}, false
|
| 57 |
+
}
|
| 58 |
+
p.inUse[target]++
|
| 59 |
+
p.bumpQueue(target)
|
| 60 |
+
return acc, true
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
return p.tryAcquire(exclude)
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
func (p *Pool) tryAcquire(exclude map[string]bool) (config.Account, bool) {
|
| 67 |
+
for i := 0; i < len(p.queue); i++ {
|
| 68 |
+
id := p.queue[i]
|
| 69 |
+
if exclude[id] || !p.canAcquireIDLocked(id) {
|
| 70 |
+
continue
|
| 71 |
+
}
|
| 72 |
+
acc, ok := p.store.FindAccount(id)
|
| 73 |
+
if !ok {
|
| 74 |
+
continue
|
| 75 |
+
}
|
| 76 |
+
p.inUse[id]++
|
| 77 |
+
p.bumpQueue(id)
|
| 78 |
+
return acc, true
|
| 79 |
+
}
|
| 80 |
+
return config.Account{}, false
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
func (p *Pool) bumpQueue(accountID string) {
|
| 84 |
+
for i, id := range p.queue {
|
| 85 |
+
if id != accountID {
|
| 86 |
+
continue
|
| 87 |
+
}
|
| 88 |
+
p.queue = append(p.queue[:i], p.queue[i+1:]...)
|
| 89 |
+
p.queue = append(p.queue, accountID)
|
| 90 |
+
return
|
| 91 |
+
}
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
func normalizeExclude(exclude map[string]bool) map[string]bool {
|
| 95 |
+
if exclude == nil {
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type Pool struct {
|
| 11 |
+
store *config.Store
|
| 12 |
+
mu sync.Mutex
|
| 13 |
+
queue []string
|
| 14 |
+
inUse map[string]int
|
| 15 |
+
waiters []chan struct{}
|
| 16 |
+
maxInflightPerAccount int
|
| 17 |
+
recommendedConcurrency int
|
| 18 |
+
maxQueueSize int
|
| 19 |
+
globalMaxInflight int
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
func NewPool(store *config.Store) *Pool {
|
| 23 |
+
maxPer := 2
|
| 24 |
+
if store != nil {
|
| 25 |
+
maxPer = store.RuntimeAccountMaxInflight()
|
| 26 |
+
}
|
| 27 |
+
p := &Pool{
|
| 28 |
+
store: store,
|
| 29 |
+
inUse: map[string]int{},
|
| 30 |
+
maxInflightPerAccount: maxPer,
|
| 31 |
+
}
|
| 32 |
+
p.Reset()
|
| 33 |
+
return p
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
func (p *Pool) Reset() {
|
| 37 |
+
accounts := p.store.Accounts()
|
| 38 |
+
sort.SliceStable(accounts, func(i, j int) bool {
|
| 39 |
+
iHas := accounts[i].Token != ""
|
| 40 |
+
jHas := accounts[j].Token != ""
|
| 41 |
+
if iHas == jHas {
|
| 42 |
+
return i < j
|
| 43 |
+
}
|
| 44 |
+
return iHas
|
| 45 |
+
})
|
| 46 |
+
ids := make([]string, 0, len(accounts))
|
| 47 |
+
for _, a := range accounts {
|
| 48 |
+
id := a.Identifier()
|
| 49 |
+
if id != "" {
|
| 50 |
+
ids = append(ids, id)
|
| 51 |
+
}
|
| 52 |
+
}
|
| 53 |
+
if p.store != nil {
|
| 54 |
+
p.maxInflightPerAccount = p.store.RuntimeAccountMaxInflight()
|
| 55 |
+
} else {
|
| 56 |
+
p.maxInflightPerAccount = maxInflightFromEnv()
|
| 57 |
+
}
|
| 58 |
+
recommended := defaultRecommendedConcurrency(len(ids), p.maxInflightPerAccount)
|
| 59 |
+
queueLimit := maxQueueFromEnv(recommended)
|
| 60 |
+
globalLimit := recommended
|
| 61 |
+
if p.store != nil {
|
| 62 |
+
queueLimit = p.store.RuntimeAccountMaxQueue(recommended)
|
| 63 |
+
globalLimit = p.store.RuntimeGlobalMaxInflight(recommended)
|
| 64 |
+
}
|
| 65 |
+
p.mu.Lock()
|
| 66 |
+
defer p.mu.Unlock()
|
| 67 |
+
p.drainWaitersLocked()
|
| 68 |
+
p.queue = ids
|
| 69 |
+
p.inUse = map[string]int{}
|
| 70 |
+
p.recommendedConcurrency = recommended
|
| 71 |
+
p.maxQueueSize = queueLimit
|
| 72 |
+
p.globalMaxInflight = globalLimit
|
| 73 |
+
config.Logger.Info(
|
| 74 |
+
"[init_account_queue] initialized",
|
| 75 |
+
"total", len(ids),
|
| 76 |
+
"max_inflight_per_account", p.maxInflightPerAccount,
|
| 77 |
+
"global_max_inflight", p.globalMaxInflight,
|
| 78 |
+
"recommended_concurrency", p.recommendedConcurrency,
|
| 79 |
+
"max_queue_size", p.maxQueueSize,
|
| 80 |
+
)
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
func (p *Pool) Release(accountID string) {
|
| 84 |
+
if accountID == "" {
|
| 85 |
+
return
|
| 86 |
+
}
|
| 87 |
+
p.mu.Lock()
|
| 88 |
+
defer p.mu.Unlock()
|
| 89 |
+
count := p.inUse[accountID]
|
| 90 |
+
if count <= 0 {
|
| 91 |
+
return
|
| 92 |
+
}
|
| 93 |
+
if count == 1 {
|
| 94 |
+
delete(p.inUse, accountID)
|
| 95 |
+
p.notifyWaiterLocked()
|
| 96 |
+
return
|
| 97 |
+
}
|
| 98 |
+
p.inUse[accountID] = count - 1
|
| 99 |
+
p.notifyWaiterLocked()
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
func (p *Pool) Status() map[string]any {
|
| 103 |
+
p.mu.Lock()
|
| 104 |
+
defer p.mu.Unlock()
|
| 105 |
+
available := make([]string, 0, len(p.queue))
|
| 106 |
+
inUseAccounts := make([]string, 0, len(p.inUse))
|
| 107 |
+
inUseSlots := 0
|
| 108 |
+
for _, id := range p.queue {
|
| 109 |
+
if p.inUse[id] < p.maxInflightPerAccount {
|
| 110 |
+
available = append(available, id)
|
| 111 |
+
}
|
| 112 |
+
}
|
| 113 |
+
for id, count := range p.inUse {
|
| 114 |
+
if count > 0 {
|
| 115 |
+
inUseAccounts = append(inUseAccounts, id)
|
| 116 |
+
inUseSlots += count
|
| 117 |
+
}
|
| 118 |
+
}
|
| 119 |
+
sort.Strings(inUseAccounts)
|
| 120 |
+
return map[string]any{
|
| 121 |
+
"available": len(available),
|
| 122 |
+
"in_use": inUseSlots,
|
| 123 |
+
"total": len(p.store.Accounts()),
|
| 124 |
+
"available_accounts": available,
|
| 125 |
+
"in_use_accounts": inUseAccounts,
|
| 126 |
+
"max_inflight_per_account": p.maxInflightPerAccount,
|
| 127 |
+
"global_max_inflight": p.globalMaxInflight,
|
| 128 |
+
"recommended_concurrency": p.recommendedConcurrency,
|
| 129 |
+
"waiting": len(p.waiters),
|
| 130 |
+
"max_queue_size": p.maxQueueSize,
|
| 131 |
+
}
|
| 132 |
+
}
|
internal/account/pool_edge_test.go
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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6 |
+
"testing"
|
| 7 |
+
"time"
|
| 8 |
+
|
| 9 |
+
"ds2api/internal/config"
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
// ─── Pool edge cases ─────────────────────────────────────────────────
|
| 13 |
+
|
| 14 |
+
func TestPoolEmptyNoAccounts(t *testing.T) {
|
| 15 |
+
t.Setenv("DS2API_ACCOUNT_MAX_INFLIGHT", "2")
|
| 16 |
+
t.Setenv("DS2API_ACCOUNT_MAX_QUEUE", "")
|
| 17 |
+
t.Setenv("DS2API_CONFIG_JSON", `{"keys":["k1"],"accounts":[]}`)
|
| 18 |
+
pool := NewPool(config.LoadStore())
|
| 19 |
+
if _, ok := pool.Acquire("", nil); ok {
|
| 20 |
+
t.Fatal("expected acquire to fail with no accounts")
|
| 21 |
+
}
|
| 22 |
+
status := pool.Status()
|
| 23 |
+
if total, ok := status["total"].(int); !ok || total != 0 {
|
| 24 |
+
t.Fatalf("unexpected total: %#v", status["total"])
|
| 25 |
+
}
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
func TestPoolReleaseNonExistentAccount(t *testing.T) {
|
| 29 |
+
pool := newPoolForTest(t, "2")
|
| 30 |
+
pool.Release("nonexistent@example.com") // should not panic
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
func TestPoolReleaseAlreadyReleased(t *testing.T) {
|
| 34 |
+
pool := newPoolForTest(t, "2")
|
| 35 |
+
acc, ok := pool.Acquire("", nil)
|
| 36 |
+
if !ok {
|
| 37 |
+
t.Fatal("expected acquire success")
|
| 38 |
+
}
|
| 39 |
+
pool.Release(acc.Identifier())
|
| 40 |
+
pool.Release(acc.Identifier()) // double release should not panic
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
func TestPoolAcquireTargetNotFound(t *testing.T) {
|
| 44 |
+
pool := newPoolForTest(t, "2")
|
| 45 |
+
if _, ok := pool.Acquire("nonexistent@example.com", nil); ok {
|
| 46 |
+
t.Fatal("expected acquire to fail for non-existent target")
|
| 47 |
+
}
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
func TestPoolAcquireWithExclusionList(t *testing.T) {
|
| 51 |
+
pool := newPoolForTest(t, "2")
|
| 52 |
+
acc, ok := pool.Acquire("", map[string]bool{"acc1@example.com": true})
|
| 53 |
+
if !ok {
|
| 54 |
+
t.Fatal("expected acquire success with exclusion")
|
| 55 |
+
}
|
| 56 |
+
if acc.Identifier() != "acc2@example.com" {
|
| 57 |
+
t.Fatalf("expected acc2 when acc1 excluded, got %q", acc.Identifier())
|
| 58 |
+
}
|
| 59 |
+
pool.Release(acc.Identifier())
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
func TestPoolAcquireAllExcluded(t *testing.T) {
|
| 63 |
+
pool := newPoolForTest(t, "2")
|
| 64 |
+
if _, ok := pool.Acquire("", map[string]bool{
|
| 65 |
+
"acc1@example.com": true,
|
| 66 |
+
"acc2@example.com": true,
|
| 67 |
+
}); ok {
|
| 68 |
+
t.Fatal("expected acquire to fail when all accounts excluded")
|
| 69 |
+
}
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
func TestPoolStatusFields(t *testing.T) {
|
| 73 |
+
pool := newPoolForTest(t, "2")
|
| 74 |
+
status := pool.Status()
|
| 75 |
+
|
| 76 |
+
// Check all expected fields are present
|
| 77 |
+
for _, key := range []string{"total", "available", "max_inflight_per_account", "recommended_concurrency", "available_accounts", "in_use_accounts", "waiting", "max_queue_size"} {
|
| 78 |
+
if _, ok := status[key]; !ok {
|
| 79 |
+
t.Fatalf("missing status field: %s", key)
|
| 80 |
+
}
|
| 81 |
+
}
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
func TestPoolStatusAccountDetails(t *testing.T) {
|
| 85 |
+
pool := newPoolForTest(t, "2")
|
| 86 |
+
acc, _ := pool.Acquire("acc1@example.com", nil)
|
| 87 |
+
|
| 88 |
+
status := pool.Status()
|
| 89 |
+
inUseAccounts, ok := status["in_use_accounts"].([]string)
|
| 90 |
+
if !ok {
|
| 91 |
+
t.Fatalf("unexpected in_use_accounts type: %T", status["in_use_accounts"])
|
| 92 |
+
}
|
| 93 |
+
found := false
|
| 94 |
+
for _, id := range inUseAccounts {
|
| 95 |
+
if id == "acc1@example.com" {
|
| 96 |
+
found = true
|
| 97 |
+
break
|
| 98 |
+
}
|
| 99 |
+
}
|
| 100 |
+
if !found {
|
| 101 |
+
t.Fatalf("expected acc1 in in_use_accounts, got %v", inUseAccounts)
|
| 102 |
+
}
|
| 103 |
+
if status["in_use"] != 1 {
|
| 104 |
+
t.Fatalf("expected 1 in_use, got %v", status["in_use"])
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
pool.Release(acc.Identifier())
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
func TestPoolAcquireWaitContextCancelled(t *testing.T) {
|
| 111 |
+
pool := newSingleAccountPoolForTest(t, "1")
|
| 112 |
+
// Exhaust the pool
|
| 113 |
+
first, ok := pool.Acquire("", nil)
|
| 114 |
+
if !ok {
|
| 115 |
+
t.Fatal("expected first acquire to succeed")
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
ctx, cancel := context.WithCancel(context.Background())
|
| 119 |
+
|
| 120 |
+
var wg sync.WaitGroup
|
| 121 |
+
wg.Add(1)
|
| 122 |
+
var waitOK bool
|
| 123 |
+
go func() {
|
| 124 |
+
defer wg.Done()
|
| 125 |
+
_, waitOK = pool.AcquireWait(ctx, "", nil)
|
| 126 |
+
}()
|
| 127 |
+
|
| 128 |
+
// Wait until queued
|
| 129 |
+
waitForWaitingCount(t, pool, 1)
|
| 130 |
+
|
| 131 |
+
// Cancel context
|
| 132 |
+
cancel()
|
| 133 |
+
|
| 134 |
+
wg.Wait()
|
| 135 |
+
if waitOK {
|
| 136 |
+
t.Fatal("expected acquire to fail after context cancellation")
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
pool.Release(first.Identifier())
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
func TestPoolAcquireWaitTargetAccount(t *testing.T) {
|
| 143 |
+
pool := newPoolForTest(t, "1")
|
| 144 |
+
// Exhaust acc1
|
| 145 |
+
acc1, ok := pool.Acquire("acc1@example.com", nil)
|
| 146 |
+
if !ok {
|
| 147 |
+
t.Fatal("expected acquire acc1 success")
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
// Acquire acc2 directly (should succeed since acc2 is free)
|
| 151 |
+
ctx := context.Background()
|
| 152 |
+
acc2, ok := pool.AcquireWait(ctx, "acc2@example.com", nil)
|
| 153 |
+
if !ok {
|
| 154 |
+
t.Fatal("expected acquire acc2 success via AcquireWait")
|
| 155 |
+
}
|
| 156 |
+
if acc2.Identifier() != "acc2@example.com" {
|
| 157 |
+
t.Fatalf("expected acc2, got %q", acc2.Identifier())
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
pool.Release(acc1.Identifier())
|
| 161 |
+
pool.Release(acc2.Identifier())
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
func TestPoolMaxQueueSizeOverride(t *testing.T) {
|
| 165 |
+
t.Setenv("DS2API_ACCOUNT_MAX_INFLIGHT", "1")
|
| 166 |
+
t.Setenv("DS2API_ACCOUNT_MAX_QUEUE", "5")
|
| 167 |
+
t.Setenv("DS2API_CONFIG_JSON", `{"keys":["k1"],"accounts":[{"email":"acc1@example.com","token":"t1"}]}`)
|
| 168 |
+
pool := NewPool(config.LoadStore())
|
| 169 |
+
status := pool.Status()
|
| 170 |
+
if got, ok := status["max_queue_size"].(int); !ok || got != 5 {
|
| 171 |
+
t.Fatalf("expected max_queue_size=5, got %#v", status["max_queue_size"])
|
| 172 |
+
}
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
func TestPoolMultipleAcquireReleaseCycles(t *testing.T) {
|
| 176 |
+
pool := newSingleAccountPoolForTest(t, "1")
|
| 177 |
+
for i := 0; i < 10; i++ {
|
| 178 |
+
acc, ok := pool.Acquire("", nil)
|
| 179 |
+
if !ok {
|
| 180 |
+
t.Fatalf("acquire failed at cycle %d", i)
|
| 181 |
+
}
|
| 182 |
+
pool.Release(acc.Identifier())
|
| 183 |
+
}
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
func TestPoolConcurrentAcquireWait(t *testing.T) {
|
| 187 |
+
pool := newSingleAccountPoolForTest(t, "1")
|
| 188 |
+
first, ok := pool.Acquire("", nil)
|
| 189 |
+
if !ok {
|
| 190 |
+
t.Fatal("expected first acquire success")
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
const waiters = 3
|
| 194 |
+
results := make(chan bool, waiters)
|
| 195 |
+
|
| 196 |
+
for i := 0; i < waiters; i++ {
|
| 197 |
+
go func() {
|
| 198 |
+
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
| 199 |
+
defer cancel()
|
| 200 |
+
_, ok := pool.AcquireWait(ctx, "", nil)
|
| 201 |
+
results <- ok
|
| 202 |
+
}()
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
// Wait for all to be queued (only 1 can queue)
|
| 206 |
+
time.Sleep(50 * time.Millisecond)
|
| 207 |
+
|
| 208 |
+
// Release and allow queued requests to proceed
|
| 209 |
+
pool.Release(first.Identifier())
|
| 210 |
+
|
| 211 |
+
successCount := 0
|
| 212 |
+
timeoutCount := 0
|
| 213 |
+
for i := 0; i < waiters; i++ {
|
| 214 |
+
select {
|
| 215 |
+
case ok := <-results:
|
| 216 |
+
if ok {
|
| 217 |
+
successCount++
|
| 218 |
+
// Release for next waiter
|
| 219 |
+
pool.Release("acc1@example.com")
|
| 220 |
+
} else {
|
| 221 |
+
timeoutCount++
|
| 222 |
+
}
|
| 223 |
+
case <-time.After(3 * time.Second):
|
| 224 |
+
t.Fatal("timed out waiting for results")
|
| 225 |
+
}
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
// At least 1 should succeed; 2 may fail due to queue limit
|
| 229 |
+
if successCount < 1 {
|
| 230 |
+
t.Fatalf("expected at least 1 success, got success=%d timeout=%d", successCount, timeoutCount)
|
| 231 |
+
}
|
| 232 |
+
}
|
internal/account/pool_limits.go
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package account
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"os"
|
| 5 |
+
"strconv"
|
| 6 |
+
"strings"
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
func (p *Pool) ApplyRuntimeLimits(maxInflightPerAccount, maxQueueSize, globalMaxInflight int) {
|
| 10 |
+
if maxInflightPerAccount <= 0 {
|
| 11 |
+
maxInflightPerAccount = 1
|
| 12 |
+
}
|
| 13 |
+
if maxQueueSize < 0 {
|
| 14 |
+
maxQueueSize = 0
|
| 15 |
+
}
|
| 16 |
+
if globalMaxInflight <= 0 {
|
| 17 |
+
globalMaxInflight = maxInflightPerAccount * len(p.store.Accounts())
|
| 18 |
+
if globalMaxInflight <= 0 {
|
| 19 |
+
globalMaxInflight = maxInflightPerAccount
|
| 20 |
+
}
|
| 21 |
+
}
|
| 22 |
+
p.mu.Lock()
|
| 23 |
+
defer p.mu.Unlock()
|
| 24 |
+
p.maxInflightPerAccount = maxInflightPerAccount
|
| 25 |
+
p.maxQueueSize = maxQueueSize
|
| 26 |
+
p.globalMaxInflight = globalMaxInflight
|
| 27 |
+
p.recommendedConcurrency = defaultRecommendedConcurrency(len(p.queue), p.maxInflightPerAccount)
|
| 28 |
+
p.notifyWaiterLocked()
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
func maxInflightFromEnv() int {
|
| 32 |
+
if raw := strings.TrimSpace(os.Getenv("DS2API_ACCOUNT_MAX_INFLIGHT")); raw != "" {
|
| 33 |
+
if n, err := strconv.Atoi(raw); err == nil && n > 0 {
|
| 34 |
+
return n
|
| 35 |
+
}
|
| 36 |
+
}
|
| 37 |
+
return 2
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
func defaultRecommendedConcurrency(accountCount, maxInflightPerAccount int) int {
|
| 41 |
+
if accountCount <= 0 {
|
| 42 |
+
return 0
|
| 43 |
+
}
|
| 44 |
+
if maxInflightPerAccount <= 0 {
|
| 45 |
+
maxInflightPerAccount = 2
|
| 46 |
+
}
|
| 47 |
+
return accountCount * maxInflightPerAccount
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
func maxQueueFromEnv(defaultSize int) int {
|
| 51 |
+
if raw := strings.TrimSpace(os.Getenv("DS2API_ACCOUNT_MAX_QUEUE")); raw != "" {
|
| 52 |
+
if n, err := strconv.Atoi(raw); err == nil && n >= 0 {
|
| 53 |
+
return n
|
| 54 |
+
}
|
| 55 |
+
}
|
| 56 |
+
if defaultSize < 0 {
|
| 57 |
+
return 0
|
| 58 |
+
}
|
| 59 |
+
return defaultSize
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
func (p *Pool) canAcquireIDLocked(accountID string) bool {
|
| 63 |
+
if accountID == "" {
|
| 64 |
+
return false
|
| 65 |
+
}
|
| 66 |
+
if p.inUse[accountID] >= p.maxInflightPerAccount {
|
| 67 |
+
return false
|
| 68 |
+
}
|
| 69 |
+
if p.globalMaxInflight > 0 && p.currentInUseLocked() >= p.globalMaxInflight {
|
| 70 |
+
return false
|
| 71 |
+
}
|
| 72 |
+
return true
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
func (p *Pool) currentInUseLocked() int {
|
| 76 |
+
total := 0
|
| 77 |
+
for _, n := range p.inUse {
|
| 78 |
+
total += n
|
| 79 |
+
}
|
| 80 |
+
return total
|
| 81 |
+
}
|
internal/account/pool_test.go
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package account
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"sync"
|
| 6 |
+
"testing"
|
| 7 |
+
"time"
|
| 8 |
+
|
| 9 |
+
"ds2api/internal/config"
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
func newPoolForTest(t *testing.T, maxInflight string) *Pool {
|
| 13 |
+
t.Helper()
|
| 14 |
+
t.Setenv("DS2API_ACCOUNT_MAX_INFLIGHT", maxInflight)
|
| 15 |
+
t.Setenv("DS2API_ACCOUNT_MAX_QUEUE", "")
|
| 16 |
+
t.Setenv("DS2API_CONFIG_JSON", `{
|
| 17 |
+
"keys":["k1"],
|
| 18 |
+
"accounts":[
|
| 19 |
+
{"email":"acc1@example.com","token":"token1"},
|
| 20 |
+
{"email":"acc2@example.com","token":"token2"}
|
| 21 |
+
]
|
| 22 |
+
}`)
|
| 23 |
+
store := config.LoadStore()
|
| 24 |
+
return NewPool(store)
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
func newSingleAccountPoolForTest(t *testing.T, maxInflight string) *Pool {
|
| 28 |
+
t.Helper()
|
| 29 |
+
t.Setenv("DS2API_ACCOUNT_MAX_INFLIGHT", maxInflight)
|
| 30 |
+
t.Setenv("DS2API_ACCOUNT_MAX_QUEUE", "")
|
| 31 |
+
t.Setenv("DS2API_CONFIG_JSON", `{
|
| 32 |
+
"keys":["k1"],
|
| 33 |
+
"accounts":[{"email":"acc1@example.com","token":"token1"}]
|
| 34 |
+
}`)
|
| 35 |
+
return NewPool(config.LoadStore())
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
func waitForWaitingCount(t *testing.T, pool *Pool, want int) {
|
| 39 |
+
t.Helper()
|
| 40 |
+
deadline := time.Now().Add(800 * time.Millisecond)
|
| 41 |
+
for time.Now().Before(deadline) {
|
| 42 |
+
status := pool.Status()
|
| 43 |
+
if got, ok := status["waiting"].(int); ok && got == want {
|
| 44 |
+
return
|
| 45 |
+
}
|
| 46 |
+
time.Sleep(10 * time.Millisecond)
|
| 47 |
+
}
|
| 48 |
+
status := pool.Status()
|
| 49 |
+
t.Fatalf("waiting count did not reach %d, current status=%v", want, status)
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
func TestPoolRoundRobinWithConcurrentSlots(t *testing.T) {
|
| 53 |
+
pool := newPoolForTest(t, "2")
|
| 54 |
+
|
| 55 |
+
order := make([]string, 0, 4)
|
| 56 |
+
for i := 0; i < 4; i++ {
|
| 57 |
+
acc, ok := pool.Acquire("", nil)
|
| 58 |
+
if !ok {
|
| 59 |
+
t.Fatalf("expected acquire success at step %d", i+1)
|
| 60 |
+
}
|
| 61 |
+
order = append(order, acc.Identifier())
|
| 62 |
+
}
|
| 63 |
+
want := []string{"acc1@example.com", "acc2@example.com", "acc1@example.com", "acc2@example.com"}
|
| 64 |
+
for i := range want {
|
| 65 |
+
if order[i] != want[i] {
|
| 66 |
+
t.Fatalf("unexpected order at %d: got %q want %q (full=%v)", i, order[i], want[i], order)
|
| 67 |
+
}
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
if _, ok := pool.Acquire("", nil); ok {
|
| 71 |
+
t.Fatalf("expected acquire to fail when all inflight slots are occupied")
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
pool.Release("acc1@example.com")
|
| 75 |
+
acc, ok := pool.Acquire("", nil)
|
| 76 |
+
if !ok || acc.Identifier() != "acc1@example.com" {
|
| 77 |
+
t.Fatalf("expected reacquire acc1 after releasing one slot, got ok=%v id=%q", ok, acc.Identifier())
|
| 78 |
+
}
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
func TestPoolTargetAccountInflightLimit(t *testing.T) {
|
| 82 |
+
pool := newPoolForTest(t, "2")
|
| 83 |
+
|
| 84 |
+
for i := 0; i < 2; i++ {
|
| 85 |
+
if _, ok := pool.Acquire("acc1@example.com", nil); !ok {
|
| 86 |
+
t.Fatalf("expected target acquire success at step %d", i+1)
|
| 87 |
+
}
|
| 88 |
+
}
|
| 89 |
+
if _, ok := pool.Acquire("acc1@example.com", nil); ok {
|
| 90 |
+
t.Fatalf("expected third acquire on same target to fail due to inflight limit")
|
| 91 |
+
}
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
func TestPoolConcurrentAcquireDistribution(t *testing.T) {
|
| 95 |
+
pool := newPoolForTest(t, "2")
|
| 96 |
+
|
| 97 |
+
start := make(chan struct{})
|
| 98 |
+
results := make(chan string, 6)
|
| 99 |
+
var wg sync.WaitGroup
|
| 100 |
+
for i := 0; i < 6; i++ {
|
| 101 |
+
wg.Add(1)
|
| 102 |
+
go func() {
|
| 103 |
+
defer wg.Done()
|
| 104 |
+
<-start
|
| 105 |
+
acc, ok := pool.Acquire("", nil)
|
| 106 |
+
if !ok {
|
| 107 |
+
results <- "FAIL"
|
| 108 |
+
return
|
| 109 |
+
}
|
| 110 |
+
results <- acc.Identifier()
|
| 111 |
+
}()
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
close(start)
|
| 115 |
+
wg.Wait()
|
| 116 |
+
close(results)
|
| 117 |
+
|
| 118 |
+
success := 0
|
| 119 |
+
fail := 0
|
| 120 |
+
perAccount := map[string]int{}
|
| 121 |
+
for id := range results {
|
| 122 |
+
if id == "FAIL" {
|
| 123 |
+
fail++
|
| 124 |
+
continue
|
| 125 |
+
}
|
| 126 |
+
success++
|
| 127 |
+
perAccount[id]++
|
| 128 |
+
}
|
| 129 |
+
if success != 4 || fail != 2 {
|
| 130 |
+
t.Fatalf("unexpected concurrent acquire result: success=%d fail=%d perAccount=%v", success, fail, perAccount)
|
| 131 |
+
}
|
| 132 |
+
for id, n := range perAccount {
|
| 133 |
+
if n > 2 {
|
| 134 |
+
t.Fatalf("account %s exceeded inflight limit: %d", id, n)
|
| 135 |
+
}
|
| 136 |
+
}
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
func TestPoolStatusRecommendedConcurrencyDefault(t *testing.T) {
|
| 140 |
+
pool := newPoolForTest(t, "")
|
| 141 |
+
status := pool.Status()
|
| 142 |
+
|
| 143 |
+
if got, ok := status["max_inflight_per_account"].(int); !ok || got != 2 {
|
| 144 |
+
t.Fatalf("unexpected max_inflight_per_account: %#v", status["max_inflight_per_account"])
|
| 145 |
+
}
|
| 146 |
+
if got, ok := status["recommended_concurrency"].(int); !ok || got != 4 {
|
| 147 |
+
t.Fatalf("unexpected recommended_concurrency: %#v", status["recommended_concurrency"])
|
| 148 |
+
}
|
| 149 |
+
if got, ok := status["max_queue_size"].(int); !ok || got != 4 {
|
| 150 |
+
t.Fatalf("unexpected max_queue_size: %#v", status["max_queue_size"])
|
| 151 |
+
}
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
func TestPoolStatusRecommendedConcurrencyRespectsOverride(t *testing.T) {
|
| 155 |
+
pool := newPoolForTest(t, "3")
|
| 156 |
+
status := pool.Status()
|
| 157 |
+
|
| 158 |
+
if got, ok := status["max_inflight_per_account"].(int); !ok || got != 3 {
|
| 159 |
+
t.Fatalf("unexpected max_inflight_per_account: %#v", status["max_inflight_per_account"])
|
| 160 |
+
}
|
| 161 |
+
if got, ok := status["recommended_concurrency"].(int); !ok || got != 6 {
|
| 162 |
+
t.Fatalf("unexpected recommended_concurrency: %#v", status["recommended_concurrency"])
|
| 163 |
+
}
|
| 164 |
+
if got, ok := status["max_queue_size"].(int); !ok || got != 6 {
|
| 165 |
+
t.Fatalf("unexpected max_queue_size: %#v", status["max_queue_size"])
|
| 166 |
+
}
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
func TestPoolGlobalMaxInflightEnv(t *testing.T) {
|
| 170 |
+
t.Setenv("DS2API_ACCOUNT_MAX_INFLIGHT", "1")
|
| 171 |
+
t.Setenv("DS2API_GLOBAL_MAX_INFLIGHT", "4")
|
| 172 |
+
t.Setenv("DS2API_CONFIG_JSON", `{
|
| 173 |
+
"keys":["k1"],
|
| 174 |
+
"accounts":[
|
| 175 |
+
{"email":"acc1@example.com","token":"token1"},
|
| 176 |
+
{"email":"acc2@example.com","token":"token2"}
|
| 177 |
+
]
|
| 178 |
+
}`)
|
| 179 |
+
|
| 180 |
+
pool := NewPool(config.LoadStore())
|
| 181 |
+
status := pool.Status()
|
| 182 |
+
if got, ok := status["global_max_inflight"].(int); !ok || got != 4 {
|
| 183 |
+
t.Fatalf("unexpected global_max_inflight: %#v", status["global_max_inflight"])
|
| 184 |
+
}
|
| 185 |
+
if got, ok := status["max_inflight_per_account"].(int); !ok || got != 1 {
|
| 186 |
+
t.Fatalf("unexpected max_inflight_per_account: %#v", status["max_inflight_per_account"])
|
| 187 |
+
}
|
| 188 |
+
if got, ok := status["recommended_concurrency"].(int); !ok || got != 2 {
|
| 189 |
+
t.Fatalf("unexpected recommended_concurrency: %#v", status["recommended_concurrency"])
|
| 190 |
+
}
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
func TestPoolDropsLegacyTokenOnlyAccountOnLoad(t *testing.T) {
|
| 194 |
+
t.Setenv("DS2API_ACCOUNT_MAX_INFLIGHT", "1")
|
| 195 |
+
t.Setenv("DS2API_CONFIG_JSON", `{
|
| 196 |
+
"keys":["k1"],
|
| 197 |
+
"accounts":[{"token":"token-only-account"}]
|
| 198 |
+
}`)
|
| 199 |
+
|
| 200 |
+
pool := NewPool(config.LoadStore())
|
| 201 |
+
status := pool.Status()
|
| 202 |
+
if got, ok := status["total"].(int); !ok || got != 0 {
|
| 203 |
+
t.Fatalf("unexpected total in pool status: %#v", status["total"])
|
| 204 |
+
}
|
| 205 |
+
if got, ok := status["available"].(int); !ok || got != 0 {
|
| 206 |
+
t.Fatalf("unexpected available in pool status: %#v", status["available"])
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
if _, ok := pool.Acquire("", nil); ok {
|
| 210 |
+
t.Fatalf("expected acquire to fail for token-only account")
|
| 211 |
+
}
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
func TestPoolAcquireRotatesIntoTokenlessAccounts(t *testing.T) {
|
| 215 |
+
t.Setenv("DS2API_ACCOUNT_MAX_INFLIGHT", "1")
|
| 216 |
+
t.Setenv("DS2API_ACCOUNT_MAX_QUEUE", "")
|
| 217 |
+
t.Setenv("DS2API_CONFIG_JSON", `{
|
| 218 |
+
"keys":["k1"],
|
| 219 |
+
"accounts":[
|
| 220 |
+
{"email":"acc1@example.com","token":"token1"},
|
| 221 |
+
{"email":"acc2@example.com","token":""},
|
| 222 |
+
{"email":"acc3@example.com","token":""}
|
| 223 |
+
]
|
| 224 |
+
}`)
|
| 225 |
+
|
| 226 |
+
pool := NewPool(config.LoadStore())
|
| 227 |
+
for i, want := range []string{"acc1@example.com", "acc2@example.com", "acc3@example.com"} {
|
| 228 |
+
acc, ok := pool.Acquire("", nil)
|
| 229 |
+
if !ok {
|
| 230 |
+
t.Fatalf("expected acquire success at step %d", i+1)
|
| 231 |
+
}
|
| 232 |
+
if got := acc.Identifier(); got != want {
|
| 233 |
+
t.Fatalf("unexpected account at step %d: got %q want %q", i+1, got, want)
|
| 234 |
+
}
|
| 235 |
+
pool.Release(acc.Identifier())
|
| 236 |
+
}
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
func TestPoolAcquireWaitQueuesAndSucceedsAfterRelease(t *testing.T) {
|
| 240 |
+
pool := newSingleAccountPoolForTest(t, "1")
|
| 241 |
+
first, ok := pool.Acquire("", nil)
|
| 242 |
+
if !ok {
|
| 243 |
+
t.Fatal("expected first acquire to succeed")
|
| 244 |
+
}
|
| 245 |
+
|
| 246 |
+
type result struct {
|
| 247 |
+
id string
|
| 248 |
+
ok bool
|
| 249 |
+
}
|
| 250 |
+
resCh := make(chan result, 1)
|
| 251 |
+
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
| 252 |
+
defer cancel()
|
| 253 |
+
go func() {
|
| 254 |
+
acc, ok := pool.AcquireWait(ctx, "", nil)
|
| 255 |
+
resCh <- result{id: acc.Identifier(), ok: ok}
|
| 256 |
+
}()
|
| 257 |
+
|
| 258 |
+
waitForWaitingCount(t, pool, 1)
|
| 259 |
+
pool.Release(first.Identifier())
|
| 260 |
+
|
| 261 |
+
select {
|
| 262 |
+
case res := <-resCh:
|
| 263 |
+
if !res.ok {
|
| 264 |
+
t.Fatal("expected queued acquire to succeed after release")
|
| 265 |
+
}
|
| 266 |
+
if res.id != "acc1@example.com" {
|
| 267 |
+
t.Fatalf("unexpected account id from queued acquire: %q", res.id)
|
| 268 |
+
}
|
| 269 |
+
case <-time.After(time.Second):
|
| 270 |
+
t.Fatal("timed out waiting for queued acquire result")
|
| 271 |
+
}
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
func TestPoolAcquireWaitQueueLimitReturnsFalse(t *testing.T) {
|
| 275 |
+
pool := newSingleAccountPoolForTest(t, "1")
|
| 276 |
+
first, ok := pool.Acquire("", nil)
|
| 277 |
+
if !ok {
|
| 278 |
+
t.Fatal("expected first acquire to succeed")
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
type result struct {
|
| 282 |
+
id string
|
| 283 |
+
ok bool
|
| 284 |
+
}
|
| 285 |
+
firstWaiter := make(chan result, 1)
|
| 286 |
+
ctx1, cancel1 := context.WithTimeout(context.Background(), 1200*time.Millisecond)
|
| 287 |
+
defer cancel1()
|
| 288 |
+
go func() {
|
| 289 |
+
acc, ok := pool.AcquireWait(ctx1, "", nil)
|
| 290 |
+
firstWaiter <- result{id: acc.Identifier(), ok: ok}
|
| 291 |
+
}()
|
| 292 |
+
waitForWaitingCount(t, pool, 1)
|
| 293 |
+
|
| 294 |
+
ctx2, cancel2 := context.WithTimeout(context.Background(), 500*time.Millisecond)
|
| 295 |
+
defer cancel2()
|
| 296 |
+
start := time.Now()
|
| 297 |
+
if _, ok := pool.AcquireWait(ctx2, "", nil); ok {
|
| 298 |
+
t.Fatal("expected second queued acquire to fail when queue is full")
|
| 299 |
+
}
|
| 300 |
+
if time.Since(start) > 120*time.Millisecond {
|
| 301 |
+
t.Fatalf("queue-full acquire should fail fast, took %s", time.Since(start))
|
| 302 |
+
}
|
| 303 |
+
|
| 304 |
+
pool.Release(first.Identifier())
|
| 305 |
+
select {
|
| 306 |
+
case res := <-firstWaiter:
|
| 307 |
+
if !res.ok {
|
| 308 |
+
t.Fatal("expected first queued acquire to succeed after release")
|
| 309 |
+
}
|
| 310 |
+
case <-time.After(time.Second):
|
| 311 |
+
t.Fatal("timed out waiting for first queued acquire")
|
| 312 |
+
}
|
| 313 |
+
}
|
internal/account/pool_waiters.go
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package account
|
| 2 |
+
|
| 3 |
+
func (p *Pool) canQueueLocked(target string, exclude map[string]bool) bool {
|
| 4 |
+
if target != "" {
|
| 5 |
+
if exclude[target] {
|
| 6 |
+
return false
|
| 7 |
+
}
|
| 8 |
+
if _, ok := p.store.FindAccount(target); !ok {
|
| 9 |
+
return false
|
| 10 |
+
}
|
| 11 |
+
}
|
| 12 |
+
if p.maxQueueSize <= 0 {
|
| 13 |
+
return false
|
| 14 |
+
}
|
| 15 |
+
return len(p.waiters) < p.maxQueueSize
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
func (p *Pool) notifyWaiterLocked() {
|
| 19 |
+
if len(p.waiters) == 0 {
|
| 20 |
+
return
|
| 21 |
+
}
|
| 22 |
+
waiter := p.waiters[0]
|
| 23 |
+
p.waiters = p.waiters[1:]
|
| 24 |
+
close(waiter)
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
func (p *Pool) removeWaiterLocked(waiter chan struct{}) bool {
|
| 28 |
+
for i, w := range p.waiters {
|
| 29 |
+
if w != waiter {
|
| 30 |
+
continue
|
| 31 |
+
}
|
| 32 |
+
p.waiters = append(p.waiters[:i], p.waiters[i+1:]...)
|
| 33 |
+
return true
|
| 34 |
+
}
|
| 35 |
+
return false
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
func (p *Pool) drainWaitersLocked() {
|
| 39 |
+
for _, waiter := range p.waiters {
|
| 40 |
+
close(waiter)
|
| 41 |
+
}
|
| 42 |
+
p.waiters = nil
|
| 43 |
+
}
|
internal/assistantturn/stream.go
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package assistantturn
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"ds2api/internal/httpapi/openai/shared"
|
| 5 |
+
"ds2api/internal/sse"
|
| 6 |
+
)
|
| 7 |
+
|
| 8 |
+
type StreamEventType string
|
| 9 |
+
|
| 10 |
+
const (
|
| 11 |
+
StreamEventTextDelta StreamEventType = "text_delta"
|
| 12 |
+
StreamEventThinkingDelta StreamEventType = "thinking_delta"
|
| 13 |
+
StreamEventToolCall StreamEventType = "tool_call"
|
| 14 |
+
StreamEventDone StreamEventType = "done"
|
| 15 |
+
StreamEventError StreamEventType = "error"
|
| 16 |
+
StreamEventPing StreamEventType = "ping"
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
type StreamEvent struct {
|
| 20 |
+
Type StreamEventType
|
| 21 |
+
Text string
|
| 22 |
+
Thinking string
|
| 23 |
+
ToolCall any
|
| 24 |
+
Error *OutputError
|
| 25 |
+
Usage *Usage
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
type Accumulator struct {
|
| 29 |
+
inner shared.StreamAccumulator
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
type AccumulatorOptions struct {
|
| 33 |
+
ThinkingEnabled bool
|
| 34 |
+
SearchEnabled bool
|
| 35 |
+
StripReferenceMarkers bool
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
func NewAccumulator(opts AccumulatorOptions) *Accumulator {
|
| 39 |
+
return &Accumulator{
|
| 40 |
+
inner: shared.StreamAccumulator{
|
| 41 |
+
ThinkingEnabled: opts.ThinkingEnabled,
|
| 42 |
+
SearchEnabled: opts.SearchEnabled,
|
| 43 |
+
StripReferenceMarkers: opts.StripReferenceMarkers,
|
| 44 |
+
},
|
| 45 |
+
}
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
func (a *Accumulator) Apply(parsed sse.LineResult) shared.StreamAccumulatorResult {
|
| 49 |
+
if a == nil {
|
| 50 |
+
return shared.StreamAccumulatorResult{}
|
| 51 |
+
}
|
| 52 |
+
return a.inner.Apply(parsed)
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
func (a *Accumulator) Snapshot() (rawText, text, rawThinking, thinking, detectionThinking string) {
|
| 56 |
+
if a == nil {
|
| 57 |
+
return "", "", "", "", ""
|
| 58 |
+
}
|
| 59 |
+
return a.inner.RawText.String(),
|
| 60 |
+
a.inner.Text.String(),
|
| 61 |
+
a.inner.RawThinking.String(),
|
| 62 |
+
a.inner.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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package assistantturn
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"net/http"
|
| 5 |
+
"strings"
|
| 6 |
+
|
| 7 |
+
"ds2api/internal/httpapi/openai/shared"
|
| 8 |
+
"ds2api/internal/promptcompat"
|
| 9 |
+
"ds2api/internal/sse"
|
| 10 |
+
"ds2api/internal/toolcall"
|
| 11 |
+
"ds2api/internal/util"
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
type StopReason string
|
| 15 |
+
|
| 16 |
+
const (
|
| 17 |
+
StopReasonStop StopReason = "stop"
|
| 18 |
+
StopReasonToolCalls StopReason = "tool_calls"
|
| 19 |
+
StopReasonContentFilter StopReason = "content_filter"
|
| 20 |
+
StopReasonError StopReason = "error"
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
type Usage struct {
|
| 24 |
+
InputTokens int
|
| 25 |
+
OutputTokens int
|
| 26 |
+
ReasoningTokens int
|
| 27 |
+
TotalTokens int
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
type OutputError struct {
|
| 31 |
+
Status int
|
| 32 |
+
Message string
|
| 33 |
+
Code string
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
type Turn struct {
|
| 37 |
+
Model string
|
| 38 |
+
Prompt string
|
| 39 |
+
RawText string
|
| 40 |
+
RawThinking string
|
| 41 |
+
DetectionThinking string
|
| 42 |
+
Text string
|
| 43 |
+
Thinking string
|
| 44 |
+
ToolCalls []toolcall.ParsedToolCall
|
| 45 |
+
ParsedToolCalls toolcall.ToolCallParseResult
|
| 46 |
+
CitationLinks map[int]string
|
| 47 |
+
ContentFilter bool
|
| 48 |
+
ResponseMessageID int
|
| 49 |
+
StopReason StopReason
|
| 50 |
+
Usage Usage
|
| 51 |
+
Error *OutputError
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
type FinalizeOptions struct {
|
| 55 |
+
AlreadyEmittedToolCalls bool
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
type FinalOutcome struct {
|
| 59 |
+
FinishReason string
|
| 60 |
+
Error *OutputError
|
| 61 |
+
Usage Usage
|
| 62 |
+
HasToolCalls bool
|
| 63 |
+
HasVisibleText bool
|
| 64 |
+
HasVisibleOutput bool
|
| 65 |
+
ShouldFail bool
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
type BuildOptions struct {
|
| 69 |
+
Model string
|
| 70 |
+
Prompt string
|
| 71 |
+
RefFileTokens int
|
| 72 |
+
SearchEnabled bool
|
| 73 |
+
StripReferenceMarkers bool
|
| 74 |
+
ToolNames []string
|
| 75 |
+
ToolsRaw any
|
| 76 |
+
ToolChoice promptcompat.ToolChoicePolicy
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
type StreamSnapshot struct {
|
| 80 |
+
RawText string
|
| 81 |
+
VisibleText string
|
| 82 |
+
RawThinking string
|
| 83 |
+
VisibleThinking string
|
| 84 |
+
DetectionThinking string
|
| 85 |
+
ContentFilter bool
|
| 86 |
+
CitationLinks map[int]string
|
| 87 |
+
ResponseMessageID int
|
| 88 |
+
AlreadyEmittedCalls bool
|
| 89 |
+
AdditionalToolCalls []toolcall.ParsedToolCall
|
| 90 |
+
AlreadyEmittedToolRaw bool
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
func BuildTurnFromCollected(result sse.CollectResult, opts BuildOptions) Turn {
|
| 94 |
+
thinking := shared.CleanVisibleOutput(result.Thinking, opts.StripReferenceMarkers)
|
| 95 |
+
text := shared.CleanVisibleOutput(result.Text, opts.StripReferenceMarkers)
|
| 96 |
+
if opts.SearchEnabled {
|
| 97 |
+
text = shared.ReplaceCitationMarkersWithLinks(text, result.CitationLinks)
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
parsed := shared.DetectAssistantToolCalls(result.Text, text, result.Thinking, result.ToolDetectionThinking, opts.ToolNames)
|
| 101 |
+
calls := toolcall.NormalizeParsedToolCallsForSchemas(parsed.Calls, opts.ToolsRaw)
|
| 102 |
+
parsed.Calls = calls
|
| 103 |
+
|
| 104 |
+
stopReason := StopReasonStop
|
| 105 |
+
if result.ContentFilter {
|
| 106 |
+
stopReason = StopReasonContentFilter
|
| 107 |
+
}
|
| 108 |
+
if len(calls) > 0 {
|
| 109 |
+
stopReason = StopReasonToolCalls
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
turn := Turn{
|
| 113 |
+
Model: opts.Model,
|
| 114 |
+
Prompt: opts.Prompt,
|
| 115 |
+
RawText: result.Text,
|
| 116 |
+
RawThinking: result.Thinking,
|
| 117 |
+
DetectionThinking: result.ToolDetectionThinking,
|
| 118 |
+
Text: text,
|
| 119 |
+
Thinking: thinking,
|
| 120 |
+
ToolCalls: calls,
|
| 121 |
+
ParsedToolCalls: parsed,
|
| 122 |
+
CitationLinks: result.CitationLinks,
|
| 123 |
+
ContentFilter: result.ContentFilter,
|
| 124 |
+
ResponseMessageID: result.ResponseMessageID,
|
| 125 |
+
StopReason: stopReason,
|
| 126 |
+
}
|
| 127 |
+
turn.Usage = BuildUsage(opts.Model, opts.Prompt, thinking, text, opts.RefFileTokens)
|
| 128 |
+
turn.Error = ValidateTurn(turn, opts.ToolChoice)
|
| 129 |
+
if turn.Error != nil {
|
| 130 |
+
turn.StopReason = StopReasonError
|
| 131 |
+
}
|
| 132 |
+
return turn
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
func BuildTurnFromStreamSnapshot(snapshot StreamSnapshot, opts BuildOptions) Turn {
|
| 136 |
+
thinking := shared.CleanVisibleOutput(snapshot.VisibleThinking, opts.StripReferenceMarkers)
|
| 137 |
+
text := shared.CleanVisibleOutput(snapshot.VisibleText, opts.StripReferenceMarkers)
|
| 138 |
+
if opts.SearchEnabled {
|
| 139 |
+
text = shared.ReplaceCitationMarkersWithLinks(text, snapshot.CitationLinks)
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
parsed := shared.DetectAssistantToolCalls(snapshot.RawText, text, snapshot.RawThinking, snapshot.DetectionThinking, opts.ToolNames)
|
| 143 |
+
calls := parsed.Calls
|
| 144 |
+
if len(calls) == 0 && len(snapshot.AdditionalToolCalls) > 0 {
|
| 145 |
+
calls = snapshot.AdditionalToolCalls
|
| 146 |
+
}
|
| 147 |
+
calls = toolcall.NormalizeParsedToolCallsForSchemas(calls, opts.ToolsRaw)
|
| 148 |
+
parsed.Calls = calls
|
| 149 |
+
|
| 150 |
+
stopReason := StopReasonStop
|
| 151 |
+
if snapshot.ContentFilter {
|
| 152 |
+
stopReason = StopReasonContentFilter
|
| 153 |
+
}
|
| 154 |
+
if len(calls) > 0 || snapshot.AlreadyEmittedCalls || snapshot.AlreadyEmittedToolRaw {
|
| 155 |
+
stopReason = StopReasonToolCalls
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
turn := Turn{
|
| 159 |
+
Model: opts.Model,
|
| 160 |
+
Prompt: opts.Prompt,
|
| 161 |
+
RawText: snapshot.RawText,
|
| 162 |
+
RawThinking: snapshot.RawThinking,
|
| 163 |
+
DetectionThinking: snapshot.DetectionThinking,
|
| 164 |
+
Text: text,
|
| 165 |
+
Thinking: thinking,
|
| 166 |
+
ToolCalls: calls,
|
| 167 |
+
ParsedToolCalls: parsed,
|
| 168 |
+
CitationLinks: snapshot.CitationLinks,
|
| 169 |
+
ContentFilter: snapshot.ContentFilter,
|
| 170 |
+
ResponseMessageID: snapshot.ResponseMessageID,
|
| 171 |
+
StopReason: stopReason,
|
| 172 |
+
}
|
| 173 |
+
turn.Usage = BuildUsage(opts.Model, opts.Prompt, thinking, text, opts.RefFileTokens)
|
| 174 |
+
if !snapshot.AlreadyEmittedCalls && !snapshot.AlreadyEmittedToolRaw {
|
| 175 |
+
turn.Error = ValidateTurn(turn, opts.ToolChoice)
|
| 176 |
+
}
|
| 177 |
+
if turn.Error != nil && len(calls) == 0 {
|
| 178 |
+
turn.StopReason = StopReasonError
|
| 179 |
+
}
|
| 180 |
+
return turn
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
func BuildUsage(model, prompt, thinking, text string, refFileTokens int) Usage {
|
| 184 |
+
inputTokens := util.CountPromptTokens(prompt, model) + refFileTokens
|
| 185 |
+
reasoningTokens := util.CountOutputTokens(thinking, model)
|
| 186 |
+
outputTokens := reasoningTokens + util.CountOutputTokens(text, model)
|
| 187 |
+
return Usage{
|
| 188 |
+
InputTokens: inputTokens,
|
| 189 |
+
OutputTokens: outputTokens,
|
| 190 |
+
ReasoningTokens: reasoningTokens,
|
| 191 |
+
TotalTokens: inputTokens + outputTokens,
|
| 192 |
+
}
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
func ValidateTurn(turn Turn, policy promptcompat.ToolChoicePolicy) *OutputError {
|
| 196 |
+
if policy.IsRequired() && len(turn.ToolCalls) == 0 {
|
| 197 |
+
return &OutputError{
|
| 198 |
+
Status: http.StatusUnprocessableEntity,
|
| 199 |
+
Message: "tool_choice requires at least one valid tool call.",
|
| 200 |
+
Code: "tool_choice_violation",
|
| 201 |
+
}
|
| 202 |
+
}
|
| 203 |
+
if len(turn.ToolCalls) > 0 {
|
| 204 |
+
return nil
|
| 205 |
+
}
|
| 206 |
+
if strings.TrimSpace(turn.Text) != "" {
|
| 207 |
+
return nil
|
| 208 |
+
}
|
| 209 |
+
status, message, code := UpstreamEmptyOutputDetail(turn.ContentFilter, turn.Text, turn.Thinking)
|
| 210 |
+
return &OutputError{Status: status, Message: message, Code: code}
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
func UpstreamEmptyOutputDetail(contentFilter bool, text, thinking string) (int, string, string) {
|
| 214 |
+
_ = text
|
| 215 |
+
if contentFilter {
|
| 216 |
+
return http.StatusBadRequest, "Upstream content filtered the response and returned no output.", "content_filter"
|
| 217 |
+
}
|
| 218 |
+
if strings.TrimSpace(thinking) != "" {
|
| 219 |
+
return http.StatusTooManyRequests, "Upstream account hit a rate limit and returned reasoning without visible output.", "upstream_empty_output"
|
| 220 |
+
}
|
| 221 |
+
return http.StatusServiceUnavailable, "Upstream service is unavailable and returned no output.", "upstream_unavailable"
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
// ShouldRetryEmptyOutput returns true when the turn produced no visible text
|
| 225 |
+
// and has no tool calls or content filter. This includes thinking-only responses,
|
| 226 |
+
// where the model returned reasoning but no answer — a retry may yield text.
|
| 227 |
+
func ShouldRetryEmptyOutput(turn Turn, attempts, maxAttempts int) bool {
|
| 228 |
+
return attempts < maxAttempts &&
|
| 229 |
+
!turn.ContentFilter &&
|
| 230 |
+
len(turn.ToolCalls) == 0 &&
|
| 231 |
+
strings.TrimSpace(turn.Text) == ""
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
func FinalizeTurn(turn Turn, opts FinalizeOptions) FinalOutcome {
|
| 235 |
+
hasToolCalls := len(turn.ToolCalls) > 0 || opts.AlreadyEmittedToolCalls
|
| 236 |
+
hasVisibleText := strings.TrimSpace(turn.Text) != ""
|
| 237 |
+
hasVisibleThinking := strings.TrimSpace(turn.Thinking) != ""
|
| 238 |
+
err := turn.Error
|
| 239 |
+
if hasToolCalls {
|
| 240 |
+
err = nil
|
| 241 |
+
}
|
| 242 |
+
finishReason := FinishReason(turn)
|
| 243 |
+
if hasToolCalls {
|
| 244 |
+
finishReason = "tool_calls"
|
| 245 |
+
}
|
| 246 |
+
return FinalOutcome{
|
| 247 |
+
FinishReason: finishReason,
|
| 248 |
+
Error: err,
|
| 249 |
+
Usage: turn.Usage,
|
| 250 |
+
HasToolCalls: hasToolCalls,
|
| 251 |
+
HasVisibleText: hasVisibleText,
|
| 252 |
+
HasVisibleOutput: hasVisibleText || hasVisibleThinking || hasToolCalls,
|
| 253 |
+
ShouldFail: err != nil,
|
| 254 |
+
}
|
| 255 |
+
}
|
| 256 |
+
|
| 257 |
+
func OpenAIChatUsage(turn Turn) map[string]any {
|
| 258 |
+
return map[string]any{
|
| 259 |
+
"prompt_tokens": turn.Usage.InputTokens,
|
| 260 |
+
"completion_tokens": turn.Usage.OutputTokens,
|
| 261 |
+
"total_tokens": turn.Usage.TotalTokens,
|
| 262 |
+
"completion_tokens_details": map[string]any{
|
| 263 |
+
"reasoning_tokens": turn.Usage.ReasoningTokens,
|
| 264 |
+
},
|
| 265 |
+
}
|
| 266 |
+
}
|
| 267 |
+
|
| 268 |
+
func OpenAIResponsesUsage(turn Turn) map[string]any {
|
| 269 |
+
return map[string]any{
|
| 270 |
+
"input_tokens": turn.Usage.InputTokens,
|
| 271 |
+
"output_tokens": turn.Usage.OutputTokens,
|
| 272 |
+
"total_tokens": turn.Usage.TotalTokens,
|
| 273 |
+
}
|
| 274 |
+
}
|
| 275 |
+
|
| 276 |
+
func FinishReason(turn Turn) string {
|
| 277 |
+
switch turn.StopReason {
|
| 278 |
+
case StopReasonToolCalls:
|
| 279 |
+
return "tool_calls"
|
| 280 |
+
case StopReasonContentFilter:
|
| 281 |
+
return "content_filter"
|
| 282 |
+
default:
|
| 283 |
+
return "stop"
|
| 284 |
+
}
|
| 285 |
+
}
|
internal/assistantturn/turn_test.go
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package assistantturn
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"net/http"
|
| 5 |
+
"testing"
|
| 6 |
+
|
| 7 |
+
"ds2api/internal/promptcompat"
|
| 8 |
+
"ds2api/internal/sse"
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
func TestBuildTurnFromCollectedTextCitation(t *testing.T) {
|
| 12 |
+
turn := BuildTurnFromCollected(sse.CollectResult{
|
| 13 |
+
Text: "See [citation:1]",
|
| 14 |
+
CitationLinks: map[int]string{1: "https://example.com"},
|
| 15 |
+
}, BuildOptions{Model: "deepseek-v4-flash", Prompt: "prompt", SearchEnabled: true})
|
| 16 |
+
if turn.Text != "See [1](https://example.com)" {
|
| 17 |
+
t.Fatalf("text mismatch: %q", turn.Text)
|
| 18 |
+
}
|
| 19 |
+
if turn.StopReason != StopReasonStop {
|
| 20 |
+
t.Fatalf("stop reason mismatch: %q", turn.StopReason)
|
| 21 |
+
}
|
| 22 |
+
if turn.Error != nil {
|
| 23 |
+
t.Fatalf("unexpected error: %#v", turn.Error)
|
| 24 |
+
}
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
func TestBuildTurnFromCollectedKeepsNonStreamReferenceLinks(t *testing.T) {
|
| 28 |
+
turn := BuildTurnFromCollected(sse.CollectResult{
|
| 29 |
+
Text: "结论[reference:0],补充[reference:1]。",
|
| 30 |
+
CitationLinks: map[int]string{
|
| 31 |
+
1: "https://example.com/a",
|
| 32 |
+
2: "https://example.com/b",
|
| 33 |
+
},
|
| 34 |
+
}, BuildOptions{Model: "deepseek-v4-flash-search", Prompt: "prompt", SearchEnabled: true})
|
| 35 |
+
want := "结论[0](https://example.com/a),补充[1](https://example.com/b)。"
|
| 36 |
+
if turn.Text != want {
|
| 37 |
+
t.Fatalf("text mismatch: got %q want %q", turn.Text, want)
|
| 38 |
+
}
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
func TestBuildTurnFromCollectedToolCall(t *testing.T) {
|
| 42 |
+
turn := BuildTurnFromCollected(sse.CollectResult{
|
| 43 |
+
Text: `<tool_calls><invoke name="Write"><parameter name="content">{"x":1}</parameter></invoke></tool_calls>`,
|
| 44 |
+
}, BuildOptions{
|
| 45 |
+
ToolNames: []string{"Write"},
|
| 46 |
+
ToolsRaw: []any{map[string]any{
|
| 47 |
+
"name": "Write",
|
| 48 |
+
"input_schema": map[string]any{
|
| 49 |
+
"type": "object",
|
| 50 |
+
"properties": map[string]any{
|
| 51 |
+
"content": map[string]any{"type": "string"},
|
| 52 |
+
},
|
| 53 |
+
},
|
| 54 |
+
}},
|
| 55 |
+
})
|
| 56 |
+
if len(turn.ToolCalls) != 1 {
|
| 57 |
+
t.Fatalf("expected one tool call, got %d", len(turn.ToolCalls))
|
| 58 |
+
}
|
| 59 |
+
if turn.StopReason != StopReasonToolCalls {
|
| 60 |
+
t.Fatalf("stop reason mismatch: %q", turn.StopReason)
|
| 61 |
+
}
|
| 62 |
+
if _, ok := turn.ToolCalls[0].Input["content"].(string); !ok {
|
| 63 |
+
t.Fatalf("expected content coerced to string, got %#v", turn.ToolCalls[0].Input["content"])
|
| 64 |
+
}
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
func TestBuildTurnFromCollectedThinkingOnlyIsEmptyOutput(t *testing.T) {
|
| 68 |
+
turn := BuildTurnFromCollected(sse.CollectResult{Thinking: "hidden"}, BuildOptions{})
|
| 69 |
+
if turn.Error == nil || turn.Error.Code != "upstream_empty_output" {
|
| 70 |
+
t.Fatalf("expected empty output error, got %#v", turn.Error)
|
| 71 |
+
}
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
func TestBuildTurnFromCollectedPureEmptyOutputIsUpstreamUnavailable(t *testing.T) {
|
| 75 |
+
turn := BuildTurnFromCollected(sse.CollectResult{}, BuildOptions{})
|
| 76 |
+
if turn.Error == nil || turn.Error.Status != http.StatusServiceUnavailable || turn.Error.Code != "upstream_unavailable" {
|
| 77 |
+
t.Fatalf("expected upstream unavailable error, got %#v", turn.Error)
|
| 78 |
+
}
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
func TestBuildTurnFromCollectedToolChoiceRequired(t *testing.T) {
|
| 82 |
+
turn := BuildTurnFromCollected(sse.CollectResult{Text: "hello"}, BuildOptions{
|
| 83 |
+
ToolChoice: promptcompat.ToolChoicePolicy{Mode: promptcompat.ToolChoiceRequired},
|
| 84 |
+
})
|
| 85 |
+
if turn.Error == nil || turn.Error.Code != "tool_choice_violation" {
|
| 86 |
+
t.Fatalf("expected tool choice violation, got %#v", turn.Error)
|
| 87 |
+
}
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
func TestBuildTurnFromStreamSnapshotUsesVisibleTextAndRawToolDetection(t *testing.T) {
|
| 91 |
+
turn := BuildTurnFromStreamSnapshot(StreamSnapshot{
|
| 92 |
+
RawText: `<tool_calls><invoke name="Write"><parameter name="content">{"x":1}</parameter></invoke></tool_calls>`,
|
| 93 |
+
VisibleText: "",
|
| 94 |
+
}, BuildOptions{
|
| 95 |
+
ToolNames: []string{"Write"},
|
| 96 |
+
ToolsRaw: []any{map[string]any{
|
| 97 |
+
"name": "Write",
|
| 98 |
+
"schema": map[string]any{
|
| 99 |
+
"type": "object",
|
| 100 |
+
"properties": map[string]any{
|
| 101 |
+
"content": map[string]any{"type": "string"},
|
| 102 |
+
},
|
| 103 |
+
},
|
| 104 |
+
}},
|
| 105 |
+
})
|
| 106 |
+
if len(turn.ToolCalls) != 1 {
|
| 107 |
+
t.Fatalf("expected stream snapshot tool call, got %d", len(turn.ToolCalls))
|
| 108 |
+
}
|
| 109 |
+
if _, ok := turn.ToolCalls[0].Input["content"].(string); !ok {
|
| 110 |
+
t.Fatalf("expected stream snapshot schema coercion, got %#v", turn.ToolCalls[0].Input["content"])
|
| 111 |
+
}
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
func TestBuildTurnFromStreamSnapshotAlreadyEmittedToolAvoidsEmptyError(t *testing.T) {
|
| 115 |
+
turn := BuildTurnFromStreamSnapshot(StreamSnapshot{AlreadyEmittedCalls: true}, BuildOptions{})
|
| 116 |
+
if turn.Error != nil {
|
| 117 |
+
t.Fatalf("unexpected empty-output error after emitted tool call: %#v", turn.Error)
|
| 118 |
+
}
|
| 119 |
+
if turn.StopReason != StopReasonToolCalls {
|
| 120 |
+
t.Fatalf("stop reason mismatch: %q", turn.StopReason)
|
| 121 |
+
}
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
func TestFinalizeTurnStopOutcome(t *testing.T) {
|
| 125 |
+
turn := BuildTurnFromCollected(sse.CollectResult{Text: "hello"}, BuildOptions{})
|
| 126 |
+
outcome := FinalizeTurn(turn, FinalizeOptions{})
|
| 127 |
+
if outcome.ShouldFail {
|
| 128 |
+
t.Fatalf("unexpected failure: %#v", outcome.Error)
|
| 129 |
+
}
|
| 130 |
+
if outcome.FinishReason != "stop" || !outcome.HasVisibleText || !outcome.HasVisibleOutput {
|
| 131 |
+
t.Fatalf("unexpected outcome: %#v", outcome)
|
| 132 |
+
}
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
func TestFinalizeTurnToolCallsOutcome(t *testing.T) {
|
| 136 |
+
turn := BuildTurnFromStreamSnapshot(StreamSnapshot{AlreadyEmittedCalls: true}, BuildOptions{})
|
| 137 |
+
outcome := FinalizeTurn(turn, FinalizeOptions{AlreadyEmittedToolCalls: true})
|
| 138 |
+
if outcome.ShouldFail || outcome.FinishReason != "tool_calls" || !outcome.HasToolCalls {
|
| 139 |
+
t.Fatalf("unexpected tool outcome: %#v", outcome)
|
| 140 |
+
}
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
func TestFinalizeTurnContentFilterOutcome(t *testing.T) {
|
| 144 |
+
turn := BuildTurnFromCollected(sse.CollectResult{ContentFilter: true}, BuildOptions{})
|
| 145 |
+
outcome := FinalizeTurn(turn, FinalizeOptions{})
|
| 146 |
+
if !outcome.ShouldFail || outcome.Error == nil || outcome.Error.Code != "content_filter" {
|
| 147 |
+
t.Fatalf("expected content filter failure, got %#v", outcome)
|
| 148 |
+
}
|
| 149 |
+
}
|
internal/auth/admin.go
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package auth
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"crypto/hmac"
|
| 5 |
+
"crypto/sha256"
|
| 6 |
+
"crypto/subtle"
|
| 7 |
+
"encoding/base64"
|
| 8 |
+
"encoding/hex"
|
| 9 |
+
"encoding/json"
|
| 10 |
+
"errors"
|
| 11 |
+
"log/slog"
|
| 12 |
+
"net/http"
|
| 13 |
+
"os"
|
| 14 |
+
"strconv"
|
| 15 |
+
"strings"
|
| 16 |
+
"sync"
|
| 17 |
+
"time"
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
var warnOnce sync.Once
|
| 21 |
+
|
| 22 |
+
type AdminConfigReader interface {
|
| 23 |
+
AdminPasswordHash() string
|
| 24 |
+
AdminJWTExpireHours() int
|
| 25 |
+
AdminJWTValidAfterUnix() int64
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
func AdminKey() string {
|
| 29 |
+
return effectiveAdminKey(nil)
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
func effectiveAdminKey(store AdminConfigReader) string {
|
| 33 |
+
if store != nil {
|
| 34 |
+
if hash := strings.TrimSpace(store.AdminPasswordHash()); hash != "" {
|
| 35 |
+
return ""
|
| 36 |
+
}
|
| 37 |
+
}
|
| 38 |
+
if v := strings.TrimSpace(os.Getenv("DS2API_ADMIN_KEY")); v != "" {
|
| 39 |
+
return v
|
| 40 |
+
}
|
| 41 |
+
warnOnce.Do(func() {
|
| 42 |
+
slog.Warn("⚠️ DS2API_ADMIN_KEY is not set! Using insecure default \"admin\". Set a strong key in production!")
|
| 43 |
+
})
|
| 44 |
+
return "admin"
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
func jwtSecret(store AdminConfigReader) string {
|
| 48 |
+
if v := strings.TrimSpace(os.Getenv("DS2API_JWT_SECRET")); v != "" {
|
| 49 |
+
return v
|
| 50 |
+
}
|
| 51 |
+
if store != nil {
|
| 52 |
+
if hash := strings.TrimSpace(store.AdminPasswordHash()); hash != "" {
|
| 53 |
+
return hash
|
| 54 |
+
}
|
| 55 |
+
}
|
| 56 |
+
return effectiveAdminKey(store)
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
func jwtExpireHours(store AdminConfigReader) int {
|
| 60 |
+
if store != nil {
|
| 61 |
+
if n := store.AdminJWTExpireHours(); n > 0 {
|
| 62 |
+
return n
|
| 63 |
+
}
|
| 64 |
+
}
|
| 65 |
+
if v := strings.TrimSpace(os.Getenv("DS2API_JWT_EXPIRE_HOURS")); v != "" {
|
| 66 |
+
if n, err := strconv.Atoi(v); err == nil && n > 0 {
|
| 67 |
+
return n
|
| 68 |
+
}
|
| 69 |
+
}
|
| 70 |
+
return 24
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
func CreateJWT(expireHours int) (string, error) {
|
| 74 |
+
return CreateJWTWithStore(expireHours, nil)
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
func CreateJWTWithStore(expireHours int, store AdminConfigReader) (string, error) {
|
| 78 |
+
if expireHours <= 0 {
|
| 79 |
+
expireHours = jwtExpireHours(store)
|
| 80 |
+
}
|
| 81 |
+
issuedAt := time.Now().Unix()
|
| 82 |
+
// If sessions were invalidated in this same second, move iat forward by
|
| 83 |
+
// one second so newly minted tokens remain valid with strict cutoff checks.
|
| 84 |
+
if store != nil {
|
| 85 |
+
if validAfter := store.AdminJWTValidAfterUnix(); validAfter >= issuedAt {
|
| 86 |
+
issuedAt = validAfter + 1
|
| 87 |
+
}
|
| 88 |
+
}
|
| 89 |
+
expireAt := time.Unix(issuedAt, 0).Add(time.Duration(expireHours) * time.Hour).Unix()
|
| 90 |
+
header := map[string]any{"alg": "HS256", "typ": "JWT"}
|
| 91 |
+
payload := map[string]any{"iat": issuedAt, "exp": expireAt, "role": "admin"}
|
| 92 |
+
h, _ := json.Marshal(header)
|
| 93 |
+
p, _ := json.Marshal(payload)
|
| 94 |
+
headerB64 := rawB64Encode(h)
|
| 95 |
+
payloadB64 := rawB64Encode(p)
|
| 96 |
+
msg := headerB64 + "." + payloadB64
|
| 97 |
+
sig := signHS256(msg, store)
|
| 98 |
+
return msg + "." + rawB64Encode(sig), nil
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
func VerifyJWT(token string) (map[string]any, error) {
|
| 102 |
+
return VerifyJWTWithStore(token, nil)
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
func VerifyJWTWithStore(token string, store AdminConfigReader) (map[string]any, error) {
|
| 106 |
+
parts := strings.Split(token, ".")
|
| 107 |
+
if len(parts) != 3 {
|
| 108 |
+
return nil, errors.New("invalid token format")
|
| 109 |
+
}
|
| 110 |
+
msg := parts[0] + "." + parts[1]
|
| 111 |
+
expected := signHS256(msg, store)
|
| 112 |
+
actual, err := rawB64Decode(parts[2])
|
| 113 |
+
if err != nil {
|
| 114 |
+
return nil, errors.New("invalid signature")
|
| 115 |
+
}
|
| 116 |
+
if !hmac.Equal(expected, actual) {
|
| 117 |
+
return nil, errors.New("invalid signature")
|
| 118 |
+
}
|
| 119 |
+
payloadBytes, err := rawB64Decode(parts[1])
|
| 120 |
+
if err != nil {
|
| 121 |
+
return nil, errors.New("invalid payload")
|
| 122 |
+
}
|
| 123 |
+
var payload map[string]any
|
| 124 |
+
if err := json.Unmarshal(payloadBytes, &payload); err != nil {
|
| 125 |
+
return nil, errors.New("invalid payload")
|
| 126 |
+
}
|
| 127 |
+
exp, _ := payload["exp"].(float64)
|
| 128 |
+
if int64(exp) < time.Now().Unix() {
|
| 129 |
+
return nil, errors.New("token expired")
|
| 130 |
+
}
|
| 131 |
+
if store != nil {
|
| 132 |
+
validAfter := store.AdminJWTValidAfterUnix()
|
| 133 |
+
if validAfter > 0 {
|
| 134 |
+
iat, _ := payload["iat"].(float64)
|
| 135 |
+
if int64(iat) <= validAfter {
|
| 136 |
+
return nil, errors.New("token expired")
|
| 137 |
+
}
|
| 138 |
+
}
|
| 139 |
+
}
|
| 140 |
+
return payload, nil
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
func VerifyAdminRequest(r *http.Request) error {
|
| 144 |
+
return VerifyAdminRequestWithStore(r, nil)
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
func VerifyAdminRequestWithStore(r *http.Request, store AdminConfigReader) error {
|
| 148 |
+
authHeader := strings.TrimSpace(r.Header.Get("Authorization"))
|
| 149 |
+
if !strings.HasPrefix(strings.ToLower(authHeader), "bearer ") {
|
| 150 |
+
return errors.New("authentication required")
|
| 151 |
+
}
|
| 152 |
+
token := strings.TrimSpace(authHeader[7:])
|
| 153 |
+
if token == "" {
|
| 154 |
+
return errors.New("authentication required")
|
| 155 |
+
}
|
| 156 |
+
if VerifyAdminCredential(token, store) {
|
| 157 |
+
return nil
|
| 158 |
+
}
|
| 159 |
+
if _, err := VerifyJWTWithStore(token, store); err == nil {
|
| 160 |
+
return nil
|
| 161 |
+
}
|
| 162 |
+
return errors.New("invalid credentials")
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
func VerifyAdminCredential(candidate string, store AdminConfigReader) bool {
|
| 166 |
+
candidate = strings.TrimSpace(candidate)
|
| 167 |
+
if candidate == "" {
|
| 168 |
+
return false
|
| 169 |
+
}
|
| 170 |
+
if store != nil {
|
| 171 |
+
hash := strings.TrimSpace(store.AdminPasswordHash())
|
| 172 |
+
if hash != "" {
|
| 173 |
+
return verifyAdminPasswordHash(candidate, hash)
|
| 174 |
+
}
|
| 175 |
+
}
|
| 176 |
+
key := effectiveAdminKey(store)
|
| 177 |
+
if key == "" {
|
| 178 |
+
return false
|
| 179 |
+
}
|
| 180 |
+
return subtle.ConstantTimeCompare([]byte(candidate), []byte(key)) == 1
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
func UsingDefaultAdminKey(store AdminConfigReader) bool {
|
| 184 |
+
if store != nil && strings.TrimSpace(store.AdminPasswordHash()) != "" {
|
| 185 |
+
return false
|
| 186 |
+
}
|
| 187 |
+
return strings.TrimSpace(os.Getenv("DS2API_ADMIN_KEY")) == ""
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
func HashAdminPassword(raw string) string {
|
| 191 |
+
raw = strings.TrimSpace(raw)
|
| 192 |
+
if raw == "" {
|
| 193 |
+
return ""
|
| 194 |
+
}
|
| 195 |
+
sum := sha256.Sum256([]byte(raw))
|
| 196 |
+
return "sha256:" + hex.EncodeToString(sum[:])
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
func verifyAdminPasswordHash(candidate, encoded string) bool {
|
| 200 |
+
encoded = strings.TrimSpace(strings.ToLower(encoded))
|
| 201 |
+
if encoded == "" {
|
| 202 |
+
return false
|
| 203 |
+
}
|
| 204 |
+
if strings.HasPrefix(encoded, "sha256:") {
|
| 205 |
+
want := strings.TrimPrefix(encoded, "sha256:")
|
| 206 |
+
sum := sha256.Sum256([]byte(candidate))
|
| 207 |
+
got := hex.EncodeToString(sum[:])
|
| 208 |
+
return subtle.ConstantTimeCompare([]byte(got), []byte(want)) == 1
|
| 209 |
+
}
|
| 210 |
+
return subtle.ConstantTimeCompare([]byte(candidate), []byte(encoded)) == 1
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
func signHS256(msg string, store AdminConfigReader) []byte {
|
| 214 |
+
h := hmac.New(sha256.New, []byte(jwtSecret(store)))
|
| 215 |
+
_, _ = h.Write([]byte(msg))
|
| 216 |
+
return h.Sum(nil)
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
func rawB64Encode(b []byte) string {
|
| 220 |
+
return base64.RawURLEncoding.EncodeToString(b)
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
func rawB64Decode(s string) ([]byte, error) {
|
| 224 |
+
return base64.RawURLEncoding.DecodeString(s)
|
| 225 |
+
}
|
internal/auth/admin_test.go
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package auth
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"net/http"
|
| 5 |
+
"testing"
|
| 6 |
+
|
| 7 |
+
"ds2api/internal/config"
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
func TestJWTCreateVerify(t *testing.T) {
|
| 11 |
+
token, err := CreateJWT(1)
|
| 12 |
+
if err != nil {
|
| 13 |
+
t.Fatalf("create jwt failed: %v", err)
|
| 14 |
+
}
|
| 15 |
+
payload, err := VerifyJWT(token)
|
| 16 |
+
if err != nil {
|
| 17 |
+
t.Fatalf("verify jwt failed: %v", err)
|
| 18 |
+
}
|
| 19 |
+
if payload["role"] != "admin" {
|
| 20 |
+
t.Fatalf("unexpected payload: %#v", payload)
|
| 21 |
+
}
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
func TestVerifyAdminRequest(t *testing.T) {
|
| 25 |
+
token, _ := CreateJWT(1)
|
| 26 |
+
req, _ := http.NewRequest(http.MethodGet, "/admin/config", nil)
|
| 27 |
+
req.Header.Set("Authorization", "Bearer "+token)
|
| 28 |
+
if err := VerifyAdminRequest(req); err != nil {
|
| 29 |
+
t.Fatalf("expected token accepted: %v", err)
|
| 30 |
+
}
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
func TestVerifyJWTWithStoreValidAfter(t *testing.T) {
|
| 34 |
+
t.Setenv("DS2API_CONFIG_JSON", `{"admin":{"password_hash":"`+HashAdminPassword("oldpass")+`"}}`)
|
| 35 |
+
store := config.LoadStore()
|
| 36 |
+
token, err := CreateJWTWithStore(1, store)
|
| 37 |
+
if err != nil {
|
| 38 |
+
t.Fatalf("create jwt failed: %v", err)
|
| 39 |
+
}
|
| 40 |
+
if _, err := VerifyJWTWithStore(token, store); err != nil {
|
| 41 |
+
t.Fatalf("verify before invalidation failed: %v", err)
|
| 42 |
+
}
|
| 43 |
+
if err := store.Update(func(c *config.Config) error {
|
| 44 |
+
c.Admin.JWTValidAfterUnix = 1<<62 - 1
|
| 45 |
+
return nil
|
| 46 |
+
}); err != nil {
|
| 47 |
+
t.Fatalf("set valid-after failed: %v", err)
|
| 48 |
+
}
|
| 49 |
+
if _, err := VerifyJWTWithStore(token, store); err == nil {
|
| 50 |
+
t.Fatal("expected token invalid after valid-after update")
|
| 51 |
+
}
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
func TestVerifyJWTWithStoreSameSecondInvalidationAndRelogin(t *testing.T) {
|
| 55 |
+
t.Setenv("DS2API_CONFIG_JSON", `{"admin":{"password_hash":"`+HashAdminPassword("oldpass")+`"}}`)
|
| 56 |
+
store := config.LoadStore()
|
| 57 |
+
|
| 58 |
+
oldToken, err := CreateJWTWithStore(1, store)
|
| 59 |
+
if err != nil {
|
| 60 |
+
t.Fatalf("create old jwt failed: %v", err)
|
| 61 |
+
}
|
| 62 |
+
oldPayload, err := VerifyJWTWithStore(oldToken, store)
|
| 63 |
+
if err != nil {
|
| 64 |
+
t.Fatalf("verify old jwt before invalidation failed: %v", err)
|
| 65 |
+
}
|
| 66 |
+
oldIAT, _ := oldPayload["iat"].(float64)
|
| 67 |
+
|
| 68 |
+
if err := store.Update(func(c *config.Config) error {
|
| 69 |
+
c.Admin.JWTValidAfterUnix = int64(oldIAT)
|
| 70 |
+
return nil
|
| 71 |
+
}); err != nil {
|
| 72 |
+
t.Fatalf("set valid-after failed: %v", err)
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
if _, err := VerifyJWTWithStore(oldToken, store); err == nil {
|
| 76 |
+
t.Fatal("expected old token invalid when iat == valid-after")
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
newToken, err := CreateJWTWithStore(1, store)
|
| 80 |
+
if err != nil {
|
| 81 |
+
t.Fatalf("create new jwt failed: %v", err)
|
| 82 |
+
}
|
| 83 |
+
if _, err := VerifyJWTWithStore(newToken, store); err != nil {
|
| 84 |
+
t.Fatalf("expected new token valid after invalidation cutoff: %v", err)
|
| 85 |
+
}
|
| 86 |
+
}
|
internal/auth/auth_edge_test.go
ADDED
|
@@ -0,0 +1,442 @@
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package auth
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"errors"
|
| 6 |
+
"net/http"
|
| 7 |
+
"testing"
|
| 8 |
+
|
| 9 |
+
"ds2api/internal/account"
|
| 10 |
+
"ds2api/internal/config"
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
// ─── extractCallerToken edge cases ───────────────────────────────────
|
| 14 |
+
|
| 15 |
+
func TestExtractCallerTokenBearerPrefix(t *testing.T) {
|
| 16 |
+
req, _ := http.NewRequest("POST", "/", nil)
|
| 17 |
+
req.Header.Set("Authorization", "Bearer my-token")
|
| 18 |
+
if got := extractCallerToken(req); got != "my-token" {
|
| 19 |
+
t.Fatalf("expected my-token, got %q", got)
|
| 20 |
+
}
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
func TestExtractCallerTokenBearerCaseInsensitive(t *testing.T) {
|
| 24 |
+
req, _ := http.NewRequest("POST", "/", nil)
|
| 25 |
+
req.Header.Set("Authorization", "BEARER My-Token")
|
| 26 |
+
if got := extractCallerToken(req); got != "My-Token" {
|
| 27 |
+
t.Fatalf("expected My-Token, got %q", got)
|
| 28 |
+
}
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
func TestExtractCallerTokenBearerEmpty(t *testing.T) {
|
| 32 |
+
req, _ := http.NewRequest("POST", "/", nil)
|
| 33 |
+
req.Header.Set("Authorization", "Bearer ")
|
| 34 |
+
if got := extractCallerToken(req); got != "" {
|
| 35 |
+
t.Fatalf("expected empty for 'Bearer ', got %q", got)
|
| 36 |
+
}
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
func TestExtractCallerTokenXAPIKey(t *testing.T) {
|
| 40 |
+
req, _ := http.NewRequest("POST", "/", nil)
|
| 41 |
+
req.Header.Set("x-api-key", "x-api-key-token")
|
| 42 |
+
if got := extractCallerToken(req); got != "x-api-key-token" {
|
| 43 |
+
t.Fatalf("expected x-api-key-token, got %q", got)
|
| 44 |
+
}
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
func TestExtractCallerTokenBearerPreferredOverXAPIKey(t *testing.T) {
|
| 48 |
+
req, _ := http.NewRequest("POST", "/", nil)
|
| 49 |
+
req.Header.Set("Authorization", "Bearer bearer-token")
|
| 50 |
+
req.Header.Set("x-api-key", "x-api-key-token")
|
| 51 |
+
if got := extractCallerToken(req); got != "bearer-token" {
|
| 52 |
+
t.Fatalf("expected bearer-token, got %q", got)
|
| 53 |
+
}
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
func TestExtractCallerTokenMissingHeaders(t *testing.T) {
|
| 57 |
+
req, _ := http.NewRequest("POST", "/", nil)
|
| 58 |
+
if got := extractCallerToken(req); got != "" {
|
| 59 |
+
t.Fatalf("expected empty for missing headers, got %q", got)
|
| 60 |
+
}
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
func TestExtractCallerTokenNonBearerAuth(t *testing.T) {
|
| 64 |
+
req, _ := http.NewRequest("POST", "/", nil)
|
| 65 |
+
req.Header.Set("Authorization", "Basic abc123")
|
| 66 |
+
if got := extractCallerToken(req); got != "" {
|
| 67 |
+
t.Fatalf("expected empty for Basic auth, got %q", got)
|
| 68 |
+
}
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
// ─── Context helpers ─────────────────────────────────────────────────
|
| 72 |
+
|
| 73 |
+
func TestWithAuthAndFromContext(t *testing.T) {
|
| 74 |
+
a := &RequestAuth{DeepSeekToken: "test-token"}
|
| 75 |
+
ctx := WithAuth(context.Background(), a)
|
| 76 |
+
got, ok := FromContext(ctx)
|
| 77 |
+
if !ok || got.DeepSeekToken != "test-token" {
|
| 78 |
+
t.Fatalf("expected token from context, got ok=%v token=%q", ok, got.DeepSeekToken)
|
| 79 |
+
}
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
func TestFromContextMissing(t *testing.T) {
|
| 83 |
+
_, ok := FromContext(context.Background())
|
| 84 |
+
if ok {
|
| 85 |
+
t.Fatal("expected not ok from empty context")
|
| 86 |
+
}
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
// ─── RefreshToken edge cases ─────────────────────────────────────────
|
| 90 |
+
|
| 91 |
+
func TestRefreshTokenNotConfigToken(t *testing.T) {
|
| 92 |
+
r := newTestResolver(t)
|
| 93 |
+
a := &RequestAuth{UseConfigToken: false, resolver: r}
|
| 94 |
+
if r.RefreshToken(context.Background(), a) {
|
| 95 |
+
t.Fatal("expected false for non-config token")
|
| 96 |
+
}
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
func TestRefreshTokenEmptyAccountID(t *testing.T) {
|
| 100 |
+
r := newTestResolver(t)
|
| 101 |
+
a := &RequestAuth{UseConfigToken: true, AccountID: "", resolver: r}
|
| 102 |
+
if r.RefreshToken(context.Background(), a) {
|
| 103 |
+
t.Fatal("expected false for empty account ID")
|
| 104 |
+
}
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
func TestRefreshTokenSuccess(t *testing.T) {
|
| 108 |
+
r := newTestResolver(t)
|
| 109 |
+
// First acquire an account
|
| 110 |
+
req, _ := http.NewRequest("POST", "/", nil)
|
| 111 |
+
req.Header.Set("Authorization", "Bearer managed-key")
|
| 112 |
+
a, err := r.Determine(req)
|
| 113 |
+
if err != nil {
|
| 114 |
+
t.Fatalf("determine failed: %v", err)
|
| 115 |
+
}
|
| 116 |
+
defer r.Release(a)
|
| 117 |
+
|
| 118 |
+
if !r.RefreshToken(context.Background(), a) {
|
| 119 |
+
t.Fatal("expected refresh to succeed")
|
| 120 |
+
}
|
| 121 |
+
if a.DeepSeekToken != "fresh-token" {
|
| 122 |
+
t.Fatalf("expected fresh-token after refresh, got %q", a.DeepSeekToken)
|
| 123 |
+
}
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
// ─── MarkTokenInvalid edge cases ─────────────────────────────────────
|
| 127 |
+
|
| 128 |
+
func TestMarkTokenInvalidNotConfigToken(t *testing.T) {
|
| 129 |
+
r := newTestResolver(t)
|
| 130 |
+
a := &RequestAuth{UseConfigToken: false, DeepSeekToken: "direct", resolver: r}
|
| 131 |
+
r.MarkTokenInvalid(a)
|
| 132 |
+
// Should not panic, token should be unchanged for non-config
|
| 133 |
+
_ = a.DeepSeekToken // Actual behavior may clear it; this test only asserts no panic.
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
func TestMarkTokenInvalidEmptyAccountID(t *testing.T) {
|
| 137 |
+
r := newTestResolver(t)
|
| 138 |
+
a := &RequestAuth{UseConfigToken: true, AccountID: "", DeepSeekToken: "tok", resolver: r}
|
| 139 |
+
r.MarkTokenInvalid(a)
|
| 140 |
+
// Should not panic
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
func TestMarkTokenInvalidClearsToken(t *testing.T) {
|
| 144 |
+
r := newTestResolver(t)
|
| 145 |
+
req, _ := http.NewRequest("POST", "/", nil)
|
| 146 |
+
req.Header.Set("Authorization", "Bearer managed-key")
|
| 147 |
+
a, err := r.Determine(req)
|
| 148 |
+
if err != nil {
|
| 149 |
+
t.Fatalf("determine failed: %v", err)
|
| 150 |
+
}
|
| 151 |
+
defer r.Release(a)
|
| 152 |
+
|
| 153 |
+
r.MarkTokenInvalid(a)
|
| 154 |
+
if a.DeepSeekToken != "" {
|
| 155 |
+
t.Fatalf("expected empty token after invalidation, got %q", a.DeepSeekToken)
|
| 156 |
+
}
|
| 157 |
+
if a.Account.Token != "" {
|
| 158 |
+
t.Fatalf("expected empty account token after invalidation, got %q", a.Account.Token)
|
| 159 |
+
}
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
// ─── SwitchAccount edge cases ────────────────────────────────────────
|
| 163 |
+
|
| 164 |
+
func TestSwitchAccountNotConfigToken(t *testing.T) {
|
| 165 |
+
r := newTestResolver(t)
|
| 166 |
+
a := &RequestAuth{UseConfigToken: false, resolver: r}
|
| 167 |
+
if r.SwitchAccount(context.Background(), a) {
|
| 168 |
+
t.Fatal("expected false for non-config token")
|
| 169 |
+
}
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
func TestSwitchAccountNilTriedAccounts(t *testing.T) {
|
| 173 |
+
t.Setenv("DS2API_CONFIG_JSON", `{
|
| 174 |
+
"keys":["managed-key"],
|
| 175 |
+
"accounts":[
|
| 176 |
+
{"email":"acc1@test.com","token":"t1"},
|
| 177 |
+
{"email":"acc2@test.com","token":"t2"}
|
| 178 |
+
]
|
| 179 |
+
}`)
|
| 180 |
+
store := config.LoadStore()
|
| 181 |
+
pool := account.NewPool(store)
|
| 182 |
+
r := NewResolver(store, pool, func(_ context.Context, _ config.Account) (string, error) {
|
| 183 |
+
return "new-token", nil
|
| 184 |
+
})
|
| 185 |
+
|
| 186 |
+
// First acquire
|
| 187 |
+
req, _ := http.NewRequest("POST", "/", nil)
|
| 188 |
+
req.Header.Set("Authorization", "Bearer managed-key")
|
| 189 |
+
a, err := r.Determine(req)
|
| 190 |
+
if err != nil {
|
| 191 |
+
t.Fatalf("determine failed: %v", err)
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
oldID := a.AccountID
|
| 195 |
+
a.TriedAccounts = nil // test nil initialization in SwitchAccount
|
| 196 |
+
if !r.SwitchAccount(context.Background(), a) {
|
| 197 |
+
t.Fatal("expected switch to succeed")
|
| 198 |
+
}
|
| 199 |
+
if a.AccountID == oldID {
|
| 200 |
+
t.Fatalf("expected different account after switch")
|
| 201 |
+
}
|
| 202 |
+
r.Release(a)
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
func TestSwitchAccountSkipsLoginFailureAndContinues(t *testing.T) {
|
| 206 |
+
t.Setenv("DS2API_CONFIG_JSON", `{
|
| 207 |
+
"keys":["managed-key"],
|
| 208 |
+
"accounts":[
|
| 209 |
+
{"email":"acc1@test.com","password":"pwd","token":"t1"},
|
| 210 |
+
{"email":"acc2@test.com","password":"pwd"},
|
| 211 |
+
{"email":"acc3@test.com","password":"pwd","token":"t3"}
|
| 212 |
+
]
|
| 213 |
+
}`)
|
| 214 |
+
store := config.LoadStore()
|
| 215 |
+
pool := account.NewPool(store)
|
| 216 |
+
r := NewResolver(store, pool, func(_ context.Context, acc config.Account) (string, error) {
|
| 217 |
+
if acc.Email == "acc2@test.com" {
|
| 218 |
+
return "", errors.New("login failed")
|
| 219 |
+
}
|
| 220 |
+
return "new-token", nil
|
| 221 |
+
})
|
| 222 |
+
|
| 223 |
+
req, _ := http.NewRequest("POST", "/", nil)
|
| 224 |
+
req.Header.Set("Authorization", "Bearer managed-key")
|
| 225 |
+
a, err := r.Determine(req)
|
| 226 |
+
if err != nil {
|
| 227 |
+
t.Fatalf("determine failed: %v", err)
|
| 228 |
+
}
|
| 229 |
+
defer r.Release(a)
|
| 230 |
+
if a.AccountID != "acc1@test.com" {
|
| 231 |
+
t.Fatalf("expected first account, got %q", a.AccountID)
|
| 232 |
+
}
|
| 233 |
+
if !r.SwitchAccount(context.Background(), a) {
|
| 234 |
+
t.Fatal("expected switch to succeed after skipping failed account")
|
| 235 |
+
}
|
| 236 |
+
if a.AccountID != "acc3@test.com" {
|
| 237 |
+
t.Fatalf("expected fallback to third account, got %q", a.AccountID)
|
| 238 |
+
}
|
| 239 |
+
if !a.TriedAccounts["acc2@test.com"] {
|
| 240 |
+
t.Fatalf("expected failed account to be marked as tried")
|
| 241 |
+
}
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
func TestSwitchAccountRespectsPinnedTargetAccount(t *testing.T) {
|
| 245 |
+
t.Setenv("DS2API_CONFIG_JSON", `{
|
| 246 |
+
"keys":["managed-key"],
|
| 247 |
+
"accounts":[
|
| 248 |
+
{"email":"acc1@test.com","token":"t1"},
|
| 249 |
+
{"email":"acc2@test.com","token":"t2"}
|
| 250 |
+
]
|
| 251 |
+
}`)
|
| 252 |
+
store := config.LoadStore()
|
| 253 |
+
pool := account.NewPool(store)
|
| 254 |
+
r := NewResolver(store, pool, func(_ context.Context, _ config.Account) (string, error) {
|
| 255 |
+
return "new-token", nil
|
| 256 |
+
})
|
| 257 |
+
|
| 258 |
+
req, _ := http.NewRequest("POST", "/", nil)
|
| 259 |
+
req.Header.Set("Authorization", "Bearer managed-key")
|
| 260 |
+
req.Header.Set("X-Ds2-Target-Account", "acc1@test.com")
|
| 261 |
+
a, err := r.Determine(req)
|
| 262 |
+
if err != nil {
|
| 263 |
+
t.Fatalf("determine failed: %v", err)
|
| 264 |
+
}
|
| 265 |
+
defer r.Release(a)
|
| 266 |
+
if r.SwitchAccount(context.Background(), a) {
|
| 267 |
+
t.Fatal("expected switch to be disabled for pinned target account")
|
| 268 |
+
}
|
| 269 |
+
if a.AccountID != "acc1@test.com" {
|
| 270 |
+
t.Fatalf("expected pinned account to remain selected, got %q", a.AccountID)
|
| 271 |
+
}
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
// ─── Release edge cases ─────────────────────────────────────────────
|
| 275 |
+
|
| 276 |
+
func TestReleaseNilAuth(t *testing.T) {
|
| 277 |
+
r := newTestResolver(t)
|
| 278 |
+
r.Release(nil) // should not panic
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
func TestReleaseNonConfigToken(t *testing.T) {
|
| 282 |
+
r := newTestResolver(t)
|
| 283 |
+
a := &RequestAuth{UseConfigToken: false}
|
| 284 |
+
r.Release(a) // should not panic
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
func TestReleaseEmptyAccountID(t *testing.T) {
|
| 288 |
+
r := newTestResolver(t)
|
| 289 |
+
a := &RequestAuth{UseConfigToken: true, AccountID: ""}
|
| 290 |
+
r.Release(a) // should not panic
|
| 291 |
+
}
|
| 292 |
+
|
| 293 |
+
// ─── JWT edge cases ──────────────────────────────────────────────────
|
| 294 |
+
|
| 295 |
+
func TestVerifyJWTInvalidFormat(t *testing.T) {
|
| 296 |
+
_, err := VerifyJWT("not-a-jwt")
|
| 297 |
+
if err == nil {
|
| 298 |
+
t.Fatal("expected error for invalid JWT format")
|
| 299 |
+
}
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
func TestVerifyJWTInvalidSignature(t *testing.T) {
|
| 303 |
+
token, _ := CreateJWT(1)
|
| 304 |
+
// Tamper with the signature
|
| 305 |
+
parts := splitJWT(token)
|
| 306 |
+
if len(parts) == 3 {
|
| 307 |
+
tampered := parts[0] + "." + parts[1] + ".invalid_signature"
|
| 308 |
+
_, err := VerifyJWT(tampered)
|
| 309 |
+
if err == nil {
|
| 310 |
+
t.Fatal("expected error for tampered signature")
|
| 311 |
+
}
|
| 312 |
+
}
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
func TestVerifyJWTExpired(t *testing.T) {
|
| 316 |
+
// Create a token with 0 hours expiry - will use default, so we can't easily test
|
| 317 |
+
// Instead test with bad payload
|
| 318 |
+
_, err := VerifyJWT("eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjF9.invalid")
|
| 319 |
+
if err == nil {
|
| 320 |
+
t.Fatal("expected error for expired/invalid JWT")
|
| 321 |
+
}
|
| 322 |
+
}
|
| 323 |
+
|
| 324 |
+
func TestCreateJWTDefaultExpiry(t *testing.T) {
|
| 325 |
+
token, err := CreateJWT(0) // should use default
|
| 326 |
+
if err != nil {
|
| 327 |
+
t.Fatalf("create jwt failed: %v", err)
|
| 328 |
+
}
|
| 329 |
+
_, err = VerifyJWT(token)
|
| 330 |
+
if err != nil {
|
| 331 |
+
t.Fatalf("verify jwt failed: %v", err)
|
| 332 |
+
}
|
| 333 |
+
}
|
| 334 |
+
|
| 335 |
+
// ─── VerifyAdminRequest edge cases ───────────────────────────────────
|
| 336 |
+
|
| 337 |
+
func TestVerifyAdminRequestNoHeader(t *testing.T) {
|
| 338 |
+
req, _ := http.NewRequest("GET", "/admin/config", nil)
|
| 339 |
+
if err := VerifyAdminRequest(req); err == nil {
|
| 340 |
+
t.Fatal("expected error for missing auth")
|
| 341 |
+
}
|
| 342 |
+
}
|
| 343 |
+
|
| 344 |
+
func TestVerifyAdminRequestEmptyBearer(t *testing.T) {
|
| 345 |
+
req, _ := http.NewRequest("GET", "/admin/config", nil)
|
| 346 |
+
req.Header.Set("Authorization", "Bearer ")
|
| 347 |
+
if err := VerifyAdminRequest(req); err == nil {
|
| 348 |
+
t.Fatal("expected error for empty bearer")
|
| 349 |
+
}
|
| 350 |
+
}
|
| 351 |
+
|
| 352 |
+
func TestVerifyAdminRequestWithAdminKey(t *testing.T) {
|
| 353 |
+
t.Setenv("DS2API_ADMIN_KEY", "test-admin-key")
|
| 354 |
+
req, _ := http.NewRequest("GET", "/admin/config", nil)
|
| 355 |
+
req.Header.Set("Authorization", "Bearer test-admin-key")
|
| 356 |
+
if err := VerifyAdminRequest(req); err != nil {
|
| 357 |
+
t.Fatalf("expected admin key accepted: %v", err)
|
| 358 |
+
}
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
func TestVerifyAdminRequestInvalidCredentials(t *testing.T) {
|
| 362 |
+
t.Setenv("DS2API_ADMIN_KEY", "correct-key")
|
| 363 |
+
req, _ := http.NewRequest("GET", "/admin/config", nil)
|
| 364 |
+
req.Header.Set("Authorization", "Bearer wrong-key")
|
| 365 |
+
if err := VerifyAdminRequest(req); err == nil {
|
| 366 |
+
t.Fatal("expected error for wrong key")
|
| 367 |
+
}
|
| 368 |
+
}
|
| 369 |
+
|
| 370 |
+
func TestVerifyAdminRequestBasicAuth(t *testing.T) {
|
| 371 |
+
req, _ := http.NewRequest("GET", "/admin/config", nil)
|
| 372 |
+
req.Header.Set("Authorization", "Basic abc123")
|
| 373 |
+
if err := VerifyAdminRequest(req); err == nil {
|
| 374 |
+
t.Fatal("expected error for Basic auth")
|
| 375 |
+
}
|
| 376 |
+
}
|
| 377 |
+
|
| 378 |
+
// ─── Determine with login failure ────────────────────────────────────
|
| 379 |
+
|
| 380 |
+
func TestDetermineWithLoginFailure(t *testing.T) {
|
| 381 |
+
t.Setenv("DS2API_CONFIG_JSON", `{
|
| 382 |
+
"keys":["managed-key"],
|
| 383 |
+
"accounts":[{"email":"acc@test.com","password":"pwd"}]
|
| 384 |
+
}`)
|
| 385 |
+
store := config.LoadStore()
|
| 386 |
+
pool := account.NewPool(store)
|
| 387 |
+
r := NewResolver(store, pool, func(_ context.Context, _ config.Account) (string, error) {
|
| 388 |
+
return "", errors.New("login failed")
|
| 389 |
+
})
|
| 390 |
+
|
| 391 |
+
req, _ := http.NewRequest("POST", "/", nil)
|
| 392 |
+
req.Header.Set("Authorization", "Bearer managed-key")
|
| 393 |
+
_, err := r.Determine(req)
|
| 394 |
+
if err == nil {
|
| 395 |
+
t.Fatal("expected error when login fails")
|
| 396 |
+
}
|
| 397 |
+
}
|
| 398 |
+
|
| 399 |
+
// ─── Determine with target account ───────────────────────────────────
|
| 400 |
+
|
| 401 |
+
func TestDetermineWithTargetAccount(t *testing.T) {
|
| 402 |
+
t.Setenv("DS2API_CONFIG_JSON", `{
|
| 403 |
+
"keys":["managed-key"],
|
| 404 |
+
"accounts":[
|
| 405 |
+
{"email":"acc1@test.com","token":"t1"},
|
| 406 |
+
{"email":"acc2@test.com","token":"t2"}
|
| 407 |
+
]
|
| 408 |
+
}`)
|
| 409 |
+
store := config.LoadStore()
|
| 410 |
+
pool := account.NewPool(store)
|
| 411 |
+
r := NewResolver(store, pool, func(_ context.Context, _ config.Account) (string, error) {
|
| 412 |
+
return "fresh-token", nil
|
| 413 |
+
})
|
| 414 |
+
|
| 415 |
+
req, _ := http.NewRequest("POST", "/", nil)
|
| 416 |
+
req.Header.Set("Authorization", "Bearer managed-key")
|
| 417 |
+
req.Header.Set("X-Ds2-Target-Account", "acc2@test.com")
|
| 418 |
+
a, err := r.Determine(req)
|
| 419 |
+
if err != nil {
|
| 420 |
+
t.Fatalf("determine failed: %v", err)
|
| 421 |
+
}
|
| 422 |
+
defer r.Release(a)
|
| 423 |
+
if a.AccountID != "acc2@test.com" {
|
| 424 |
+
t.Fatalf("expected target account acc2, got %q", a.AccountID)
|
| 425 |
+
}
|
| 426 |
+
}
|
| 427 |
+
|
| 428 |
+
// helper
|
| 429 |
+
func splitJWT(token string) []string {
|
| 430 |
+
result := make([]string, 0, 3)
|
| 431 |
+
start := 0
|
| 432 |
+
count := 0
|
| 433 |
+
for i := 0; i < len(token); i++ {
|
| 434 |
+
if token[i] == '.' {
|
| 435 |
+
result = append(result, token[start:i])
|
| 436 |
+
start = i + 1
|
| 437 |
+
count++
|
| 438 |
+
}
|
| 439 |
+
}
|
| 440 |
+
result = append(result, token[start:])
|
| 441 |
+
return result
|
| 442 |
+
}
|
internal/auth/request.go
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package auth
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"crypto/sha256"
|
| 6 |
+
"encoding/hex"
|
| 7 |
+
"errors"
|
| 8 |
+
"net/http"
|
| 9 |
+
"strings"
|
| 10 |
+
"sync"
|
| 11 |
+
"time"
|
| 12 |
+
|
| 13 |
+
"ds2api/internal/account"
|
| 14 |
+
"ds2api/internal/config"
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
type ctxKey string
|
| 18 |
+
|
| 19 |
+
const authCtxKey ctxKey = "auth_context"
|
| 20 |
+
|
| 21 |
+
var (
|
| 22 |
+
ErrUnauthorized = errors.New("unauthorized: missing auth token")
|
| 23 |
+
ErrNoAccount = errors.New("no accounts configured or all accounts are busy")
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
type RequestAuth struct {
|
| 27 |
+
UseConfigToken bool
|
| 28 |
+
DeepSeekToken string
|
| 29 |
+
CallerID string
|
| 30 |
+
AccountID string
|
| 31 |
+
TargetAccount string
|
| 32 |
+
Account config.Account
|
| 33 |
+
TriedAccounts map[string]bool
|
| 34 |
+
resolver *Resolver
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
type LoginFunc func(ctx context.Context, acc config.Account) (string, error)
|
| 38 |
+
|
| 39 |
+
type Resolver struct {
|
| 40 |
+
Store *config.Store
|
| 41 |
+
Pool *account.Pool
|
| 42 |
+
Login LoginFunc
|
| 43 |
+
|
| 44 |
+
mu sync.Mutex
|
| 45 |
+
tokenRefreshedAt map[string]time.Time
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
func NewResolver(store *config.Store, pool *account.Pool, login LoginFunc) *Resolver {
|
| 49 |
+
return &Resolver{
|
| 50 |
+
Store: store,
|
| 51 |
+
Pool: pool,
|
| 52 |
+
Login: login,
|
| 53 |
+
tokenRefreshedAt: map[string]time.Time{},
|
| 54 |
+
}
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
func (r *Resolver) Determine(req *http.Request) (*RequestAuth, error) {
|
| 58 |
+
callerKey := extractCallerToken(req)
|
| 59 |
+
if callerKey == "" {
|
| 60 |
+
return nil, ErrUnauthorized
|
| 61 |
+
}
|
| 62 |
+
callerID := callerTokenID(callerKey)
|
| 63 |
+
ctx := req.Context()
|
| 64 |
+
if !r.Store.HasAPIKey(callerKey) {
|
| 65 |
+
return &RequestAuth{
|
| 66 |
+
UseConfigToken: false,
|
| 67 |
+
DeepSeekToken: callerKey,
|
| 68 |
+
CallerID: callerID,
|
| 69 |
+
resolver: r,
|
| 70 |
+
TriedAccounts: map[string]bool{},
|
| 71 |
+
}, nil
|
| 72 |
+
}
|
| 73 |
+
target := strings.TrimSpace(req.Header.Get("X-Ds2-Target-Account"))
|
| 74 |
+
a, err := r.acquireManagedRequestAuth(ctx, callerID, target)
|
| 75 |
+
if err != nil {
|
| 76 |
+
return nil, err
|
| 77 |
+
}
|
| 78 |
+
return a, nil
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
func (r *Resolver) acquireManagedRequestAuth(ctx context.Context, callerID, target string) (*RequestAuth, error) {
|
| 82 |
+
tried := map[string]bool{}
|
| 83 |
+
var lastEnsureErr error
|
| 84 |
+
for {
|
| 85 |
+
if target == "" && len(tried) >= len(r.Store.Accounts()) {
|
| 86 |
+
if lastEnsureErr != nil {
|
| 87 |
+
return nil, lastEnsureErr
|
| 88 |
+
}
|
| 89 |
+
return nil, ErrNoAccount
|
| 90 |
+
}
|
| 91 |
+
acc, ok := r.Pool.AcquireWait(ctx, target, tried)
|
| 92 |
+
if !ok {
|
| 93 |
+
if lastEnsureErr != nil {
|
| 94 |
+
return nil, lastEnsureErr
|
| 95 |
+
}
|
| 96 |
+
return nil, ErrNoAccount
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
a := &RequestAuth{
|
| 100 |
+
UseConfigToken: true,
|
| 101 |
+
CallerID: callerID,
|
| 102 |
+
AccountID: acc.Identifier(),
|
| 103 |
+
TargetAccount: target,
|
| 104 |
+
Account: acc,
|
| 105 |
+
TriedAccounts: tried,
|
| 106 |
+
resolver: r,
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
if err := r.ensureManagedToken(ctx, a); err != nil {
|
| 110 |
+
lastEnsureErr = err
|
| 111 |
+
tried[a.AccountID] = true
|
| 112 |
+
r.Pool.Release(a.AccountID)
|
| 113 |
+
if target != "" {
|
| 114 |
+
return nil, err
|
| 115 |
+
}
|
| 116 |
+
continue
|
| 117 |
+
}
|
| 118 |
+
return a, nil
|
| 119 |
+
}
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
// DetermineCaller resolves caller identity without acquiring any pooled account.
|
| 123 |
+
// Use this for local-cache lookup routes that only need tenant isolation.
|
| 124 |
+
func (r *Resolver) DetermineCaller(req *http.Request) (*RequestAuth, error) {
|
| 125 |
+
callerKey := extractCallerToken(req)
|
| 126 |
+
if callerKey == "" {
|
| 127 |
+
return nil, ErrUnauthorized
|
| 128 |
+
}
|
| 129 |
+
callerID := callerTokenID(callerKey)
|
| 130 |
+
a := &RequestAuth{
|
| 131 |
+
UseConfigToken: false,
|
| 132 |
+
CallerID: callerID,
|
| 133 |
+
resolver: r,
|
| 134 |
+
TriedAccounts: map[string]bool{},
|
| 135 |
+
}
|
| 136 |
+
if r == nil || r.Store == nil || !r.Store.HasAPIKey(callerKey) {
|
| 137 |
+
a.DeepSeekToken = callerKey
|
| 138 |
+
}
|
| 139 |
+
return a, nil
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
func WithAuth(ctx context.Context, a *RequestAuth) context.Context {
|
| 143 |
+
return context.WithValue(ctx, authCtxKey, a)
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
func FromContext(ctx context.Context) (*RequestAuth, bool) {
|
| 147 |
+
v := ctx.Value(authCtxKey)
|
| 148 |
+
a, ok := v.(*RequestAuth)
|
| 149 |
+
return a, ok
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
func (r *Resolver) loginAndPersist(ctx context.Context, a *RequestAuth) error {
|
| 153 |
+
token, err := r.Login(ctx, a.Account)
|
| 154 |
+
if err != nil {
|
| 155 |
+
return err
|
| 156 |
+
}
|
| 157 |
+
a.Account.Token = token
|
| 158 |
+
a.DeepSeekToken = token
|
| 159 |
+
r.markTokenRefreshedNow(a.AccountID)
|
| 160 |
+
return r.Store.UpdateAccountToken(a.AccountID, token)
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
func (r *Resolver) RefreshToken(ctx context.Context, a *RequestAuth) bool {
|
| 164 |
+
if !a.UseConfigToken || a.AccountID == "" {
|
| 165 |
+
return false
|
| 166 |
+
}
|
| 167 |
+
_ = r.Store.UpdateAccountToken(a.AccountID, "")
|
| 168 |
+
a.Account.Token = ""
|
| 169 |
+
if err := r.loginAndPersist(ctx, a); err != nil {
|
| 170 |
+
config.Logger.Error("[refresh_token] failed", "account", a.AccountID, "error", err)
|
| 171 |
+
return false
|
| 172 |
+
}
|
| 173 |
+
return true
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
func (r *Resolver) MarkTokenInvalid(a *RequestAuth) {
|
| 177 |
+
if !a.UseConfigToken || a.AccountID == "" {
|
| 178 |
+
return
|
| 179 |
+
}
|
| 180 |
+
a.Account.Token = ""
|
| 181 |
+
a.DeepSeekToken = ""
|
| 182 |
+
r.clearTokenRefreshMark(a.AccountID)
|
| 183 |
+
_ = r.Store.UpdateAccountToken(a.AccountID, "")
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
func (r *Resolver) SwitchAccount(ctx context.Context, a *RequestAuth) bool {
|
| 187 |
+
if !a.UseConfigToken {
|
| 188 |
+
return false
|
| 189 |
+
}
|
| 190 |
+
if strings.TrimSpace(a.TargetAccount) != "" {
|
| 191 |
+
return false
|
| 192 |
+
}
|
| 193 |
+
if a.TriedAccounts == nil {
|
| 194 |
+
a.TriedAccounts = map[string]bool{}
|
| 195 |
+
}
|
| 196 |
+
if a.AccountID != "" {
|
| 197 |
+
a.TriedAccounts[a.AccountID] = true
|
| 198 |
+
r.Pool.Release(a.AccountID)
|
| 199 |
+
}
|
| 200 |
+
for {
|
| 201 |
+
acc, ok := r.Pool.Acquire("", a.TriedAccounts)
|
| 202 |
+
if !ok {
|
| 203 |
+
return false
|
| 204 |
+
}
|
| 205 |
+
a.Account = acc
|
| 206 |
+
a.AccountID = acc.Identifier()
|
| 207 |
+
if err := r.ensureManagedToken(ctx, a); err != nil {
|
| 208 |
+
a.TriedAccounts[a.AccountID] = true
|
| 209 |
+
r.Pool.Release(a.AccountID)
|
| 210 |
+
continue
|
| 211 |
+
}
|
| 212 |
+
return true
|
| 213 |
+
}
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
func (a *RequestAuth) SwitchAccount(ctx context.Context) bool {
|
| 217 |
+
if a == nil || a.resolver == nil {
|
| 218 |
+
return false
|
| 219 |
+
}
|
| 220 |
+
return a.resolver.SwitchAccount(ctx, a)
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
func (r *Resolver) Release(a *RequestAuth) {
|
| 224 |
+
if a == nil || !a.UseConfigToken || a.AccountID == "" {
|
| 225 |
+
return
|
| 226 |
+
}
|
| 227 |
+
r.Pool.Release(a.AccountID)
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
func extractCallerToken(req *http.Request) string {
|
| 231 |
+
authHeader := strings.TrimSpace(req.Header.Get("Authorization"))
|
| 232 |
+
if strings.HasPrefix(strings.ToLower(authHeader), "bearer ") {
|
| 233 |
+
token := strings.TrimSpace(authHeader[7:])
|
| 234 |
+
if token != "" {
|
| 235 |
+
return token
|
| 236 |
+
}
|
| 237 |
+
}
|
| 238 |
+
if key := strings.TrimSpace(req.Header.Get("x-api-key")); key != "" {
|
| 239 |
+
return key
|
| 240 |
+
}
|
| 241 |
+
// Gemini/Google clients commonly send API key via x-goog-api-key.
|
| 242 |
+
if key := strings.TrimSpace(req.Header.Get("x-goog-api-key")); key != "" {
|
| 243 |
+
return key
|
| 244 |
+
}
|
| 245 |
+
// Gemini AI Studio compatibility: allow query key fallback only when no
|
| 246 |
+
// header-based credential is present.
|
| 247 |
+
if key := strings.TrimSpace(req.URL.Query().Get("key")); key != "" {
|
| 248 |
+
return key
|
| 249 |
+
}
|
| 250 |
+
return strings.TrimSpace(req.URL.Query().Get("api_key"))
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
func callerTokenID(token string) string {
|
| 254 |
+
token = strings.TrimSpace(token)
|
| 255 |
+
if token == "" {
|
| 256 |
+
return ""
|
| 257 |
+
}
|
| 258 |
+
sum := sha256.Sum256([]byte(token))
|
| 259 |
+
return "caller:" + hex.EncodeToString(sum[:8])
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
func (r *Resolver) ensureManagedToken(ctx context.Context, a *RequestAuth) error {
|
| 263 |
+
if strings.TrimSpace(a.Account.Token) == "" {
|
| 264 |
+
return r.loginAndPersist(ctx, a)
|
| 265 |
+
}
|
| 266 |
+
if r.shouldForceRefresh(a.AccountID) {
|
| 267 |
+
if err := r.loginAndPersist(ctx, a); err != nil {
|
| 268 |
+
return err
|
| 269 |
+
}
|
| 270 |
+
return nil
|
| 271 |
+
}
|
| 272 |
+
a.DeepSeekToken = a.Account.Token
|
| 273 |
+
return nil
|
| 274 |
+
}
|
| 275 |
+
|
| 276 |
+
func (r *Resolver) shouldForceRefresh(accountID string) bool {
|
| 277 |
+
if r == nil || r.Store == nil {
|
| 278 |
+
return false
|
| 279 |
+
}
|
| 280 |
+
if strings.TrimSpace(accountID) == "" {
|
| 281 |
+
return false
|
| 282 |
+
}
|
| 283 |
+
intervalHours := r.Store.RuntimeTokenRefreshIntervalHours()
|
| 284 |
+
if intervalHours <= 0 {
|
| 285 |
+
return false
|
| 286 |
+
}
|
| 287 |
+
now := time.Now()
|
| 288 |
+
r.mu.Lock()
|
| 289 |
+
defer r.mu.Unlock()
|
| 290 |
+
last, ok := r.tokenRefreshedAt[accountID]
|
| 291 |
+
if !ok || last.IsZero() {
|
| 292 |
+
r.tokenRefreshedAt[accountID] = now
|
| 293 |
+
return false
|
| 294 |
+
}
|
| 295 |
+
return now.Sub(last) >= time.Duration(intervalHours)*time.Hour
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
func (r *Resolver) markTokenRefreshedNow(accountID string) {
|
| 299 |
+
if strings.TrimSpace(accountID) == "" {
|
| 300 |
+
return
|
| 301 |
+
}
|
| 302 |
+
r.mu.Lock()
|
| 303 |
+
defer r.mu.Unlock()
|
| 304 |
+
r.tokenRefreshedAt[accountID] = time.Now()
|
| 305 |
+
}
|
| 306 |
+
|
| 307 |
+
func (r *Resolver) clearTokenRefreshMark(accountID string) {
|
| 308 |
+
if strings.TrimSpace(accountID) == "" {
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package auth
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"errors"
|
| 6 |
+
"net/http"
|
| 7 |
+
"sync/atomic"
|
| 8 |
+
"testing"
|
| 9 |
+
"time"
|
| 10 |
+
|
| 11 |
+
"ds2api/internal/account"
|
| 12 |
+
"ds2api/internal/config"
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
func newTestResolver(t *testing.T) *Resolver {
|
| 16 |
+
t.Helper()
|
| 17 |
+
t.Setenv("DS2API_CONFIG_JSON", `{
|
| 18 |
+
"keys":["managed-key"],
|
| 19 |
+
"accounts":[{"email":"acc@example.com","password":"pwd","token":"account-token"}]
|
| 20 |
+
}`)
|
| 21 |
+
store := config.LoadStore()
|
| 22 |
+
pool := account.NewPool(store)
|
| 23 |
+
return NewResolver(store, pool, func(_ context.Context, _ config.Account) (string, error) {
|
| 24 |
+
return "fresh-token", nil
|
| 25 |
+
})
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
func TestDetermineWithXAPIKeyUsesDirectToken(t *testing.T) {
|
| 29 |
+
r := newTestResolver(t)
|
| 30 |
+
req, _ := http.NewRequest(http.MethodPost, "/anthropic/v1/messages", nil)
|
| 31 |
+
req.Header.Set("x-api-key", "direct-token")
|
| 32 |
+
|
| 33 |
+
auth, err := r.Determine(req)
|
| 34 |
+
if err != nil {
|
| 35 |
+
t.Fatalf("determine failed: %v", err)
|
| 36 |
+
}
|
| 37 |
+
if auth.UseConfigToken {
|
| 38 |
+
t.Fatalf("expected direct token mode")
|
| 39 |
+
}
|
| 40 |
+
if auth.DeepSeekToken != "direct-token" {
|
| 41 |
+
t.Fatalf("unexpected token: %q", auth.DeepSeekToken)
|
| 42 |
+
}
|
| 43 |
+
if auth.CallerID == "" {
|
| 44 |
+
t.Fatalf("expected caller id to be populated")
|
| 45 |
+
}
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
func TestDetermineWithXAPIKeyManagedKeyAcquiresAccount(t *testing.T) {
|
| 49 |
+
r := newTestResolver(t)
|
| 50 |
+
req, _ := http.NewRequest(http.MethodPost, "/anthropic/v1/messages", nil)
|
| 51 |
+
req.Header.Set("x-api-key", "managed-key")
|
| 52 |
+
|
| 53 |
+
auth, err := r.Determine(req)
|
| 54 |
+
if err != nil {
|
| 55 |
+
t.Fatalf("determine failed: %v", err)
|
| 56 |
+
}
|
| 57 |
+
defer r.Release(auth)
|
| 58 |
+
if !auth.UseConfigToken {
|
| 59 |
+
t.Fatalf("expected managed key mode")
|
| 60 |
+
}
|
| 61 |
+
if auth.AccountID != "acc@example.com" {
|
| 62 |
+
t.Fatalf("unexpected account id: %q", auth.AccountID)
|
| 63 |
+
}
|
| 64 |
+
if auth.DeepSeekToken != "fresh-token" {
|
| 65 |
+
t.Fatalf("unexpected account token: %q", auth.DeepSeekToken)
|
| 66 |
+
}
|
| 67 |
+
if auth.CallerID == "" {
|
| 68 |
+
t.Fatalf("expected caller id to be populated")
|
| 69 |
+
}
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
func TestDetermineCallerWithManagedKeySkipsAccountAcquire(t *testing.T) {
|
| 73 |
+
r := newTestResolver(t)
|
| 74 |
+
req, _ := http.NewRequest(http.MethodGet, "/v1/responses/resp_1", nil)
|
| 75 |
+
req.Header.Set("x-api-key", "managed-key")
|
| 76 |
+
|
| 77 |
+
a, err := r.DetermineCaller(req)
|
| 78 |
+
if err != nil {
|
| 79 |
+
t.Fatalf("determine caller failed: %v", err)
|
| 80 |
+
}
|
| 81 |
+
if a.CallerID == "" {
|
| 82 |
+
t.Fatalf("expected caller id to be populated")
|
| 83 |
+
}
|
| 84 |
+
if a.UseConfigToken {
|
| 85 |
+
t.Fatalf("expected no config-token lease for caller-only auth")
|
| 86 |
+
}
|
| 87 |
+
if a.AccountID != "" {
|
| 88 |
+
t.Fatalf("expected empty account id, got %q", a.AccountID)
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
func TestCallerTokenIDStable(t *testing.T) {
|
| 93 |
+
a := callerTokenID("token-a")
|
| 94 |
+
b := callerTokenID("token-a")
|
| 95 |
+
c := callerTokenID("token-b")
|
| 96 |
+
if a == "" || b == "" || c == "" {
|
| 97 |
+
t.Fatalf("expected non-empty caller ids")
|
| 98 |
+
}
|
| 99 |
+
if a != b {
|
| 100 |
+
t.Fatalf("expected stable caller id, got %q and %q", a, b)
|
| 101 |
+
}
|
| 102 |
+
if a == c {
|
| 103 |
+
t.Fatalf("expected different caller id for different tokens")
|
| 104 |
+
}
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
func TestDetermineMissingToken(t *testing.T) {
|
| 108 |
+
r := newTestResolver(t)
|
| 109 |
+
req, _ := http.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
|
| 110 |
+
|
| 111 |
+
_, err := r.Determine(req)
|
| 112 |
+
if err == nil {
|
| 113 |
+
t.Fatal("expected unauthorized error")
|
| 114 |
+
}
|
| 115 |
+
if err != ErrUnauthorized {
|
| 116 |
+
t.Fatalf("unexpected error: %v", err)
|
| 117 |
+
}
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
func TestDetermineWithQueryKeyUsesDirectToken(t *testing.T) {
|
| 121 |
+
r := newTestResolver(t)
|
| 122 |
+
req, _ := http.NewRequest(http.MethodPost, "/v1beta/models/gemini-2.5-pro:generateContent?key=direct-query-key", nil)
|
| 123 |
+
|
| 124 |
+
a, err := r.Determine(req)
|
| 125 |
+
if err != nil {
|
| 126 |
+
t.Fatalf("determine failed: %v", err)
|
| 127 |
+
}
|
| 128 |
+
if a.UseConfigToken {
|
| 129 |
+
t.Fatalf("expected direct token mode")
|
| 130 |
+
}
|
| 131 |
+
if a.DeepSeekToken != "direct-query-key" {
|
| 132 |
+
t.Fatalf("unexpected token: %q", a.DeepSeekToken)
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
func TestDetermineWithXGoogAPIKeyUsesDirectToken(t *testing.T) {
|
| 137 |
+
r := newTestResolver(t)
|
| 138 |
+
req, _ := http.NewRequest(http.MethodPost, "/v1beta/models/gemini-2.5-pro:streamGenerateContent?alt=sse", nil)
|
| 139 |
+
req.Header.Set("x-goog-api-key", "goog-header-key")
|
| 140 |
+
|
| 141 |
+
a, err := r.Determine(req)
|
| 142 |
+
if err != nil {
|
| 143 |
+
t.Fatalf("determine failed: %v", err)
|
| 144 |
+
}
|
| 145 |
+
if a.UseConfigToken {
|
| 146 |
+
t.Fatalf("expected direct token mode")
|
| 147 |
+
}
|
| 148 |
+
if a.DeepSeekToken != "goog-header-key" {
|
| 149 |
+
t.Fatalf("unexpected token: %q", a.DeepSeekToken)
|
| 150 |
+
}
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
func TestDetermineWithAPIKeyQueryParamUsesDirectToken(t *testing.T) {
|
| 154 |
+
r := newTestResolver(t)
|
| 155 |
+
req, _ := http.NewRequest(http.MethodPost, "/v1beta/models/gemini-2.5-pro:generateContent?api_key=direct-api-key", nil)
|
| 156 |
+
|
| 157 |
+
a, err := r.Determine(req)
|
| 158 |
+
if err != nil {
|
| 159 |
+
t.Fatalf("determine failed: %v", err)
|
| 160 |
+
}
|
| 161 |
+
if a.UseConfigToken {
|
| 162 |
+
t.Fatalf("expected direct token mode")
|
| 163 |
+
}
|
| 164 |
+
if a.DeepSeekToken != "direct-api-key" {
|
| 165 |
+
t.Fatalf("unexpected token: %q", a.DeepSeekToken)
|
| 166 |
+
}
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
func TestDetermineHeaderTokenPrecedenceOverQueryKey(t *testing.T) {
|
| 170 |
+
r := newTestResolver(t)
|
| 171 |
+
req, _ := http.NewRequest(http.MethodPost, "/v1beta/models/gemini-2.5-pro:generateContent?key=query-key", nil)
|
| 172 |
+
req.Header.Set("x-api-key", "managed-key")
|
| 173 |
+
|
| 174 |
+
a, err := r.Determine(req)
|
| 175 |
+
if err != nil {
|
| 176 |
+
t.Fatalf("determine failed: %v", err)
|
| 177 |
+
}
|
| 178 |
+
defer r.Release(a)
|
| 179 |
+
if !a.UseConfigToken {
|
| 180 |
+
t.Fatalf("expected managed key mode from header token")
|
| 181 |
+
}
|
| 182 |
+
if a.AccountID == "" {
|
| 183 |
+
t.Fatalf("expected managed account to be acquired")
|
| 184 |
+
}
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
func TestDetermineCallerMissingToken(t *testing.T) {
|
| 188 |
+
r := newTestResolver(t)
|
| 189 |
+
req, _ := http.NewRequest(http.MethodGet, "/v1/responses/resp_1", nil)
|
| 190 |
+
|
| 191 |
+
_, err := r.DetermineCaller(req)
|
| 192 |
+
if err == nil {
|
| 193 |
+
t.Fatal("expected unauthorized error")
|
| 194 |
+
}
|
| 195 |
+
if err != ErrUnauthorized {
|
| 196 |
+
t.Fatalf("unexpected error: %v", err)
|
| 197 |
+
}
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
func TestDetermineManagedAccountForcesRefreshEverySixHours(t *testing.T) {
|
| 201 |
+
t.Setenv("DS2API_CONFIG_JSON", `{
|
| 202 |
+
"keys":["managed-key"],
|
| 203 |
+
"accounts":[{"email":"acc@example.com","password":"pwd","token":"seed-token"}]
|
| 204 |
+
}`)
|
| 205 |
+
store := config.LoadStore()
|
| 206 |
+
if err := store.UpdateAccountToken("acc@example.com", "seed-token"); err != nil {
|
| 207 |
+
t.Fatalf("update token failed: %v", err)
|
| 208 |
+
}
|
| 209 |
+
pool := account.NewPool(store)
|
| 210 |
+
|
| 211 |
+
var loginCount int32
|
| 212 |
+
resolver := NewResolver(store, pool, func(_ context.Context, _ config.Account) (string, error) {
|
| 213 |
+
n := atomic.AddInt32(&loginCount, 1)
|
| 214 |
+
return "fresh-token-" + string(rune('0'+n)), nil
|
| 215 |
+
})
|
| 216 |
+
|
| 217 |
+
req, _ := http.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
|
| 218 |
+
req.Header.Set("x-api-key", "managed-key")
|
| 219 |
+
|
| 220 |
+
a1, err := resolver.Determine(req)
|
| 221 |
+
if err != nil {
|
| 222 |
+
t.Fatalf("determine failed: %v", err)
|
| 223 |
+
}
|
| 224 |
+
if a1.DeepSeekToken != "seed-token" {
|
| 225 |
+
t.Fatalf("expected initial token without forced refresh, got %q", a1.DeepSeekToken)
|
| 226 |
+
}
|
| 227 |
+
resolver.Release(a1)
|
| 228 |
+
if got := atomic.LoadInt32(&loginCount); got != 0 {
|
| 229 |
+
t.Fatalf("expected no login before refresh interval, got %d", got)
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
resolver.mu.Lock()
|
| 233 |
+
resolver.tokenRefreshedAt["acc@example.com"] = time.Now().Add(-7 * time.Hour)
|
| 234 |
+
resolver.mu.Unlock()
|
| 235 |
+
|
| 236 |
+
a2, err := resolver.Determine(req)
|
| 237 |
+
if err != nil {
|
| 238 |
+
t.Fatalf("determine after interval failed: %v", err)
|
| 239 |
+
}
|
| 240 |
+
defer resolver.Release(a2)
|
| 241 |
+
if a2.DeepSeekToken != "fresh-token-1" {
|
| 242 |
+
t.Fatalf("expected refreshed token after interval, got %q", a2.DeepSeekToken)
|
| 243 |
+
}
|
| 244 |
+
if got := atomic.LoadInt32(&loginCount); got != 1 {
|
| 245 |
+
t.Fatalf("expected exactly one forced refresh login, got %d", got)
|
| 246 |
+
}
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
func TestDetermineManagedAccountUsesUpdatedRefreshInterval(t *testing.T) {
|
| 250 |
+
t.Setenv("DS2API_CONFIG_JSON", `{
|
| 251 |
+
"keys":["managed-key"],
|
| 252 |
+
"accounts":[{"email":"acc@example.com","password":"pwd","token":"seed-token"}],
|
| 253 |
+
"runtime":{"token_refresh_interval_hours":6}
|
| 254 |
+
}`)
|
| 255 |
+
store := config.LoadStore()
|
| 256 |
+
if err := store.UpdateAccountToken("acc@example.com", "seed-token"); err != nil {
|
| 257 |
+
t.Fatalf("update token failed: %v", err)
|
| 258 |
+
}
|
| 259 |
+
pool := account.NewPool(store)
|
| 260 |
+
|
| 261 |
+
var loginCount int32
|
| 262 |
+
resolver := NewResolver(store, pool, func(_ context.Context, _ config.Account) (string, error) {
|
| 263 |
+
n := atomic.AddInt32(&loginCount, 1)
|
| 264 |
+
return "fresh-token-" + string(rune('0'+n)), nil
|
| 265 |
+
})
|
| 266 |
+
|
| 267 |
+
req, _ := http.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
|
| 268 |
+
req.Header.Set("x-api-key", "managed-key")
|
| 269 |
+
|
| 270 |
+
a1, err := resolver.Determine(req)
|
| 271 |
+
if err != nil {
|
| 272 |
+
t.Fatalf("determine failed: %v", err)
|
| 273 |
+
}
|
| 274 |
+
if a1.DeepSeekToken != "seed-token" {
|
| 275 |
+
t.Fatalf("expected initial token without forced refresh, got %q", a1.DeepSeekToken)
|
| 276 |
+
}
|
| 277 |
+
resolver.Release(a1)
|
| 278 |
+
if got := atomic.LoadInt32(&loginCount); got != 0 {
|
| 279 |
+
t.Fatalf("expected no login before runtime update, got %d", got)
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
if err := store.Update(func(c *config.Config) error {
|
| 283 |
+
c.Runtime.TokenRefreshIntervalHours = 1
|
| 284 |
+
return nil
|
| 285 |
+
}); err != nil {
|
| 286 |
+
t.Fatalf("update runtime failed: %v", err)
|
| 287 |
+
}
|
| 288 |
+
|
| 289 |
+
resolver.mu.Lock()
|
| 290 |
+
resolver.tokenRefreshedAt["acc@example.com"] = time.Now().Add(-2 * time.Hour)
|
| 291 |
+
resolver.mu.Unlock()
|
| 292 |
+
|
| 293 |
+
a2, err := resolver.Determine(req)
|
| 294 |
+
if err != nil {
|
| 295 |
+
t.Fatalf("determine after runtime update failed: %v", err)
|
| 296 |
+
}
|
| 297 |
+
defer resolver.Release(a2)
|
| 298 |
+
if a2.DeepSeekToken != "fresh-token-1" {
|
| 299 |
+
t.Fatalf("expected refreshed token after runtime update, got %q", a2.DeepSeekToken)
|
| 300 |
+
}
|
| 301 |
+
if got := atomic.LoadInt32(&loginCount); got != 1 {
|
| 302 |
+
t.Fatalf("expected exactly one login after runtime update, got %d", got)
|
| 303 |
+
}
|
| 304 |
+
}
|
| 305 |
+
|
| 306 |
+
func TestDetermineManagedAccountRetriesOtherAccountOnLoginFailure(t *testing.T) {
|
| 307 |
+
t.Setenv("DS2API_CONFIG_JSON", `{
|
| 308 |
+
"keys":["managed-key"],
|
| 309 |
+
"accounts":[
|
| 310 |
+
{"email":"bad@example.com","password":"pwd"},
|
| 311 |
+
{"email":"good@example.com","password":"pwd","token":"good-token"}
|
| 312 |
+
]
|
| 313 |
+
}`)
|
| 314 |
+
store := config.LoadStore()
|
| 315 |
+
pool := account.NewPool(store)
|
| 316 |
+
resolver := NewResolver(store, pool, func(_ context.Context, acc config.Account) (string, error) {
|
| 317 |
+
if acc.Email == "bad@example.com" {
|
| 318 |
+
return "", errors.New("stale account")
|
| 319 |
+
}
|
| 320 |
+
return "fresh-good-token", nil
|
| 321 |
+
})
|
| 322 |
+
|
| 323 |
+
req, _ := http.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
|
| 324 |
+
req.Header.Set("x-api-key", "managed-key")
|
| 325 |
+
|
| 326 |
+
a, err := resolver.Determine(req)
|
| 327 |
+
if err != nil {
|
| 328 |
+
t.Fatalf("determine failed: %v", err)
|
| 329 |
+
}
|
| 330 |
+
defer resolver.Release(a)
|
| 331 |
+
if a.AccountID != "good@example.com" {
|
| 332 |
+
t.Fatalf("expected fallback to good account, got %q", a.AccountID)
|
| 333 |
+
}
|
| 334 |
+
if a.DeepSeekToken == "" {
|
| 335 |
+
t.Fatal("expected non-empty token from fallback account")
|
| 336 |
+
}
|
| 337 |
+
if !a.TriedAccounts["bad@example.com"] {
|
| 338 |
+
t.Fatalf("expected bad account to be tracked as tried")
|
| 339 |
+
}
|
| 340 |
+
}
|
| 341 |
+
|
| 342 |
+
func TestDetermineTargetAccountDoesNotFallbackOnLoginFailure(t *testing.T) {
|
| 343 |
+
t.Setenv("DS2API_CONFIG_JSON", `{
|
| 344 |
+
"keys":["managed-key"],
|
| 345 |
+
"accounts":[
|
| 346 |
+
{"email":"bad@example.com","password":"pwd"},
|
| 347 |
+
{"email":"good@example.com","password":"pwd","token":"good-token"}
|
| 348 |
+
]
|
| 349 |
+
}`)
|
| 350 |
+
store := config.LoadStore()
|
| 351 |
+
pool := account.NewPool(store)
|
| 352 |
+
resolver := NewResolver(store, pool, func(_ context.Context, acc config.Account) (string, error) {
|
| 353 |
+
if acc.Email == "bad@example.com" {
|
| 354 |
+
return "", errors.New("stale account")
|
| 355 |
+
}
|
| 356 |
+
return "fresh-good-token", nil
|
| 357 |
+
})
|
| 358 |
+
|
| 359 |
+
req, _ := http.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
|
| 360 |
+
req.Header.Set("x-api-key", "managed-key")
|
| 361 |
+
req.Header.Set("X-Ds2-Target-Account", "bad@example.com")
|
| 362 |
+
|
| 363 |
+
_, err := resolver.Determine(req)
|
| 364 |
+
if err == nil {
|
| 365 |
+
t.Fatal("expected determine to fail for broken target account")
|
| 366 |
+
}
|
| 367 |
+
}
|
| 368 |
+
|
| 369 |
+
func TestDetermineManagedAccountReturnsLastEnsureErrorWhenAllFail(t *testing.T) {
|
| 370 |
+
t.Setenv("DS2API_CONFIG_JSON", `{
|
| 371 |
+
"keys":["managed-key"],
|
| 372 |
+
"accounts":[
|
| 373 |
+
{"email":"bad1@example.com","password":"pwd"},
|
| 374 |
+
{"email":"bad2@example.com","password":"pwd"}
|
| 375 |
+
]
|
| 376 |
+
}`)
|
| 377 |
+
store := config.LoadStore()
|
| 378 |
+
pool := account.NewPool(store)
|
| 379 |
+
ensureErr := errors.New("all credentials stale")
|
| 380 |
+
resolver := NewResolver(store, pool, func(_ context.Context, _ config.Account) (string, error) {
|
| 381 |
+
return "", ensureErr
|
| 382 |
+
})
|
| 383 |
+
|
| 384 |
+
req, _ := http.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
|
| 385 |
+
req.Header.Set("x-api-key", "managed-key")
|
| 386 |
+
|
| 387 |
+
_, err := resolver.Determine(req)
|
| 388 |
+
if err == nil {
|
| 389 |
+
t.Fatal("expected determine to fail")
|
| 390 |
+
}
|
| 391 |
+
if !errors.Is(err, ensureErr) {
|
| 392 |
+
t.Fatalf("expected ensure error, got %v", err)
|
| 393 |
+
}
|
| 394 |
+
if errors.Is(err, ErrNoAccount) {
|
| 395 |
+
t.Fatalf("expected auth-style ensure error, got ErrNoAccount")
|
| 396 |
+
}
|
| 397 |
+
}
|
internal/chathistory/store.go
ADDED
|
@@ -0,0 +1,810 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package chathistory
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"encoding/json"
|
| 5 |
+
"errors"
|
| 6 |
+
"fmt"
|
| 7 |
+
"os"
|
| 8 |
+
"path/filepath"
|
| 9 |
+
"sort"
|
| 10 |
+
"strings"
|
| 11 |
+
"sync"
|
| 12 |
+
"time"
|
| 13 |
+
|
| 14 |
+
"github.com/google/uuid"
|
| 15 |
+
|
| 16 |
+
"ds2api/internal/config"
|
| 17 |
+
"ds2api/internal/util"
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
const (
|
| 21 |
+
FileVersion = 2
|
| 22 |
+
DisabledLimit = 0
|
| 23 |
+
DefaultLimit = 20
|
| 24 |
+
MaxLimit = 50
|
| 25 |
+
defaultPreviewAt = 160
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
var allowedLimits = map[int]struct{}{
|
| 29 |
+
DisabledLimit: {},
|
| 30 |
+
10: {},
|
| 31 |
+
20: {},
|
| 32 |
+
50: {},
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
var ErrDisabled = errors.New("chat history disabled")
|
| 36 |
+
|
| 37 |
+
type Entry struct {
|
| 38 |
+
ID string `json:"id"`
|
| 39 |
+
Revision int64 `json:"revision"`
|
| 40 |
+
CreatedAt int64 `json:"created_at"`
|
| 41 |
+
UpdatedAt int64 `json:"updated_at"`
|
| 42 |
+
CompletedAt int64 `json:"completed_at,omitempty"`
|
| 43 |
+
Status string `json:"status"`
|
| 44 |
+
CallerID string `json:"caller_id,omitempty"`
|
| 45 |
+
AccountID string `json:"account_id,omitempty"`
|
| 46 |
+
Surface string `json:"surface,omitempty"`
|
| 47 |
+
Model string `json:"model,omitempty"`
|
| 48 |
+
Stream bool `json:"stream"`
|
| 49 |
+
UserInput string `json:"user_input,omitempty"`
|
| 50 |
+
Messages []Message `json:"messages,omitempty"`
|
| 51 |
+
HistoryText string `json:"history_text,omitempty"`
|
| 52 |
+
FinalPrompt string `json:"final_prompt,omitempty"`
|
| 53 |
+
ReasoningContent string `json:"reasoning_content,omitempty"`
|
| 54 |
+
Content string `json:"content,omitempty"`
|
| 55 |
+
Error string `json:"error,omitempty"`
|
| 56 |
+
StatusCode int `json:"status_code,omitempty"`
|
| 57 |
+
ElapsedMs int64 `json:"elapsed_ms,omitempty"`
|
| 58 |
+
FinishReason string `json:"finish_reason,omitempty"`
|
| 59 |
+
Usage map[string]any `json:"usage,omitempty"`
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
type Message struct {
|
| 63 |
+
Role string `json:"role"`
|
| 64 |
+
Content string `json:"content"`
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
type SummaryEntry struct {
|
| 68 |
+
ID string `json:"id"`
|
| 69 |
+
Revision int64 `json:"revision"`
|
| 70 |
+
CreatedAt int64 `json:"created_at"`
|
| 71 |
+
UpdatedAt int64 `json:"updated_at"`
|
| 72 |
+
CompletedAt int64 `json:"completed_at,omitempty"`
|
| 73 |
+
Status string `json:"status"`
|
| 74 |
+
CallerID string `json:"caller_id,omitempty"`
|
| 75 |
+
AccountID string `json:"account_id,omitempty"`
|
| 76 |
+
Surface string `json:"surface,omitempty"`
|
| 77 |
+
Model string `json:"model,omitempty"`
|
| 78 |
+
Stream bool `json:"stream"`
|
| 79 |
+
UserInput string `json:"user_input,omitempty"`
|
| 80 |
+
Preview string `json:"preview,omitempty"`
|
| 81 |
+
StatusCode int `json:"status_code,omitempty"`
|
| 82 |
+
ElapsedMs int64 `json:"elapsed_ms,omitempty"`
|
| 83 |
+
FinishReason string `json:"finish_reason,omitempty"`
|
| 84 |
+
DetailRevision int64 `json:"detail_revision"`
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
type File struct {
|
| 88 |
+
Version int `json:"version"`
|
| 89 |
+
Limit int `json:"limit"`
|
| 90 |
+
Revision int64 `json:"revision"`
|
| 91 |
+
Items []SummaryEntry `json:"items"`
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
type StartParams struct {
|
| 95 |
+
CallerID string
|
| 96 |
+
AccountID string
|
| 97 |
+
Surface string
|
| 98 |
+
Model string
|
| 99 |
+
Stream bool
|
| 100 |
+
UserInput string
|
| 101 |
+
Messages []Message
|
| 102 |
+
HistoryText string
|
| 103 |
+
FinalPrompt string
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
type UpdateParams struct {
|
| 107 |
+
Status string
|
| 108 |
+
ReasoningContent string
|
| 109 |
+
Content string
|
| 110 |
+
Error string
|
| 111 |
+
StatusCode int
|
| 112 |
+
ElapsedMs int64
|
| 113 |
+
FinishReason string
|
| 114 |
+
Usage map[string]any
|
| 115 |
+
Completed bool
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
type detailEnvelope struct {
|
| 119 |
+
Version int `json:"version"`
|
| 120 |
+
Item Entry `json:"item"`
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
type legacyFile struct {
|
| 124 |
+
Version int `json:"version"`
|
| 125 |
+
Limit int `json:"limit"`
|
| 126 |
+
Items []Entry `json:"items"`
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
type legacyProbe struct {
|
| 130 |
+
Items []map[string]json.RawMessage `json:"items"`
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
type Store struct {
|
| 134 |
+
mu sync.Mutex
|
| 135 |
+
path string
|
| 136 |
+
detailDir string
|
| 137 |
+
state File
|
| 138 |
+
details map[string]Entry
|
| 139 |
+
dirty map[string]struct{}
|
| 140 |
+
deleted map[string]struct{}
|
| 141 |
+
err error
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
func New(path string) *Store {
|
| 145 |
+
s := &Store{
|
| 146 |
+
path: strings.TrimSpace(path),
|
| 147 |
+
detailDir: strings.TrimSpace(path) + ".d",
|
| 148 |
+
state: File{
|
| 149 |
+
Version: FileVersion,
|
| 150 |
+
Limit: DefaultLimit,
|
| 151 |
+
Revision: 0,
|
| 152 |
+
Items: []SummaryEntry{},
|
| 153 |
+
},
|
| 154 |
+
details: map[string]Entry{},
|
| 155 |
+
dirty: map[string]struct{}{},
|
| 156 |
+
deleted: map[string]struct{}{},
|
| 157 |
+
}
|
| 158 |
+
s.mu.Lock()
|
| 159 |
+
defer s.mu.Unlock()
|
| 160 |
+
s.err = s.loadLocked()
|
| 161 |
+
return s
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
func (s *Store) Path() string {
|
| 165 |
+
if s == nil {
|
| 166 |
+
return ""
|
| 167 |
+
}
|
| 168 |
+
return s.path
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
func (s *Store) DetailDir() string {
|
| 172 |
+
if s == nil {
|
| 173 |
+
return ""
|
| 174 |
+
}
|
| 175 |
+
return s.detailDir
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
func (s *Store) Err() error {
|
| 179 |
+
if s == nil {
|
| 180 |
+
return errors.New("chat history store is nil")
|
| 181 |
+
}
|
| 182 |
+
s.mu.Lock()
|
| 183 |
+
defer s.mu.Unlock()
|
| 184 |
+
return s.err
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
func (s *Store) Snapshot() (File, error) {
|
| 188 |
+
if s == nil {
|
| 189 |
+
return File{}, errors.New("chat history store is nil")
|
| 190 |
+
}
|
| 191 |
+
s.mu.Lock()
|
| 192 |
+
defer s.mu.Unlock()
|
| 193 |
+
if s.err != nil {
|
| 194 |
+
return File{}, s.err
|
| 195 |
+
}
|
| 196 |
+
return cloneFile(s.state), nil
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
func (s *Store) Revision() (int64, error) {
|
| 200 |
+
if s == nil {
|
| 201 |
+
return 0, errors.New("chat history store is nil")
|
| 202 |
+
}
|
| 203 |
+
s.mu.Lock()
|
| 204 |
+
defer s.mu.Unlock()
|
| 205 |
+
if s.err != nil {
|
| 206 |
+
return 0, s.err
|
| 207 |
+
}
|
| 208 |
+
return s.state.Revision, nil
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
func (s *Store) Enabled() bool {
|
| 212 |
+
if s == nil {
|
| 213 |
+
return false
|
| 214 |
+
}
|
| 215 |
+
s.mu.Lock()
|
| 216 |
+
defer s.mu.Unlock()
|
| 217 |
+
if s.err != nil {
|
| 218 |
+
return false
|
| 219 |
+
}
|
| 220 |
+
return s.state.Limit != DisabledLimit
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
func (s *Store) Get(id string) (Entry, error) {
|
| 224 |
+
if s == nil {
|
| 225 |
+
return Entry{}, errors.New("chat history store is nil")
|
| 226 |
+
}
|
| 227 |
+
s.mu.Lock()
|
| 228 |
+
defer s.mu.Unlock()
|
| 229 |
+
if s.err != nil {
|
| 230 |
+
return Entry{}, s.err
|
| 231 |
+
}
|
| 232 |
+
item, ok := s.details[strings.TrimSpace(id)]
|
| 233 |
+
if !ok {
|
| 234 |
+
return Entry{}, errors.New("chat history entry not found")
|
| 235 |
+
}
|
| 236 |
+
return cloneEntry(item), nil
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
func (s *Store) DetailRevision(id string) (int64, error) {
|
| 240 |
+
if s == nil {
|
| 241 |
+
return 0, errors.New("chat history store is nil")
|
| 242 |
+
}
|
| 243 |
+
s.mu.Lock()
|
| 244 |
+
defer s.mu.Unlock()
|
| 245 |
+
if s.err != nil {
|
| 246 |
+
return 0, s.err
|
| 247 |
+
}
|
| 248 |
+
item, ok := s.details[strings.TrimSpace(id)]
|
| 249 |
+
if !ok {
|
| 250 |
+
return 0, errors.New("chat history entry not found")
|
| 251 |
+
}
|
| 252 |
+
return item.Revision, nil
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
func (s *Store) Start(params StartParams) (Entry, error) {
|
| 256 |
+
if s == nil {
|
| 257 |
+
return Entry{}, errors.New("chat history store is nil")
|
| 258 |
+
}
|
| 259 |
+
s.mu.Lock()
|
| 260 |
+
defer s.mu.Unlock()
|
| 261 |
+
if s.err != nil {
|
| 262 |
+
return Entry{}, s.err
|
| 263 |
+
}
|
| 264 |
+
if s.state.Limit == DisabledLimit {
|
| 265 |
+
return Entry{}, ErrDisabled
|
| 266 |
+
}
|
| 267 |
+
now := time.Now().UnixMilli()
|
| 268 |
+
revision := s.nextRevisionLocked()
|
| 269 |
+
entry := Entry{
|
| 270 |
+
ID: "chat_" + strings.ReplaceAll(uuid.NewString(), "-", ""),
|
| 271 |
+
Revision: revision,
|
| 272 |
+
CreatedAt: now,
|
| 273 |
+
UpdatedAt: now,
|
| 274 |
+
Status: "streaming",
|
| 275 |
+
CallerID: strings.TrimSpace(params.CallerID),
|
| 276 |
+
AccountID: strings.TrimSpace(params.AccountID),
|
| 277 |
+
Surface: strings.TrimSpace(params.Surface),
|
| 278 |
+
Model: strings.TrimSpace(params.Model),
|
| 279 |
+
Stream: params.Stream,
|
| 280 |
+
UserInput: strings.TrimSpace(params.UserInput),
|
| 281 |
+
Messages: cloneMessages(params.Messages),
|
| 282 |
+
HistoryText: params.HistoryText,
|
| 283 |
+
FinalPrompt: strings.TrimSpace(params.FinalPrompt),
|
| 284 |
+
}
|
| 285 |
+
s.details[entry.ID] = entry
|
| 286 |
+
s.markDetailDirtyLocked(entry.ID)
|
| 287 |
+
s.rebuildIndexLocked()
|
| 288 |
+
if err := s.saveLocked(); err != nil {
|
| 289 |
+
return cloneEntry(entry), err
|
| 290 |
+
}
|
| 291 |
+
return cloneEntry(entry), nil
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
func (s *Store) Update(id string, params UpdateParams) (Entry, error) {
|
| 295 |
+
if s == nil {
|
| 296 |
+
return Entry{}, errors.New("chat history store is nil")
|
| 297 |
+
}
|
| 298 |
+
s.mu.Lock()
|
| 299 |
+
defer s.mu.Unlock()
|
| 300 |
+
if s.err != nil {
|
| 301 |
+
return Entry{}, s.err
|
| 302 |
+
}
|
| 303 |
+
target := strings.TrimSpace(id)
|
| 304 |
+
if target == "" {
|
| 305 |
+
return Entry{}, errors.New("history id is required")
|
| 306 |
+
}
|
| 307 |
+
item, ok := s.details[target]
|
| 308 |
+
if !ok {
|
| 309 |
+
return Entry{}, errors.New("chat history entry not found")
|
| 310 |
+
}
|
| 311 |
+
now := time.Now().UnixMilli()
|
| 312 |
+
item.Revision = s.nextRevisionLocked()
|
| 313 |
+
item.UpdatedAt = now
|
| 314 |
+
if params.Status != "" {
|
| 315 |
+
item.Status = params.Status
|
| 316 |
+
}
|
| 317 |
+
if params.ReasoningContent != "" || item.ReasoningContent == "" {
|
| 318 |
+
item.ReasoningContent = params.ReasoningContent
|
| 319 |
+
}
|
| 320 |
+
if params.Content != "" || item.Content == "" {
|
| 321 |
+
item.Content = params.Content
|
| 322 |
+
}
|
| 323 |
+
item.Error = strings.TrimSpace(params.Error)
|
| 324 |
+
item.StatusCode = params.StatusCode
|
| 325 |
+
item.ElapsedMs = params.ElapsedMs
|
| 326 |
+
item.FinishReason = strings.TrimSpace(params.FinishReason)
|
| 327 |
+
if params.Usage != nil {
|
| 328 |
+
item.Usage = cloneMap(params.Usage)
|
| 329 |
+
}
|
| 330 |
+
if params.Completed {
|
| 331 |
+
item.CompletedAt = now
|
| 332 |
+
}
|
| 333 |
+
s.details[target] = item
|
| 334 |
+
s.markDetailDirtyLocked(target)
|
| 335 |
+
s.rebuildIndexLocked()
|
| 336 |
+
if err := s.saveLocked(); err != nil {
|
| 337 |
+
return Entry{}, err
|
| 338 |
+
}
|
| 339 |
+
return cloneEntry(item), nil
|
| 340 |
+
}
|
| 341 |
+
|
| 342 |
+
func (s *Store) Delete(id string) error {
|
| 343 |
+
if s == nil {
|
| 344 |
+
return errors.New("chat history store is nil")
|
| 345 |
+
}
|
| 346 |
+
s.mu.Lock()
|
| 347 |
+
defer s.mu.Unlock()
|
| 348 |
+
if s.err != nil {
|
| 349 |
+
return s.err
|
| 350 |
+
}
|
| 351 |
+
target := strings.TrimSpace(id)
|
| 352 |
+
if target == "" {
|
| 353 |
+
return errors.New("history id is required")
|
| 354 |
+
}
|
| 355 |
+
if _, ok := s.details[target]; !ok {
|
| 356 |
+
return errors.New("chat history entry not found")
|
| 357 |
+
}
|
| 358 |
+
s.markDetailDeletedLocked(target)
|
| 359 |
+
delete(s.details, target)
|
| 360 |
+
s.nextRevisionLocked()
|
| 361 |
+
s.rebuildIndexLocked()
|
| 362 |
+
if err := s.saveLocked(); err != nil {
|
| 363 |
+
return err
|
| 364 |
+
}
|
| 365 |
+
return nil
|
| 366 |
+
}
|
| 367 |
+
|
| 368 |
+
func (s *Store) Clear() error {
|
| 369 |
+
if s == nil {
|
| 370 |
+
return errors.New("chat history store is nil")
|
| 371 |
+
}
|
| 372 |
+
s.mu.Lock()
|
| 373 |
+
defer s.mu.Unlock()
|
| 374 |
+
if s.err != nil {
|
| 375 |
+
return s.err
|
| 376 |
+
}
|
| 377 |
+
for id := range s.details {
|
| 378 |
+
s.markDetailDeletedLocked(id)
|
| 379 |
+
}
|
| 380 |
+
s.details = map[string]Entry{}
|
| 381 |
+
s.nextRevisionLocked()
|
| 382 |
+
s.rebuildIndexLocked()
|
| 383 |
+
if err := s.saveLocked(); err != nil {
|
| 384 |
+
return err
|
| 385 |
+
}
|
| 386 |
+
return nil
|
| 387 |
+
}
|
| 388 |
+
|
| 389 |
+
func (s *Store) SetLimit(limit int) (File, error) {
|
| 390 |
+
if s == nil {
|
| 391 |
+
return File{}, errors.New("chat history store is nil")
|
| 392 |
+
}
|
| 393 |
+
s.mu.Lock()
|
| 394 |
+
defer s.mu.Unlock()
|
| 395 |
+
if s.err != nil {
|
| 396 |
+
return File{}, s.err
|
| 397 |
+
}
|
| 398 |
+
if !isAllowedLimit(limit) {
|
| 399 |
+
return File{}, fmt.Errorf("unsupported chat history limit: %d", limit)
|
| 400 |
+
}
|
| 401 |
+
s.state.Limit = limit
|
| 402 |
+
s.nextRevisionLocked()
|
| 403 |
+
s.rebuildIndexLocked()
|
| 404 |
+
if err := s.saveLocked(); err != nil {
|
| 405 |
+
return File{}, err
|
| 406 |
+
}
|
| 407 |
+
return cloneFile(s.state), nil
|
| 408 |
+
}
|
| 409 |
+
|
| 410 |
+
func (s *Store) loadLocked() error {
|
| 411 |
+
if strings.TrimSpace(s.path) == "" {
|
| 412 |
+
return errors.New("chat history path is required")
|
| 413 |
+
}
|
| 414 |
+
if err := os.MkdirAll(filepath.Dir(s.path), 0o755); err != nil && filepath.Dir(s.path) != "." {
|
| 415 |
+
return fmt.Errorf("create chat history dir: %w", err)
|
| 416 |
+
}
|
| 417 |
+
if err := os.MkdirAll(s.detailDir, 0o755); err != nil {
|
| 418 |
+
return fmt.Errorf("create chat history detail dir: %w", err)
|
| 419 |
+
}
|
| 420 |
+
|
| 421 |
+
raw, err := os.ReadFile(s.path)
|
| 422 |
+
if err != nil {
|
| 423 |
+
if errors.Is(err, os.ErrNotExist) {
|
| 424 |
+
if saveErr := s.saveLocked(); saveErr != nil {
|
| 425 |
+
config.Logger.Warn("[chat_history] bootstrap write failed", "path", s.path, "error", saveErr)
|
| 426 |
+
}
|
| 427 |
+
return nil
|
| 428 |
+
}
|
| 429 |
+
return fmt.Errorf("read chat history index: %w", err)
|
| 430 |
+
}
|
| 431 |
+
|
| 432 |
+
legacy, legacyOK, legacyErr := parseLegacy(raw)
|
| 433 |
+
if legacyErr != nil {
|
| 434 |
+
return legacyErr
|
| 435 |
+
}
|
| 436 |
+
if legacyOK {
|
| 437 |
+
s.loadLegacyLocked(legacy)
|
| 438 |
+
if err := s.saveLocked(); err != nil {
|
| 439 |
+
config.Logger.Warn("[chat_history] legacy migration writeback failed", "path", s.path, "error", err)
|
| 440 |
+
}
|
| 441 |
+
return nil
|
| 442 |
+
}
|
| 443 |
+
|
| 444 |
+
var state File
|
| 445 |
+
if err := json.Unmarshal(raw, &state); err != nil {
|
| 446 |
+
return fmt.Errorf("decode chat history index: %w", err)
|
| 447 |
+
}
|
| 448 |
+
if state.Version == 0 {
|
| 449 |
+
state.Version = FileVersion
|
| 450 |
+
}
|
| 451 |
+
if !isAllowedLimit(state.Limit) {
|
| 452 |
+
state.Limit = DefaultLimit
|
| 453 |
+
}
|
| 454 |
+
s.state = cloneFile(state)
|
| 455 |
+
s.details = map[string]Entry{}
|
| 456 |
+
for _, item := range state.Items {
|
| 457 |
+
detail, err := readDetailFile(filepath.Join(s.detailDir, item.ID+".json"))
|
| 458 |
+
if err != nil {
|
| 459 |
+
return err
|
| 460 |
+
}
|
| 461 |
+
s.details[item.ID] = detail
|
| 462 |
+
}
|
| 463 |
+
s.rebuildIndexLocked()
|
| 464 |
+
if saveErr := s.saveLocked(); saveErr != nil {
|
| 465 |
+
config.Logger.Warn("[chat_history] index rewrite failed", "path", s.path, "error", saveErr)
|
| 466 |
+
}
|
| 467 |
+
return nil
|
| 468 |
+
}
|
| 469 |
+
|
| 470 |
+
func (s *Store) loadLegacyLocked(legacy legacyFile) {
|
| 471 |
+
s.state.Version = FileVersion
|
| 472 |
+
s.state.Limit = legacy.Limit
|
| 473 |
+
if !isAllowedLimit(s.state.Limit) {
|
| 474 |
+
s.state.Limit = DefaultLimit
|
| 475 |
+
}
|
| 476 |
+
s.details = map[string]Entry{}
|
| 477 |
+
s.dirty = map[string]struct{}{}
|
| 478 |
+
s.deleted = map[string]struct{}{}
|
| 479 |
+
maxRevision := int64(0)
|
| 480 |
+
for _, item := range legacy.Items {
|
| 481 |
+
if strings.TrimSpace(item.ID) == "" {
|
| 482 |
+
continue
|
| 483 |
+
}
|
| 484 |
+
item.Messages = cloneMessages(item.Messages)
|
| 485 |
+
if item.Revision == 0 {
|
| 486 |
+
if item.UpdatedAt > 0 {
|
| 487 |
+
item.Revision = item.UpdatedAt
|
| 488 |
+
} else {
|
| 489 |
+
item.Revision = time.Now().UnixNano()
|
| 490 |
+
}
|
| 491 |
+
}
|
| 492 |
+
if item.Revision > maxRevision {
|
| 493 |
+
maxRevision = item.Revision
|
| 494 |
+
}
|
| 495 |
+
s.details[item.ID] = item
|
| 496 |
+
s.markDetailDirtyLocked(item.ID)
|
| 497 |
+
}
|
| 498 |
+
s.state.Revision = maxRevision
|
| 499 |
+
s.rebuildIndexLocked()
|
| 500 |
+
}
|
| 501 |
+
|
| 502 |
+
func (s *Store) saveLocked() error {
|
| 503 |
+
s.state.Version = FileVersion
|
| 504 |
+
if !isAllowedLimit(s.state.Limit) {
|
| 505 |
+
s.state.Limit = DefaultLimit
|
| 506 |
+
}
|
| 507 |
+
s.rebuildIndexLocked()
|
| 508 |
+
|
| 509 |
+
if err := os.MkdirAll(s.detailDir, 0o755); err != nil {
|
| 510 |
+
return fmt.Errorf("create chat history detail dir: %w", err)
|
| 511 |
+
}
|
| 512 |
+
for _, id := range sortedDetailIDs(s.deleted) {
|
| 513 |
+
path := filepath.Join(s.detailDir, id+".json")
|
| 514 |
+
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
|
| 515 |
+
return fmt.Errorf("remove stale chat history detail: %w", err)
|
| 516 |
+
}
|
| 517 |
+
}
|
| 518 |
+
for _, id := range sortedDetailIDs(s.dirty) {
|
| 519 |
+
item, ok := s.details[id]
|
| 520 |
+
if !ok {
|
| 521 |
+
continue
|
| 522 |
+
}
|
| 523 |
+
path := filepath.Join(s.detailDir, id+".json")
|
| 524 |
+
payload, err := json.MarshalIndent(detailEnvelope{
|
| 525 |
+
Version: FileVersion,
|
| 526 |
+
Item: item,
|
| 527 |
+
}, "", " ")
|
| 528 |
+
if err != nil {
|
| 529 |
+
return fmt.Errorf("encode chat history detail: %w", err)
|
| 530 |
+
}
|
| 531 |
+
if err := writeFileAtomic(path, append(payload, '\n')); err != nil {
|
| 532 |
+
return err
|
| 533 |
+
}
|
| 534 |
+
}
|
| 535 |
+
|
| 536 |
+
payload, err := json.MarshalIndent(s.state, "", " ")
|
| 537 |
+
if err != nil {
|
| 538 |
+
return fmt.Errorf("encode chat history index: %w", err)
|
| 539 |
+
}
|
| 540 |
+
if err := writeFileAtomic(s.path, append(payload, '\n')); err != nil {
|
| 541 |
+
return err
|
| 542 |
+
}
|
| 543 |
+
s.clearPendingDetailChangesLocked()
|
| 544 |
+
return nil
|
| 545 |
+
}
|
| 546 |
+
|
| 547 |
+
func (s *Store) rebuildIndexLocked() {
|
| 548 |
+
summaries := make([]SummaryEntry, 0, len(s.details))
|
| 549 |
+
for _, item := range s.details {
|
| 550 |
+
summaries = append(summaries, summaryFromEntry(item))
|
| 551 |
+
}
|
| 552 |
+
sort.Slice(summaries, func(i, j int) bool {
|
| 553 |
+
if summaries[i].CreatedAt == summaries[j].CreatedAt {
|
| 554 |
+
if summaries[i].Revision == summaries[j].Revision {
|
| 555 |
+
return summaries[i].UpdatedAt > summaries[j].UpdatedAt
|
| 556 |
+
}
|
| 557 |
+
return summaries[i].Revision > summaries[j].Revision
|
| 558 |
+
}
|
| 559 |
+
return summaries[i].CreatedAt > summaries[j].CreatedAt
|
| 560 |
+
})
|
| 561 |
+
if s.state.Limit < DisabledLimit || !isAllowedLimit(s.state.Limit) {
|
| 562 |
+
s.state.Limit = DefaultLimit
|
| 563 |
+
}
|
| 564 |
+
if s.state.Limit == DisabledLimit {
|
| 565 |
+
s.state.Items = summaries
|
| 566 |
+
return
|
| 567 |
+
}
|
| 568 |
+
if len(summaries) > s.state.Limit {
|
| 569 |
+
keep := make(map[string]struct{}, s.state.Limit)
|
| 570 |
+
for _, item := range summaries[:s.state.Limit] {
|
| 571 |
+
keep[item.ID] = struct{}{}
|
| 572 |
+
}
|
| 573 |
+
for id := range s.details {
|
| 574 |
+
if _, ok := keep[id]; !ok {
|
| 575 |
+
s.markDetailDeletedLocked(id)
|
| 576 |
+
delete(s.details, id)
|
| 577 |
+
}
|
| 578 |
+
}
|
| 579 |
+
summaries = summaries[:s.state.Limit]
|
| 580 |
+
}
|
| 581 |
+
s.state.Items = summaries
|
| 582 |
+
}
|
| 583 |
+
|
| 584 |
+
func (s *Store) nextRevisionLocked() int64 {
|
| 585 |
+
next := time.Now().UnixNano()
|
| 586 |
+
if next <= s.state.Revision {
|
| 587 |
+
next = s.state.Revision + 1
|
| 588 |
+
}
|
| 589 |
+
s.state.Revision = next
|
| 590 |
+
return next
|
| 591 |
+
}
|
| 592 |
+
|
| 593 |
+
func summaryFromEntry(item Entry) SummaryEntry {
|
| 594 |
+
return SummaryEntry{
|
| 595 |
+
ID: item.ID,
|
| 596 |
+
Revision: item.Revision,
|
| 597 |
+
CreatedAt: item.CreatedAt,
|
| 598 |
+
UpdatedAt: item.UpdatedAt,
|
| 599 |
+
CompletedAt: item.CompletedAt,
|
| 600 |
+
Status: item.Status,
|
| 601 |
+
CallerID: item.CallerID,
|
| 602 |
+
AccountID: item.AccountID,
|
| 603 |
+
Surface: item.Surface,
|
| 604 |
+
Model: item.Model,
|
| 605 |
+
Stream: item.Stream,
|
| 606 |
+
UserInput: item.UserInput,
|
| 607 |
+
Preview: buildPreview(item),
|
| 608 |
+
StatusCode: item.StatusCode,
|
| 609 |
+
ElapsedMs: item.ElapsedMs,
|
| 610 |
+
FinishReason: item.FinishReason,
|
| 611 |
+
DetailRevision: item.Revision,
|
| 612 |
+
}
|
| 613 |
+
}
|
| 614 |
+
|
| 615 |
+
func buildPreview(item Entry) string {
|
| 616 |
+
candidate := strings.TrimSpace(item.Content)
|
| 617 |
+
if candidate == "" {
|
| 618 |
+
candidate = strings.TrimSpace(item.ReasoningContent)
|
| 619 |
+
}
|
| 620 |
+
if candidate == "" {
|
| 621 |
+
candidate = strings.TrimSpace(item.Error)
|
| 622 |
+
}
|
| 623 |
+
if candidate == "" {
|
| 624 |
+
candidate = strings.TrimSpace(item.UserInput)
|
| 625 |
+
}
|
| 626 |
+
if truncated, ok := util.TruncateRunes(candidate, defaultPreviewAt); ok {
|
| 627 |
+
return truncated + "..."
|
| 628 |
+
}
|
| 629 |
+
return candidate
|
| 630 |
+
}
|
| 631 |
+
|
| 632 |
+
func readDetailFile(path string) (Entry, error) {
|
| 633 |
+
raw, err := os.ReadFile(path)
|
| 634 |
+
if err != nil {
|
| 635 |
+
return Entry{}, fmt.Errorf("read chat history detail: %w", err)
|
| 636 |
+
}
|
| 637 |
+
var env detailEnvelope
|
| 638 |
+
if err := json.Unmarshal(raw, &env); err != nil {
|
| 639 |
+
return Entry{}, fmt.Errorf("decode chat history detail: %w", err)
|
| 640 |
+
}
|
| 641 |
+
return cloneEntry(env.Item), nil
|
| 642 |
+
}
|
| 643 |
+
|
| 644 |
+
func parseLegacy(raw []byte) (legacyFile, bool, error) {
|
| 645 |
+
var legacy legacyFile
|
| 646 |
+
if err := json.Unmarshal(raw, &legacy); err != nil {
|
| 647 |
+
return legacyFile{}, false, nil
|
| 648 |
+
}
|
| 649 |
+
if len(legacy.Items) == 0 {
|
| 650 |
+
return legacy, false, nil
|
| 651 |
+
}
|
| 652 |
+
var probe legacyProbe
|
| 653 |
+
if err := json.Unmarshal(raw, &probe); err == nil {
|
| 654 |
+
for _, item := range probe.Items {
|
| 655 |
+
if _, ok := item["detail_revision"]; ok {
|
| 656 |
+
return legacy, false, nil
|
| 657 |
+
}
|
| 658 |
+
}
|
| 659 |
+
}
|
| 660 |
+
return legacy, true, nil
|
| 661 |
+
}
|
| 662 |
+
|
| 663 |
+
func writeFileAtomic(path string, body []byte) error {
|
| 664 |
+
dir := filepath.Dir(path)
|
| 665 |
+
if dir == "" {
|
| 666 |
+
dir = "."
|
| 667 |
+
}
|
| 668 |
+
if dir != "." {
|
| 669 |
+
if err := os.MkdirAll(dir, 0o755); err != nil {
|
| 670 |
+
return fmt.Errorf("create chat history dir: %w", err)
|
| 671 |
+
}
|
| 672 |
+
}
|
| 673 |
+
tmpFile, err := os.CreateTemp(dir, ".chat-history-*.tmp")
|
| 674 |
+
if err != nil {
|
| 675 |
+
return fmt.Errorf("create temp chat history: %w", err)
|
| 676 |
+
}
|
| 677 |
+
tmpPath := tmpFile.Name()
|
| 678 |
+
cleanup := func() error {
|
| 679 |
+
if err := os.Remove(tmpPath); err != nil && !errors.Is(err, os.ErrNotExist) {
|
| 680 |
+
return fmt.Errorf("remove temp chat history: %w", err)
|
| 681 |
+
}
|
| 682 |
+
return nil
|
| 683 |
+
}
|
| 684 |
+
withCleanup := func(primary error, closeErr error) error {
|
| 685 |
+
errs := []error{primary}
|
| 686 |
+
if closeErr != nil {
|
| 687 |
+
errs = append(errs, fmt.Errorf("close temp chat history: %w", closeErr))
|
| 688 |
+
}
|
| 689 |
+
if cleanupErr := cleanup(); cleanupErr != nil {
|
| 690 |
+
errs = append(errs, cleanupErr)
|
| 691 |
+
}
|
| 692 |
+
return errors.Join(errs...)
|
| 693 |
+
}
|
| 694 |
+
if _, err := tmpFile.Write(body); err != nil {
|
| 695 |
+
return withCleanup(fmt.Errorf("write temp chat history: %w", err), tmpFile.Close())
|
| 696 |
+
}
|
| 697 |
+
if err := tmpFile.Sync(); err != nil {
|
| 698 |
+
return withCleanup(fmt.Errorf("sync temp chat history: %w", err), tmpFile.Close())
|
| 699 |
+
}
|
| 700 |
+
if err := tmpFile.Close(); err != nil {
|
| 701 |
+
if cleanupErr := cleanup(); cleanupErr != nil {
|
| 702 |
+
return errors.Join(fmt.Errorf("close temp chat history: %w", err), cleanupErr)
|
| 703 |
+
}
|
| 704 |
+
return fmt.Errorf("close temp chat history: %w", err)
|
| 705 |
+
}
|
| 706 |
+
if err := os.Rename(tmpPath, path); err != nil {
|
| 707 |
+
if cleanupErr := cleanup(); cleanupErr != nil {
|
| 708 |
+
return errors.Join(fmt.Errorf("promote temp chat history: %w", err), cleanupErr)
|
| 709 |
+
}
|
| 710 |
+
return fmt.Errorf("promote temp chat history: %w", err)
|
| 711 |
+
}
|
| 712 |
+
return nil
|
| 713 |
+
}
|
| 714 |
+
|
| 715 |
+
func ListETag(revision int64) string {
|
| 716 |
+
return fmt.Sprintf(`W/"chat-history-list-%d"`, revision)
|
| 717 |
+
}
|
| 718 |
+
|
| 719 |
+
func DetailETag(id string, revision int64) string {
|
| 720 |
+
return fmt.Sprintf(`W/"chat-history-detail-%s-%d"`, strings.TrimSpace(id), revision)
|
| 721 |
+
}
|
| 722 |
+
|
| 723 |
+
func isAllowedLimit(limit int) bool {
|
| 724 |
+
_, ok := allowedLimits[limit]
|
| 725 |
+
return ok
|
| 726 |
+
}
|
| 727 |
+
|
| 728 |
+
func (s *Store) markDetailDirtyLocked(id string) {
|
| 729 |
+
id = strings.TrimSpace(id)
|
| 730 |
+
if id == "" {
|
| 731 |
+
return
|
| 732 |
+
}
|
| 733 |
+
if s.dirty == nil {
|
| 734 |
+
s.dirty = map[string]struct{}{}
|
| 735 |
+
}
|
| 736 |
+
if s.deleted == nil {
|
| 737 |
+
s.deleted = map[string]struct{}{}
|
| 738 |
+
}
|
| 739 |
+
s.dirty[id] = struct{}{}
|
| 740 |
+
delete(s.deleted, id)
|
| 741 |
+
}
|
| 742 |
+
|
| 743 |
+
func (s *Store) markDetailDeletedLocked(id string) {
|
| 744 |
+
id = strings.TrimSpace(id)
|
| 745 |
+
if id == "" {
|
| 746 |
+
return
|
| 747 |
+
}
|
| 748 |
+
if s.dirty == nil {
|
| 749 |
+
s.dirty = map[string]struct{}{}
|
| 750 |
+
}
|
| 751 |
+
if s.deleted == nil {
|
| 752 |
+
s.deleted = map[string]struct{}{}
|
| 753 |
+
}
|
| 754 |
+
s.deleted[id] = struct{}{}
|
| 755 |
+
delete(s.dirty, id)
|
| 756 |
+
}
|
| 757 |
+
|
| 758 |
+
func (s *Store) clearPendingDetailChangesLocked() {
|
| 759 |
+
s.dirty = map[string]struct{}{}
|
| 760 |
+
s.deleted = map[string]struct{}{}
|
| 761 |
+
}
|
| 762 |
+
|
| 763 |
+
func sortedDetailIDs(ids map[string]struct{}) []string {
|
| 764 |
+
if len(ids) == 0 {
|
| 765 |
+
return nil
|
| 766 |
+
}
|
| 767 |
+
out := make([]string, 0, len(ids))
|
| 768 |
+
for id := range ids {
|
| 769 |
+
out = append(out, id)
|
| 770 |
+
}
|
| 771 |
+
sort.Strings(out)
|
| 772 |
+
return out
|
| 773 |
+
}
|
| 774 |
+
|
| 775 |
+
func cloneFile(in File) File {
|
| 776 |
+
out := File{
|
| 777 |
+
Version: in.Version,
|
| 778 |
+
Limit: in.Limit,
|
| 779 |
+
Revision: in.Revision,
|
| 780 |
+
Items: make([]SummaryEntry, len(in.Items)),
|
| 781 |
+
}
|
| 782 |
+
copy(out.Items, in.Items)
|
| 783 |
+
return out
|
| 784 |
+
}
|
| 785 |
+
|
| 786 |
+
func cloneEntry(item Entry) Entry {
|
| 787 |
+
item.Usage = cloneMap(item.Usage)
|
| 788 |
+
item.Messages = cloneMessages(item.Messages)
|
| 789 |
+
return item
|
| 790 |
+
}
|
| 791 |
+
|
| 792 |
+
func cloneMap(in map[string]any) map[string]any {
|
| 793 |
+
if in == nil {
|
| 794 |
+
return nil
|
| 795 |
+
}
|
| 796 |
+
out := make(map[string]any, len(in))
|
| 797 |
+
for k, v := range in {
|
| 798 |
+
out[k] = v
|
| 799 |
+
}
|
| 800 |
+
return out
|
| 801 |
+
}
|
| 802 |
+
|
| 803 |
+
func cloneMessages(messages []Message) []Message {
|
| 804 |
+
if len(messages) == 0 {
|
| 805 |
+
return []Message{}
|
| 806 |
+
}
|
| 807 |
+
out := make([]Message, len(messages))
|
| 808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|
+
|
| 15 |
+
func blockDetailDir(t *testing.T, detailDir string) func() {
|
| 16 |
+
t.Helper()
|
| 17 |
+
blockedDir := detailDir + ".blocked"
|
| 18 |
+
if err := os.RemoveAll(blockedDir); err != nil {
|
| 19 |
+
t.Fatalf("remove blocked detail dir failed: %v", err)
|
| 20 |
+
}
|
| 21 |
+
if err := os.Rename(detailDir, blockedDir); err != nil {
|
| 22 |
+
t.Fatalf("move detail dir aside failed: %v", err)
|
| 23 |
+
}
|
| 24 |
+
if err := os.RemoveAll(detailDir); err != nil {
|
| 25 |
+
t.Fatalf("remove blocked detail path failed: %v", err)
|
| 26 |
+
}
|
| 27 |
+
if err := os.WriteFile(detailDir, []byte("blocked"), 0o644); err != nil {
|
| 28 |
+
t.Fatalf("write blocked detail path failed: %v", err)
|
| 29 |
+
}
|
| 30 |
+
var once sync.Once
|
| 31 |
+
return func() {
|
| 32 |
+
t.Helper()
|
| 33 |
+
once.Do(func() {
|
| 34 |
+
if err := os.RemoveAll(detailDir); err != nil {
|
| 35 |
+
t.Fatalf("remove blocking detail path failed: %v", err)
|
| 36 |
+
}
|
| 37 |
+
if err := os.Rename(blockedDir, detailDir); err != nil {
|
| 38 |
+
t.Fatalf("restore detail dir failed: %v", err)
|
| 39 |
+
}
|
| 40 |
+
})
|
| 41 |
+
}
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
func TestStoreCreatesAndPersistsEntries(t *testing.T) {
|
| 45 |
+
path := filepath.Join(t.TempDir(), "chat_history.json")
|
| 46 |
+
store := New(path)
|
| 47 |
+
|
| 48 |
+
started, err := store.Start(StartParams{
|
| 49 |
+
CallerID: "caller:abc",
|
| 50 |
+
AccountID: "user@example.com",
|
| 51 |
+
Model: "deepseek-v4-flash",
|
| 52 |
+
Stream: true,
|
| 53 |
+
UserInput: "hello",
|
| 54 |
+
})
|
| 55 |
+
if err != nil {
|
| 56 |
+
t.Fatalf("start entry failed: %v", err)
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
updated, err := store.Update(started.ID, UpdateParams{
|
| 60 |
+
Status: "success",
|
| 61 |
+
ReasoningContent: "thinking",
|
| 62 |
+
Content: "answer",
|
| 63 |
+
StatusCode: 200,
|
| 64 |
+
ElapsedMs: 321,
|
| 65 |
+
FinishReason: "stop",
|
| 66 |
+
Usage: map[string]any{"total_tokens": 9},
|
| 67 |
+
Completed: true,
|
| 68 |
+
})
|
| 69 |
+
if err != nil {
|
| 70 |
+
t.Fatalf("update entry failed: %v", err)
|
| 71 |
+
}
|
| 72 |
+
if updated.Status != "success" || updated.Content != "answer" {
|
| 73 |
+
t.Fatalf("unexpected updated entry: %#v", updated)
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
snapshot, err := store.Snapshot()
|
| 77 |
+
if err != nil {
|
| 78 |
+
t.Fatalf("snapshot failed: %v", err)
|
| 79 |
+
}
|
| 80 |
+
if snapshot.Limit != DefaultLimit {
|
| 81 |
+
t.Fatalf("unexpected default limit: %d", snapshot.Limit)
|
| 82 |
+
}
|
| 83 |
+
if len(snapshot.Items) != 1 {
|
| 84 |
+
t.Fatalf("expected one item, got %d", len(snapshot.Items))
|
| 85 |
+
}
|
| 86 |
+
if snapshot.Items[0].CompletedAt == 0 {
|
| 87 |
+
t.Fatalf("expected completed_at to be populated")
|
| 88 |
+
}
|
| 89 |
+
if snapshot.Items[0].Preview != "answer" {
|
| 90 |
+
t.Fatalf("expected summary preview=answer, got %#v", snapshot.Items[0])
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
reloaded := New(path)
|
| 94 |
+
reloadedSnapshot, err := reloaded.Snapshot()
|
| 95 |
+
if err != nil {
|
| 96 |
+
t.Fatalf("reload snapshot failed: %v", err)
|
| 97 |
+
}
|
| 98 |
+
if len(reloadedSnapshot.Items) != 1 {
|
| 99 |
+
t.Fatalf("unexpected reloaded summaries: %#v", reloadedSnapshot.Items)
|
| 100 |
+
}
|
| 101 |
+
full, err := reloaded.Get(started.ID)
|
| 102 |
+
if err != nil {
|
| 103 |
+
t.Fatalf("get detail failed: %v", err)
|
| 104 |
+
}
|
| 105 |
+
if full.Content != "answer" {
|
| 106 |
+
t.Fatalf("expected detail content=answer, got %#v", full)
|
| 107 |
+
}
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
func TestBuildPreviewPreservesUTF8MB4Characters(t *testing.T) {
|
| 111 |
+
long := strings.Repeat("😀", defaultPreviewAt+1)
|
| 112 |
+
preview := buildPreview(Entry{Content: long})
|
| 113 |
+
if !utf8.ValidString(preview) {
|
| 114 |
+
t.Fatalf("expected valid utf-8 preview, got %q", preview)
|
| 115 |
+
}
|
| 116 |
+
if preview != strings.Repeat("😀", defaultPreviewAt)+"..." {
|
| 117 |
+
t.Fatalf("unexpected preview: %q", preview)
|
| 118 |
+
}
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
func TestStoreTrimsToConfiguredLimit(t *testing.T) {
|
| 122 |
+
path := filepath.Join(t.TempDir(), "chat_history.json")
|
| 123 |
+
store := New(path)
|
| 124 |
+
if _, err := store.SetLimit(10); err != nil {
|
| 125 |
+
t.Fatalf("set limit failed: %v", err)
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
for i := 0; i < 12; i++ {
|
| 129 |
+
entry, err := store.Start(StartParams{Model: "deepseek-v4-flash", UserInput: "msg"})
|
| 130 |
+
if err != nil {
|
| 131 |
+
t.Fatalf("start %d failed: %v", i, err)
|
| 132 |
+
}
|
| 133 |
+
if _, err := store.Update(entry.ID, UpdateParams{Status: "success", Content: "ok", Completed: true}); err != nil {
|
| 134 |
+
t.Fatalf("update %d failed: %v", i, err)
|
| 135 |
+
}
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
snapshot, err := store.Snapshot()
|
| 139 |
+
if err != nil {
|
| 140 |
+
t.Fatalf("snapshot failed: %v", err)
|
| 141 |
+
}
|
| 142 |
+
if len(snapshot.Items) != 10 {
|
| 143 |
+
t.Fatalf("expected 10 items, got %d", len(snapshot.Items))
|
| 144 |
+
}
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
func TestStoreDeleteClearAndLimitValidation(t *testing.T) {
|
| 148 |
+
path := filepath.Join(t.TempDir(), "chat_history.json")
|
| 149 |
+
store := New(path)
|
| 150 |
+
entry, err := store.Start(StartParams{UserInput: "hello"})
|
| 151 |
+
if err != nil {
|
| 152 |
+
t.Fatalf("start failed: %v", err)
|
| 153 |
+
}
|
| 154 |
+
if err := store.Delete(entry.ID); err != nil {
|
| 155 |
+
t.Fatalf("delete failed: %v", err)
|
| 156 |
+
}
|
| 157 |
+
snapshot, err := store.Snapshot()
|
| 158 |
+
if err != nil {
|
| 159 |
+
t.Fatalf("snapshot failed: %v", err)
|
| 160 |
+
}
|
| 161 |
+
if len(snapshot.Items) != 0 {
|
| 162 |
+
t.Fatalf("expected empty items after delete, got %d", len(snapshot.Items))
|
| 163 |
+
}
|
| 164 |
+
if _, err := store.SetLimit(999); err == nil {
|
| 165 |
+
t.Fatalf("expected invalid limit error")
|
| 166 |
+
}
|
| 167 |
+
if err := store.Clear(); err != nil {
|
| 168 |
+
t.Fatalf("clear failed: %v", err)
|
| 169 |
+
}
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
func TestStoreDisablePreservesHistoryAndBlocksNewEntries(t *testing.T) {
|
| 173 |
+
path := filepath.Join(t.TempDir(), "chat_history.json")
|
| 174 |
+
store := New(path)
|
| 175 |
+
|
| 176 |
+
entry, err := store.Start(StartParams{UserInput: "hello"})
|
| 177 |
+
if err != nil {
|
| 178 |
+
t.Fatalf("start failed: %v", err)
|
| 179 |
+
}
|
| 180 |
+
if _, err := store.Update(entry.ID, UpdateParams{Status: "success", Content: "world", Completed: true}); err != nil {
|
| 181 |
+
t.Fatalf("update failed: %v", err)
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
snapshot, err := store.SetLimit(DisabledLimit)
|
| 185 |
+
if err != nil {
|
| 186 |
+
t.Fatalf("disable failed: %v", err)
|
| 187 |
+
}
|
| 188 |
+
if snapshot.Limit != DisabledLimit {
|
| 189 |
+
t.Fatalf("expected disabled limit, got %d", snapshot.Limit)
|
| 190 |
+
}
|
| 191 |
+
if len(snapshot.Items) != 1 {
|
| 192 |
+
t.Fatalf("expected disabled mode to preserve summaries, got %d", len(snapshot.Items))
|
| 193 |
+
}
|
| 194 |
+
if store.Enabled() {
|
| 195 |
+
t.Fatalf("expected store to report disabled")
|
| 196 |
+
}
|
| 197 |
+
if _, err := store.Start(StartParams{UserInput: "later"}); err != ErrDisabled {
|
| 198 |
+
t.Fatalf("expected ErrDisabled, got %v", err)
|
| 199 |
+
}
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
func TestStoreConcurrentUpdatesKeepSplitFilesValid(t *testing.T) {
|
| 203 |
+
path := filepath.Join(t.TempDir(), "chat_history.json")
|
| 204 |
+
store := New(path)
|
| 205 |
+
|
| 206 |
+
var wg sync.WaitGroup
|
| 207 |
+
for i := 0; i < 8; i++ {
|
| 208 |
+
wg.Add(1)
|
| 209 |
+
go func(idx int) {
|
| 210 |
+
defer wg.Done()
|
| 211 |
+
entry, err := store.Start(StartParams{
|
| 212 |
+
CallerID: "caller:test",
|
| 213 |
+
Model: "deepseek-v4-flash",
|
| 214 |
+
UserInput: "hello",
|
| 215 |
+
})
|
| 216 |
+
if err != nil {
|
| 217 |
+
t.Errorf("start failed: %v", err)
|
| 218 |
+
return
|
| 219 |
+
}
|
| 220 |
+
_, err = store.Update(entry.ID, UpdateParams{
|
| 221 |
+
Status: "success",
|
| 222 |
+
Content: "answer",
|
| 223 |
+
ElapsedMs: int64(idx),
|
| 224 |
+
Completed: true,
|
| 225 |
+
})
|
| 226 |
+
if err != nil {
|
| 227 |
+
t.Errorf("update failed: %v", err)
|
| 228 |
+
}
|
| 229 |
+
}(i)
|
| 230 |
+
}
|
| 231 |
+
wg.Wait()
|
| 232 |
+
|
| 233 |
+
snapshot, err := store.Snapshot()
|
| 234 |
+
if err != nil {
|
| 235 |
+
t.Fatalf("snapshot failed: %v", err)
|
| 236 |
+
}
|
| 237 |
+
if len(snapshot.Items) != 8 {
|
| 238 |
+
t.Fatalf("expected 8 items, got %d", len(snapshot.Items))
|
| 239 |
+
}
|
| 240 |
+
|
| 241 |
+
raw, err := os.ReadFile(path)
|
| 242 |
+
if err != nil {
|
| 243 |
+
t.Fatalf("read index failed: %v", err)
|
| 244 |
+
}
|
| 245 |
+
var persisted File
|
| 246 |
+
if err := json.Unmarshal(raw, &persisted); err != nil {
|
| 247 |
+
t.Fatalf("persisted index is invalid json: %v", err)
|
| 248 |
+
}
|
| 249 |
+
if len(persisted.Items) != 8 {
|
| 250 |
+
t.Fatalf("expected persisted items=8, got %d", len(persisted.Items))
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
detailFiles, err := os.ReadDir(path + ".d")
|
| 254 |
+
if err != nil {
|
| 255 |
+
t.Fatalf("read detail dir failed: %v", err)
|
| 256 |
+
}
|
| 257 |
+
if len(detailFiles) != 8 {
|
| 258 |
+
t.Fatalf("expected 8 detail files, got %d", len(detailFiles))
|
| 259 |
+
}
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
func TestStoreAutoMigratesLegacyMonolith(t *testing.T) {
|
| 263 |
+
path := filepath.Join(t.TempDir(), "chat_history.json")
|
| 264 |
+
legacy := legacyFile{
|
| 265 |
+
Version: 1,
|
| 266 |
+
Limit: 20,
|
| 267 |
+
Items: []Entry{{
|
| 268 |
+
ID: "chat_legacy",
|
| 269 |
+
CreatedAt: 1,
|
| 270 |
+
UpdatedAt: 2,
|
| 271 |
+
Status: "success",
|
| 272 |
+
UserInput: "hello",
|
| 273 |
+
Content: "world",
|
| 274 |
+
ReasoningContent: "thinking",
|
| 275 |
+
}},
|
| 276 |
+
}
|
| 277 |
+
body, _ := json.MarshalIndent(legacy, "", " ")
|
| 278 |
+
if err := os.WriteFile(path, body, 0o644); err != nil {
|
| 279 |
+
t.Fatalf("write legacy file failed: %v", err)
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
store := New(path)
|
| 283 |
+
if err := store.Err(); err != nil {
|
| 284 |
+
t.Fatalf("expected legacy migration success, got %v", err)
|
| 285 |
+
}
|
| 286 |
+
snapshot, err := store.Snapshot()
|
| 287 |
+
if err != nil {
|
| 288 |
+
t.Fatalf("snapshot failed: %v", err)
|
| 289 |
+
}
|
| 290 |
+
if len(snapshot.Items) != 1 {
|
| 291 |
+
t.Fatalf("expected one migrated summary, got %#v", snapshot.Items)
|
| 292 |
+
}
|
| 293 |
+
full, err := store.Get("chat_legacy")
|
| 294 |
+
if err != nil {
|
| 295 |
+
t.Fatalf("get migrated detail failed: %v", err)
|
| 296 |
+
}
|
| 297 |
+
if full.Content != "world" {
|
| 298 |
+
t.Fatalf("expected migrated detail content preserved, got %#v", full)
|
| 299 |
+
}
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
func TestStoreAutoMigratesMetadataOnlyLegacyMonolith(t *testing.T) {
|
| 303 |
+
path := filepath.Join(t.TempDir(), "chat_history.json")
|
| 304 |
+
legacy := legacyFile{
|
| 305 |
+
Version: 1,
|
| 306 |
+
Limit: 20,
|
| 307 |
+
Items: []Entry{{
|
| 308 |
+
ID: "chat_metadata_only",
|
| 309 |
+
Revision: 0,
|
| 310 |
+
CreatedAt: 1,
|
| 311 |
+
UpdatedAt: 2,
|
| 312 |
+
Status: "error",
|
| 313 |
+
CallerID: "caller:test",
|
| 314 |
+
AccountID: "acct:test",
|
| 315 |
+
Model: "deepseek-v4-flash",
|
| 316 |
+
Stream: true,
|
| 317 |
+
UserInput: "hello",
|
| 318 |
+
Error: "boom",
|
| 319 |
+
StatusCode: 500,
|
| 320 |
+
ElapsedMs: 12,
|
| 321 |
+
FinishReason: "error",
|
| 322 |
+
}},
|
| 323 |
+
}
|
| 324 |
+
body, _ := json.MarshalIndent(legacy, "", " ")
|
| 325 |
+
if err := os.WriteFile(path, body, 0o644); err != nil {
|
| 326 |
+
t.Fatalf("write legacy file failed: %v", err)
|
| 327 |
+
}
|
| 328 |
+
|
| 329 |
+
store := New(path)
|
| 330 |
+
if err := store.Err(); err != nil {
|
| 331 |
+
t.Fatalf("expected legacy metadata-only migration success, got %v", err)
|
| 332 |
+
}
|
| 333 |
+
snapshot, err := store.Snapshot()
|
| 334 |
+
if err != nil {
|
| 335 |
+
t.Fatalf("snapshot failed: %v", err)
|
| 336 |
+
}
|
| 337 |
+
if len(snapshot.Items) != 1 {
|
| 338 |
+
t.Fatalf("expected one migrated summary, got %#v", snapshot.Items)
|
| 339 |
+
}
|
| 340 |
+
full, err := store.Get("chat_metadata_only")
|
| 341 |
+
if err != nil {
|
| 342 |
+
t.Fatalf("get migrated detail failed: %v", err)
|
| 343 |
+
}
|
| 344 |
+
if full.Error != "boom" || full.UserInput != "hello" {
|
| 345 |
+
t.Fatalf("expected metadata-only legacy fields preserved, got %#v", full)
|
| 346 |
+
}
|
| 347 |
+
if _, err := os.Stat(filepath.Join(store.DetailDir(), "chat_metadata_only.json")); err != nil {
|
| 348 |
+
t.Fatalf("expected migrated detail file to exist: %v", err)
|
| 349 |
+
}
|
| 350 |
+
}
|
| 351 |
+
|
| 352 |
+
func TestStoreLegacyMigrationBestEffortWhenRewriteFails(t *testing.T) {
|
| 353 |
+
path := filepath.Join(t.TempDir(), "chat_history.json")
|
| 354 |
+
longID := "chat_" + strings.Repeat("x", 320)
|
| 355 |
+
legacy := legacyFile{
|
| 356 |
+
Version: 1,
|
| 357 |
+
Limit: 20,
|
| 358 |
+
Items: []Entry{{
|
| 359 |
+
ID: longID,
|
| 360 |
+
CreatedAt: 1,
|
| 361 |
+
UpdatedAt: 2,
|
| 362 |
+
Status: "success",
|
| 363 |
+
UserInput: "hello",
|
| 364 |
+
Content: "world",
|
| 365 |
+
}},
|
| 366 |
+
}
|
| 367 |
+
body, err := json.MarshalIndent(legacy, "", " ")
|
| 368 |
+
if err != nil {
|
| 369 |
+
t.Fatalf("marshal legacy file failed: %v", err)
|
| 370 |
+
}
|
| 371 |
+
if err := os.WriteFile(path, body, 0o644); err != nil {
|
| 372 |
+
t.Fatalf("write legacy file failed: %v", err)
|
| 373 |
+
}
|
| 374 |
+
|
| 375 |
+
store := New(path)
|
| 376 |
+
if err := store.Err(); err != nil {
|
| 377 |
+
t.Fatalf("expected store to stay usable after migration writeback failure, got %v", err)
|
| 378 |
+
}
|
| 379 |
+
if !store.Enabled() {
|
| 380 |
+
t.Fatal("expected store to remain enabled after best-effort migration")
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
snapshot, err := store.Snapshot()
|
| 384 |
+
if err != nil {
|
| 385 |
+
t.Fatalf("snapshot failed: %v", err)
|
| 386 |
+
}
|
| 387 |
+
if len(snapshot.Items) != 1 || snapshot.Items[0].ID != longID {
|
| 388 |
+
t.Fatalf("unexpected snapshot after best-effort migration: %#v", snapshot.Items)
|
| 389 |
+
}
|
| 390 |
+
full, err := store.Get(longID)
|
| 391 |
+
if err != nil {
|
| 392 |
+
t.Fatalf("get migrated detail failed: %v", err)
|
| 393 |
+
}
|
| 394 |
+
if full.Content != "world" {
|
| 395 |
+
t.Fatalf("expected migrated content to stay in memory, got %#v", full)
|
| 396 |
+
}
|
| 397 |
+
if _, statErr := os.Stat(filepath.Join(store.DetailDir(), longID+".json")); statErr == nil {
|
| 398 |
+
t.Fatal("expected detail write to fail for overlong legacy id")
|
| 399 |
+
}
|
| 400 |
+
}
|
| 401 |
+
|
| 402 |
+
func TestStoreTransientPersistenceFailureDoesNotLatch(t *testing.T) {
|
| 403 |
+
path := filepath.Join(t.TempDir(), "chat_history.json")
|
| 404 |
+
store := New(path)
|
| 405 |
+
|
| 406 |
+
first, err := store.Start(StartParams{UserInput: "first"})
|
| 407 |
+
if err != nil {
|
| 408 |
+
t.Fatalf("start first failed: %v", err)
|
| 409 |
+
}
|
| 410 |
+
restore := blockDetailDir(t, store.DetailDir())
|
| 411 |
+
t.Cleanup(restore)
|
| 412 |
+
|
| 413 |
+
blocked, err := store.Start(StartParams{UserInput: "blocked"})
|
| 414 |
+
if err == nil {
|
| 415 |
+
t.Fatalf("expected start failure while detail dir is blocked")
|
| 416 |
+
}
|
| 417 |
+
if blocked.ID == "" {
|
| 418 |
+
t.Fatalf("expected in-memory entry from failed start")
|
| 419 |
+
}
|
| 420 |
+
if err := store.Err(); err != nil {
|
| 421 |
+
t.Fatalf("transient start failure should not latch store error: %v", err)
|
| 422 |
+
}
|
| 423 |
+
if _, err := store.Update(first.ID, UpdateParams{Status: "success", Content: "one", Completed: true}); err == nil {
|
| 424 |
+
t.Fatalf("expected update failure while detail dir is blocked")
|
| 425 |
+
}
|
| 426 |
+
if err := store.Err(); err != nil {
|
| 427 |
+
t.Fatalf("transient update failure should not latch store error: %v", err)
|
| 428 |
+
}
|
| 429 |
+
|
| 430 |
+
restore()
|
| 431 |
+
|
| 432 |
+
if _, err := store.Update(blocked.ID, UpdateParams{Status: "success", Content: "two", Completed: true}); err != nil {
|
| 433 |
+
t.Fatalf("update after restore failed: %v", err)
|
| 434 |
+
}
|
| 435 |
+
if _, err := store.Start(StartParams{UserInput: "later"}); err != nil {
|
| 436 |
+
t.Fatalf("start after restore failed: %v", err)
|
| 437 |
+
}
|
| 438 |
+
full, err := store.Get(blocked.ID)
|
| 439 |
+
if err != nil {
|
| 440 |
+
t.Fatalf("get restored entry failed: %v", err)
|
| 441 |
+
}
|
| 442 |
+
if full.Content != "two" || full.Status != "success" {
|
| 443 |
+
t.Fatalf("expected restored entry persisted, got %#v", full)
|
| 444 |
+
}
|
| 445 |
+
}
|
| 446 |
+
|
| 447 |
+
func TestStoreWritesOnlyChangedDetailFiles(t *testing.T) {
|
| 448 |
+
path := filepath.Join(t.TempDir(), "chat_history.json")
|
| 449 |
+
store := New(path)
|
| 450 |
+
|
| 451 |
+
first, err := store.Start(StartParams{UserInput: "one"})
|
| 452 |
+
if err != nil {
|
| 453 |
+
t.Fatalf("start first failed: %v", err)
|
| 454 |
+
}
|
| 455 |
+
if _, err := store.Update(first.ID, UpdateParams{Status: "success", Content: "first", Completed: true}); err != nil {
|
| 456 |
+
t.Fatalf("update first failed: %v", err)
|
| 457 |
+
}
|
| 458 |
+
second, err := store.Start(StartParams{UserInput: "two"})
|
| 459 |
+
if err != nil {
|
| 460 |
+
t.Fatalf("start second failed: %v", err)
|
| 461 |
+
}
|
| 462 |
+
if _, err := store.Update(second.ID, UpdateParams{Status: "success", Content: "second", Completed: true}); err != nil {
|
| 463 |
+
t.Fatalf("update second failed: %v", err)
|
| 464 |
+
}
|
| 465 |
+
|
| 466 |
+
firstPath := filepath.Join(store.DetailDir(), first.ID+".json")
|
| 467 |
+
secondPath := filepath.Join(store.DetailDir(), second.ID+".json")
|
| 468 |
+
beforeFirst, err := os.ReadFile(firstPath)
|
| 469 |
+
if err != nil {
|
| 470 |
+
t.Fatalf("read first detail before update failed: %v", err)
|
| 471 |
+
}
|
| 472 |
+
beforeSecond, err := os.ReadFile(secondPath)
|
| 473 |
+
if err != nil {
|
| 474 |
+
t.Fatalf("read second detail before update failed: %v", err)
|
| 475 |
+
}
|
| 476 |
+
|
| 477 |
+
if _, err := store.Update(first.ID, UpdateParams{Status: "success", Content: "first-updated", Completed: true}); err != nil {
|
| 478 |
+
t.Fatalf("update first again failed: %v", err)
|
| 479 |
+
}
|
| 480 |
+
|
| 481 |
+
afterFirst, err := os.ReadFile(firstPath)
|
| 482 |
+
if err != nil {
|
| 483 |
+
t.Fatalf("read first detail after update failed: %v", err)
|
| 484 |
+
}
|
| 485 |
+
afterSecond, err := os.ReadFile(secondPath)
|
| 486 |
+
if err != nil {
|
| 487 |
+
t.Fatalf("read second detail after update failed: %v", err)
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
if bytes.Equal(beforeFirst, afterFirst) {
|
| 491 |
+
t.Fatalf("expected first detail file to change after update")
|
| 492 |
+
}
|
| 493 |
+
if !bytes.Equal(beforeSecond, afterSecond) {
|
| 494 |
+
t.Fatalf("expected untouched detail file to remain byte-identical")
|
| 495 |
+
}
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
func TestStoreOrdersByCreationTimeNotStreamingUpdates(t *testing.T) {
|
| 499 |
+
path := filepath.Join(t.TempDir(), "chat_history.json")
|
| 500 |
+
store := New(path)
|
| 501 |
+
|
| 502 |
+
first, err := store.Start(StartParams{UserInput: "first"})
|
| 503 |
+
if err != nil {
|
| 504 |
+
t.Fatalf("start first failed: %v", err)
|
| 505 |
+
}
|
| 506 |
+
time.Sleep(time.Millisecond)
|
| 507 |
+
second, err := store.Start(StartParams{UserInput: "second"})
|
| 508 |
+
if err != nil {
|
| 509 |
+
t.Fatalf("start second failed: %v", err)
|
| 510 |
+
}
|
| 511 |
+
time.Sleep(time.Millisecond)
|
| 512 |
+
if _, err := store.Update(first.ID, UpdateParams{Status: "streaming", Content: "still running"}); err != nil {
|
| 513 |
+
t.Fatalf("update first failed: %v", err)
|
| 514 |
+
}
|
| 515 |
+
|
| 516 |
+
snapshot, err := store.Snapshot()
|
| 517 |
+
if err != nil {
|
| 518 |
+
t.Fatalf("snapshot failed: %v", err)
|
| 519 |
+
}
|
| 520 |
+
if len(snapshot.Items) != 2 {
|
| 521 |
+
t.Fatalf("expected two items, got %#v", snapshot.Items)
|
| 522 |
+
}
|
| 523 |
+
if snapshot.Items[0].ID != second.ID || snapshot.Items[1].ID != first.ID {
|
| 524 |
+
t.Fatalf("expected creation-time order to stay stable, got %#v", snapshot.Items)
|
| 525 |
+
}
|
| 526 |
+
}
|
| 527 |
+
|
| 528 |
+
func TestUpdatePreservesContentWhenNewContentIsEmpty(t *testing.T) {
|
| 529 |
+
path := filepath.Join(t.TempDir(), "chat_history.json")
|
| 530 |
+
store := New(path)
|
| 531 |
+
|
| 532 |
+
started, err := store.Start(StartParams{
|
| 533 |
+
CallerID: "caller:abc",
|
| 534 |
+
Model: "deepseek-v4-flash",
|
| 535 |
+
Stream: true,
|
| 536 |
+
UserInput: "hello",
|
| 537 |
+
})
|
| 538 |
+
if err != nil {
|
| 539 |
+
t.Fatalf("start entry failed: %v", err)
|
| 540 |
+
}
|
| 541 |
+
|
| 542 |
+
if _, err := store.Update(started.ID, UpdateParams{
|
| 543 |
+
Status: "streaming",
|
| 544 |
+
ReasoningContent: "let me think",
|
| 545 |
+
Content: "I'll help you with that.",
|
| 546 |
+
}); err != nil {
|
| 547 |
+
t.Fatalf("progress update failed: %v", err)
|
| 548 |
+
}
|
| 549 |
+
|
| 550 |
+
updated, err := store.Update(started.ID, UpdateParams{
|
| 551 |
+
Status: "success",
|
| 552 |
+
Content: "",
|
| 553 |
+
Completed: true,
|
| 554 |
+
})
|
| 555 |
+
if err != nil {
|
| 556 |
+
t.Fatalf("success update failed: %v", err)
|
| 557 |
+
}
|
| 558 |
+
|
| 559 |
+
if updated.Content != "I'll help you with that." {
|
| 560 |
+
t.Fatalf("expected content to be preserved, got %q", updated.Content)
|
| 561 |
+
}
|
| 562 |
+
if updated.ReasoningContent != "let me think" {
|
| 563 |
+
t.Fatalf("expected reasoning content to be preserved, got %q", updated.ReasoningContent)
|
| 564 |
+
}
|
| 565 |
+
|
| 566 |
+
full, err := store.Get(started.ID)
|
| 567 |
+
if err != nil {
|
| 568 |
+
t.Fatalf("get entry failed: %v", err)
|
| 569 |
+
}
|
| 570 |
+
if full.Content != "I'll help you with that." {
|
| 571 |
+
t.Fatalf("expected persisted content to be preserved, got %q", full.Content)
|
| 572 |
+
}
|
| 573 |
+
if full.ReasoningContent != "let me think" {
|
| 574 |
+
t.Fatalf("expected persisted reasoning content to be preserved, got %q", full.ReasoningContent)
|
| 575 |
+
}
|
| 576 |
+
}
|
| 577 |
+
|
| 578 |
+
func TestUpdateAllowsSettingContentFromEmpty(t *testing.T) {
|
| 579 |
+
path := filepath.Join(t.TempDir(), "chat_history.json")
|
| 580 |
+
store := New(path)
|
| 581 |
+
|
| 582 |
+
started, err := store.Start(StartParams{
|
| 583 |
+
CallerID: "caller:abc",
|
| 584 |
+
Model: "deepseek-v4-flash",
|
| 585 |
+
Stream: true,
|
| 586 |
+
UserInput: "hello",
|
| 587 |
+
})
|
| 588 |
+
if err != nil {
|
| 589 |
+
t.Fatalf("start entry failed: %v", err)
|
| 590 |
+
}
|
| 591 |
+
|
| 592 |
+
updated, err := store.Update(started.ID, UpdateParams{
|
| 593 |
+
Status: "success",
|
| 594 |
+
Content: "final answer",
|
| 595 |
+
})
|
| 596 |
+
if err != nil {
|
| 597 |
+
t.Fatalf("update failed: %v", err)
|
| 598 |
+
}
|
| 599 |
+
if updated.Content != "final answer" {
|
| 600 |
+
t.Fatalf("expected content to be set, got %q", updated.Content)
|
| 601 |
+
}
|
| 602 |
+
}
|
| 603 |
+
|
| 604 |
+
func TestUpdateAllowsOverwritingContentWithNewValue(t *testing.T) {
|
| 605 |
+
path := filepath.Join(t.TempDir(), "chat_history.json")
|
| 606 |
+
store := New(path)
|
| 607 |
+
|
| 608 |
+
started, err := store.Start(StartParams{
|
| 609 |
+
CallerID: "caller:abc",
|
| 610 |
+
Model: "deepseek-v4-flash",
|
| 611 |
+
Stream: true,
|
| 612 |
+
UserInput: "hello",
|
| 613 |
+
})
|
| 614 |
+
if err != nil {
|
| 615 |
+
t.Fatalf("start entry failed: %v", err)
|
| 616 |
+
}
|
| 617 |
+
|
| 618 |
+
if _, err := store.Update(started.ID, UpdateParams{
|
| 619 |
+
Status: "streaming",
|
| 620 |
+
Content: "partial",
|
| 621 |
+
}); err != nil {
|
| 622 |
+
t.Fatalf("first update failed: %v", err)
|
| 623 |
+
}
|
| 624 |
+
|
| 625 |
+
updated, err := store.Update(started.ID, UpdateParams{
|
| 626 |
+
Status: "success",
|
| 627 |
+
Content: "final answer",
|
| 628 |
+
})
|
| 629 |
+
if err != nil {
|
| 630 |
+
t.Fatalf("second update failed: %v", err)
|
| 631 |
+
}
|
| 632 |
+
if updated.Content != "final answer" {
|
| 633 |
+
t.Fatalf("expected content to be overwritten, got %q", updated.Content)
|
| 634 |
+
}
|
| 635 |
+
}
|
internal/claudeconv/convert.go
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package claudeconv
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"strings"
|
| 5 |
+
|
| 6 |
+
"ds2api/internal/config"
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
func ConvertClaudeToDeepSeek(claudeReq map[string]any, aliasProvider config.ModelAliasReader, defaultClaudeModel string) map[string]any {
|
| 10 |
+
messages, _ := claudeReq["messages"].([]any)
|
| 11 |
+
model, _ := claudeReq["model"].(string)
|
| 12 |
+
if model == "" {
|
| 13 |
+
model = defaultClaudeModel
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
dsModel, ok := config.ResolveModel(aliasProvider, model)
|
| 17 |
+
if !ok || strings.TrimSpace(dsModel) == "" {
|
| 18 |
+
dsModel = "deepseek-v4-flash"
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
convertedMessages := make([]any, 0, len(messages)+1)
|
| 22 |
+
if system, ok := claudeReq["system"].(string); ok && system != "" {
|
| 23 |
+
convertedMessages = append(convertedMessages, map[string]any{"role": "system", "content": system})
|
| 24 |
+
}
|
| 25 |
+
convertedMessages = append(convertedMessages, messages...)
|
| 26 |
+
|
| 27 |
+
out := map[string]any{"model": dsModel, "messages": convertedMessages}
|
| 28 |
+
for _, k := range []string{"temperature", "top_p", "stream"} {
|
| 29 |
+
if v, ok := claudeReq[k]; ok {
|
| 30 |
+
out[k] = v
|
| 31 |
+
}
|
| 32 |
+
}
|
| 33 |
+
if stopSeq, ok := claudeReq["stop_sequences"]; ok {
|
| 34 |
+
out["stop"] = stopSeq
|
| 35 |
+
}
|
| 36 |
+
return out
|
| 37 |
+
}
|