Compare commits
21
Commits
android-v1.0.0
...
v3.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
93498d13c9 | ||
|
|
0801dcac51 | ||
|
|
77b0d75beb | ||
|
|
17a1cf0e9a | ||
|
|
27fa16b1a3 | ||
|
|
f02d6bcd20 | ||
|
|
4d1ae35749 | ||
|
|
34d1e1c103 | ||
|
|
9e32a1cac7 | ||
|
|
3f4a616b17 | ||
|
|
476b5d9ffd | ||
|
|
6a9718d3fa | ||
|
|
8c1ecc0874 | ||
|
|
ef98473116 | ||
|
|
805e5704dd | ||
|
|
321ee7abf7 | ||
|
|
38f3a042ca | ||
|
|
11804fc017 | ||
|
|
0f843f8b7a | ||
|
|
c7c6af6b93 | ||
|
|
3b8f878623 |
@@ -1,81 +0,0 @@
|
||||
name: Android TWA APK
|
||||
|
||||
# 把线上站点(https://zhanbu.lufei.de)打成一个 Android APK:
|
||||
# - 用 Chrome 内核(Trusted Web Activity)跑,全屏无地址栏
|
||||
# - 站点更新 = App 更新,不需要重新发版
|
||||
# - 域名归属由 https://zhanbu.lufei.de/.well-known/assetlinks.json 校验
|
||||
#
|
||||
# 手动触发:Actions → Android TWA APK → Run workflow;产物在 Artifacts。
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
tags:
|
||||
- 'android-*'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '17'
|
||||
|
||||
# 直接用 runner 预装的 Android SDK(setup-android@v3 会去装已下线的 `tools` 包而失败)
|
||||
- name: Install SDK packages
|
||||
run: |
|
||||
set -e
|
||||
SDK="${ANDROID_HOME:-/usr/local/lib/android/sdk}"
|
||||
echo "ANDROID_HOME=$SDK"
|
||||
SDKMANAGER="$(command -v sdkmanager || true)"
|
||||
if [ -z "$SDKMANAGER" ]; then
|
||||
SDKMANAGER="$(find "$SDK" -name sdkmanager -type f | sort | tail -1)"
|
||||
fi
|
||||
echo "sdkmanager=$SDKMANAGER"
|
||||
yes | "$SDKMANAGER" --licenses > /dev/null || true
|
||||
"$SDKMANAGER" --install "platforms;android-34" "build-tools;34.0.0" "platform-tools"
|
||||
echo "$SDK/platform-tools" >> "$GITHUB_PATH"
|
||||
|
||||
- name: Set up Gradle
|
||||
uses: gradle/actions/setup-gradle@v4
|
||||
with:
|
||||
gradle-version: '8.7'
|
||||
|
||||
- name: Decode signing keystore
|
||||
env:
|
||||
KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
|
||||
run: |
|
||||
if [ -z "$KEYSTORE_BASE64" ]; then
|
||||
echo "缺少 secrets.ANDROID_KEYSTORE_BASE64(keystore 的 base64)" >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '%s' "$KEYSTORE_BASE64" | base64 -d > android/app/keystore.jks
|
||||
|
||||
- name: Build release APK
|
||||
working-directory: android
|
||||
env:
|
||||
KEYSTORE_PATH: keystore.jks
|
||||
KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
|
||||
KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
|
||||
KEY_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
|
||||
run: gradle assembleRelease --no-daemon --stacktrace
|
||||
|
||||
- name: Show APK info
|
||||
working-directory: android
|
||||
run: |
|
||||
ls -lh app/build/outputs/apk/release/
|
||||
$ANDROID_HOME/build-tools/34.0.0/aapt2 dump badging app/build/outputs/apk/release/app-release.apk | head -5 || true
|
||||
|
||||
- name: Upload APK
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: yehe-liuyao-twa
|
||||
path: android/app/build/outputs/apk/release/*.apk
|
||||
if-no-files-found: error
|
||||
+1
-2
@@ -19,5 +19,4 @@ __pycache__
|
||||
|
||||
.llm.local
|
||||
|
||||
.android/
|
||||
.scratch-android.json
|
||||
|
||||
|
||||
@@ -91,8 +91,8 @@
|
||||
- 解卦 prompt:400–550 字,硬上限 600;四段 = 取用 / 盘面 / 走势 / 应期。
|
||||
- 大模型 key **只存用户本机 localStorage**,随请求体转发一次,不落库、不写日志、不回显;
|
||||
自建部署的 env 兜底 key 只放 `.llm.local`(已 gitignore),不进仓库、不进 D1。
|
||||
- 不得修改 `C:\Users\奇哥\Desktop\bazi-web` 源码(只允许读取 / 复制)。
|
||||
- 部署目标是 Cloudflare Workers,但**暂不部署**;`npm run check:portability` 必须保持通过。
|
||||
- 不得修改 `bazi-web` 源码(只允许读取 / 复制)。
|
||||
- 已部署到 Cloudflare Workers:<https://zhanbu.lufei.de>(部署步骤已写进 `README.md`);`npm run check:portability` 必须保持通过。
|
||||
|
||||
## 命令
|
||||
|
||||
@@ -105,12 +105,14 @@ npm run build && npm run build:vinext
|
||||
|
||||
重启 3001:kill 占用端口的 PID 后 `rm -f .vinext/dev/lock.json`。
|
||||
|
||||
UI 实测脚本写在 `C:\Users\奇哥\Desktop\bazi-web\scratch\*.mjs`(那里才有 `playwright-core`),
|
||||
UI 实测脚本写在 `bazi-web/scratch/*.mjs`(那里才有 `playwright-core`),
|
||||
浏览器 `C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`,加 `--no-proxy-server`;
|
||||
时间输入框约 1s 后才自动填入,等待 ≥1500ms 再断言。
|
||||
|
||||
## 下一步(按序)
|
||||
|
||||
> 已上线,线上问题优先修:手机端体验、案例页内容扩充、古籍原文校核。
|
||||
|
||||
1. **S2 盘面收尾**:字号线宽 / 神煞字号(看板 12.5 vs 12)统一 —— 版式不可动,只能微调字重。
|
||||
2. **`/classics` 填入经校核的周易原文**(来源与版本必须标注,未核校就保持空态)。
|
||||
3. **部署准备**:Node ≥26.12、`cf auth login`、secret 注入实测(仍不要真部署)。
|
||||
|
||||
@@ -1,165 +1,294 @@
|
||||
# 易林寻踪 · 六爻确定性排盘
|
||||
# 野鹤六爻 · 六爻确定性排盘
|
||||
|
||||
从 [bazi-web](https://github.com/woniu336/bazi-web) 抽出的六爻排盘工具,单进程跑:
|
||||
三钱摇卦 · 纳甲装卦 · 世应六亲 · 十三神煞 · 四段解卦,附《增删卜易》卦例 100 例研读。
|
||||
排盘由确定性引擎计算,解读依盘面事实展开;大模型由用户自带(key 只存本机浏览器)。
|
||||
|
||||
| 工具 | 保留 | 移除 |
|
||||
- 线上:<https://zhanbu.lufei.de>
|
||||
- 技术栈:Next.js 16(App Router)+ vinext / Cloudflare Workers + D1 + PWA
|
||||
|
||||
| 页面 | 内容 |
|
||||
| --- | --- |
|
||||
| `/` 起卦 | 所问 / 性别 / 时间 + 三钱摇卦(Web Crypto)· 可手动指定本卦变卦 · 移动端底部悬浮起卦 |
|
||||
| `/liuyao` 排盘 | 纳甲、安世应、定六亲、旬空、伏神、六神、月卦身、十三神煞;四段解卦(取用 / 盘面 / 走势 / 应期) |
|
||||
| `/examples` 案例 | 《增删卜易》卦例 100 例:古筮知识 / 原注 / 用神·吉凶·应期;每例可一键还原盘面 |
|
||||
| `/cases` 历史排盘 | 只存起卦输入,打开时由引擎重排同一卦 |
|
||||
| `/classics` 古籍 | 周易经传与象数文献入口(原文核校后逐步加入) |
|
||||
|
||||
> 本文即是**部署文档**:从零把本项目部署到 Cloudflare Workers + D1 + 自有域名。
|
||||
> 更深的取舍与约束见 [docs/cloudflare.md](docs/cloudflare.md),开发交接见 [NEXT.md](NEXT.md)。
|
||||
|
||||
---
|
||||
|
||||
## 0. 先决条件
|
||||
|
||||
| 项 | 要求 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| **首页**(`/`) | 求测事项 / 性别 / 婚否 / 时间 + 三钱摇卦;可手动指定本卦/变卦 | 起卦 UI 不藏求测人与时间信息 |
|
||||
| **六爻**(`/liuyao`) | 纳甲装卦、安世应、定六亲、旬空、伏神、六神、月卦身、十三神煞;可请求禅意解读 | 模型不重排盘,只解释确定性事实 |
|
||||
| **案例**(`/examples`) | 《增删卜易》卦例 100 例:古筮知识 / 原注 / 用神·吉凶·应期要点;每例可一键还原盘面 | 只摘录原文,不作现成断语 |
|
||||
| **易学典籍**(`/classics`) | 周易经传与象数文献入口 / 分类框架 | 原文与版本核校后逐步加入 |
|
||||
| Node.js | ≥ 20(推荐 22) | 构建与 CLI |
|
||||
| Cloudflare 账号 | 免费即可 | Workers / D1 / 自定义域名都在免费额度内 |
|
||||
| 域名 | 已托管在同一个 CF 账号 | 否则无法用 Custom Domain 绑定 |
|
||||
| `cf` CLI | `npm i -g cf` | 新版官方 CLI(也可以用 `npx cf`) |
|
||||
|
||||
排盘由确定性引擎负责;解读依盘面事实展开,不重排、不改写盘面。问句用于表达所问与解读上下文,不参与物理排盘计算。
|
||||
```bash
|
||||
node -v # v22.x
|
||||
npm i -g cf
|
||||
cf --version
|
||||
```
|
||||
|
||||
## 起卦首页与视觉
|
||||
|
||||
首页参考用户提供的 `设计参考.txt` 与设计图:顶部导航「六爻 / 古籍 / 历史排盘」、
|
||||
淡墨山水、宣纸求测笺与真铜钱摇卦。页首只保留「取象于天地,观变于阴阳」,标题区较短。
|
||||
|
||||
- 求测事项、性别、婚否、时间都在明面;婚否只作落款记录。
|
||||
- 三枚铜钱用 `coin-4`(字)/ `coin-3`(背)真图,保持原设计尺寸(移动约 74px / 宽屏 84px);
|
||||
使用 2x/3x sourceSet,Web Crypto 掷币,动画落定后提交结果。
|
||||
- 爻象生成台排在铜钱下方;手动指定为可输入的六十四卦下拉(全名/简称均可搜),动爻自动比对。
|
||||
- 手机单列,PC 使用更宽的居中宣纸卡;三枚铜钱、字段、爻象保持在同一中轴。
|
||||
- `/classics` 已预留周易经传与易学典籍入口,当前是分类/来源校核空态,原文按来源与版本核验后再加入。
|
||||
|
||||
> 正在做的下一批任务与交接上下文:见 [NEXT.md](NEXT.md)。
|
||||
|
||||
## 跑起来
|
||||
本地先跑通一次(可选但强烈建议):
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm run dev # 前台:http://localhost:3000
|
||||
npm run dev:bg # 后台:日志写 logs/dev.out.log,按端口重启旧进程
|
||||
npm test # 引擎自证 + 差分对齐(见下)
|
||||
|
||||
# Cloudflare Workers 回路(分支 spike/vinext 验证通过;M1 起成为部署目标)
|
||||
npm run dev:vinext # vite dev(workerd,带本地 D1 绑定)
|
||||
npm run build:vinext # vite build
|
||||
npm run start:vinext # vite preview(生产包本地验证)
|
||||
npm run deploy:vinext # 需要先 cf auth login
|
||||
npm run dev:vinext # http://localhost:3001,workerd + 本地 D1
|
||||
npm run check # schema + portability + 测试
|
||||
```
|
||||
|
||||
`npm run dev/build` 走 `scripts/next.mjs`:先清掉宿主进程可能泄漏进来的
|
||||
`__NEXT_PRIVATE_STANDALONE_CONFIG` 等私有变量再启动 Next。不清的话,
|
||||
这些变量会被当成真实配置读入(distDir 被改写、outputFileTracingRoot 指到不存在的路径),
|
||||
表现为 dev 起不来或 build 报 `TypeError: generate is not a function`。
|
||||
---
|
||||
|
||||
手机用局域网 IP 打开时,`next.config.ts` 会把本机所有非回环 IPv4 放进
|
||||
`allowedDevOrigins`。否则 Next 16 会拦掉 `/_next/static/chunks/*.js`,
|
||||
页面看着完整、按钮全部不动(React 没 hydration)。
|
||||
|
||||
## 目录
|
||||
|
||||
```
|
||||
app/ 首页 / 六爻页 / 历史排盘 / 古籍
|
||||
components/liuyao/ 六爻:LiuyaoView(起卦表单)· CastWorkbench(三钱/大衍)· ManualCast · HexagramBoard(古法卦单)
|
||||
lib/liuyao/najia.ts 六爻确定性排盘引擎(core.py 的逐条移植)
|
||||
lib/liuyao/board-view.ts 引擎结果 → 盘面视图数据 + 复制文本
|
||||
lib/liuyao/ganzhi.ts 起卦时刻 → 四柱干支
|
||||
lib/hexagram/ 六爻几何与 64 卦查表(矢量爻象用)
|
||||
tests/ 差分基准与引擎自证
|
||||
```
|
||||
|
||||
## 解卦与大模型设置
|
||||
|
||||
盘面下方有「解 卦」入口:只把**盘面事实**(含十三神煞与卦爻辞)发到本站 `/api/read`,
|
||||
prompt 在服务端拼装,流式返回四段式解读(取用 / 盘面 / 走势 / 应期)。
|
||||
UI 取纸上批注的克制排版;可展开「所呈事实」核对到底发送了什么。
|
||||
|
||||
**大模型由用户自带**,全站只有一处设置:右上角「设置」。
|
||||
|
||||
- 配置**只保存在本机浏览器**(`localStorage['liuyao.llm.v1']`),不上传、不入库;
|
||||
每次解卦随请求体带上,服务端只做一次转发,不落库、不写日志。
|
||||
- 通用「OpenAI 兼容」协议:预置 DeepSeek / OpenAI / Moonshot / 智谱 / 通义 / OpenRouter /
|
||||
SiliconFlow / Ollama(本机,可无 key),也可自定义任意网关(填到 `/v1` 为止)。
|
||||
- 「测试连接」会打一次极短请求,直接看到上游返回或报错。
|
||||
- 没配时会明确提示去「设置」,不会假装解读。
|
||||
- 自建/私人部署仍可用服务端环境变量兜底:`LLM_API_KEY`(可选 `LLM_BASE_URL` / `LLM_MODEL` /
|
||||
`LLM_THINKING` / `LLM_REASONING_EFFORT`);本地密钥放 `.llm.local`(已 gitignore)。
|
||||
|
||||
## 六爻盘面版式
|
||||
|
||||
`components/liuyao/HexagramBoard.tsx` 是 bazi-web `components/zhanbu/MobileHexagramPoster.tsx`
|
||||
embedded 分支的逐行搬运,只换数据来源:
|
||||
|
||||
- 占问 + 男占/女占落款、时空看板(公历 / 月建+日辰 / 旬空 / 十三神煞)
|
||||
- 双卦对瞻表头(本卦 · 变卦,附归魂/游魂/六冲/六合)
|
||||
- 定宽栅格:六神 32 / 本卦纳甲 68 / 爻画 46 / 世应 18 / 动爻 22 / 变卦纳甲 68 / 变爻画 46 / 动变标签 52
|
||||
- 伏神就地引出 `↑伏神: 妻财子水`
|
||||
|
||||
版式未靠目测:同一份盘面数据分别交给原组件与本仓库组件渲染 4 类卦例
|
||||
(初爻动附伏神 / 静卦 / 六爻全动 / 混杂多动),逐元素比对 DOM 结构、文本、相对几何与
|
||||
字号/字重/颜色,结果完全一致。问句与性别只作落款,不参与计算。
|
||||
|
||||
|
||||
## 六爻引擎的验证方式
|
||||
|
||||
`lib/liuyao/najia.ts` 是对 bazi-web `src/engine/core.py::HexagramEngine` 的逐条移植。
|
||||
为了不靠"看起来对",用原引擎生成差分基准再逐案比对:
|
||||
## 1. 登录 Cloudflare
|
||||
|
||||
```bash
|
||||
# 基准已提交在 tests/fixtures/python-baseline.json(4696 案,SHA-256 指纹)
|
||||
python tests/generate_python_baseline.py # 需要 bazi-web 在同级目录;仅重建基准时用
|
||||
npm test
|
||||
cf auth login
|
||||
```
|
||||
|
||||
- 4096 种三钱投掷组合(固定丙午年 / 申月 / 己丑日 / 申时)
|
||||
- 600 组随机年/月/日/时 + 投掷(覆盖十神起例、神煞、旬空全干支)
|
||||
- 比对字段:本卦/变卦名、动爻、旬空、月卦身、驿马桃花禄神贵人、
|
||||
六爻的纳甲/六亲/世应/六神/伏神(含飞伏生克描述)/动爻变出
|
||||
设备码流程:终端会给出一个链接和验证码,浏览器打开
|
||||
<https://dash.cloudflare.com/oauth2/device/verify> 输入验证码确认即可(5 分钟内有效)。
|
||||
|
||||
新增的「天医(月建前一位)」「文昌(依日干)」不参与差分(原 core.py 没有),
|
||||
由 `tests/liuyao-engine.test.ts` 单独断言。
|
||||
```bash
|
||||
cf auth whoami # 确认已登录
|
||||
cf auth list # 查看本地 profile
|
||||
```
|
||||
|
||||
## 服务端边界(为 Cloudflare 预留)
|
||||
> CI 或不想用浏览器授权时,也可以在环境变量里放 `CLOUDFLARE_API_TOKEN`(需要 Workers / D1 / Zone 权限)。
|
||||
|
||||
- `lib/store/`:卦例存储接口(异步)—— 本地 localStorage / 远端 D1 两种实现。
|
||||
`/cases` 里可收藏、打开复原(只存起卦输入,盘面由引擎重算)、删除。
|
||||
接上 D1 后按**匿名设备 Cookie** 归属(`ly_device`),旧本地卦例首次访问自动迁移;
|
||||
换浏览器/清 Cookie 会得到新的卦例夹(跨设备需以后接账号)。
|
||||
- `lib/readings/`:解卦**事实契约**(客户端只发盘面事实与问句)。
|
||||
`app/api/read/route.ts` 是服务端流式代理:prompt 在服务端拼(`route` 同目录 `prompt.ts`),
|
||||
大模型配置由请求体带上(`lib/llm/server.ts` 校验 + 拦内网地址),没配时明确返回 501。
|
||||
- `lib/llm/`:用户侧大模型设置(供应商预设、校验、localStorage 读写)与同源转发校验。
|
||||
---
|
||||
|
||||
## 案例(`/examples`)
|
||||
## 2. 建 D1 数据库
|
||||
|
||||
`public/data/zengshan-cases.json` 由 `scripts/extract-zengshan-cases.mjs` 从朱辰彬《增删卜易卦例初探》
|
||||
整理文本抽取(前 100 例):例号 / 古筮知识 / 占问 / 干支旬空 / 本卦变卦 / 原注 / 用神·吉凶·应期要点,
|
||||
长段落截断,不改写。
|
||||
```bash
|
||||
cf d1 create --name liuyao-db
|
||||
```
|
||||
|
||||
- 每例的「排盘」由卦名反推六次投掷(6/7/8/9),再取一个与古例**同月建、同日辰**的公历时刻
|
||||
(古例不记年,脚本在 1990–2026 里找最早的同组合日),点开即是与原例一致的盘面。
|
||||
- 原例缺月建或干支的极少数条目不给排盘入口,页面上注明原因。
|
||||
- 版式:桌面端右侧吸顶侧栏(检索 / 六冲·六合·游魂·归魂 快筛 / 页码 / 读法 / 配色),
|
||||
每例一张卡(卦盘独立成块、原注按句断段、三条断语各成一卡);配色可切「暖纸 / 冷白」,记在本机。
|
||||
- 重新生成:`node scripts/extract-zengshan-cases.mjs <源txt> 100`。
|
||||
- `scripts/check-portability.mjs`:`npm run check:portability` 守住 Workers 兼容性
|
||||
(禁 `fs`/`node:*`、`next/image`、`next/font`、锁死 `output: 'export'`)。
|
||||
- 目标与约束、部署触发条件见 [docs/cloudflare.md](docs/cloudflare.md)。
|
||||
会返回一个 `uuid`。**不用手工建表** —— 应用首次访问 `/api/cases` 时会惰性执行
|
||||
`migrations/0001_init.sql`(`CREATE TABLE IF NOT EXISTS cases ...`)。
|
||||
|
||||
## 刻意不做的事
|
||||
想手动建也可以:
|
||||
|
||||
- 盘面上不标用神、不印吉凶判词:断语只出现在「解卦」正文里,不压在确定性盘面上。
|
||||
- 不为个案写特例:引擎只有查表与确定性算法,没有 `if case_id == ...` 之类的补丁。
|
||||
```bash
|
||||
cf d1 query <uuid> --sql "$(cat migrations/0001_init.sql)"
|
||||
cf d1 query <uuid> --sql "SELECT name FROM sqlite_master WHERE type='table'"
|
||||
```
|
||||
|
||||
## 起卦随机源(可核查)
|
||||
> 数据库名必须和 `cloudflare.config.ts` 里的 `bindings.d1({ name: 'liuyao-db' })` 一致。
|
||||
> 部署时 `--provision` 默认开启,D1 不存在会自动创建。
|
||||
|
||||
起卦的每一次投掷都来自 **Web Crypto**(`crypto.getRandomValues`),不存在 `Math.random`:
|
||||
---
|
||||
|
||||
- `lib/liuyao/random.ts`:逐位取 Uint32 最低有效位(2^32 可整除 2,天然无偏);
|
||||
- 环境缺少 Web Crypto 时**直接报错**,不静默回落到 PRNG。
|
||||
- `/design` 页会实时跑 2000 掷并显示字/背占比与爻值偏差,可自行核对。
|
||||
- 测试(`tests/random.test.ts`)钉三件事:每次投掷都真的调用了 `getRandomValues`、
|
||||
大样本分布通过卡方检验、起卦相关源码里不得出现 `Math.random`(注释除外)。
|
||||
## 3. 配置域名与变量
|
||||
|
||||
独立核查(50 万掷):字/背 = 750499 / 749501(字面 50.033%),
|
||||
卡方 字背 0.664(df=1,临界 3.84)、爻值 3.284(df=3,临界 7.81)—— 均通过。
|
||||
部署配置在 `cloudflare.config.ts`(TypeScript,有类型检查,写错字段会当场报错)。
|
||||
|
||||
## 铜钱与布局
|
||||
### 3.1 自定义域名
|
||||
|
||||
- 铜钱照片:`public/images/coin-4.png`(字面)/ `coin-3.png`(背面),
|
||||
`components/liuyao/Coin.tsx` 用 3D `rotateY` 真翻转,落地由结果决定(正面 0°/背面 180°),
|
||||
翻滚中靠静态薄环 + 落地阴影保持"三枚始终可数",不会出现照片转到 90° 而"凭空消失"。
|
||||
- 布局:移动单栏;`lg`(≥1024)起为**案头两页**——左侧起卦与盘面(520px),右侧九宫与解卦(自适应)。
|
||||
用环境变量传,避免把域名写死在仓库里:
|
||||
|
||||
```bash
|
||||
WORKER_DOMAIN=zhanbu.example.com npx cf deploy
|
||||
```
|
||||
|
||||
配置里对应的是 **Custom Domain**(会自动建 DNS 记录 + 证书):
|
||||
|
||||
```ts
|
||||
...(workerDomain ? { domains: [workerDomain] } : {}),
|
||||
```
|
||||
|
||||
> 注意:不要用 `triggers.fetch({ pattern })` 代替 —— 路由不会自动建 DNS 记录,
|
||||
> 会得到「部署成功但域名打不开」。Custom Domain 才是子域名的正确姿势。
|
||||
|
||||
不设 `WORKER_DOMAIN` 就只挂 `*.workers.dev`(首次部署会问一次子域名)。
|
||||
|
||||
### 3.2 运行时变量
|
||||
|
||||
| 变量 | 必需 | 作用 |
|
||||
| --- | --- | --- |
|
||||
| `LLM_ALLOWED_HOSTS` | 有默认值 | 上游域名白名单(逗号分隔后缀)。默认已含 opencode.ai / deepseek.com / api.openai.com / api.moonshot.cn / open.bigmodel.cn / dashscope.aliyuncs.com / openrouter.ai / api.siliconflow.cn |
|
||||
| `LLM_API_KEY` / `LLM_BASE_URL` / `LLM_MODEL` | 否 | 服务端兜底模型(正常不需要:用户在页面「设置」里自带 key) |
|
||||
| `LLM_THINKING` / `LLM_REASONING_EFFORT` | 否 | 兜底模型的思考模式 / 强度 |
|
||||
|
||||
**大模型 key 不需要配到服务端**:用户在右上角「设置」里填,只存自己浏览器的
|
||||
`localStorage['liuyao.llm.v1']`,解卦时随请求体发给 `/api/read`,服务端只转发一次。
|
||||
|
||||
想改白名单,直接传环境变量即可覆盖默认值:
|
||||
|
||||
```bash
|
||||
LLM_ALLOWED_HOSTS=opencode.ai,api.deepseek.com npx cf deploy
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 部署
|
||||
|
||||
```bash
|
||||
WORKER_DOMAIN=zhanbu.example.com npx cf deploy
|
||||
```
|
||||
|
||||
`cf deploy` 会先跑构建(`build:vinext`),再上传静态资源 + Worker。成功输出类似:
|
||||
|
||||
```
|
||||
✨ Success! Uploaded 46 files
|
||||
Total Upload: 1553.77 KiB / gzip: 487.06 KiB
|
||||
Your Worker has access to the following bindings:
|
||||
env.DB (liuyao-db) D1 Database
|
||||
env.ASSETS Assets
|
||||
env.LLM_ALLOWED_HOSTS ("opencode.ai,…") Environment Variable
|
||||
Uploaded liuyao
|
||||
Deployed liuyao triggers
|
||||
zhanbu.example.com (custom domain)
|
||||
◆ Deploy complete
|
||||
```
|
||||
|
||||
只检查不发布(强烈建议首次先跑):
|
||||
|
||||
```bash
|
||||
WORKER_DOMAIN=zhanbu.example.com npx cf deploy --dry-run
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. 上线验收清单
|
||||
|
||||
```bash
|
||||
curl -I https://zhanbu.example.com/ # 200
|
||||
curl -I https://zhanbu.example.com/examples # 200
|
||||
curl -I https://zhanbu.example.com/cases # 200
|
||||
curl -I https://zhanbu.example.com/manifest.webmanifest # 200(PWA)
|
||||
curl -I https://zhanbu.example.com/sw.js # 200(离线壳)
|
||||
curl -I https://zhanbu.example.com/data/zengshan-cases.json # 200(案例数据)
|
||||
```
|
||||
|
||||
接口自检(应分别得到 501 / 403 / 403):
|
||||
|
||||
```bash
|
||||
# 1) 没配模型 → 501
|
||||
curl -s -X POST https://zhanbu.example.com/api/read \
|
||||
-H 'Content-Type: application/json' -d '{"facts":{"kind":"liuyao","lines":[]}}'
|
||||
|
||||
# 2) 跨站 Origin → 403
|
||||
curl -s -X POST https://zhanbu.example.com/api/read \
|
||||
-H 'Content-Type: application/json' -H 'Origin: https://evil.example.com' \
|
||||
-d '{"facts":{"kind":"liuyao","lines":[]}}'
|
||||
|
||||
# 3) 白名单外上游 → 403
|
||||
curl -s -X POST https://zhanbu.example.com/api/read \
|
||||
-H 'Content-Type: application/json' -H 'Origin: https://zhanbu.example.com' \
|
||||
-d '{"facts":{"kind":"liuyao","lines":[]},"llm":{"baseUrl":"https://evil.example.com/v1","model":"x","apiKey":"k"}}'
|
||||
```
|
||||
|
||||
D1 是否就绪:
|
||||
|
||||
```bash
|
||||
cf d1 query <uuid> --sql "SELECT name FROM sqlite_master WHERE type='table'"
|
||||
# 应看到 cases
|
||||
```
|
||||
|
||||
浏览器里再走一遍:起卦 → 排盘 → 设置里填模型 → 测试连接 → 解卦 → 历史排盘能回看。
|
||||
|
||||
---
|
||||
|
||||
## 6. 边缘限流(建议)
|
||||
|
||||
免费套餐的限制:**每个 phase 只能 1 条规则、`period` 只能是 10 秒、不能用 `matches` 运算符**。
|
||||
所以规则只能写成「10 秒 N 次 + 路径包含」。
|
||||
|
||||
```bash
|
||||
# 找到 zone 的 http_ratelimit 规则集
|
||||
cf rulesets list --zone example.com # 取 phase=http_ratelimit 的 id
|
||||
|
||||
# 规则文件(注意 characteristics 必须带 cf.colo.id;mitigation_timeout 只能为 0 或 ≥ period)
|
||||
cat > rl.json <<'EOF'
|
||||
[
|
||||
{
|
||||
"action": "block",
|
||||
"description": "API 限流(10 秒内最多 4 次)",
|
||||
"enabled": true,
|
||||
"expression": "(http.request.uri.path contains \"/api/\")",
|
||||
"ratelimit": {
|
||||
"characteristics": ["ip.src", "cf.colo.id"],
|
||||
"mitigation_timeout": 10,
|
||||
"period": 10,
|
||||
"requests_per_period": 4
|
||||
}
|
||||
}
|
||||
]
|
||||
EOF
|
||||
|
||||
cf rulesets update <ruleset-id> --zone example.com --id <ruleset-id> --rules @rl.json
|
||||
```
|
||||
|
||||
> 应用内还有一层:`/api/read` 8 次/分 + 60 次/时(进程内计数,只在单实例内准确)。
|
||||
> 想要「每分钟 / 每小时」粒度的边缘规则需要 Pro(Advanced Rate Limiting)。
|
||||
|
||||
---
|
||||
|
||||
## 7. 日常更新与回滚
|
||||
|
||||
```bash
|
||||
git pull
|
||||
npm run check # 先本地全绿
|
||||
WORKER_DOMAIN=zhanbu.example.com npx cf deploy # 重新发布(秒级)
|
||||
```
|
||||
|
||||
- **回滚**:`cf workers deployments list liuyao` 找到上一版本,
|
||||
`cf workers deployments rollback liuyao`(或控制台 Workers → Deployments 一键回滚)。
|
||||
- **看日志**:`cf workers tail liuyao` 或控制台 Workers Logs。
|
||||
- **D1 备份**:`cf d1 export <uuid> --output backup.sql`(定期存一份)。
|
||||
|
||||
---
|
||||
|
||||
## 8. 常见坑
|
||||
|
||||
| 现象 | 原因 / 处理 |
|
||||
| --- | --- |
|
||||
| 部署成功但域名 502/000 | 用了 `triggers.fetch` 路由却没 DNS 记录 → 改用 Custom Domain(`domains: [...]`);证书签发需要 1–2 分钟 |
|
||||
| 静态资源 307 循环 | `public/` 下文件名带 `@`(如 `coin-4@2x.png`):Workers Assets 会把 `@` 编码成 `%40` 再跳回来。用 `-2x` / `-3x`。`npm run check:portability` 已加守卫 |
|
||||
| 页面能开但按钮全不动 | 手机用局域网 IP 访问 dev 时被 Next 拦了 chunk:`next.config.ts` 已把非回环 IPv4 放进 `allowedDevOrigins`;线上不受影响 |
|
||||
| 解卦返回 501 | 没配模型:页面右上角「设置」里填 baseUrl / model / key |
|
||||
| 解卦返回 403「上游域名不在允许列表内」 | 目标供应商没进 `LLM_ALLOWED_HOSTS`:加进环境变量重新部署 |
|
||||
| 解卦返回 403「仅接受本站页面发起的请求」 | 请求带了别的站点的 `Origin`:这是防代理设计,正常用页面点不受影响 |
|
||||
| D1 报 `no such table: cases` | 首次访问 `/api/cases` 会自动建表;确认 `DB` 绑定名与配置一致 |
|
||||
|
||||
---
|
||||
|
||||
## 9. 目录与关键文件
|
||||
|
||||
```
|
||||
cloudflare.config.ts Worker 名 / 绑定 / 自定义域名(部署配置的唯一事实源)
|
||||
migrations/*.sql D1 表结构(gen:schema 生成运行时建表常量)
|
||||
app/api/read/route.ts 解卦 SSE 代理(同源校验 + 双窗限流 + 上游白名单)
|
||||
app/api/llm-test/route.ts 模型连通性测试
|
||||
app/api/cases/route.ts 卦例读写(D1,按匿名设备 Cookie 隔离)
|
||||
lib/llm/settings.ts 供应商预设 / 校验 / localStorage
|
||||
lib/llm/server.ts 服务端校验 + SSRF 拦截 + 白名单
|
||||
public/sw.js PWA 离线壳
|
||||
scripts/check-portability.mjs Workers 兼容性守卫(禁 node:*、next/image、@ 文件名等)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 10. 技术要点
|
||||
|
||||
**随机源**:每次投掷都来自 Web Crypto(`crypto.getRandomValues`),逐位取 Uint32 最低有效位,
|
||||
天然无偏;缺 Web Crypto 直接报错,不回落 PRNG。三钱概率严格 6/7/8/9 = 1/8 · 3/8 · 3/8 · 1/8,
|
||||
`tests/random.test.ts` 钉住分布与「起卦路径不得出现 Math.random」。
|
||||
|
||||
**案例页**:`public/data/zengshan-cases.json` 由 `scripts/extract-zengshan-cases.mjs`
|
||||
从《增删卜易卦例初探》整理文本抽取 100 例(原文不截断);卦盘不是照抄原文,
|
||||
而是由卦名反推六次投掷、再取「同月建同日辰」的公历重排,所以与「排出此卦」看到的盘面一致。
|
||||
|
||||
**刻意不做**:盘面上不标用神、不印吉凶判词(断语只在解卦正文里);不取用神规则化、不排应期;
|
||||
不为个案写特例(引擎只有查表与确定性算法)。
|
||||
|
||||
**断卦提示词**:完整规范在 [`docs/prompt-liuyao.md`](docs/prompt-liuyao.md)(v3,含"代码引擎负责排盘事实、
|
||||
AI 只负责推理"的两层职责与八条硬约束);运行时只用其中精编版(`app/api/read/prompt.ts`,四段 400–550 字)。
|
||||
|
||||
**PWA**:`app/manifest.ts` + `public/sw.js`,装到主屏后全屏无地址栏,起卦与排盘离线可用;
|
||||
Service Worker 只在非本机域名注册(localhost 自动注销,避免开发缓存脏 chunk)。
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
plugins {
|
||||
id 'com.android.application'
|
||||
}
|
||||
|
||||
android {
|
||||
namespace 'de.lufei.zhanbu'
|
||||
compileSdk 34
|
||||
|
||||
defaultConfig {
|
||||
applicationId 'de.lufei.zhanbu'
|
||||
minSdk 23
|
||||
targetSdk 34
|
||||
versionCode 1
|
||||
versionName '1.0.0'
|
||||
resValue 'string', 'asset_statements', '[{"relation": ["delegate_permission/common.handle_all_urls"], "target": {"namespace": "web", "site_url": "https://zhanbu.lufei.de"}}]'
|
||||
}
|
||||
|
||||
signingConfigs {
|
||||
release {
|
||||
// CI 里由 secrets 注入:KEYSTORE_PATH / KEYSTORE_PASSWORD / KEY_ALIAS / KEY_PASSWORD
|
||||
def storePath = System.getenv('KEYSTORE_PATH') ?: 'keystore.jks'
|
||||
storeFile file(storePath)
|
||||
storePassword System.getenv('KEYSTORE_PASSWORD')
|
||||
keyAlias System.getenv('KEY_ALIAS') ?: 'liuyao'
|
||||
keyPassword System.getenv('KEY_PASSWORD') ?: System.getenv('KEYSTORE_PASSWORD')
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
signingConfig signingConfigs.release
|
||||
minifyEnabled false
|
||||
shrinkResources false
|
||||
}
|
||||
debug {
|
||||
applicationIdSuffix '.debug'
|
||||
}
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_17
|
||||
targetCompatibility JavaVersion.VERSION_17
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'com.google.androidbrowserhelper:androidbrowserhelper:2.5.0'
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
|
||||
<application
|
||||
android:allowBackup="true"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.LauncherActivity">
|
||||
|
||||
<!-- TWA 启动器:用 Chrome 内核打开线上站,全屏无地址栏 -->
|
||||
<activity
|
||||
android:name="com.google.androidbrowserhelper.trusted.LauncherActivity"
|
||||
android:exported="true"
|
||||
android:theme="@style/Theme.LauncherActivity">
|
||||
|
||||
<meta-data
|
||||
android:name="android.support.customtabs.trusted.DEFAULT_URL"
|
||||
android:value="@string/default_url" />
|
||||
<meta-data
|
||||
android:name="android.support.customtabs.trusted.STATUS_BAR_COLOR"
|
||||
android:resource="@color/colorPrimary" />
|
||||
<meta-data
|
||||
android:name="android.support.customtabs.trusted.NAVIGATION_BAR_COLOR"
|
||||
android:resource="@color/colorPrimary" />
|
||||
<meta-data
|
||||
android:name="android.support.customtabs.trusted.SPLASH_IMAGE_DRAWABLE"
|
||||
android:resource="@mipmap/ic_launcher" />
|
||||
<meta-data
|
||||
android:name="android.support.customtabs.trusted.SPLASH_SCREEN_BACKGROUND_COLOR"
|
||||
android:resource="@color/colorPrimary" />
|
||||
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name="com.google.androidbrowserhelper.trusted.FocusActivity"
|
||||
android:exported="false" />
|
||||
<activity
|
||||
android:name="com.google.androidbrowserhelper.trusted.WebViewFallbackActivity"
|
||||
android:exported="false" />
|
||||
</application>
|
||||
</manifest>
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 788 B |
Binary file not shown.
|
Before Width: | Height: | Size: 744 B |
Binary file not shown.
|
Before Width: | Height: | Size: 905 B |
Binary file not shown.
|
Before Width: | Height: | Size: 1.0 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 1.2 KiB |
@@ -1,5 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="colorPrimary">#F7F4EF</color>
|
||||
<color name="colorAccent">#C23A2B</color>
|
||||
</resources>
|
||||
@@ -1,5 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="app_name">野鹤六爻</string>
|
||||
<string name="default_url">https://zhanbu.lufei.de/</string>
|
||||
</resources>
|
||||
@@ -1,8 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<style name="Theme.LauncherActivity" parent="android:Theme.Material.Light.NoActionBar">
|
||||
<item name="android:statusBarColor">@color/colorPrimary</item>
|
||||
<item name="android:navigationBarColor">@color/colorPrimary</item>
|
||||
<item name="android:windowBackground">@color/colorPrimary</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -1,3 +0,0 @@
|
||||
plugins {
|
||||
id 'com.android.application' version '8.5.2' apply false
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
|
||||
android.useAndroidX=true
|
||||
android.nonTransitiveRClass=true
|
||||
@@ -1,16 +0,0 @@
|
||||
pluginManagement {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
gradlePluginPortal()
|
||||
}
|
||||
}
|
||||
dependencyResolutionManagement {
|
||||
repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS)
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
rootProject.name = 'yehe-liuyao'
|
||||
include ':app'
|
||||
+36
-3
@@ -2,13 +2,15 @@
|
||||
* 解卦 prompt(服务端专用)
|
||||
* ========================
|
||||
* 原则:
|
||||
* 1. 盘面由引擎确定性排出,模型**不重排**、不改写干支/六亲/世应/旬空/动变;
|
||||
* 1. 盘面由引擎确定性排出,模型**不重排**、不改写干支/六亲/世应/旬空/动变(第 5 条是硬约束);
|
||||
* 2. 只使用事实里出现的爻辞与神煞,缺的不补、不编;
|
||||
* 3. prompt 只在这里拼,不随客户端 bundle 下发;
|
||||
* 4. 输出走「禅意」写法:四段、少而准,不写报告体、不罗列盘面。
|
||||
* 4. 输出走「禅意」写法:四段、少而准,不写报告体、不罗列盘面;
|
||||
* 5. 事实层与推理层分开:缺失字段标「未提供」,不补算、不把推测写成事实。
|
||||
*/
|
||||
|
||||
import type { ReadingFacts } from '@/lib/readings/types';
|
||||
import { PROMPT_SPEC } from '@/lib/readings/prompt-spec.generated';
|
||||
|
||||
const SYSTEM_PROMPT = `# 你是谁
|
||||
你是一位六爻解卦者。熟悉《易冒》《黄金策》《增删卜易》《卜筮正宗》等通行法理,也清楚自己的边界:只作传统文化参考,不替代医疗、法律、财务的专业判断。
|
||||
@@ -19,8 +21,14 @@ const SYSTEM_PROMPT = `# 你是谁
|
||||
- 只使用事实中出现的爻辞与神煞,没有给出的不要补、不要编;
|
||||
- 不要虚构古籍原文。能确证才引;不确定就写「通行法理如此」。
|
||||
|
||||
# 事实层铁律
|
||||
- 盘面事实是唯一来源:纳甲、六亲、六神、世应、伏神、旬空、月建日辰、动变、神煞一律照用,不重算、不改写、不因流派差异改动。
|
||||
- 事实里没给的(神煞、爻辞、字段)标「未提供」,不补算、不写成事实;用户质疑盘面时,说明由确定性引擎排出,解释层不改写。
|
||||
- 事实与推断分开写:哪些是盘面,哪些是你的判断,不得混成一句。
|
||||
|
||||
# 断卦次序(内部执行,不要把这些步骤逐条复述)
|
||||
1. 取用神:自占取世爻;问父母/文书取父母;问财/妻取妻财;问官/工作/病邪取官鬼;问子女/医药取子孙;问同辈/竞争取兄弟。代占先说明关系。用神多现时取动、取世应、取旺、取近,并说明取舍。
|
||||
专项路由:宠物取子孙为生命主体(不得与医药混用);失物按物类(财物妻财、文书舟车父母、禽兽子孙);求财妻财为主、子孙为生财原神;工作官鬼看岗位、父母看文书、应爻看单位;家宅父母看房屋、官鬼看风险。
|
||||
2. 看月建日辰:用神旺相休囚、月破日破、生扶冲克、旬空、墓绝。
|
||||
3. 看动变:动爻生克、回头生克、化进退、化空破墓绝、六合六冲、三合、反吟伏吟,以及变爻对本爻的作用。
|
||||
4. 看世应:世为己,应为对方或事所;看生克冲合。
|
||||
@@ -123,13 +131,38 @@ function liuyaoBrief(facts: Extract<ReadingFacts, { kind: 'liuyao' }>): string {
|
||||
}
|
||||
|
||||
/** 六爻专用:系统提示与用户消息 */
|
||||
/**
|
||||
* 拼 prompt:整份规范(原版全量,不选章、不压缩)+ 本次盘面事实
|
||||
*
|
||||
* 规范正文见 docs/prompt-liuyao.md,构建期由 scripts/build-prompt-spec.mjs
|
||||
* 内联成 lib/readings/prompt-spec.generated.ts(Workers 无 fs)。
|
||||
*/
|
||||
export function buildLiuyaoPrompt(facts: Extract<ReadingFacts, { kind: 'liuyao' }>): { system: string; user: string } {
|
||||
const system = composeSystem();
|
||||
|
||||
const ask = '请按四段写出这一卦的解读。盘面已是定局,不必重排,也不要复述全部爻位。';
|
||||
return {
|
||||
system: SYSTEM_PROMPT,
|
||||
system,
|
||||
user: `${liuyaoBrief(facts)}
|
||||
|
||||
${ask}
|
||||
(以上事实由引擎确定性排出;不要改写事实本身。)`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 按问句组装 system:
|
||||
* 核心章(零/一/二/三/四/五/六/十五/十六/十八/十九/二十)
|
||||
* + 命中的专项章(七…十四,整章原样)
|
||||
* + §十七 头部(四层 + 四段模板)+ 通用清单 A + 命中专项对应的输出清单
|
||||
*/
|
||||
/**
|
||||
* system = 整份规范(59k 字 / ≈40k token),不做任何选章、不用关键词正则。
|
||||
*
|
||||
* 为什么全量:断卦是模型的判断工作,哪一章适用应由它自己理解;
|
||||
* 用正则预选章会替模型做决定,漏命中就少一整章规则,误命中又白烧 token。
|
||||
* 成本实测 ≈$0.006/次,对本站量级可忽略。
|
||||
*/
|
||||
export function composeSystem(): string {
|
||||
return PROMPT_SPEC;
|
||||
}
|
||||
|
||||
+57
-24
@@ -21,7 +21,13 @@ import { buildLiuyaoPrompt } from './prompt';
|
||||
import type { ReadingFacts } from '@/lib/readings/types';
|
||||
import { buildChatRequestBody } from '@/lib/readings/llm-request';
|
||||
import { buildProviderHeaders } from '@/lib/readings/provider-headers';
|
||||
import { normalizeLlmRequest, upstreamHostAllowed, type LlmRequestConfig } from '@/lib/llm/server';
|
||||
import {
|
||||
friendlyUpstreamError,
|
||||
normalizeLlmRequest,
|
||||
shouldRetryUpstream,
|
||||
upstreamHostAllowed,
|
||||
type LlmRequestConfig,
|
||||
} from '@/lib/llm/server';
|
||||
|
||||
const MAX_BODY_BYTES = 64 * 1024;
|
||||
/** 分钟窗 + 小时窗双限:分钟挡突发,小时挡刷量(进程内计数,多实例时偏松,正式上限交给 CF 边缘限流) */
|
||||
@@ -133,32 +139,59 @@ export async function POST(req: Request): Promise<Response> {
|
||||
|
||||
const { system, user } = buildLiuyaoPrompt(facts);
|
||||
|
||||
let upstream: Response;
|
||||
try {
|
||||
upstream = await fetch(`${config.baseUrl}/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: buildProviderHeaders(config.baseUrl, config.key),
|
||||
body: JSON.stringify(
|
||||
buildChatRequestBody({
|
||||
model: config.model,
|
||||
thinking: config.thinking,
|
||||
reasoningEffort: config.reasoningEffort,
|
||||
messages: [
|
||||
{ role: 'system', content: system },
|
||||
{ role: 'user', content: user },
|
||||
],
|
||||
}),
|
||||
),
|
||||
signal: AbortSignal.timeout(120_000),
|
||||
});
|
||||
} catch (e) {
|
||||
return Response.json({ error: `上游模型不可达:${(e as Error).message}` }, { status: 502 });
|
||||
const requestBody = JSON.stringify(
|
||||
buildChatRequestBody({
|
||||
model: config.model,
|
||||
// 整份规范约 36k token:若模型默认开思考,会把输出预算全吃掉(实测 content 为空、finish_reason=length)。
|
||||
// 本产品只要 400–550 字正文,默认关闭思考;用户在「设置」里显式开启才传 enabled。
|
||||
thinking: config.thinking ?? 'disabled',
|
||||
reasoningEffort: config.reasoningEffort,
|
||||
messages: [
|
||||
{ role: 'system', content: system },
|
||||
{ role: 'user', content: user },
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* 36k token 的前缀在网关满载时会被拒(429 / prefill_cap_refused / overloaded),属于瞬时错误。
|
||||
* 在服务端重试(间隔 2.5s、6s)比让用户手动重点体验好;此时还没开始流式输出,重试是安全的。
|
||||
*/
|
||||
// 网关在长前缀满载时给的建议是 "retry after 30 s",所以间隔按 5s / 20s 起步;
|
||||
// 若上游消息里给了 "after N s",以它为准(上限 35s)。
|
||||
const RETRY_DELAYS = [5_000, 20_000];
|
||||
let upstream: Response | null = null;
|
||||
let lastError = '';
|
||||
|
||||
for (let attempt = 0; attempt <= RETRY_DELAYS.length; attempt += 1) {
|
||||
try {
|
||||
upstream = await fetch(`${config.baseUrl}/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: buildProviderHeaders(config.baseUrl, config.key),
|
||||
body: requestBody,
|
||||
signal: AbortSignal.timeout(120_000),
|
||||
});
|
||||
} catch (e) {
|
||||
return Response.json({ error: `上游模型不可达:${(e as Error).message}` }, { status: 502 });
|
||||
}
|
||||
|
||||
if (upstream.ok && upstream.body) break;
|
||||
|
||||
lastError = await upstream.text().catch(() => '');
|
||||
if (!shouldRetryUpstream(upstream.status, lastError) || attempt === RETRY_DELAYS.length) {
|
||||
return new Response(
|
||||
`data: ${JSON.stringify({ error: friendlyUpstreamError(upstream.status, lastError) })}\n\n`,
|
||||
{ status: 200, headers: { 'Content-Type': 'text/event-stream; charset=utf-8' } },
|
||||
);
|
||||
}
|
||||
const hinted = Number(/after\s+(\d{1,2})\s*s/i.exec(lastError)?.[1] ?? 0);
|
||||
const waitMs = hinted > 0 ? Math.min(hinted * 1000, 35_000) : RETRY_DELAYS[attempt];
|
||||
await new Promise((r) => setTimeout(r, waitMs));
|
||||
}
|
||||
|
||||
if (!upstream.ok || !upstream.body) {
|
||||
const text = await upstream.text().catch(() => '');
|
||||
if (!upstream || !upstream.ok || !upstream.body) {
|
||||
return new Response(
|
||||
`data: ${JSON.stringify({ error: `上游模型返回 ${upstream.status}:${text.slice(0, 200)}` })}\n\n`,
|
||||
`data: ${JSON.stringify({ error: friendlyUpstreamError(429, lastError) })}\n\n`,
|
||||
{ status: 200, headers: { 'Content-Type': 'text/event-stream; charset=utf-8' } },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -362,9 +362,18 @@ export default function CastPage() {
|
||||
</div>
|
||||
|
||||
{/* 墨绿漆面 + 赭金双边按钮(移动端改由底部悬浮条承载) */}
|
||||
<div className="mx-auto mt-5 hidden max-w-[300px] rounded-[6px] border border-[#9C7A48] p-[2px] shadow-[0_2px_7px_rgba(96,76,43,0.16)] sm:block">
|
||||
<button type="button" disabled={rolling || complete} onClick={doToss} className="press h-[50px] w-full rounded-[4px] border border-[#D8C392]/50 bg-[linear-gradient(180deg,#456557_0%,#29453B_100%)] font-song text-[17px] font-medium tracking-[0.4em] text-[#F5E9CB] shadow-[inset_0_1px_0_rgba(255,255,255,0.14)] transition-colors hover:bg-[#223D34] disabled:cursor-not-allowed disabled:opacity-60">
|
||||
{rolling ? '铜钱翻落' : complete ? '六爻已备' : '掷钱起爻'}
|
||||
<div className="mx-auto mt-5 hidden max-w-[360px] items-stretch gap-2.5 sm:flex">
|
||||
<div className="flex-1 rounded-[6px] border border-[#9C7A48] p-[2px] shadow-[0_2px_7px_rgba(96,76,43,0.16)]">
|
||||
<button type="button" disabled={rolling || complete} onClick={doToss} className="press h-[50px] w-full rounded-[4px] border border-[#D8C392]/50 bg-[linear-gradient(180deg,#456557_0%,#29453B_100%)] font-song text-[17px] font-medium tracking-[0.4em] text-[#F5E9CB] shadow-[inset_0_1px_0_rgba(255,255,255,0.14)] transition-colors hover:bg-[#223D34] disabled:cursor-not-allowed disabled:opacity-60">
|
||||
{rolling ? '铜钱翻落' : complete ? '六爻已备' : '掷钱起爻'}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSheet('manual')}
|
||||
className="press h-[50px] w-[76px] shrink-0 self-center rounded-[4px] border border-[#9C7A48] bg-[#FBF7EC] font-song text-[13px] tracking-[0.14em] text-[#3F4A42] shadow-[0_2px_7px_rgba(96,76,43,0.14)] transition-colors hover:border-[#8E6337] hover:text-[#8E6337]"
|
||||
>
|
||||
指定
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -374,14 +383,6 @@ export default function CastPage() {
|
||||
重新起卦
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSheet('manual')}
|
||||
className="press inline-flex h-9 items-center gap-1.5 rounded-[3px] border border-[#9C7A48] bg-[#FBF7EC] px-3 font-song text-[12px] tracking-[0.08em] text-[#3F4A42] shadow-[0_2px_7px_rgba(96,76,43,0.14)] transition-colors hover:border-[#8E6337] hover:text-[#8E6337]"
|
||||
>
|
||||
<PenLine size={13} strokeWidth={1.7} />
|
||||
手动指定
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
@@ -410,14 +411,23 @@ export default function CastPage() {
|
||||
|
||||
{/* 移动端:起卦按钮悬浮在底部,单手可及 */}
|
||||
<div className="safe-bottom fixed inset-x-0 bottom-0 z-30 border-t border-[#D7CDB8] bg-[#F6F2E9]/95 px-4 pt-2.5 backdrop-blur-md sm:hidden">
|
||||
<div className="mx-auto max-w-[420px] rounded-[6px] border border-[#9C7A48] p-[2px] shadow-[0_2px_10px_rgba(96,76,43,0.18)]">
|
||||
<div className="mx-auto flex max-w-[420px] items-stretch gap-2.5">
|
||||
<div className="flex-1 rounded-[6px] border border-[#9C7A48] p-[2px] shadow-[0_2px_10px_rgba(96,76,43,0.18)]">
|
||||
<button
|
||||
type="button"
|
||||
disabled={rolling || complete}
|
||||
onClick={doToss}
|
||||
className="press h-[48px] w-full rounded-[4px] border border-[#D8C392]/50 bg-[linear-gradient(180deg,#456557_0%,#29453B_100%)] font-song text-[16px] font-medium tracking-[0.36em] text-[#F5E9CB] shadow-[inset_0_1px_0_rgba(255,255,255,0.14)] transition-colors hover:bg-[#223D34] disabled:cursor-not-allowed disabled:opacity-60"
|
||||
>
|
||||
{rolling ? '铜钱翻落' : complete ? '六爻已备' : '掷钱起爻'}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
disabled={rolling || complete}
|
||||
onClick={doToss}
|
||||
className="press h-[48px] w-full rounded-[4px] border border-[#D8C392]/50 bg-[linear-gradient(180deg,#456557_0%,#29453B_100%)] font-song text-[16px] font-medium tracking-[0.36em] text-[#F5E9CB] shadow-[inset_0_1px_0_rgba(255,255,255,0.14)] transition-colors hover:bg-[#223D34] disabled:cursor-not-allowed disabled:opacity-60"
|
||||
onClick={() => setSheet('manual')}
|
||||
className="press h-[48px] w-[72px] shrink-0 self-center rounded-[4px] border border-[#9C7A48] bg-[#FBF7EC] font-song text-[13px] tracking-[0.14em] text-[#3F4A42] shadow-[0_2px_7px_rgba(96,76,43,0.14)] transition-colors hover:border-[#8E6337] hover:text-[#8E6337]"
|
||||
>
|
||||
{rolling ? '铜钱翻落' : complete ? '六爻已备' : '掷钱起爻'}
|
||||
指定
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -304,7 +304,9 @@ const ReadingPanel = React.forwardRef<ReadingPanelHandle, ReadingPanelProps>(fun
|
||||
<div className="mt-4 space-y-1.5 font-serif text-[12px] leading-relaxed text-[#8e3a2c]">
|
||||
<p>{error}</p>
|
||||
<p className="text-[11px] text-[#9C907F]">
|
||||
检查右上角「设置」里的接口地址、模型名与 API Key;「测试连接」能直接看到上游返回。
|
||||
{/繁忙|429|overloaded|capacity/i.test(error)
|
||||
? '上游瞬时繁忙,服务端已自动重试过;稍等几秒点「重 试」即可,不会重复计费。'
|
||||
: '检查右上角「设置」里的接口地址、模型名与 API Key;「测试连接」能直接看到上游返回。'}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -24,7 +24,7 @@ import {
|
||||
type LlmSettings,
|
||||
} from '@/lib/llm/settings';
|
||||
|
||||
const EMPTY: LlmSettings = { provider: 'deepseek', baseUrl: 'https://api.deepseek.com/v1', model: 'deepseek-flash', apiKey: '' };
|
||||
const EMPTY: LlmSettings = { provider: 'deepseek', baseUrl: 'https://api.deepseek.com/v1', model: 'deepseek-chat', apiKey: '', thinking: 'disabled' };
|
||||
|
||||
const FIELD =
|
||||
'h-10 w-full rounded-[3px] border border-[#D9CDB6] bg-white px-2.5 font-mono text-[12.5px] text-[#2F4438] outline-none transition-colors focus:border-[#9A7040]';
|
||||
@@ -185,7 +185,7 @@ export default function SettingsDialog({ open, onClose }: { open: boolean; onClo
|
||||
<input
|
||||
value={draft.model}
|
||||
onChange={(e) => setDraft({ ...draft, model: e.target.value })}
|
||||
placeholder="deepseek-flash"
|
||||
placeholder="deepseek-chat"
|
||||
spellCheck={false}
|
||||
list="llm-models"
|
||||
className={FIELD}
|
||||
|
||||
@@ -108,6 +108,16 @@ export default function SiteHeader({
|
||||
</>
|
||||
)}
|
||||
<span aria-hidden className="hidden h-4 w-px bg-[#C8BEA8] sm:block" />
|
||||
<a
|
||||
href="https://github.com/woniu336/liuyao"
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
aria-label="项目主页(GitHub)"
|
||||
title="项目主页"
|
||||
className="press flex h-8 items-center rounded-full border border-[#C3B79E] bg-[#FCF9F0]/70 px-3 font-song text-[12px] text-[#4A4438] no-underline transition-colors hover:border-[#9A7040] hover:text-[#8E6337]"
|
||||
>
|
||||
项目
|
||||
</a>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSettingsOpen(true)}
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
# Cloudflare 部署备忘
|
||||
|
||||
目标:Cloudflare Workers(vinext / workerd),**暂不部署**,先把约束钉住。
|
||||
目标:Cloudflare Workers(vinext / workerd)。**部署步骤见根目录 `README.md`**;本文只记取舍与约束。
|
||||
|
||||
## 运行形态
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -102,6 +102,32 @@ export function upstreamHostAllowed(baseUrl: string): { ok: true } | { ok: false
|
||||
return hit ? { ok: true } : { ok: false, error: `上游域名不在允许列表内:${host}` };
|
||||
}
|
||||
|
||||
/**
|
||||
* 上游是否值得重试(纯函数,便于测试)。
|
||||
*
|
||||
* 整份规范约 36k token 的前缀在网关满载时会被拒(429 / prefill_cap_refused / overloaded),
|
||||
* 这类错误是瞬时的:同一请求隔几秒再来往往就成功,所以在服务端重试一次比让用户重点便宜。
|
||||
*/
|
||||
export function shouldRetryUpstream(status: number, bodyText: string): boolean {
|
||||
if (status === 429 || status === 502 || status === 503 || status === 504) return true;
|
||||
return /overloaded|prefill_cap_refused|at capacity|rate.?limit|too many requests|retry shortly/i.test(bodyText);
|
||||
}
|
||||
|
||||
/** 把上游错误翻译成一句人话(前端不再显示原始 JSON) */
|
||||
export function friendlyUpstreamError(status: number, bodyText: string): string {
|
||||
if (status === 429 || /overloaded|at capacity|prefill_cap_refused/i.test(bodyText)) {
|
||||
return '上游模型当前繁忙(429),稍等几秒再点「重试」即可;本次请求没有产生费用。';
|
||||
}
|
||||
if (status === 401 || status === 403) {
|
||||
return '上游拒绝了这个 key(401/403):请到「设置」里核对 API Key 是否有权限。';
|
||||
}
|
||||
if (status === 404) {
|
||||
return '上游 404:接口地址或模型名不对,请检查「设置」里的 Base URL 与模型名。';
|
||||
}
|
||||
const brief = bodyText.replace(/\s+/g, ' ').slice(0, 160);
|
||||
return `上游返回 ${status}:${brief}`;
|
||||
}
|
||||
|
||||
/** 私人部署兜底:服务端环境变量(客户端没配时才会用到) */
|
||||
function envFallback(): LlmRequestConfig | null {
|
||||
if (typeof process === 'undefined') return null;
|
||||
|
||||
+3
-2
@@ -38,10 +38,11 @@ export interface LlmProviderPreset {
|
||||
export const LLM_PROVIDERS: LlmProviderPreset[] = [
|
||||
{
|
||||
id: 'deepseek',
|
||||
label: 'DeepSeek',
|
||||
label: 'DeepSeek 官方(支持上下文缓存)',
|
||||
baseUrl: 'https://api.deepseek.com/v1',
|
||||
models: ['deepseek-flash', 'deepseek-chat', 'deepseek-reasoner'],
|
||||
models: ['deepseek-chat', 'deepseek-reasoner'],
|
||||
needsKey: true,
|
||||
hint: '官方 API 会自动缓存重复前缀:本站提示词约 4 万 token,第二次起命中缓存后输入按缓存价计(约为原价 1/10),预填充也更快,长前缀不易被限流。',
|
||||
},
|
||||
{
|
||||
id: 'opencode-go',
|
||||
|
||||
File diff suppressed because one or more lines are too long
+3
-1
@@ -16,7 +16,9 @@
|
||||
"deploy:vinext": "vinext-cloudflare deploy",
|
||||
"gen:schema": "node scripts/gen-db-schema.mjs",
|
||||
"check:schema": "node scripts/gen-db-schema.mjs --check",
|
||||
"check": "npm run check:schema && npm run check:portability && npm test"
|
||||
"check": "npm run check:schema && npm run check:prompt && npm run check:portability && npm test",
|
||||
"gen:prompt": "node scripts/build-prompt-spec.mjs",
|
||||
"check:prompt": "node scripts/build-prompt-spec.mjs --check"
|
||||
},
|
||||
"dependencies": {
|
||||
"@vinext/cloudflare": "^1.3.3",
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
[
|
||||
{
|
||||
"relation": ["delegate_permission/common.handle_all_urls"],
|
||||
"target": {
|
||||
"namespace": "android_app",
|
||||
"package_name": "de.lufei.zhanbu",
|
||||
"sha256_cert_fingerprints": [
|
||||
"30:08:90:89:79:40:AD:EF:B9:88:7E:A6:5E:CA:17:60:2D:08:19:2E:63:97:DC:A2:B0:09:9B:6D:34:B7:B9:93"
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,93 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* 把完整断卦规范(docs/prompt-liuyao.md)内联成 TS 模块。
|
||||
*
|
||||
* node scripts/build-prompt-spec.mjs # 生成
|
||||
* node scripts/build-prompt-spec.mjs --check # 只校验是否最新(CI 用)
|
||||
*
|
||||
* 为什么内联:Workers 没有 fs,读不到仓库里的 md。
|
||||
* 为什么拆章:整份 5.4 万字(≈36k token)每次全发,网关满载时容易被拒(429/prefill_cap_refused),
|
||||
* 且首字要 9–10 秒。拆成"章 + 输出清单"后可按问句只发「核心章 + 命中的专项章」,
|
||||
* **内容一字不改**(整章原样搬运),只是发送策略变化。
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import process from 'node:process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const src = path.join(root, 'docs', 'prompt-liuyao.md');
|
||||
const out = path.join(root, 'lib', 'readings', 'prompt-spec.generated.ts');
|
||||
|
||||
const text = fs.readFileSync(src, 'utf8').replace(/\r\n/g, '\n');
|
||||
|
||||
// ---- 按 `# 零、…` 这种一级标题切章 ----
|
||||
const heads = [...text.matchAll(/^# ([零一二三四五六七八九十]+)、(.+)$/gm)];
|
||||
const chapters = {};
|
||||
for (let i = 0; i < heads.length; i += 1) {
|
||||
const start = heads[i].index;
|
||||
const end = i + 1 < heads.length ? heads[i + 1].index : text.length;
|
||||
chapters[heads[i][1]] = text.slice(start, end).trimEnd();
|
||||
}
|
||||
const preface = text.slice(0, heads[0]?.index ?? 0).trimEnd();
|
||||
|
||||
// ---- 把「输出格式」章再拆成 头部 + A~J(章号随文档顺延,动态识别) ----
|
||||
const outputChapterId = Object.entries(chapters).find(([, v]) => v.includes('## A. 通用人事占'))?.[0] ?? '';
|
||||
const ch17 = chapters[outputChapterId] ?? '';
|
||||
const fmtHeads = [...ch17.matchAll(/^## ([A-J])\. (.+)$/gm)];
|
||||
const outputHead = fmtHeads.length ? ch17.slice(0, fmtHeads[0].index).trimEnd() : ch17;
|
||||
const formats = {};
|
||||
for (let i = 0; i < fmtHeads.length; i += 1) {
|
||||
const start = fmtHeads[i].index;
|
||||
const end = i + 1 < fmtHeads.length ? fmtHeads[i + 1].index : ch17.length;
|
||||
formats[fmtHeads[i][1]] = ch17.slice(start, end).trimEnd();
|
||||
}
|
||||
|
||||
const q = (s) => JSON.stringify(s);
|
||||
const body = `/* 由 scripts/build-prompt-spec.mjs 生成,请勿手改。
|
||||
* 事实源:docs/prompt-liuyao.md(整章原样搬运,未做任何改写)
|
||||
*/
|
||||
|
||||
/** 完整规范(原版全文,${text.length} 字):给"详版/外部 Agent"投放用 */
|
||||
export const PROMPT_SPEC = ${q(text)};
|
||||
|
||||
/** 前言(版本与投放说明,运行时不发) */
|
||||
export const SPEC_PREFACE = ${q(preface)};
|
||||
|
||||
/** 按章切开(零 / 一 / … / 二十二),内容与原文逐字一致 */
|
||||
export const SPEC_CHAPTERS: Record<string, string> = {
|
||||
${Object.entries(chapters).map(([k, v]) => ` ${q(k)}: ${q(v)},`).join('\n')}
|
||||
};
|
||||
|
||||
/** §十七 的头部(四层输出 + 四段模板与字数预算) */
|
||||
export const OUTPUT_HEAD = ${q(outputHead)};
|
||||
|
||||
/** §十七 里的 A~I 输出清单(按专项取用) */
|
||||
export const OUTPUT_FORMATS: Record<string, string> = {
|
||||
${Object.entries(formats).map(([k, v]) => ` ${q(k)}: ${q(v)},`).join('\n')}
|
||||
};
|
||||
|
||||
/** 「输出格式」所在章号(运行时用它的头部 + 选中清单替换整章) */
|
||||
export const OUTPUT_CHAPTER_ID = ${q(Object.entries(chapters).find(([, v]) => v.includes('## A. 通用人事占'))?.[0] ?? '')};
|
||||
|
||||
/** 核心章列表(仅文档完整性校验用;运行时发全量) */
|
||||
export const CORE_CHAPTER_IDS = ${q(['零', '一', '二', '三', '四', '五', '六', '十六', '十七', '十八', '十九', '二十', '二十一'])};
|
||||
|
||||
/** 专项 → 输出清单的对应表(文档完整性校验用;运行时已改为全量发送,不再选章) */
|
||||
export const CHAPTER_FORMAT_MAP: Record<string, string> = ${q({ 七: 'B', 八: 'C', 九: 'D', 十: 'E', 十一: 'F', 十二: 'G', 十三: 'H', 十四: 'I', 十五: 'J' })};
|
||||
`;
|
||||
|
||||
if (process.argv.includes('--check')) {
|
||||
const cur = fs.existsSync(out) ? fs.readFileSync(out, 'utf8') : '';
|
||||
if (cur !== body) {
|
||||
console.error('[check:prompt] lib/readings/prompt-spec.generated.ts 与 docs/prompt-liuyao.md 不一致,请运行 npm run gen:prompt');
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(`[check:prompt] OK(${text.length} 字 / ${Object.keys(chapters).length} 章 / ${Object.keys(formats).length} 个输出清单,与规范一致)`);
|
||||
} else {
|
||||
fs.mkdirSync(path.dirname(out), { recursive: true });
|
||||
fs.writeFileSync(out, body, 'utf8');
|
||||
console.log(
|
||||
`[gen:prompt] 写入 ${path.relative(root, out)}:${text.length} 字 / ${Object.keys(chapters).length} 章 / ${Object.keys(formats).length} 个输出清单`,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* 线上模型回归(可选,默认跳过)
|
||||
* ==============================
|
||||
* 用途:用真实供应商验证「整份规范 + 专项规则」是否真的被模型用上(专项命中)。
|
||||
*
|
||||
* 运行方式(不把 key 写进仓库):
|
||||
* LIUYAO_LIVE_KEY=oc_sk_xxx LIUYAO_LIVE_MODEL=deepseek-v4.1-flash \
|
||||
* npx vitest run tests/live-specialty.test.ts
|
||||
*
|
||||
* 断言只做"是否按专项口径作答"的粗筛(避免把模型措辞当成契约):
|
||||
* - 四段标题齐全;
|
||||
* - 宠物走失:提到「子孙」且不出现"肯定被偷/必能找回"这类绝对话;
|
||||
* - 求财:提到「妻财」或「财爻」,且不承诺收益率。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { buildLiuyaoPrompt } from '../app/api/read/prompt';
|
||||
import { buildLiuyaoReadingFacts } from '../lib/readings/facts';
|
||||
import { buildLiuyaoInput, castTimeInfo, parseTimeInput } from '../lib/liuyao/ganzhi';
|
||||
import { castLiuyao } from '../lib/liuyao/najia';
|
||||
|
||||
const KEY = process.env.LIUYAO_LIVE_KEY;
|
||||
const MODEL = process.env.LIUYAO_LIVE_MODEL || 'deepseek-v4.1-flash';
|
||||
const BASE = process.env.LIUYAO_LIVE_BASE || 'https://opencode.ai/zen/go/v1';
|
||||
|
||||
const time = castTimeInfo(parseTimeInput('2026-11-07T15:30'));
|
||||
const chart = castLiuyao(buildLiuyaoInput(time, [8, 7, 9, 8, 7, 8]));
|
||||
|
||||
/** 网关在 36k 前缀满载时会返回 prefill_cap_refused,重试即可(最多 2 次,间隔 30s) */
|
||||
async function ask(question: string, retry = 2): Promise<string> {
|
||||
const { system, user } = buildLiuyaoPrompt(buildLiuyaoReadingFacts(chart, time, question));
|
||||
const res = await fetch(`${BASE}/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${KEY}`,
|
||||
'x-opencode-session': `liuyao-test-${Date.now()}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: MODEL,
|
||||
stream: false,
|
||||
temperature: 0.3,
|
||||
max_tokens: 2000,
|
||||
// 整份规范 36k token,若开思考会把输出预算全吃掉(实测 content 为空、finish_reason=length)
|
||||
thinking: { type: 'disabled' },
|
||||
messages: [
|
||||
{ role: 'system', content: system },
|
||||
{ role: 'user', content: user },
|
||||
],
|
||||
}),
|
||||
});
|
||||
const json = (await res.json()) as {
|
||||
choices?: { message?: { content?: string } }[];
|
||||
usage?: { prompt_tokens?: number };
|
||||
error?: unknown;
|
||||
};
|
||||
const content = json.choices?.[0]?.message?.content;
|
||||
if (content) return content;
|
||||
const raw = JSON.stringify(json.error ?? json);
|
||||
if (retry > 0 && /prefill_cap_refused|overloaded|429/.test(raw)) {
|
||||
await new Promise((r) => setTimeout(r, 30_000));
|
||||
return ask(question, retry - 1);
|
||||
}
|
||||
throw new Error(`上游异常:${raw}`);
|
||||
}
|
||||
|
||||
const live = KEY ? describe : describe.skip;
|
||||
|
||||
live('真实模型:专项是否命中', () => {
|
||||
it('宠物走失 → 以子孙为主、不给绝对承诺', async () => {
|
||||
const out = await ask('我家猫昨天从阳台跑丢了,还能找回来吗');
|
||||
console.log('\n--- 宠物走失 ---\n' + out);
|
||||
expect(out).toMatch(/一、取用/);
|
||||
expect(out).toMatch(/四、应期/);
|
||||
expect(out).toMatch(/子孙/);
|
||||
expect(out).not.toMatch(/肯定被偷|一定是被偷|必能找回|保证找回/);
|
||||
}, 180_000);
|
||||
|
||||
it('求财 → 妻财为主用,不承诺收益', async () => {
|
||||
const out = await ask('这笔欠款这个月能到账吗');
|
||||
console.log('\n--- 求财 ---\n' + out);
|
||||
expect(out).toMatch(/一、取用/);
|
||||
expect(out).toMatch(/妻财|财爻/);
|
||||
expect(out).not.toMatch(/保证.{0,4}收益|必涨|一定回本/);
|
||||
}, 180_000);
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* 线上 Worker 端到端回归(默认跳过)
|
||||
* ================================
|
||||
* 用途:验证**已部署**的 Worker 用的是最新提示词与默认关闭思考。
|
||||
* 运行:LIUYAO_LIVE_KEY=oc_sk_xxx npx vitest run tests/live-worker.test.ts
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { buildLiuyaoReadingFacts } from '../lib/readings/facts';
|
||||
import { buildLiuyaoInput, castTimeInfo, parseTimeInput } from '../lib/liuyao/ganzhi';
|
||||
import { castLiuyao } from '../lib/liuyao/najia';
|
||||
|
||||
const KEY = process.env.LIUYAO_LIVE_KEY;
|
||||
const BASE = process.env.LIUYAO_LIVE_SITE || 'https://zhanbu.lufei.de';
|
||||
|
||||
const time = castTimeInfo(parseTimeInput('2026-11-07T15:30'));
|
||||
const chart = castLiuyao(buildLiuyaoInput(time, [8, 7, 9, 8, 7, 8]));
|
||||
|
||||
const live = KEY ? describe : describe.skip;
|
||||
|
||||
live('已部署 Worker:解卦链路', () => {
|
||||
it('宠物走失问句 → 200 且返回四段正文(说明整份规范 + 关闭思考已生效)', async () => {
|
||||
const facts = buildLiuyaoReadingFacts(chart, time, '我家猫昨天从阳台跑丢了,还能找回来吗');
|
||||
const res = await fetch(`${BASE}/api/read`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Origin: BASE },
|
||||
body: JSON.stringify({
|
||||
facts,
|
||||
llm: { baseUrl: 'https://opencode.ai/zen/go/v1', model: 'deepseek-v4.1-flash', apiKey: KEY },
|
||||
}),
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
const text = await res.text();
|
||||
const out = text
|
||||
.split('\n')
|
||||
.filter((l) => l.startsWith('data:'))
|
||||
.map((l) => {
|
||||
try {
|
||||
return (JSON.parse(l.slice(5).trim()) as { content?: string }).content ?? '';
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
})
|
||||
.join('');
|
||||
console.log('\n--- 线上 Worker 输出 ---\n' + out);
|
||||
expect(out).toMatch(/一、取用/);
|
||||
expect(out).toMatch(/四、应期/);
|
||||
expect(out).toMatch(/子孙/);
|
||||
expect(out.length).toBeGreaterThan(300);
|
||||
}, 240_000);
|
||||
|
||||
it('高考问句 → 200 且按学业专项分层(子孙为主体、父母文书、官鬼录取)', async () => {
|
||||
const facts = buildLiuyaoReadingFacts(chart, time, '孩子今年高考,能不能上本科,志愿怎么填');
|
||||
const res = await fetch(`${BASE}/api/read`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Origin: BASE },
|
||||
body: JSON.stringify({
|
||||
facts,
|
||||
llm: { baseUrl: 'https://opencode.ai/zen/go/v1', model: 'deepseek-v4.1-flash', apiKey: KEY },
|
||||
}),
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
const text = await res.text();
|
||||
const out = text
|
||||
.split('\n')
|
||||
.filter((l) => l.startsWith('data:'))
|
||||
.map((l) => {
|
||||
try {
|
||||
return (JSON.parse(l.slice(5).trim()) as { content?: string }).content ?? '';
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
})
|
||||
.join('');
|
||||
console.log('\n--- 线上 Worker · 学业 ---\n' + out);
|
||||
expect(out).toMatch(/一、取用/);
|
||||
expect(out).toMatch(/四、应期/);
|
||||
expect(out).toMatch(/子孙/);
|
||||
expect(out).toMatch(/父母|文书|试卷/);
|
||||
expect(out).toMatch(/官鬼|录取/);
|
||||
}, 240_000);
|
||||
});
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
validateLlmSettings,
|
||||
type LlmSettings,
|
||||
} from '../lib/llm/settings';
|
||||
import { normalizeLlmRequest, upstreamHostAllowed } from '../lib/llm/server';
|
||||
import { friendlyUpstreamError, normalizeLlmRequest, shouldRetryUpstream, upstreamHostAllowed } from '../lib/llm/server';
|
||||
|
||||
const deepseek: LlmSettings = {
|
||||
provider: 'deepseek',
|
||||
@@ -118,6 +118,26 @@ describe('服务端校验(防打内网 / 形态硬约束)', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('上游瞬时错误要重试,客户端错误不重试', () => {
|
||||
// 网关满载/限流 → 重试
|
||||
expect(shouldRetryUpstream(429, '')).toBe(true);
|
||||
expect(shouldRetryUpstream(503, '')).toBe(true);
|
||||
expect(shouldRetryUpstream(500, '{"message":"[overloaded] retry shortly"}')).toBe(true);
|
||||
expect(shouldRetryUpstream(400, '{"message":"[prefill_cap_refused] the cell is at capacity"}')).toBe(true);
|
||||
// key 错、模型名错 → 不重试
|
||||
expect(shouldRetryUpstream(401, 'invalid api key')).toBe(false);
|
||||
expect(shouldRetryUpstream(404, 'model not found')).toBe(false);
|
||||
expect(shouldRetryUpstream(400, 'invalid request')).toBe(false);
|
||||
});
|
||||
|
||||
it('上游错误翻成人话(不把 JSON 直接丢给用户)', () => {
|
||||
expect(friendlyUpstreamError(429, '')).toContain('繁忙');
|
||||
expect(friendlyUpstreamError(200, '[overloaded]')).toContain('繁忙');
|
||||
expect(friendlyUpstreamError(401, 'x')).toContain('API Key');
|
||||
expect(friendlyUpstreamError(404, 'x')).toContain('Base URL');
|
||||
expect(friendlyUpstreamError(400, 'bad thing')).toContain('400');
|
||||
});
|
||||
|
||||
it('没传 llm 时退回服务端环境变量(没配就是 null)', () => {
|
||||
const r = normalizeLlmRequest(undefined);
|
||||
expect(r.ok).toBe(true);
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { SPEC_CHAPTERS, CORE_CHAPTER_IDS, OUTPUT_CHAPTER_ID, OUTPUT_FORMATS } from '../lib/readings/prompt-spec.generated';
|
||||
|
||||
const spec = fs.readFileSync(path.resolve(__dirname, '..', 'docs', 'prompt-liuyao.md'), 'utf8').replace(/\r\n/g, '\n');
|
||||
|
||||
/** 中文数字 → 序号,用于比较章节顺序 */
|
||||
const NUMS = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十',
|
||||
'十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九',
|
||||
'二十', '二十一', '二十二', '二十三'];
|
||||
|
||||
describe('提示词章节结构自洽(防顺延漏改)', () => {
|
||||
it('章节编号从零起连续,且与正文标题一致', () => {
|
||||
const ids = Object.keys(SPEC_CHAPTERS);
|
||||
expect(ids).toEqual(NUMS.slice(0, ids.length));
|
||||
for (const id of ids) {
|
||||
expect(SPEC_CHAPTERS[id].startsWith('# ' + id + '、'), `第 ${id} 章标题不匹配`).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('正文里引用的「第X章 / §X」都存在', () => {
|
||||
const ids = new Set(Object.keys(SPEC_CHAPTERS));
|
||||
// 只校验落在本文档编号范围内(零..二十三)的引用;
|
||||
// 像「《易林补遗》第六十章」这种外部书章号不参与校验。
|
||||
const inRange = new Set(NUMS);
|
||||
const bad: string[] = [];
|
||||
for (const m of spec.matchAll(/第([零一二三四五六七八九十]+)章/g)) {
|
||||
if (inRange.has(m[1]) && !ids.has(m[1])) bad.push(m[0]);
|
||||
}
|
||||
for (const m of spec.matchAll(/§([零一二三四五六七八九十]+)/g)) {
|
||||
if (inRange.has(m[1]) && !ids.has(m[1])) bad.push(m[0]);
|
||||
}
|
||||
expect(bad, `引用了不存在的章号:${[...new Set(bad)].join('、')}`).toEqual([]);
|
||||
});
|
||||
|
||||
it('核心章都是真实存在的章,且不含专项章', () => {
|
||||
const ids = new Set(Object.keys(SPEC_CHAPTERS));
|
||||
for (const id of CORE_CHAPTER_IDS) expect(ids.has(id), `核心章 ${id} 不存在`).toBe(true);
|
||||
// 专项章(七~十五)不得出现在核心列表里
|
||||
for (const id of ['七', '八', '九', '十', '十一', '十二', '十三', '十四', '十五']) {
|
||||
expect(CORE_CHAPTER_IDS, `专项章 ${id} 混进了核心章`).not.toContain(id);
|
||||
}
|
||||
});
|
||||
|
||||
it('输出格式章存在,且 A~J 十个清单齐全', () => {
|
||||
expect(Object.keys(SPEC_CHAPTERS)).toContain(OUTPUT_CHAPTER_ID);
|
||||
expect(Object.keys(OUTPUT_FORMATS)).toEqual(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']);
|
||||
expect(SPEC_CHAPTERS[OUTPUT_CHAPTER_ID]).toContain('## J. 学业、升学与资格考试专项');
|
||||
});
|
||||
|
||||
it('学业专项独立成章,含事项分类 / 用神 / 流程 / 应期 / 安全边界', () => {
|
||||
const edu = SPEC_CHAPTERS['十五'];
|
||||
expect(edu).toContain('学业、升学与职业资格考试专项');
|
||||
for (const must of ['三轴用神', '事项分类', '推演流程', '应期', '安全与现实边界', '严禁的机械断法', '子孙的双重语义']) {
|
||||
expect(edu, `学业章缺「${must}」`).toContain(must);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,101 +1,74 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { castLiuyao } from '../lib/liuyao/najia';
|
||||
import type { CastTimeInfo } from '../lib/liuyao/ganzhi';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { buildLiuyaoPrompt, composeSystem } from '../app/api/read/prompt';
|
||||
import { buildLiuyaoReadingFacts } from '../lib/readings/facts';
|
||||
import { buildLiuyaoPrompt } from '../app/api/read/prompt';
|
||||
import { buildLiuyaoInput, castTimeInfo, parseTimeInput } from '../lib/liuyao/ganzhi';
|
||||
import { castLiuyao } from '../lib/liuyao/najia';
|
||||
import { PROMPT_SPEC } from '../lib/readings/prompt-spec.generated';
|
||||
|
||||
const time: CastTimeInfo = {
|
||||
iso: '',
|
||||
solarText: '2026年11月5日 12:02',
|
||||
lunarText: '二〇二六年 农历九月廿七',
|
||||
ganzhiText: '丙午年 戊申月 己丑日 庚午时',
|
||||
yearGz: '丙午',
|
||||
monthGz: '戊申',
|
||||
dayGz: '己丑',
|
||||
hourGz: '庚午',
|
||||
monthBranch: '申',
|
||||
hourBranch: '午',
|
||||
};
|
||||
const specDoc = fs.readFileSync(path.resolve(__dirname, '..', 'docs', 'prompt-liuyao.md'), 'utf8').replace(/\r\n/g, '\n');
|
||||
|
||||
function factsOf(coins: number[]) {
|
||||
const chart = castLiuyao({
|
||||
yearGz: '丙午',
|
||||
monthBranch: '申',
|
||||
dayGz: '己丑',
|
||||
hourBranch: '午',
|
||||
coins,
|
||||
});
|
||||
return buildLiuyaoReadingFacts(chart, time, '测试');
|
||||
}
|
||||
const time = castTimeInfo(parseTimeInput('2026-11-05T20:56'));
|
||||
const chart = castLiuyao(buildLiuyaoInput(time, [7, 7, 8, 9, 7, 8]));
|
||||
const promptFor = (q: string) => buildLiuyaoPrompt(buildLiuyaoReadingFacts(chart, time, q));
|
||||
|
||||
describe('解卦 prompt(精简版)', () => {
|
||||
const facts = factsOf([0, 1, 1, 1, 1, 1]);
|
||||
const { system, user } = buildLiuyaoPrompt(facts);
|
||||
|
||||
it('系统提示仍在两千字内,且明确「不重排盘」', () => {
|
||||
expect(system.length).toBeLessThan(2000);
|
||||
expect(system).toContain('不要重排盘');
|
||||
expect(system).toContain('不断死');
|
||||
expect(system).toContain('应期');
|
||||
describe('运行时提示词 = 整份规范(全量,不选章、不压缩)', () => {
|
||||
it('system 恒等于规范全文,与问句无关', () => {
|
||||
expect(composeSystem()).toBe(specDoc);
|
||||
for (const q of ['', '我家猫跑丢了', '孩子今年高考', '面试完顺便问财运']) {
|
||||
expect(promptFor(q).system, `问句「${q}」的 system 不是全量`).toBe(specDoc);
|
||||
}
|
||||
});
|
||||
|
||||
it('移除了排盘教程与报告式自检', () => {
|
||||
expect(system).not.toContain('六神起法');
|
||||
expect(system).not.toContain('排盘规范');
|
||||
expect(system).not.toContain('自检清单');
|
||||
expect(system).not.toContain('输入核对');
|
||||
expect(system).not.toContain('复盘');
|
||||
it('生成物与文档同步(改文档必须重新 gen:prompt)', () => {
|
||||
expect(PROMPT_SPEC).toBe(specDoc);
|
||||
});
|
||||
|
||||
it('保留病占专项,且限定只在病症类占问启用', () => {
|
||||
expect(system).toContain('病占专项');
|
||||
expect(system).toContain('段首必须是下面四行原文');
|
||||
expect(system).toContain('近病逢冲即愈');
|
||||
expect(system).toContain('子孙制鬼');
|
||||
expect(system).toContain('主治医生');
|
||||
expect(system).toContain('其余占问跳过本节');
|
||||
it('所有专项章都随全量发送(不再有"按问句命中")', () => {
|
||||
const { system } = promptFor('孩子今年高考');
|
||||
for (const title of [
|
||||
'# 七、人物疾病占专项',
|
||||
'# 八、六畜/宠物占专项',
|
||||
'# 九、行人、音信与人员走失专项',
|
||||
'# 十、婚姻与婚恋专项',
|
||||
'# 十一、普通失物与寻物专项',
|
||||
'# 十二、求财与经营专项',
|
||||
'# 十三、工作、事业与求职专项',
|
||||
'# 十四、家宅、房屋与迁移专项',
|
||||
'# 十五、学业、升学与职业资格考试专项',
|
||||
]) {
|
||||
expect(system, `缺章:${title}`).toContain(title);
|
||||
}
|
||||
});
|
||||
|
||||
it('字数预算:四段各有额度,全文硬上限 600 字', () => {
|
||||
expect(system).toContain('400–550');
|
||||
expect(system).toContain('硬上限 600 字');
|
||||
expect(system).toContain('取用约 100 字');
|
||||
expect(system).toContain('盘面约 180 字');
|
||||
expect(system).toContain('走势约 150 字');
|
||||
expect(system).toContain('应期约 80 字');
|
||||
});
|
||||
|
||||
it('用户消息带盘面事实、十三神煞与经文,且不含翻译注文', () => {
|
||||
expect(user).toContain('天风姤');
|
||||
expect(user).toContain('【十三神煞】');
|
||||
expect(user).toContain('劫煞');
|
||||
expect(user).toContain('【经文】');
|
||||
expect(user).toContain('卦辞');
|
||||
expect(user).toContain('初六');
|
||||
expect(user).not.toContain('翻译:');
|
||||
expect(user).not.toContain('象征:');
|
||||
});
|
||||
|
||||
it('输出要求是四段禅意写法,不要求长篇报告', () => {
|
||||
it('事实层硬约束与四段输出要求在位', () => {
|
||||
const { system } = promptFor('');
|
||||
expect(system).toContain('代码引擎输出是唯一排盘事实来源');
|
||||
expect(system).toContain('不得重复计算纳甲、六亲、六神、旬空、世应、动变');
|
||||
expect(system).toContain('一、取用');
|
||||
expect(system).toContain('四、应期');
|
||||
expect(system).not.toContain('输出格式');
|
||||
expect(system).not.toContain('13 段');
|
||||
expect(system).toContain('硬上限 600 字');
|
||||
});
|
||||
|
||||
it('神煞取值与盘面同源(来自 shensha.ts,而非模型自算)', () => {
|
||||
const f = factsOf([1, 1, 1, 1, 1, 1]);
|
||||
expect(f.shensha.guiren).toBe('子、申');
|
||||
expect(f.shensha.yima).toBe('亥');
|
||||
expect(f.shensha.taohua).toBe('午');
|
||||
expect(f.shensha.tianyi).toBe('未');
|
||||
expect(f.shensha.wenchang).toBe('酉');
|
||||
expect(f.oracle.baseGuaCi).toBe('元亨利贞。');
|
||||
it('不含被审计删除的内容', () => {
|
||||
const { system } = promptFor('');
|
||||
expect(system).not.toContain('六神起法');
|
||||
expect(system).not.toContain('# 五、排盘规范');
|
||||
expect(system).not.toContain('尝试重排');
|
||||
});
|
||||
});
|
||||
|
||||
it('六爻全动时带用九/用六', () => {
|
||||
const allYang = factsOf([9, 9, 9, 9, 9, 9]);
|
||||
expect(allYang.oracle.yong?.title).toBe('用九');
|
||||
expect(allYang.oracle.yong?.text).toContain('用九');
|
||||
describe('user 消息只带盘面事实与问句', () => {
|
||||
it('含问句与盘面,且声明事实由引擎排出', () => {
|
||||
const { user } = promptFor('这套房子租下来合适吗');
|
||||
expect(user).toContain('这套房子租下来合适吗');
|
||||
expect(user).toContain('以上事实由引擎确定性排出');
|
||||
expect(user).toContain('不要改写事实本身');
|
||||
});
|
||||
|
||||
it('不把密钥或 prompt 模板塞进 user', () => {
|
||||
const { user } = promptFor('问财运');
|
||||
expect(user).not.toMatch(/api[_-]?key|sk-|oc_sk_/i);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user