Spaces:
Running
Running
root commited on
Commit ·
7e06208
1
Parent(s): 0399aa9
协作 AI:接入 Surf Chat(令牌保存与自动续期、异步提问、接着聊、断线接回、检查连接)
Browse files- fanqie/agent.js +393 -64
- fanqie/dist/index.html +2 -2
- public/assets/{index-B6KDOQXi.css → index-DjI2iQEM.css} +0 -0
- public/assets/{index-Qi8bPEnM.js → index-ZuCQ04aJ.js} +0 -0
- public/index.html +2 -2
- ui-src/src/api.ts +13 -2
- ui-src/src/rooms/Agent.tsx +122 -41
- ui-src/src/rooms/Editor.tsx +4 -4
- ui-src/src/styles.css +12 -0
fanqie/agent.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
| 3 |
// - 作者状态(账号、首本进度、签约情况):AI 写作前必须读,按状态调整写法和节奏。
|
| 4 |
// - AI 工作守则(/guide.md):AI 能做什么、不能做什么、该读哪些接口,人和 AI 共读。
|
| 5 |
// - 检查记录(audits):自查清单、番茄平台规定检查都由 AI 执行,结果存这里,作者在工作台查看。
|
| 6 |
-
// -
|
| 7 |
// 回复存档后再据此修改。令牌只保存在服务器,浏览器和写作 AI 都只能看到末 4 位。
|
| 8 |
const path = require('path')
|
| 9 |
const fs = require('fs')
|
|
@@ -41,7 +41,7 @@ module.exports = function buildAgent(express, projects) {
|
|
| 41 |
if (p.account === 'new' || /Lv[01]\b/i.test(p.level || '')) out.push('作者是 Lv0–1 新人:按番茄 2026-10-12 起的规则,新人新书只能选「完本签约」——必须把整本写完(长篇至少 15 万字并完结)才能申请签约,所以首要目标是写完,而不是追求日更连载数据。')
|
| 42 |
if (p.first_book !== 'done') out.push('第一本还没完成:优先保证全书完整、逻辑闭环、结局落地;不要中途开新坑、不要另起新书,不要为了冲字数注水。')
|
| 43 |
if (p.contract !== 'signed') out.push('尚未签约:正文里不能出现求票、求打赏、作者感言、更新预告等签约作者才有的运营内容;不能承诺更新频率。签约审核看完整度、原创度和是否 AI 粗制滥造,每一章都要经得起人工审核。')
|
| 44 |
-
if (p.contract !== 'signed') out.push('每本书只有 3 次签约申请机会:提交前必须让 AI 跑完「自查清单」和「平台规定检查」,并把
|
| 45 |
if (p.account === 'new') out.push('新号没有历史信用:内容红线、低质规则一律按最严格标准执行,拿不准就改成更保守的写法,并在交付说明里告诉作者。')
|
| 46 |
return out
|
| 47 |
}
|
|
@@ -117,35 +117,235 @@ module.exports = function buildAgent(express, projects) {
|
|
| 117 |
})
|
| 118 |
}))
|
| 119 |
|
| 120 |
-
/* ----------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
const REV_KEY = 'agent/reviewer.json'
|
| 122 |
-
const MODES = ['openai', 'anthropic', 'custom']
|
| 123 |
-
|
| 124 |
-
const
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
router.get('/reviewer', wrap(async () => mask(await revConfig())))
|
| 126 |
router.put('/reviewer', wrap(async req => {
|
| 127 |
const b = req.body || {}
|
| 128 |
-
const
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
return mask(next)
|
| 139 |
}))
|
| 140 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
const getPath = (obj, p) => String(p || '').split('.').filter(Boolean).reduce((o, k) => (o == null ? o : o[/^\d+$/.test(k) ? Number(k) : k]), obj)
|
| 142 |
const fill = (tpl, vars, jsonMode) => String(tpl).replace(/\{\{(\w+)\}\}/g, (_, k) => { const v = vars[k] ?? ''; return jsonMode ? JSON.stringify(String(v)).slice(1, -1) : String(v) })
|
| 143 |
-
async function
|
| 144 |
-
if (!cfg.endpoint) throw bad('还没有设置
|
| 145 |
-
if (!cfg.token && cfg.mode !== 'custom') throw bad('还没有保存
|
| 146 |
const ctrl = new AbortController()
|
| 147 |
-
const timer = setTimeout(() => ctrl.abort(),
|
| 148 |
-
const t0 = Date.now()
|
| 149 |
try {
|
| 150 |
let headers = { 'Content-Type': 'application/json' }, body
|
| 151 |
if (cfg.mode === 'openai') {
|
|
@@ -161,10 +361,7 @@ module.exports = function buildAgent(express, projects) {
|
|
| 161 |
}
|
| 162 |
const r = await fetch(cfg.endpoint, { method: 'POST', headers, body, signal: ctrl.signal })
|
| 163 |
const raw = await r.text()
|
| 164 |
-
if (!r.ok) {
|
| 165 |
-
const e = bad(`审查 AI 返回 ${r.status}${r.status === 401 || r.status === 403 ? ':令牌可能已过期,请到「AI 协作 → 审查 AI」更新令牌' : ''}|${raw.slice(0, 400)}`, 502)
|
| 166 |
-
e.http = r.status; throw e
|
| 167 |
-
}
|
| 168 |
let reply = ''
|
| 169 |
const ct = r.headers.get('content-type') || ''
|
| 170 |
if (cfg.sse || ct.includes('event-stream')) {
|
|
@@ -184,12 +381,12 @@ module.exports = function buildAgent(express, projects) {
|
|
| 184 |
else reply = raw
|
| 185 |
if (typeof reply !== 'string') reply = JSON.stringify(reply)
|
| 186 |
}
|
| 187 |
-
if (!reply.trim()) throw bad('
|
| 188 |
-
return
|
| 189 |
} finally { clearTimeout(timer) }
|
| 190 |
}
|
| 191 |
|
| 192 |
-
// 把作品资料打包
|
| 193 |
async function material(pid, attach, maxChars) {
|
| 194 |
const P = await projects.getProject(pid)
|
| 195 |
const parts = []
|
|
@@ -214,56 +411,185 @@ module.exports = function buildAgent(express, projects) {
|
|
| 214 |
if (text.length > maxChars) text = text.slice(0, maxChars) + `\n\n(资料超过 ${maxChars} 字,后面已截断)`
|
| 215 |
return { text, project: P.project }
|
| 216 |
}
|
| 217 |
-
const
|
| 218 |
-
'你
|
| 219 |
-
'
|
| 220 |
-
'
|
| 221 |
-
'2. 按严重程度排序:先说会导致逻辑崩坏、违反平台规定或审核不过的问题,再说可以更好的地方;',
|
| 222 |
-
'3. 每个问题给出可执行的修改方向;没有问题的部分不用夸,直接说「无问题」;',
|
| 223 |
-
'4. 不要重写整段正文,必要时只给一两句示范。',
|
| 224 |
].join('\n')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
const logKey = pid => (pid ? projectKey(pid, 'reviewer/log.json') : 'agent/reviewer_log.json')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
router.post('/reviewer/ask', wrap(async req => {
|
| 227 |
const b = req.body || {}
|
| 228 |
const question = String(b.question || '').trim()
|
| 229 |
if (!question) throw bad('问题不能为空')
|
| 230 |
const pid = b.project_id ? cleanId(b.project_id, 'project_id') : ''
|
|
|
|
| 231 |
const cfg = await revConfig()
|
|
|
|
| 232 |
const attach = (Array.isArray(b.attach) ? b.attach : []).map(String).slice(0, 20)
|
| 233 |
const prof = await getProfile()
|
| 234 |
let mat = { text: '' }
|
| 235 |
if (pid && attach.length) mat = await material(pid, attach, cfg.max_chars || 120000)
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
}))
|
| 248 |
router.get('/reviewer/log', wrap(async req => {
|
| 249 |
const pid = req.query.project_id ? cleanId(req.query.project_id, 'project_id') : ''
|
| 250 |
const d = await readJson(logKey(pid), { items: [] })
|
| 251 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
}))
|
| 253 |
-
// 写作 AI 处理完
|
| 254 |
router.patch('/reviewer/log/:aid', wrap(async req => {
|
| 255 |
const b = req.body || {}
|
| 256 |
const pid = b.project_id ? cleanId(b.project_id, 'project_id') : ''
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 267 |
}))
|
| 268 |
|
| 269 |
/* ---------------- AI 工作守则(人和 AI 共读) ---------------- */
|
|
@@ -310,7 +636,7 @@ module.exports = function buildAgent(express, projects) {
|
|
| 310 |
'1. **动笔前**:读作者状态、作品资料、上一章结尾;确认本章目标。',
|
| 311 |
'2. **写作**:一章一章写,每章写完存为新版本(`POST .../chapters/{章节ID}/versions`,`created_by` 填 `AI`),不要覆盖作者的版本。',
|
| 312 |
'3. **自查**:写完一章,读 `/fanqie/api/agent/rules` 里的番茄平台规定,逐条检查本章,把结果写入检查记录(见第 5 节)。',
|
| 313 |
-
'4. **请
|
| 314 |
'5. **按批注修改**:作者说「按批注修改第 X 章」时,读该章待改批注,逐条改正文、存新版本;在每条批注上写 `reply`(改了什么)并把 `status` 改成 `fixed`(`PATCH .../notes/{批注ID}`)。',
|
| 315 |
'6. **交付说明**:每次工作结束,用三五句话告诉作者做了什么、哪些地方拿不准。', '')
|
| 316 |
L.push('## 5. 检查记录:自查清单与平台规定', '',
|
|
@@ -318,11 +644,14 @@ module.exports = function buildAgent(express, projects) {
|
|
| 318 |
'- 检查由你(AI)逐条阅读正文后判断,**不能用关键词匹配代替阅读**。',
|
| 319 |
'- 写入:`POST /fanqie/api/agent/audits`,字段:`project_id`、`kind`(`checklist` 自查清单 / `platform` 平台规定 / `logic` 逻辑)、`scope`(`book` / `chapter`)、`chapter_id`、`version_id`、`by`、`summary`、`items[]`(`id`、`title`、`result`=pass/warn/fail/na、`note`、`quote` 引用原文、`fix` 修改建议)。',
|
| 320 |
'- 作者在工作台「检查」和「手册 → 自查清单」里看到这些结果。', '')
|
| 321 |
-
L.push('## 6.
|
| 322 |
-
`- 当前设置:${cfg.
|
| 323 |
-
'-
|
| 324 |
-
'-
|
| 325 |
-
'- 返回
|
|
|
|
|
|
|
|
|
|
| 326 |
L.push('## 7. 作品列表', '', ...((list.projects || []).map(p => `- 《${p.title}》 ID:\`${p.project_id}\``)), '')
|
| 327 |
L.push('---', '每次请求都要带访问密码请求头 `x-app-password`。本守则地址:`/fanqie/api/agent/guide.md`。')
|
| 328 |
return L.filter(x => x !== null && x !== undefined).join('\n')
|
|
|
|
| 3 |
// - 作者状态(账号、首本进度、签约情况):AI 写作前必须读,按状态调整写法和节奏。
|
| 4 |
// - AI 工作守则(/guide.md):AI 能做什么、不能做什么、该读哪些接口,人和 AI 共读。
|
| 5 |
// - 检查记录(audits):自查清单、番茄平台规定检查都由 AI 执行,结果存这里,作者在工作台查看。
|
| 6 |
+
// - 协作 AI(reviewer):另一个 AI(默认 Surf Chat),写作 AI 在工作中向它派活(审查、调研、出主意、起草),
|
| 7 |
// 回复存档后再据此修改。令牌只保存在服务器,浏览器和写作 AI 都只能看到末 4 位。
|
| 8 |
const path = require('path')
|
| 9 |
const fs = require('fs')
|
|
|
|
| 41 |
if (p.account === 'new' || /Lv[01]\b/i.test(p.level || '')) out.push('作者是 Lv0–1 新人:按番茄 2026-10-12 起的规则,新人新书只能选「完本签约」——必须把整本写完(长篇至少 15 万字并完结)才能申请签约,所以首要目标是写完,而不是追求日更连载数据。')
|
| 42 |
if (p.first_book !== 'done') out.push('第一本还没完成:优先保证全书完整、逻辑闭环、结局落地;不要中途开新坑、不要另起新书,不要为了冲字数注水。')
|
| 43 |
if (p.contract !== 'signed') out.push('尚未签约:正文里不能出现求票、求打赏、作者感言、更新预告等签约作者才有的运营内容;不能承诺更新频率。签约审核看完整度、原创度和是否 AI 粗制滥造,每一章都要经得起人工审核。')
|
| 44 |
+
if (p.contract !== 'signed') out.push('每本书只有 3 次签约申请机会:提交前必须让 AI 跑完「自查清单」和「平台规定检查」,并把协作 AI 审查提出的问题处理完。')
|
| 45 |
if (p.account === 'new') out.push('新号没有历史信用:内容红线、低质规则一律按最严格标准执行,拿不准就改成更保守的写法,并在交付说明里告诉作者。')
|
| 46 |
return out
|
| 47 |
}
|
|
|
|
| 117 |
})
|
| 118 |
}))
|
| 119 |
|
| 120 |
+
/* ---------------- 协作 AI(另一个 AI:审查、调研、出主意……什么活都能做) ----------------
|
| 121 |
+
* 默认接 Surf Chat(asksurf.ai):协议照作者给的 surf-agent.mjs 实现——
|
| 122 |
+
* POST /muninn/v2/crypto-agent/sessions/{会话}/chat(SSE 流),断线用空消息 + last-event-id 接回;
|
| 123 |
+
* 令牌 1 小时过期,有 refreshToken 时可自动换新(会让同一份登录的浏览器被登出)。
|
| 124 |
+
* 也保留 OpenAI / Anthropic / 自定义模板三种通用接口。
|
| 125 |
+
* 提问是异步的:先存一条「进行中」记录,后台跑完再写回;写作 AI 可等一会儿,或稍后按 ask_id 取结果。 */
|
| 126 |
+
const crypto = require('crypto')
|
| 127 |
const REV_KEY = 'agent/reviewer.json'
|
| 128 |
+
const MODES = ['surf', 'openai', 'anthropic', 'custom']
|
| 129 |
+
const SURF_API = (process.env.SURF_API_BASE || 'https://api.asksurf.ai').replace(/\/$/, '')
|
| 130 |
+
const SURF_WEB = 'https://asksurf.ai'
|
| 131 |
+
const SURF_MODELS = {
|
| 132 |
+
pro: 'Pro(Surf 自动选模型)', max: 'Max(GPT-6 Astra)', 'multi-agent': 'Multi-agent Research', opus5: 'Claude Opus 5', fable5: 'Claude Fable 5',
|
| 133 |
+
'gpt-61': 'GPT-6.1 Sol', 'gpt-56': 'GPT-5.6 Sol', 'gpt-55': 'GPT-5.5', grok46: 'Grok 4.6', grok45: 'Grok 4.5',
|
| 134 |
+
}
|
| 135 |
+
const SURF_EFFORTS = ['medium', 'high', 'ultra']
|
| 136 |
+
const TASKS = { review: '审查', research: '调研', idea: '出主意', draft: '起草', other: '其他' }
|
| 137 |
+
const DEF_CFG = {
|
| 138 |
+
name: '协作 AI', mode: 'surf', endpoint: '', model: '', token: '', refresh_token: '', auto_refresh: true,
|
| 139 |
+
surf_model: 'pro', surf_effort: 'high', instant: false,
|
| 140 |
+
headers_tpl: '', body_tpl: '', reply_path: '', sse: false, max_chars: 120000, system: '',
|
| 141 |
+
}
|
| 142 |
+
const sleep = ms => new Promise(r => setTimeout(r, ms))
|
| 143 |
+
function jwtExp(t) {
|
| 144 |
+
try { const c = JSON.parse(Buffer.from(String(t).split('.')[1].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8')); return c && c.exp ? c.exp * 1000 : null } catch { return null }
|
| 145 |
+
}
|
| 146 |
+
async function revConfig() {
|
| 147 |
+
const saved = await readJson(REV_KEY, null)
|
| 148 |
+
const c = { ...DEF_CFG, ...(saved || {}) }
|
| 149 |
+
if (saved && saved.mode !== 'surf' && !saved.endpoint) c.mode = 'surf' // 旧版默认值(没填地址)迁到 Surf
|
| 150 |
+
if (c.name === '审查 AI') c.name = '协作 AI'
|
| 151 |
+
return c
|
| 152 |
+
}
|
| 153 |
+
const mask = c => {
|
| 154 |
+
const { token, refresh_token, ...rest } = c
|
| 155 |
+
const exp = token ? jwtExp(token) : null
|
| 156 |
+
return { ...rest, token_set: !!token, token_tail: token ? String(token).slice(-4) : '', refresh_set: !!refresh_token, token_expires_at: exp ? new Date(exp).toISOString() : null, surf_models: SURF_MODELS, surf_efforts: SURF_EFFORTS, tasks: TASKS }
|
| 157 |
+
}
|
| 158 |
+
// 令牌输入:Bearer 后那串 / 「Bearer xxx」/ 网页 localStorage 的 SURF_TOKENS 整段 JSON
|
| 159 |
+
function parseToken(s) {
|
| 160 |
+
s = String(s || '').trim()
|
| 161 |
+
let t = s, r = ''
|
| 162 |
+
if (/^[{"]/.test(s)) {
|
| 163 |
+
try { let o = JSON.parse(s); if (typeof o === 'string') o = JSON.parse(o); t = o.token || o.access_token || ''; r = o.refreshToken || o.refresh_token || '' }
|
| 164 |
+
catch { throw bad('令牌格式不对:请粘贴 Bearer 后面那串,或整段 {"token":"…","refreshToken":"…"}') }
|
| 165 |
+
}
|
| 166 |
+
t = String(t).replace(/^Bearer\s+/i, '').trim()
|
| 167 |
+
if (!t) throw bad('没有读到令牌')
|
| 168 |
+
return { t, r: String(r || '').trim() }
|
| 169 |
+
}
|
| 170 |
+
async function updateCfg(fn) {
|
| 171 |
+
return withLock('reviewer-config', async () => { const cur = await revConfig(); const next = fn(cur) || cur; next.updated_at = now(); await writeJson(REV_KEY, next); return next })
|
| 172 |
+
}
|
| 173 |
router.get('/reviewer', wrap(async () => mask(await revConfig())))
|
| 174 |
router.put('/reviewer', wrap(async req => {
|
| 175 |
const b = req.body || {}
|
| 176 |
+
const next = await updateCfg(cur => {
|
| 177 |
+
const n = { ...cur }
|
| 178 |
+
for (const k of ['name', 'endpoint', 'model', 'headers_tpl', 'body_tpl', 'reply_path', 'system', 'note']) if (b[k] !== undefined) n[k] = String(b[k]).slice(0, 20000)
|
| 179 |
+
if (b.mode !== undefined) { if (!MODES.includes(b.mode)) throw bad('mode 取值不对'); n.mode = b.mode }
|
| 180 |
+
if (b.surf_model !== undefined) n.surf_model = String(b.surf_model).slice(0, 40) || 'pro'
|
| 181 |
+
if (b.surf_effort !== undefined) n.surf_effort = SURF_EFFORTS.includes(b.surf_effort) ? b.surf_effort : ''
|
| 182 |
+
for (const k of ['sse', 'auto_refresh', 'instant']) if (b[k] !== undefined) n[k] = !!b[k]
|
| 183 |
+
if (b.max_chars !== undefined) n.max_chars = Math.min(400000, Math.max(5000, Number(b.max_chars) || 120000))
|
| 184 |
+
if (typeof b.token === 'string' && b.token.trim()) {
|
| 185 |
+
const { t, r } = n.mode === 'surf' ? parseToken(b.token) : { t: b.token.trim(), r: '' }
|
| 186 |
+
n.token = t; if (r) n.refresh_token = r; n.token_saved_at = now()
|
| 187 |
+
}
|
| 188 |
+
if (typeof b.refresh_token === 'string' && b.refresh_token.trim()) n.refresh_token = b.refresh_token.trim()
|
| 189 |
+
if (b.clear_token) { n.token = ''; n.refresh_token = ''; n.token_saved_at = now() }
|
| 190 |
+
return n
|
| 191 |
+
})
|
| 192 |
return mask(next)
|
| 193 |
}))
|
| 194 |
|
| 195 |
+
/* ----- Surf ----- */
|
| 196 |
+
let refreshing = null
|
| 197 |
+
async function surfRefresh(cfg, why) {
|
| 198 |
+
if (!cfg.auto_refresh || !cfg.refresh_token) return false
|
| 199 |
+
if (refreshing) { const ok = await refreshing; if (ok) { const c = await revConfig(); cfg.token = c.token; cfg.refresh_token = c.refresh_token }; return ok }
|
| 200 |
+
refreshing = (async () => {
|
| 201 |
+
try {
|
| 202 |
+
const r = await fetch(SURF_API + '/muninn/v2/auth/refresh', { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json' }, body: JSON.stringify({ refresh_token: cfg.refresh_token }) })
|
| 203 |
+
const j = await r.json().catch(() => null)
|
| 204 |
+
const d = j && (j.data || j)
|
| 205 |
+
if (!r.ok || !d || !d.access_token) { console.log('[协作 AI] 换新令牌失败', r.status, why); return false }
|
| 206 |
+
cfg.token = d.access_token; cfg.refresh_token = d.refresh_token || cfg.refresh_token
|
| 207 |
+
await updateCfg(c => ({ ...c, token: cfg.token, refresh_token: cfg.refresh_token, token_refreshed_at: now() }))
|
| 208 |
+
return true
|
| 209 |
+
} catch (e) { console.log('[协作 AI] 换新令牌出错', e.message); return false }
|
| 210 |
+
})()
|
| 211 |
+
try { return await refreshing } finally { refreshing = null }
|
| 212 |
+
}
|
| 213 |
+
async function surfEnsure(cfg) {
|
| 214 |
+
if (!cfg.token) throw Object.assign(bad('还没有保存协作 AI 的令牌:请作者到「AI 协作 → 协作 AI」粘贴', 400), { http: 401 })
|
| 215 |
+
const exp = jwtExp(cfg.token)
|
| 216 |
+
if (exp && exp - Date.now() < 120000) {
|
| 217 |
+
if (await surfRefresh(cfg, '快过期了')) return
|
| 218 |
+
if (exp <= Date.now()) throw Object.assign(bad('Surf 令牌已过期(只有 1 小时有效):请作者到「AI 协作 → 协作 AI」更新令牌', 401), { http: 401 })
|
| 219 |
+
}
|
| 220 |
+
}
|
| 221 |
+
async function surfFetch(cfg, p, o = {}, retried = false) {
|
| 222 |
+
const h = { authorization: 'Bearer ' + cfg.token, accept: o.sse ? 'text/event-stream' : 'application/json' }
|
| 223 |
+
if (o.body !== undefined) h['content-type'] = 'application/json'
|
| 224 |
+
if (o.lastId) h['last-event-id'] = o.lastId
|
| 225 |
+
if (process.env.SURF_DEVICE_ID) h['x-device-id'] = process.env.SURF_DEVICE_ID
|
| 226 |
+
const r = await fetch(SURF_API + p, { method: o.method || 'GET', headers: h, body: o.body !== undefined ? JSON.stringify(o.body) : undefined, signal: o.signal })
|
| 227 |
+
if (r.status === 401 && !retried && (await surfRefresh(cfg, '服务器说令牌失效'))) return surfFetch(cfg, p, o, true)
|
| 228 |
+
return r
|
| 229 |
+
}
|
| 230 |
+
function surfErr(status, text, prefix = 'Surf 返回') {
|
| 231 |
+
let j = null; try { j = JSON.parse(text) } catch {}
|
| 232 |
+
const m = (j && (j.message || j.error)) || String(text || '').slice(0, 300)
|
| 233 |
+
const hint = status === 401 || status === 403 ? ':令牌无效或已过期,请作者到「AI 协作 → 协作 AI」更新令牌' : status === 402 ? ':积分可能不够了' : ''
|
| 234 |
+
return Object.assign(bad(`${prefix} ${status}${hint}|${m}`, 502), { http: status, code: j && j.error_code })
|
| 235 |
+
}
|
| 236 |
+
async function surfJson(cfg, p, o = {}) {
|
| 237 |
+
const r = await surfFetch(cfg, p, o)
|
| 238 |
+
const t = await r.text()
|
| 239 |
+
let j = null; try { j = JSON.parse(t) } catch {}
|
| 240 |
+
if (!r.ok || (j && j.success === false)) throw surfErr(r.status, t)
|
| 241 |
+
return j && typeof j === 'object' && 'data' in j ? j.data : j
|
| 242 |
+
}
|
| 243 |
+
async function surfStreaming(cfg, sid) {
|
| 244 |
+
try { const d = await surfJson(cfg, '/muninn/v1/crypto-agent/sessions/streaming-status?ids=' + sid); const x = (Array.isArray(d) ? d : []).find(y => y.session_id === sid); return !!(x && x.is_streaming) } catch { return null }
|
| 245 |
+
}
|
| 246 |
+
function parseSSE(buf, onEvent) {
|
| 247 |
+
let ev = {}
|
| 248 |
+
const lines = buf.split('\n')
|
| 249 |
+
const rest = lines.pop()
|
| 250 |
+
for (let line of lines) {
|
| 251 |
+
if (line.endsWith('\r')) line = line.slice(0, -1)
|
| 252 |
+
if (line === '') { if (ev.data !== undefined || ev.event) onEvent(ev); ev = {}; continue }
|
| 253 |
+
if (line[0] === ':') continue
|
| 254 |
+
const i = line.indexOf(':')
|
| 255 |
+
const f = i < 0 ? line : line.slice(0, i)
|
| 256 |
+
let v = i < 0 ? '' : line.slice(i + 1)
|
| 257 |
+
if (v[0] === ' ') v = v.slice(1)
|
| 258 |
+
if (f === 'data') ev.data = ev.data === undefined ? v : ev.data + '\n' + v
|
| 259 |
+
else if (f === 'event') ev.event = v
|
| 260 |
+
else if (f === 'id') ev.id = v
|
| 261 |
+
}
|
| 262 |
+
const pend = []
|
| 263 |
+
if (ev.id !== undefined) pend.push('id: ' + ev.id)
|
| 264 |
+
if (ev.event !== undefined) pend.push('event: ' + ev.event)
|
| 265 |
+
if (ev.data !== undefined) ev.data.split('\n').forEach(d => pend.push('data: ' + d))
|
| 266 |
+
return (pend.length ? pend.join('\n') + '\n' : '') + rest
|
| 267 |
+
}
|
| 268 |
+
function surfHandle(ev, st) {
|
| 269 |
+
st.events++
|
| 270 |
+
if (ev.id) { st.lastId = ev.id; const n = parseInt(String(ev.id).split('#')[0], 10); if (n > 0) st.turn = n }
|
| 271 |
+
let d = null; try { d = ev.data ? JSON.parse(ev.data) : null } catch { d = ev.data }
|
| 272 |
+
const x = d && typeof d === 'object' ? d : {}
|
| 273 |
+
switch (ev.event) {
|
| 274 |
+
case 'message_chunk': { const t = x.text != null ? x.text : x.content != null ? x.content : ''; if (t) { st.sawChunk = true; st.text += t } return }
|
| 275 |
+
case 'message': if (!st.sawChunk && x.text) st.text += (st.text ? '\n\n' : '') + x.text; return
|
| 276 |
+
case 'tool': st.tools++; return
|
| 277 |
+
case 'result': st.result = { cost_usd: x.total_cost_usd != null ? +x.total_cost_usd : null, input_tokens: x.input_tokens, output_tokens: x.output_tokens }; return
|
| 278 |
+
case 'ask_user': st.ask_user = String(x.question || (x.questions && JSON.stringify(x.questions)) || '').slice(0, 2000); return
|
| 279 |
+
case 'credits_exhausted': st.error = { code: 'credits_exhausted', message: 'Surf 积分用完了' }; return
|
| 280 |
+
case 'error': {
|
| 281 |
+
const ok = x.recoverable && x.severity !== 'fatal' && x.code !== 'RATE_LIMITED' && !String(x.code || '').startsWith('GROK_FREE_')
|
| 282 |
+
if (!ok) st.error = { code: x.code || 'error', message: x.message || 'Surf 报错' }
|
| 283 |
+
return
|
| 284 |
+
}
|
| 285 |
+
case 'cancelled': st.error = { code: 'cancelled', message: '这次对话在 Surf 上被取消了' }; return
|
| 286 |
+
case 'done': st.done = true; return
|
| 287 |
+
default:
|
| 288 |
+
}
|
| 289 |
+
}
|
| 290 |
+
// 发一条消息(message 为空 = 接回服务器上正在生成的回答)
|
| 291 |
+
async function surfConverse(cfg, st, { sid, message, model, effort, instant }) {
|
| 292 |
+
const mode = instant ? 'instant' : 'task'
|
| 293 |
+
const deadline = Date.now() + 40 * 60000
|
| 294 |
+
let first = !!message, attempt = 0
|
| 295 |
+
for (;;) {
|
| 296 |
+
const ctrl = new AbortController()
|
| 297 |
+
st.abort = () => { try { ctrl.abort() } catch {} }
|
| 298 |
+
const body = first
|
| 299 |
+
? { message, mode, stream_chunks: true, ...(model && !instant ? { model } : {}), ...(effort && !instant ? { thinking_effort: effort } : {}) }
|
| 300 |
+
: { message: '', mode, stream_chunks: true }
|
| 301 |
+
let res
|
| 302 |
+
try { res = await surfFetch(cfg, `/muninn/v2/crypto-agent/sessions/${sid}/chat?lang=zh`, { method: 'POST', body, sse: true, signal: ctrl.signal, lastId: first ? null : st.lastId }) }
|
| 303 |
+
catch (e) {
|
| 304 |
+
if (st.cancelled) break
|
| 305 |
+
if (++attempt > 5 || Date.now() > deadline) throw bad('连接 Surf 失败:' + e.message, 502)
|
| 306 |
+
await sleep(Math.min(1000 * 2 ** attempt, 15000)); first = first && !st.events; continue
|
| 307 |
+
}
|
| 308 |
+
if (!res.ok) throw surfErr(res.status, await res.text(), '发送失败,Surf 返回')
|
| 309 |
+
first = false
|
| 310 |
+
const reader = res.body.getReader()
|
| 311 |
+
const dec = new TextDecoder()
|
| 312 |
+
let buf = '', lastAt = Date.now()
|
| 313 |
+
const stall = setInterval(() => { if (Date.now() - lastAt > 75000) { try { ctrl.abort() } catch {} } }, 5000)
|
| 314 |
+
try {
|
| 315 |
+
for (;;) {
|
| 316 |
+
const { done, value } = await reader.read()
|
| 317 |
+
if (done) break
|
| 318 |
+
lastAt = Date.now()
|
| 319 |
+
buf = parseSSE(buf + dec.decode(value, { stream: true }), ev => surfHandle(ev, st))
|
| 320 |
+
if (st.done) break
|
| 321 |
+
}
|
| 322 |
+
} catch { /* 断开 */ } finally { clearInterval(stall) }
|
| 323 |
+
if (st.done || st.error || st.cancelled) break
|
| 324 |
+
if (Date.now() > deadline) { st.timeout = true; break }
|
| 325 |
+
const on = await surfStreaming(cfg, sid)
|
| 326 |
+
if (on === false) break
|
| 327 |
+
if (++attempt > 8) break
|
| 328 |
+
await sleep(Math.min(1000 * attempt, 10000))
|
| 329 |
+
}
|
| 330 |
+
try { st.abort && st.abort() } catch {}
|
| 331 |
+
return st
|
| 332 |
+
}
|
| 333 |
+
// 服务器重启等原因丢了后台任务:去 Surf 上把最后一条回答取回来
|
| 334 |
+
async function surfLastReply(cfg, sid) {
|
| 335 |
+
const d = await surfJson(cfg, `/muninn/v1/crypto-agent/sessions/${sid}/messages?turn_limit=1&limit=50&event_limit=1`)
|
| 336 |
+
const msgs = (d && d.messages) || []
|
| 337 |
+
const last = msgs.filter(m => m.role && m.role !== 'user').pop()
|
| 338 |
+
return last ? String(last.content || '') : ''
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
/* ----- 通用接口 ----- */
|
| 342 |
const getPath = (obj, p) => String(p || '').split('.').filter(Boolean).reduce((o, k) => (o == null ? o : o[/^\d+$/.test(k) ? Number(k) : k]), obj)
|
| 343 |
const fill = (tpl, vars, jsonMode) => String(tpl).replace(/\{\{(\w+)\}\}/g, (_, k) => { const v = vars[k] ?? ''; return jsonMode ? JSON.stringify(String(v)).slice(1, -1) : String(v) })
|
| 344 |
+
async function callGeneric(cfg, system, prompt) {
|
| 345 |
+
if (!cfg.endpoint) throw bad('还没有设置协作 AI 的接口地址:在「AI 协作 → 协作 AI」里填写')
|
| 346 |
+
if (!cfg.token && cfg.mode !== 'custom') throw bad('还没有保存协作 AI 的令牌(Token),或令牌已被清除')
|
| 347 |
const ctrl = new AbortController()
|
| 348 |
+
const timer = setTimeout(() => ctrl.abort(), 600000)
|
|
|
|
| 349 |
try {
|
| 350 |
let headers = { 'Content-Type': 'application/json' }, body
|
| 351 |
if (cfg.mode === 'openai') {
|
|
|
|
| 361 |
}
|
| 362 |
const r = await fetch(cfg.endpoint, { method: 'POST', headers, body, signal: ctrl.signal })
|
| 363 |
const raw = await r.text()
|
| 364 |
+
if (!r.ok) throw Object.assign(bad(`协作 AI 返回 ${r.status}${r.status === 401 || r.status === 403 ? ':令牌可能已过期,请到「AI 协作 → 协作 AI」更新令牌' : ''}|${raw.slice(0, 400)}`, 502), { http: r.status })
|
|
|
|
|
|
|
|
|
|
| 365 |
let reply = ''
|
| 366 |
const ct = r.headers.get('content-type') || ''
|
| 367 |
if (cfg.sse || ct.includes('event-stream')) {
|
|
|
|
| 381 |
else reply = raw
|
| 382 |
if (typeof reply !== 'string') reply = JSON.stringify(reply)
|
| 383 |
}
|
| 384 |
+
if (!String(reply).trim()) throw bad('协作 AI 没有返回内容(检查「回复所在字段」设置)', 502)
|
| 385 |
+
return reply
|
| 386 |
} finally { clearTimeout(timer) }
|
| 387 |
}
|
| 388 |
|
| 389 |
+
// 把作品资料打包。attach: overview / bible / outline / toc / chapters:1-3 / chapter:<id或章号>
|
| 390 |
async function material(pid, attach, maxChars) {
|
| 391 |
const P = await projects.getProject(pid)
|
| 392 |
const parts = []
|
|
|
|
| 411 |
if (text.length > maxChars) text = text.slice(0, maxChars) + `\n\n(资料超过 ${maxChars} 字,后面已截断)`
|
| 412 |
return { text, project: P.project }
|
| 413 |
}
|
| 414 |
+
const BASE_SYSTEM = [
|
| 415 |
+
'你在和另一位 AI(写作 AI)协作。写作 AI 正在一个小说写作工作台上帮一位新人作者在番茄小说平台写书,它会把任务和作品资料发给你。',
|
| 416 |
+
'通用要求:用中文回答;只根据给你的资料和可靠信息判断,引用资料时标明出处(章号或条目);结论先行、条理清楚;拿不准的地方直接说拿不准。',
|
| 417 |
+
'不要编造平台规则或数据;不要提供照抄现成作品的内容;涉及番茄内容红线的写法一律不建议。',
|
|
|
|
|
|
|
|
|
|
| 418 |
].join('\n')
|
| 419 |
+
const TASK_SYSTEM = {
|
| 420 |
+
review: '本次任务:审查。你是严格、坦率的网络小说责任编辑,熟悉番茄小说的内容规范、签约标准和读者口味。按严重程度排序:先说会导致逻辑崩坏、违反平台规定或审核不过的问题,再说可以更好的地方;每个问题给出可执行的修改方向;没问题的部分直接说「无问题」;不要重写整段正文,必要时只给一两句示范。',
|
| 421 |
+
research: '本次任务:调研。请查证并整理写作 AI 问到的信息(平台规则、题材趋势、时代背景、专业知识等),注明信息来源和时间,区分「确定」和「推测」。',
|
| 422 |
+
idea: '本次任务:出主意。请给出多个差异明显的方案,每个方案说明亮点、风险和适合的读者,最后给出你的推荐和理由。',
|
| 423 |
+
draft: '本次任务:起草。请按要求写出草稿,供写作 AI 参考和改写;保持番茄平台的短句、强节奏风格,不出现违规内容。',
|
| 424 |
+
other: '',
|
| 425 |
+
}
|
| 426 |
const logKey = pid => (pid ? projectKey(pid, 'reviewer/log.json') : 'agent/reviewer_log.json')
|
| 427 |
+
async function patchRec(pid, aid, patch, insert = false) {
|
| 428 |
+
return withLock(`reviewer:${pid}`, async () => {
|
| 429 |
+
const d = await readJson(logKey(pid), { items: [] })
|
| 430 |
+
const items = d.items || []
|
| 431 |
+
const i = items.findIndex(x => x.ask_id === aid)
|
| 432 |
+
if (i >= 0) items[i] = { ...items[i], ...patch, updated_at: now() }
|
| 433 |
+
else if (insert) items.unshift(patch)
|
| 434 |
+
else return null
|
| 435 |
+
await writeJson(logKey(pid), { items: items.slice(0, 200), updated_at: now() })
|
| 436 |
+
return i >= 0 ? items[i] : patch
|
| 437 |
+
})
|
| 438 |
+
}
|
| 439 |
+
const recState = x => x.state || (x.ok ? 'done' : 'error')
|
| 440 |
+
const jobs = new Map() // ask_id -> { st, promise }
|
| 441 |
+
function startJob(pid, rec, cfg, message, attachOnly = false) {
|
| 442 |
+
const st = { text: '', turn: null, lastId: null, done: false, error: null, result: null, sawChunk: false, events: 0, tools: 0 }
|
| 443 |
+
const t0 = Date.now()
|
| 444 |
+
const promise = (async () => {
|
| 445 |
+
try {
|
| 446 |
+
let reply, extra = {}
|
| 447 |
+
if (cfg.mode === 'surf') {
|
| 448 |
+
await surfEnsure(cfg)
|
| 449 |
+
const instant = !!cfg.instant
|
| 450 |
+
await surfConverse(cfg, st, { sid: rec.session_id, message: attachOnly ? '' : message, model: cfg.surf_model || 'pro', effort: cfg.surf_effort || '', instant })
|
| 451 |
+
if (st.cancelled) throw bad('已停止')
|
| 452 |
+
if (st.error && !st.text.trim()) throw Object.assign(bad(st.error.message), { code: st.error.code })
|
| 453 |
+
reply = st.text
|
| 454 |
+
if (attachOnly) { // 中途接回的只有后半段:以 Surf 上保存的完整回答为准
|
| 455 |
+
const full = await surfLastReply(cfg, rec.session_id).catch(() => '')
|
| 456 |
+
if (full.length > reply.length) reply = full
|
| 457 |
+
}
|
| 458 |
+
if (st.ask_user) reply += `\n\n> 对方 AI 反问:${st.ask_user}`
|
| 459 |
+
if (!reply.trim()) {
|
| 460 |
+
reply = await surfLastReply(cfg, rec.session_id).catch(() => '')
|
| 461 |
+
if (!reply.trim()) throw bad(st.timeout ? '等了 40 分钟还没有结束,可能仍在 Surf 上运行,稍后再取' : '对方没有返回内容', 502)
|
| 462 |
+
}
|
| 463 |
+
extra = { turn: st.turn, partial: !st.done || undefined, cost_usd: st.result?.cost_usd ?? null, tools: st.tools || undefined, warn: st.error ? st.error.message : undefined }
|
| 464 |
+
} else {
|
| 465 |
+
reply = await callGeneric(cfg, rec._system, rec._prompt)
|
| 466 |
+
}
|
| 467 |
+
await patchRec(pid, rec.ask_id, { state: 'done', ok: true, reply: String(reply).slice(0, 80000), ms: Date.now() - t0, ...extra })
|
| 468 |
+
} catch (e) {
|
| 469 |
+
await patchRec(pid, rec.ask_id, { state: 'error', ok: false, error: e.message || String(e), http: e.http || null, code: e.code || null, ms: Date.now() - t0 }).catch(() => {})
|
| 470 |
+
} finally { jobs.delete(rec.ask_id) }
|
| 471 |
+
})()
|
| 472 |
+
jobs.set(rec.ask_id, { st, promise })
|
| 473 |
+
return { st, promise }
|
| 474 |
+
}
|
| 475 |
+
const withLive = x => {
|
| 476 |
+
const j = jobs.get(x.ask_id)
|
| 477 |
+
return j ? { ...x, state: 'running', live: true, partial_reply: j.st.text.slice(-4000) } : x
|
| 478 |
+
}
|
| 479 |
+
// 后台任务丢失(例如服务重启):去 Surf 把结果取回,或接着等
|
| 480 |
+
async function recover(pid, x) {
|
| 481 |
+
if (recState(x) !== 'running' || jobs.has(x.ask_id) || !x.session_id) return x
|
| 482 |
+
if (Date.now() - new Date(x.updated_at || x.created_at).getTime() < 60000) return x
|
| 483 |
+
const cfg = await revConfig()
|
| 484 |
+
if (cfg.mode !== 'surf' || !cfg.token) return x
|
| 485 |
+
try {
|
| 486 |
+
await surfEnsure(cfg)
|
| 487 |
+
const on = await surfStreaming(cfg, x.session_id)
|
| 488 |
+
if (on === true) { startJob(pid, x, cfg, '', true); return withLive(x) }
|
| 489 |
+
const reply = await surfLastReply(cfg, x.session_id)
|
| 490 |
+
return (await patchRec(pid, x.ask_id, reply.trim() ? { state: 'done', ok: true, reply: reply.slice(0, 80000), recovered: true } : { state: 'error', ok: false, error: '服务重启后没能取回回复,请重新提问' })) || x
|
| 491 |
+
} catch (e) { return x }
|
| 492 |
+
}
|
| 493 |
+
|
| 494 |
router.post('/reviewer/ask', wrap(async req => {
|
| 495 |
const b = req.body || {}
|
| 496 |
const question = String(b.question || '').trim()
|
| 497 |
if (!question) throw bad('问题不能为空')
|
| 498 |
const pid = b.project_id ? cleanId(b.project_id, 'project_id') : ''
|
| 499 |
+
if (pid) await getProjectOrThrow(pid)
|
| 500 |
const cfg = await revConfig()
|
| 501 |
+
const task = TASKS[b.task] ? b.task : 'review'
|
| 502 |
const attach = (Array.isArray(b.attach) ? b.attach : []).map(String).slice(0, 20)
|
| 503 |
const prof = await getProfile()
|
| 504 |
let mat = { text: '' }
|
| 505 |
if (pid && attach.length) mat = await material(pid, attach, cfg.max_chars || 120000)
|
| 506 |
+
// 接着上一次对话聊(Surf 会话保留上下文)
|
| 507 |
+
let cont = null, sid = null
|
| 508 |
+
if (cfg.mode === 'surf') {
|
| 509 |
+
if (b.continue) {
|
| 510 |
+
const d = await readJson(logKey(pid), { items: [] })
|
| 511 |
+
cont = b.continue === true || b.continue === 'last'
|
| 512 |
+
? (d.items || []).find(x => x.session_id && (!b.topic || x.topic === b.topic))
|
| 513 |
+
: (d.items || []).find(x => x.ask_id === b.continue)
|
| 514 |
+
if (!cont || !cont.session_id) throw bad('找不到要接着聊的那次对话(continue 填 ask_id,或 "last")', 404)
|
| 515 |
+
if (jobs.has(cont.ask_id)) throw bad('上一条还在进行中,等它结束再接着问', 409)
|
| 516 |
+
sid = cont.session_id
|
| 517 |
+
} else sid = crypto.randomUUID()
|
| 518 |
+
}
|
| 519 |
+
const userSys = task === 'review' && cfg.system ? cfg.system : TASK_SYSTEM[task]
|
| 520 |
+
const system = [BASE_SYSTEM, userSys, `作者当前状态:${LABEL.account[prof.account]};${LABEL.first_book[prof.first_book]};${LABEL.contract[prof.contract]}。${prof.note || ''}`].filter(Boolean).join('\n\n')
|
| 521 |
+
const prompt = [mat.project ? `作品:《${mat.project.title}》` : '', `${TASKS[task]}任务 · ${String(b.topic || '').slice(0, 80) || '提问'}\n\n${question}`, mat.text ? `\n以下是作品资料:\n\n${mat.text}` : ''].filter(Boolean).join('\n')
|
| 522 |
+
const message = cont ? prompt : `【协作说明】\n${system}\n\n【任务】\n${prompt}`
|
| 523 |
+
const rec = {
|
| 524 |
+
ask_id: id('ask'), project_id: pid || null, task, topic: String(b.topic || '').slice(0, 80), question, attach,
|
| 525 |
+
asked_by: String(b.asked_by || '写作 AI').slice(0, 40), reviewer: cfg.name || '协作 AI', created_at: now(),
|
| 526 |
+
prompt_chars: message.length, state: 'running', ok: false, status: 'new',
|
| 527 |
+
engine: cfg.mode === 'surf' ? `Surf · ${cfg.instant ? 'Instant' : (SURF_MODELS[cfg.surf_model] || cfg.surf_model)}${!cfg.instant && cfg.surf_effort ? ` · 思考 ${cfg.surf_effort}` : ''}` : `${cfg.mode} · ${cfg.model || ''}`,
|
| 528 |
+
session_id: sid, url: sid ? `${SURF_WEB}/chat/${sid}` : null, continued_from: cont ? cont.ask_id : null,
|
| 529 |
+
}
|
| 530 |
+
await patchRec(pid, rec.ask_id, rec, true)
|
| 531 |
+
const job = startJob(pid, { ...rec, _system: system, _prompt: prompt }, cfg, message)
|
| 532 |
+
const wait = Math.min(270, Math.max(0, b.wait == null ? 50 : Number(b.wait) || 0))
|
| 533 |
+
if (wait) await Promise.race([job.promise, sleep(wait * 1000)])
|
| 534 |
+
const d = await readJson(logKey(pid), { items: [] })
|
| 535 |
+
const x = (d.items || []).find(y => y.ask_id === rec.ask_id) || rec
|
| 536 |
+
return withLive(x)
|
| 537 |
}))
|
| 538 |
router.get('/reviewer/log', wrap(async req => {
|
| 539 |
const pid = req.query.project_id ? cleanId(req.query.project_id, 'project_id') : ''
|
| 540 |
const d = await readJson(logKey(pid), { items: [] })
|
| 541 |
+
const items = (d.items || []).slice(0, Number(req.query.n) || 50)
|
| 542 |
+
// 丢了后台任务的「进行中」记录,顺手去取回(不阻塞列表)
|
| 543 |
+
items.filter(x => recState(x) === 'running' && !jobs.has(x.ask_id)).slice(0, 3).forEach(x => recover(pid, x).catch(() => {}))
|
| 544 |
+
return { items: items.map(withLive) }
|
| 545 |
+
}))
|
| 546 |
+
router.get('/reviewer/log/:aid', wrap(async req => {
|
| 547 |
+
const pid = req.query.project_id ? cleanId(req.query.project_id, 'project_id') : ''
|
| 548 |
+
const wait = Math.min(270, Math.max(0, Number(req.query.wait) || 0))
|
| 549 |
+
if (wait && jobs.has(req.params.aid)) await Promise.race([jobs.get(req.params.aid).promise, sleep(wait * 1000)])
|
| 550 |
+
const d = await readJson(logKey(pid), { items: [] })
|
| 551 |
+
const x = (d.items || []).find(y => y.ask_id === req.params.aid)
|
| 552 |
+
if (!x) throw bad('没有这条记录', 404)
|
| 553 |
+
return withLive(await recover(pid, x))
|
| 554 |
+
}))
|
| 555 |
+
// 停止进行中的提问
|
| 556 |
+
router.post('/reviewer/log/:aid/cancel', wrap(async req => {
|
| 557 |
+
const pid = req.body?.project_id ? cleanId(req.body.project_id, 'project_id') : ''
|
| 558 |
+
const j = jobs.get(req.params.aid)
|
| 559 |
+
const d = await readJson(logKey(pid), { items: [] })
|
| 560 |
+
const x = (d.items || []).find(y => y.ask_id === req.params.aid)
|
| 561 |
+
if (!x) throw bad('没有这条记录', 404)
|
| 562 |
+
if (j) { j.st.cancelled = true; try { j.st.abort && j.st.abort() } catch {} }
|
| 563 |
+
const cfg = await revConfig()
|
| 564 |
+
if (cfg.mode === 'surf' && x.session_id && cfg.token) await surfJson(cfg, `/muninn/v1/crypto-agent/sessions/${x.session_id}/cancel`, { method: 'POST' }).catch(() => {})
|
| 565 |
+
if (j) await j.promise.catch(() => {})
|
| 566 |
+
return patchRec(pid, x.ask_id, { state: 'error', ok: false, error: '已停止' })
|
| 567 |
}))
|
| 568 |
+
// 写作 AI 处理完回复后,回写处理结果(采纳/部分采纳/不采纳 + 说明)
|
| 569 |
router.patch('/reviewer/log/:aid', wrap(async req => {
|
| 570 |
const b = req.body || {}
|
| 571 |
const pid = b.project_id ? cleanId(b.project_id, 'project_id') : ''
|
| 572 |
+
const patch = {}
|
| 573 |
+
if (['new', 'adopted', 'partial', 'rejected'].includes(b.status)) patch.status = b.status
|
| 574 |
+
if (b.response !== undefined) patch.response = String(b.response).slice(0, 8000)
|
| 575 |
+
const it = await patchRec(pid, req.params.aid, patch)
|
| 576 |
+
if (!it) throw bad('没有这条记录', 404)
|
| 577 |
+
return it
|
| 578 |
+
}))
|
| 579 |
+
// 检查连接:Surf 查账号、令牌剩余时间和积分(不花积分)
|
| 580 |
+
router.post('/reviewer/check', wrap(async () => {
|
| 581 |
+
const cfg = await revConfig()
|
| 582 |
+
if (cfg.mode !== 'surf') return { ok: null, mode: cfg.mode, note: '通用接口没有免费的检查方式,请用「发一条测试」' }
|
| 583 |
+
await surfEnsure(cfg)
|
| 584 |
+
const me = await surfJson(cfg, '/muninn/v1/auth/me')
|
| 585 |
+
const u = (me && (me.user || me)) || {}
|
| 586 |
+
let credits = null
|
| 587 |
+
try { credits = await surfJson(cfg, '/gateway/v1/me/credit-balance') } catch {}
|
| 588 |
+
const exp = jwtExp(cfg.token)
|
| 589 |
+
return {
|
| 590 |
+
ok: true, mode: 'surf', user: { name: u.name || u.username || u.nickname || '', email: u.email ? String(u.email).replace(/^(.).*(@.*)$/, '$1***$2') : '', plan: u.subscription?.subscription_type || null },
|
| 591 |
+
token_expires_in_min: exp ? Math.round((exp - Date.now()) / 60000) : null, auto_refresh: !!(cfg.auto_refresh && cfg.refresh_token), credits,
|
| 592 |
+
}
|
| 593 |
}))
|
| 594 |
|
| 595 |
/* ---------------- AI 工作守则(人和 AI 共读) ---------------- */
|
|
|
|
| 636 |
'1. **动笔前**:读作者状态、作品资料、上一章结尾;确认本章目标。',
|
| 637 |
'2. **写作**:一章一章写,每章写完存为新版本(`POST .../chapters/{章节ID}/versions`,`created_by` 填 `AI`),不要覆盖作者的版本。',
|
| 638 |
'3. **自查**:写完一章,读 `/fanqie/api/agent/rules` 里的番茄平台规定,逐条检查本章,把结果写入检查记录(见第 5 节)。',
|
| 639 |
+
'4. **请协作 AI 把关或帮忙**:概览、圣经、大纲有重大改动,或写完一卷,就请协作 AI 审查;需要查资料、出方案时也可以派给它(见第 6 节)。读完回复再改,并回写处理结果。',
|
| 640 |
'5. **按批注修改**:作者说「按批注修改第 X 章」时,读该章待改批注,逐条改正文、存新版本;在每条批注上写 `reply`(改了什么)并把 `status` 改成 `fixed`(`PATCH .../notes/{批注ID}`)。',
|
| 641 |
'6. **交付说明**:每次工作结束,用三五句话告诉作者做了什么、哪些地方拿不准。', '')
|
| 642 |
L.push('## 5. 检查记录:自查清单与平台规定', '',
|
|
|
|
| 644 |
'- 检查由你(AI)逐条阅读正文后判断,**不能用关键词匹配代替阅读**。',
|
| 645 |
'- 写入:`POST /fanqie/api/agent/audits`,字段:`project_id`、`kind`(`checklist` 自查清单 / `platform` 平台规定 / `logic` 逻辑)、`scope`(`book` / `chapter`)、`chapter_id`、`version_id`、`by`、`summary`、`items[]`(`id`、`title`、`result`=pass/warn/fail/na、`note`、`quote` 引用原文、`fix` 修改建议)。',
|
| 646 |
'- 作者在工作台「检查」和「手册 → 自查清单」里看到这些结果。', '')
|
| 647 |
+
L.push('## 6. 协作 AI(另一个 AI,可以派活)', '',
|
| 648 |
+
`- 当前设置:${cfg.mode === 'surf' ? `Surf Chat(${SURF_MODELS[cfg.surf_model] || cfg.surf_model})` : cfg.endpoint ? `${cfg.mode} 接口` : '接口未配置'};令牌${cfg.token ? `已保存(末 4 位 ${String(cfg.token).slice(-4)}${cfg.refresh_token && cfg.auto_refresh ? ',会自动续期' : ',约 1 小时过期'})` : '未保存'}。令牌只存在服务器上,你看不到也不需要看到。`,
|
| 649 |
+
'- 它能做的活:`review` 审查(默认)、`research` 调研、`idea` 出主意、`draft` 起草、`other` 其他。例如:问它概览、圣经、大纲是否合乎逻辑;查某个年代的生活细节;给第 X 章出三种冲突方案。',
|
| 650 |
+
'- 提问:`POST /fanqie/api/agent/reviewer/ask`,字段:`project_id`、`task`、`topic`(如「圣经逻辑」)、`question`、`attach`(可选:`overview`、`bible`、`outline`、`toc`、`chapters:1-5`、`chapter:{章节ID或章号}`)、`wait`(最多等几秒,默认 50)、`continue`(填上一次的 `ask_id` 或 `"last"`,就在同一个对话里接着问,对方记得上下文)。',
|
| 651 |
+
'- 回复要几分钟时,接口先返回 `state: "running"`;之后用 `GET /fanqie/api/agent/reviewer/log/{ask_id}?project_id=&wait=120` 取结果(`state` 变成 `done` 或 `error`)。不要重复提问同一件事。',
|
| 652 |
+
'- 读回复后自己判断采纳哪些——它的意见只是参考,与守则或作者要求冲突时以守则和作者为准。改完用 `PATCH /fanqie/api/agent/reviewer/log/{ask_id}` 回写 `status`(adopted / partial / rejected)和 `response`(怎么处理的)。',
|
| 653 |
+
'- 不把「素材采集」的任何内容发给它(你本来也读不到);只发作品资料和你自己写的问题。',
|
| 654 |
+
'- 返回令牌过期(401/403)或积分用完:停下来告诉作者,请作者到「AI 协作 → 协作 AI」更新令牌,不要自己找令牌。', '')
|
| 655 |
L.push('## 7. 作品列表', '', ...((list.projects || []).map(p => `- 《${p.title}》 ID:\`${p.project_id}\``)), '')
|
| 656 |
L.push('---', '每次请求都要带访问密码请求头 `x-app-password`。本守则地址:`/fanqie/api/agent/guide.md`。')
|
| 657 |
return L.filter(x => x !== null && x !== undefined).join('\n')
|
fanqie/dist/index.html
CHANGED
|
@@ -8,8 +8,8 @@
|
|
| 8 |
<title>小说写作台</title>
|
| 9 |
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='12' fill='%23b8432f'/%3E%3Ctext x='32' y='44' font-size='34' text-anchor='middle' fill='%23fff' font-family='serif'%3E%E6%96%87%3C/text%3E%3C/svg%3E" />
|
| 10 |
<script>try{var t=localStorage.getItem('xs_theme');if(t==='night')document.documentElement.dataset.theme='night'}catch(e){}</script>
|
| 11 |
-
<script type="module" crossorigin src="/assets/index-
|
| 12 |
-
<link rel="stylesheet" crossorigin href="/assets/index-
|
| 13 |
</head>
|
| 14 |
<body>
|
| 15 |
<div id="root"></div>
|
|
|
|
| 8 |
<title>小说写作台</title>
|
| 9 |
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='12' fill='%23b8432f'/%3E%3Ctext x='32' y='44' font-size='34' text-anchor='middle' fill='%23fff' font-family='serif'%3E%E6%96%87%3C/text%3E%3C/svg%3E" />
|
| 10 |
<script>try{var t=localStorage.getItem('xs_theme');if(t==='night')document.documentElement.dataset.theme='night'}catch(e){}</script>
|
| 11 |
+
<script type="module" crossorigin src="/assets/index-ZuCQ04aJ.js"></script>
|
| 12 |
+
<link rel="stylesheet" crossorigin href="/assets/index-DjI2iQEM.css">
|
| 13 |
</head>
|
| 14 |
<body>
|
| 15 |
<div id="root"></div>
|
public/assets/{index-B6KDOQXi.css → index-DjI2iQEM.css}
RENAMED
|
The diff for this file is too large to render.
See raw diff
|
|
|
public/assets/{index-Qi8bPEnM.js → index-ZuCQ04aJ.js}
RENAMED
|
The diff for this file is too large to render.
See raw diff
|
|
|
public/index.html
CHANGED
|
@@ -8,8 +8,8 @@
|
|
| 8 |
<title>小说写作台</title>
|
| 9 |
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='12' fill='%23b8432f'/%3E%3Ctext x='32' y='44' font-size='34' text-anchor='middle' fill='%23fff' font-family='serif'%3E%E6%96%87%3C/text%3E%3C/svg%3E" />
|
| 10 |
<script>try{var t=localStorage.getItem('xs_theme');if(t==='night')document.documentElement.dataset.theme='night'}catch(e){}</script>
|
| 11 |
-
<script type="module" crossorigin src="/assets/index-
|
| 12 |
-
<link rel="stylesheet" crossorigin href="/assets/index-
|
| 13 |
</head>
|
| 14 |
<body>
|
| 15 |
<div id="root"></div>
|
|
|
|
| 8 |
<title>小说写作台</title>
|
| 9 |
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='12' fill='%23b8432f'/%3E%3Ctext x='32' y='44' font-size='34' text-anchor='middle' fill='%23fff' font-family='serif'%3E%E6%96%87%3C/text%3E%3C/svg%3E" />
|
| 10 |
<script>try{var t=localStorage.getItem('xs_theme');if(t==='night')document.documentElement.dataset.theme='night'}catch(e){}</script>
|
| 11 |
+
<script type="module" crossorigin src="/assets/index-ZuCQ04aJ.js"></script>
|
| 12 |
+
<link rel="stylesheet" crossorigin href="/assets/index-DjI2iQEM.css">
|
| 13 |
</head>
|
| 14 |
<body>
|
| 15 |
<div id="root"></div>
|
ui-src/src/api.ts
CHANGED
|
@@ -239,12 +239,21 @@ export interface Audit {
|
|
| 239 |
chapter_number: number | null; version_id: string | null; by: string; status: 'pass' | 'warn' | 'fail'; summary: string; items: AuditItem[]; created_at: string
|
| 240 |
}
|
| 241 |
export interface ReviewerCfg {
|
| 242 |
-
name: string; mode: 'openai' | 'anthropic' | 'custom'; endpoint: string; model: string; headers_tpl: string; body_tpl: string; reply_path: string
|
| 243 |
sse: boolean; max_chars: number; system: string; note?: string; token_set: boolean; token_tail: string; token_saved_at?: string; updated_at?: string
|
|
|
|
|
|
|
|
|
|
| 244 |
}
|
| 245 |
export interface ReviewerAsk {
|
| 246 |
ask_id: string; project_id: string | null; topic: string; question: string; attach: string[]; asked_by: string; reviewer: string
|
| 247 |
created_at: string; ok: boolean; reply?: string; error?: string; http?: number | null; ms?: number; status: 'new' | 'adopted' | 'partial' | 'rejected'; response?: string
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 248 |
}
|
| 249 |
const A = '/fanqie/api/agent'
|
| 250 |
export const agentApi = {
|
|
@@ -255,7 +264,9 @@ export const agentApi = {
|
|
| 255 |
deleteAudit: (pid: string, aid: string) => del(`${A}/audits/${aid}${qs({ project_id: pid })}`),
|
| 256 |
reviewer: () => get<ReviewerCfg>(`${A}/reviewer`),
|
| 257 |
saveReviewer: (b: Partial<ReviewerCfg> & { token?: string; clear_token?: boolean }) => put<ReviewerCfg>(`${A}/reviewer`, b),
|
| 258 |
-
ask: (b: { project_id?: string; topic?: string; question: string; attach?: string[]; asked_by?: string }) => post<ReviewerAsk>(`${A}/reviewer/ask`, b),
|
|
|
|
|
|
|
| 259 |
log: (project_id?: string, n = 50) => get<{ items: ReviewerAsk[] }>(`${A}/reviewer/log${qs({ project_id, n })}`),
|
| 260 |
patchLog: (aid: string, b: { project_id?: string; status?: string; response?: string }) => patch<ReviewerAsk>(`${A}/reviewer/log/${aid}`, b),
|
| 261 |
guideMd: async () => {
|
|
|
|
| 239 |
chapter_number: number | null; version_id: string | null; by: string; status: 'pass' | 'warn' | 'fail'; summary: string; items: AuditItem[]; created_at: string
|
| 240 |
}
|
| 241 |
export interface ReviewerCfg {
|
| 242 |
+
name: string; mode: 'surf' | 'openai' | 'anthropic' | 'custom'; endpoint: string; model: string; headers_tpl: string; body_tpl: string; reply_path: string
|
| 243 |
sse: boolean; max_chars: number; system: string; note?: string; token_set: boolean; token_tail: string; token_saved_at?: string; updated_at?: string
|
| 244 |
+
refresh_set?: boolean; token_expires_at?: string | null; token_refreshed_at?: string; auto_refresh?: boolean
|
| 245 |
+
surf_model?: string; surf_effort?: string; instant?: boolean
|
| 246 |
+
surf_models?: Record<string, string>; surf_efforts?: string[]; tasks?: Record<string, string>
|
| 247 |
}
|
| 248 |
export interface ReviewerAsk {
|
| 249 |
ask_id: string; project_id: string | null; topic: string; question: string; attach: string[]; asked_by: string; reviewer: string
|
| 250 |
created_at: string; ok: boolean; reply?: string; error?: string; http?: number | null; ms?: number; status: 'new' | 'adopted' | 'partial' | 'rejected'; response?: string
|
| 251 |
+
task?: string; state?: 'running' | 'done' | 'error'; live?: boolean; partial_reply?: string; engine?: string; url?: string | null; session_id?: string | null
|
| 252 |
+
continued_from?: string | null; cost_usd?: number | null; turn?: number; partial?: boolean; warn?: string; recovered?: boolean; code?: string | null
|
| 253 |
+
}
|
| 254 |
+
export interface ReviewerCheck {
|
| 255 |
+
ok: boolean | null; mode: string; note?: string; user?: { name: string; email: string; plan: string | null }
|
| 256 |
+
token_expires_in_min?: number | null; auto_refresh?: boolean; credits?: any
|
| 257 |
}
|
| 258 |
const A = '/fanqie/api/agent'
|
| 259 |
export const agentApi = {
|
|
|
|
| 264 |
deleteAudit: (pid: string, aid: string) => del(`${A}/audits/${aid}${qs({ project_id: pid })}`),
|
| 265 |
reviewer: () => get<ReviewerCfg>(`${A}/reviewer`),
|
| 266 |
saveReviewer: (b: Partial<ReviewerCfg> & { token?: string; clear_token?: boolean }) => put<ReviewerCfg>(`${A}/reviewer`, b),
|
| 267 |
+
ask: (b: { project_id?: string; topic?: string; question: string; attach?: string[]; asked_by?: string; task?: string; wait?: number; continue?: string }) => post<ReviewerAsk>(`${A}/reviewer/ask`, b),
|
| 268 |
+
check: () => post<ReviewerCheck>(`${A}/reviewer/check`, {}),
|
| 269 |
+
cancelAsk: (aid: string, project_id?: string | null) => post<ReviewerAsk>(`${A}/reviewer/log/${aid}/cancel`, { project_id: project_id || undefined }),
|
| 270 |
log: (project_id?: string, n = 50) => get<{ items: ReviewerAsk[] }>(`${A}/reviewer/log${qs({ project_id, n })}`),
|
| 271 |
patchLog: (aid: string, b: { project_id?: string; status?: string; response?: string }) => patch<ReviewerAsk>(`${A}/reviewer/log/${aid}`, b),
|
| 272 |
guideMd: async () => {
|
ui-src/src/rooms/Agent.tsx
CHANGED
|
@@ -1,9 +1,9 @@
|
|
| 1 |
import React, { useEffect, useMemo, useState } from 'react'
|
| 2 |
import {
|
| 3 |
Bot, Copy, ScrollText, UserRound, ShieldCheck, ClipboardCheck, KeyRound, Save, Trash2, Send, CircleCheck, AlertTriangle, XCircle,
|
| 4 |
-
MinusCircle, ChevronDown, ChevronUp, MessageSquareQuote, RefreshCw,
|
| 5 |
} from 'lucide-react'
|
| 6 |
-
import { agentApi, getPassword, projectsApi, type AgentProfile, type Audit, type ReviewerAsk, type ReviewerCfg } from '../api'
|
| 7 |
import { copyText, cx, fmtAgo, fmtDate, go, useAsync } from '../lib'
|
| 8 |
import { Empty, ErrorNote, Field, Loading, Segmented, Spinner, Tabs, Tag, useConfirm, useToast } from '../ui'
|
| 9 |
import { Md } from '../md'
|
|
@@ -89,14 +89,14 @@ export default function AgentRoom({ tab }: { tab: string }) {
|
|
| 89 |
<header className="room-head">
|
| 90 |
<div>
|
| 91 |
<div className="eyebrow"><Bot size={14} />AI 协作</div>
|
| 92 |
-
<h1 className="room-title serif">写作 AI 的守则、作者状态与
|
| 93 |
-
<p className="muted small-note">写作由 AI 直接在工作台上完成:它先读这里的守则和你的状态,再动笔;写完由它自查
|
| 94 |
</div>
|
| 95 |
</header>
|
| 96 |
<Tabs<T> value={t} onChange={v => go(`agent/${v}`)} className="room-tabs" items={[
|
| 97 |
{ id: 'guide', label: <><ScrollText size={14} />AI 守则</> },
|
| 98 |
{ id: 'profile', label: <><UserRound size={14} />作者状态</> },
|
| 99 |
-
{ id: 'reviewer', label: <><
|
| 100 |
{ id: 'audits', label: <><ClipboardCheck size={14} />检查记录</> },
|
| 101 |
]} />
|
| 102 |
<div className="room-body">
|
|
@@ -117,7 +117,7 @@ function GuideTab() {
|
|
| 117 |
return (
|
| 118 |
<div className="agent-guide">
|
| 119 |
<div className="sheet tight">
|
| 120 |
-
<p className="muted small-note">这份守则是<b>写给 AI 的工作规则</b>,同时排版成你也能读的样子:它规定 AI 能读什么、不能碰什么、按什么流程写、怎么自查、怎么请
|
| 121 |
<SayToAi text={opener} hint="每次开新对话时对 AI 说" />
|
| 122 |
<div className="row gap wrap" style={{ marginTop: 10 }}>
|
| 123 |
<button className="btn small ghost" onClick={async () => { await copyText(md.data || ''); toast('守则全文已复制', 'ok') }} disabled={!md.data}><Copy size={13} />复制全文</button>
|
|
@@ -175,7 +175,22 @@ function ProfileTab() {
|
|
| 175 |
)
|
| 176 |
}
|
| 177 |
|
| 178 |
-
const MODES = [{ id: 'openai', label: 'OpenAI 兼容' }, { id: 'anthropic', label: 'Anthropic' }, { id: 'custom', label: '自定义' }] as const
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
function ReviewerTab() {
|
| 180 |
const toast = useToast()
|
| 181 |
const confirm = useConfirm()
|
|
@@ -183,69 +198,108 @@ function ReviewerTab() {
|
|
| 183 |
const [f, setF] = useState<ReviewerCfg | null>(null)
|
| 184 |
const [token, setToken] = useState('')
|
| 185 |
const [busy, setBusy] = useState('')
|
|
|
|
|
|
|
| 186 |
const [pid, setPid] = useState('')
|
| 187 |
const [scope, setScope] = useState<'book' | 'all'>('book')
|
| 188 |
const log = useAsync(() => agentApi.log(scope === 'book' ? pid || undefined : undefined, 50), [pid, scope])
|
| 189 |
useEffect(() => { if (cfg.data) setF(cfg.data) }, [cfg.data])
|
| 190 |
if (!f) return cfg.error ? <ErrorNote error={cfg.error} onRetry={cfg.reload} /> : <Loading />
|
| 191 |
const set = (k: keyof ReviewerCfg, v: any) => setF({ ...f, [k]: v })
|
|
|
|
| 192 |
const save = async (extra: Record<string, any> = {}) => {
|
| 193 |
setBusy('save')
|
| 194 |
try {
|
| 195 |
-
const { token_set, token_tail, token_saved_at, updated_at, ...rest } = f
|
| 196 |
const r = await agentApi.saveReviewer({ ...rest, ...(token.trim() ? { token: token.trim() } : {}), ...extra })
|
| 197 |
-
cfg.setData(r); setToken('');
|
|
|
|
| 198 |
} catch (e: any) { toast(e.message, 'err') } finally { setBusy('') }
|
| 199 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
const test = async () => {
|
| 201 |
setBusy('test')
|
| 202 |
try {
|
| 203 |
-
const r = await agentApi.ask({ topic: '连接测试', question: '这是一次连接测试,请只回复「收到」两个字。', asked_by: '作者(测试)' })
|
| 204 |
-
if (r.
|
| 205 |
-
|
|
|
|
| 206 |
} catch (e: any) { toast(e.message, 'err') } finally { setBusy('') }
|
| 207 |
}
|
|
|
|
| 208 |
return (
|
| 209 |
<div className="agent-grid wide-right">
|
| 210 |
<div className="sheet">
|
| 211 |
-
<h2 className="sheet-title serif"><
|
| 212 |
-
<p className="muted small-note">「
|
|
|
|
| 213 |
<div className="token-box">
|
| 214 |
-
<div className="row between">
|
| 215 |
-
<span className="tb-label"><KeyRound size={14} />认证令牌(Token)</span>
|
| 216 |
-
|
| 217 |
</div>
|
| 218 |
<div className="row gap">
|
| 219 |
-
<input className="input" type="password" autoComplete="off" value={token} onChange={e => setToken(e.target.value)} placeholder={f.token_set ? '粘贴新令牌以替换(过期时在这里更新)' : '粘贴令牌'} />
|
| 220 |
-
<button className="btn primary" disabled={!token.trim() || !!busy} onClick={() => save()}><Save size={14} />保存令牌</button>
|
| 221 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
<div className="row between">
|
| 223 |
-
<span className="muted small-note">{f.token_saved_at ? `上次保存:${fmtDate(f.token_saved_at)}` : ''}</span>
|
| 224 |
-
{f.token_set && <button className="link-btn muted" onClick={async () => { if (await confirm({ title: '清除令牌?', body: '清除后写作 AI 将无法
|
| 225 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
</div>
|
| 227 |
<div className="stack">
|
| 228 |
<Field label="名称"><input className="input" value={f.name} onChange={e => set('name', e.target.value)} /></Field>
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
<
|
| 235 |
-
<Field label="
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
</>}
|
| 237 |
-
<label
|
| 238 |
-
<Field label="审查要求(系统提示)" hint="留空则用默认:严格的番茄责任编辑,只审查不代写"><textarea className="textarea" rows={4} value={f.system} onChange={e => set('system', e.target.value)} /></Field>
|
| 239 |
</div>
|
| 240 |
-
<div className="row end gap" style={{ marginTop: 14 }}>
|
| 241 |
-
<button className="btn ghost" disabled={!!busy || !f.
|
|
|
|
| 242 |
<button className="btn primary" disabled={!!busy} onClick={() => save()}>{busy === 'save' ? <Spinner size={14} /> : <Save size={14} />}保存设置</button>
|
| 243 |
</div>
|
| 244 |
-
<p className="muted small-note" style={{ marginTop: 10 }}>你提到的参考脚本没有在项目里找到,所以这里先做成通用格式(OpenAI / Anthropic / 自定义模板都能接)。把脚本发给我后,我会按它的格式补一个专用模式。</p>
|
| 245 |
</div>
|
| 246 |
<div className="sheet">
|
| 247 |
<div className="row between wrap gap">
|
| 248 |
-
<h2 className="sheet-title serif" style={{ margin: 0 }}>
|
| 249 |
<div className="row gap">
|
| 250 |
<Segmented value={scope} onChange={setScope} items={[{ id: 'book', label: '按作品' }, { id: 'all', label: '未关联作品' }]} />
|
| 251 |
{scope === 'book' && <ProjectPicker value={pid} onChange={setPid} />}
|
|
@@ -259,28 +313,55 @@ function ReviewerTab() {
|
|
| 259 |
|
| 260 |
const ASK_ST: Record<string, { t: string; tone: string }> = { new: { t: '待处理', tone: 'warn' }, adopted: { t: '已采纳', tone: 'ok' }, partial: { t: '部分采纳', tone: 'accent' }, rejected: { t: '未采纳', tone: '' } }
|
| 261 |
export function AskLog({ items, error, reload, projectId, empty }: { items?: ReviewerAsk[]; error?: string | null; reload: () => void; projectId?: string; empty?: string }) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
if (error) return <ErrorNote error={error} onRetry={reload} />
|
| 263 |
if (!items) return <Loading />
|
| 264 |
-
if (!items.length) return <Empty title="还没有
|
| 265 |
-
return <div className="ask-log">{items.map(x => <AskItem key={x.ask_id} x={x} />)}</div>
|
| 266 |
}
|
| 267 |
-
function AskItem({ x }: { x: ReviewerAsk }) {
|
|
|
|
|
|
|
| 268 |
const [open, setOpen] = useState(false)
|
| 269 |
const st = ASK_ST[x.status] || ASK_ST.new
|
|
|
|
|
|
|
|
|
|
| 270 |
return (
|
| 271 |
-
<div className={cx('ask',
|
| 272 |
<button className="ask-head" onClick={() => setOpen(o => !o)}>
|
| 273 |
<span className="ask-topic">{x.topic || '提问'}</span>
|
| 274 |
-
{x.
|
|
|
|
|
|
|
|
|
|
| 275 |
<span className="ask-meta">{x.asked_by} · {fmtAgo(x.created_at)}</span>
|
| 276 |
{open ? <ChevronUp size={15} /> : <ChevronDown size={15} />}
|
| 277 |
</button>
|
| 278 |
<p className="ask-q">{x.question}</p>
|
| 279 |
{x.attach?.length > 0 && <div className="gap-s">{x.attach.map(a => <Tag key={a}>{ATT[a.split(':')[0]] || a}{a.includes(':') ? ` ${a.split(':')[1]}` : ''}</Tag>)}</div>}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
{open && <>
|
| 281 |
-
{
|
| 282 |
-
|
|
|
|
|
|
|
|
|
|
| 283 |
{x.response && <div className="ask-resp"><div className="ask-label">写作 AI 的处理</div><Md text={x.response} /></div>}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 284 |
</>}
|
| 285 |
</div>
|
| 286 |
)
|
|
|
|
| 1 |
import React, { useEffect, useMemo, useState } from 'react'
|
| 2 |
import {
|
| 3 |
Bot, Copy, ScrollText, UserRound, ShieldCheck, ClipboardCheck, KeyRound, Save, Trash2, Send, CircleCheck, AlertTriangle, XCircle,
|
| 4 |
+
MinusCircle, ChevronDown, ChevronUp, MessageSquareQuote, RefreshCw, Sparkles, PlugZap, ExternalLink,
|
| 5 |
} from 'lucide-react'
|
| 6 |
+
import { agentApi, getPassword, projectsApi, type AgentProfile, type Audit, type ReviewerAsk, type ReviewerCfg, type ReviewerCheck } from '../api'
|
| 7 |
import { copyText, cx, fmtAgo, fmtDate, go, useAsync } from '../lib'
|
| 8 |
import { Empty, ErrorNote, Field, Loading, Segmented, Spinner, Tabs, Tag, useConfirm, useToast } from '../ui'
|
| 9 |
import { Md } from '../md'
|
|
|
|
| 89 |
<header className="room-head">
|
| 90 |
<div>
|
| 91 |
<div className="eyebrow"><Bot size={14} />AI 协作</div>
|
| 92 |
+
<h1 className="room-title serif">写作 AI 的守则、作者状态与协作</h1>
|
| 93 |
+
<p className="muted small-note">写作由 AI 直接在工作台上完成:它先读这里的守则和你的状态,再动笔;写完由它自查,需要时向「协作 AI」派活(审查、调研、出主意)。你只需要读结果、写批注、告诉它下一步。</p>
|
| 94 |
</div>
|
| 95 |
</header>
|
| 96 |
<Tabs<T> value={t} onChange={v => go(`agent/${v}`)} className="room-tabs" items={[
|
| 97 |
{ id: 'guide', label: <><ScrollText size={14} />AI 守则</> },
|
| 98 |
{ id: 'profile', label: <><UserRound size={14} />作者状态</> },
|
| 99 |
+
{ id: 'reviewer', label: <><Sparkles size={14} />协作 AI</> },
|
| 100 |
{ id: 'audits', label: <><ClipboardCheck size={14} />检查记录</> },
|
| 101 |
]} />
|
| 102 |
<div className="room-body">
|
|
|
|
| 117 |
return (
|
| 118 |
<div className="agent-guide">
|
| 119 |
<div className="sheet tight">
|
| 120 |
+
<p className="muted small-note">这份守则是<b>写给 AI 的工作规则</b>,同时排版成你也能读的样子:它规定 AI 能读什么、不能碰什么、按什么流程写、怎么自查、怎么请协作 AI 把关。作者状态改了,守则会自动更新。</p>
|
| 121 |
<SayToAi text={opener} hint="每次开新对话时对 AI 说" />
|
| 122 |
<div className="row gap wrap" style={{ marginTop: 10 }}>
|
| 123 |
<button className="btn small ghost" onClick={async () => { await copyText(md.data || ''); toast('守则全文已复制', 'ok') }} disabled={!md.data}><Copy size={13} />复制全文</button>
|
|
|
|
| 175 |
)
|
| 176 |
}
|
| 177 |
|
| 178 |
+
const MODES = [{ id: 'surf', label: 'Surf(推荐)' }, { id: 'openai', label: 'OpenAI 兼容' }, { id: 'anthropic', label: 'Anthropic' }, { id: 'custom', label: '自定义' }] as const
|
| 179 |
+
const TASK_T: Record<string, string> = { review: '审查', research: '调研', idea: '出主意', draft: '起草', other: '其他' }
|
| 180 |
+
function leftMin(iso?: string | null) { return iso ? Math.round((new Date(iso).getTime() - Date.now()) / 60000) : null }
|
| 181 |
+
function TokenState({ f }: { f: ReviewerCfg }) {
|
| 182 |
+
if (!f.token_set) return <Tag tone="warn">未保存</Tag>
|
| 183 |
+
const m = leftMin(f.token_expires_at)
|
| 184 |
+
const auto = f.mode === 'surf' && f.refresh_set && f.auto_refresh
|
| 185 |
+
return (
|
| 186 |
+
<span className="gap-s">
|
| 187 |
+
<Tag tone="ok">已保存 · 末 4 位 {f.token_tail}</Tag>
|
| 188 |
+
{m != null && (m > 0 ? <Tag tone={m < 10 && !auto ? 'warn' : ''}>还剩 {m >= 60 ? `${Math.floor(m / 60)} 小时 ${m % 60} 分` : `${m} 分钟`}</Tag> : <Tag tone={auto ? '' : 'err'}>{auto ? '已过期 · 用时自动续期' : '已过期'}</Tag>)}
|
| 189 |
+
{f.mode === 'surf' && <Tag tone={auto ? 'ok' : ''}>{auto ? '自动续期' : '不自动续期'}</Tag>}
|
| 190 |
+
</span>
|
| 191 |
+
)
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
function ReviewerTab() {
|
| 195 |
const toast = useToast()
|
| 196 |
const confirm = useConfirm()
|
|
|
|
| 198 |
const [f, setF] = useState<ReviewerCfg | null>(null)
|
| 199 |
const [token, setToken] = useState('')
|
| 200 |
const [busy, setBusy] = useState('')
|
| 201 |
+
const [chk, setChk] = useState<ReviewerCheck | null>(null)
|
| 202 |
+
const [howto, setHowto] = useState(false)
|
| 203 |
const [pid, setPid] = useState('')
|
| 204 |
const [scope, setScope] = useState<'book' | 'all'>('book')
|
| 205 |
const log = useAsync(() => agentApi.log(scope === 'book' ? pid || undefined : undefined, 50), [pid, scope])
|
| 206 |
useEffect(() => { if (cfg.data) setF(cfg.data) }, [cfg.data])
|
| 207 |
if (!f) return cfg.error ? <ErrorNote error={cfg.error} onRetry={cfg.reload} /> : <Loading />
|
| 208 |
const set = (k: keyof ReviewerCfg, v: any) => setF({ ...f, [k]: v })
|
| 209 |
+
const surf = f.mode === 'surf'
|
| 210 |
const save = async (extra: Record<string, any> = {}) => {
|
| 211 |
setBusy('save')
|
| 212 |
try {
|
| 213 |
+
const { token_set, token_tail, token_saved_at, updated_at, refresh_set, token_expires_at, token_refreshed_at, surf_models, surf_efforts, tasks, ...rest } = f
|
| 214 |
const r = await agentApi.saveReviewer({ ...rest, ...(token.trim() ? { token: token.trim() } : {}), ...extra })
|
| 215 |
+
cfg.setData(r); setToken(''); setChk(null)
|
| 216 |
+
toast(extra.clear_token ? '令牌已清除' : token.trim() ? (r.refresh_set && surf ? '令牌已保存(含续期令牌)' : '令牌已保存') : '已保存', 'ok')
|
| 217 |
} catch (e: any) { toast(e.message, 'err') } finally { setBusy('') }
|
| 218 |
}
|
| 219 |
+
const check = async () => {
|
| 220 |
+
setBusy('check')
|
| 221 |
+
try { const r = await agentApi.check(); setChk(r); cfg.reload(); if (r.ok) toast('连接正常', 'ok') }
|
| 222 |
+
catch (e: any) { setChk(null); toast(e.message, 'err') } finally { setBusy('') }
|
| 223 |
+
}
|
| 224 |
const test = async () => {
|
| 225 |
setBusy('test')
|
| 226 |
try {
|
| 227 |
+
const r = await agentApi.ask({ task: 'other', topic: '连接测试', question: '这是一次连接测试,请只回复「收到」两个字。', asked_by: '作者(测试)', wait: 90 })
|
| 228 |
+
if (r.state === 'running') toast('已发出,对方还在回答,稍后在右边记录里看结果', 'ok')
|
| 229 |
+
else if (r.ok) toast(`连接正常:${(r.reply || '').slice(0, 40)}`, 'ok'); else toast(r.error || '失败', 'err')
|
| 230 |
+
if (scope !== 'all') setScope('all'); else log.reload()
|
| 231 |
} catch (e: any) { toast(e.message, 'err') } finally { setBusy('') }
|
| 232 |
}
|
| 233 |
+
const models = f.surf_models || {}
|
| 234 |
return (
|
| 235 |
<div className="agent-grid wide-right">
|
| 236 |
<div className="sheet">
|
| 237 |
+
<h2 className="sheet-title serif"><Sparkles size={16} />协作 AI 设置</h2>
|
| 238 |
+
<p className="muted small-note">「协作 AI」是另一个 AI,我(写作 AI)在工作中可以向它派活:<b>审查</b>概览、圣经、大纲和章节,<b>调研</b>资料,<b>出主意</b>,<b>起草</b>片段。拿到回复后我自己判断、再动手修改,问答都存在右边。令牌只保存在服务器上,页面和写作 AI 都只能看到末 4 位。</p>
|
| 239 |
+
<Field label="接入方式"><Segmented value={f.mode} onChange={v => set('mode', v)} items={MODES as any} /></Field>
|
| 240 |
<div className="token-box">
|
| 241 |
+
<div className="row between wrap gap">
|
| 242 |
+
<span className="tb-label"><KeyRound size={14} />{surf ? 'Surf 登录令牌' : '认证令牌(Token)'}</span>
|
| 243 |
+
<TokenState f={f} />
|
| 244 |
</div>
|
| 245 |
<div className="row gap">
|
| 246 |
+
<input className="input" type="password" autoComplete="off" value={token} onChange={e => setToken(e.target.value)} placeholder={surf ? '粘贴 SURF_TOKENS 整段,或 Bearer 后面那串' : f.token_set ? '粘贴新令牌以替换(过期时在这里更新)' : '粘贴令牌'} />
|
| 247 |
+
<button className="btn primary" disabled={!token.trim() || !!busy} onClick={() => save()}>{busy === 'save' ? <Spinner size={14} /> : <Save size={14} />}保存令牌</button>
|
| 248 |
</div>
|
| 249 |
+
{surf && <>
|
| 250 |
+
<button className="link-btn" onClick={() => setHowto(h => !h)}>{howto ? '收起' : '怎么拿到令牌?'}</button>
|
| 251 |
+
{howto && <ol className="howto">
|
| 252 |
+
<li>用电脑浏览器打开 <a href="https://asksurf.ai" target="_blank" rel="noreferrer">asksurf.ai</a> 并登录。<b>建议用无痕窗口单独登录一次</b>,原因见下面「自动续期」。</li>
|
| 253 |
+
<li>按 <code>F12</code> 打开开发者工具 → 「Application / 应用」→ 左侧「Local Storage」→ <code>https://asksurf.ai</code>。</li>
|
| 254 |
+
<li>找到 <code>SURF_TOKENS</code>,复制它的整段值(形如 <code>{'{"token":"…","refreshToken":"…"}'}</code>),粘贴到上面保存。这样带有续期令牌,可以长期使用。</li>
|
| 255 |
+
<li>只想临时用:在「Network / 网络」里点任意一个 <code>api.asksurf.ai</code> 请求,复制请求头 <code>Authorization</code> 里 <code>Bearer</code> 后面那串。它只有 1 小时有效。</li>
|
| 256 |
+
</ol>}
|
| 257 |
+
<label className="vault-check"><input type="checkbox" checked={!!f.auto_refresh} onChange={e => set('auto_refresh', e.target.checked)} />令牌过期时自动续期{!f.refresh_set && <span className="muted">(需要粘贴含 refreshToken 的整段)</span>}</label>
|
| 258 |
+
<p className="muted small-note">注意:自动续期会让<b>同一份登录</b>的浏览器被 Surf 登出。所以建议用无痕窗口登录一次、复制令牌后直接关掉那个窗口,平时用的浏览器不受影响。</p>
|
| 259 |
+
</>}
|
| 260 |
<div className="row between">
|
| 261 |
+
<span className="muted small-note">{f.token_refreshed_at ? `上次自动续期:${fmtDate(f.token_refreshed_at)}` : f.token_saved_at ? `上次保存:${fmtDate(f.token_saved_at)}` : ''}</span>
|
| 262 |
+
{f.token_set && <button className="link-btn muted" onClick={async () => { if (await confirm({ title: '清除令牌?', body: '清除后写作 AI 将无法向协作 AI 派活。', danger: true, ok: '清除' })) save({ clear_token: true }) }}>清除令牌</button>}
|
| 263 |
</div>
|
| 264 |
+
{chk && chk.ok && <div className="chk-ok">
|
| 265 |
+
<CircleCheck size={14} />
|
| 266 |
+
<span>已连上{chk.user?.name ? ` ${chk.user.name}` : ''}{chk.user?.email ? `(${chk.user.email})` : ''}{chk.user?.plan ? ` · ${chk.user.plan}` : ''}
|
| 267 |
+
{chk.credits != null && <> · 积分 {typeof chk.credits === 'object' ? (chk.credits.balance ?? chk.credits.credits ?? chk.credits.total ?? JSON.stringify(chk.credits).slice(0, 60)) : String(chk.credits)}</>}
|
| 268 |
+
{chk.token_expires_in_min != null && <> · 令牌还剩 {chk.token_expires_in_min} 分钟</>}</span>
|
| 269 |
+
</div>}
|
| 270 |
+
{chk && chk.ok === null && <div className="muted small-note">{chk.note}</div>}
|
| 271 |
</div>
|
| 272 |
<div className="stack">
|
| 273 |
<Field label="名称"><input className="input" value={f.name} onChange={e => set('name', e.target.value)} /></Field>
|
| 274 |
+
{surf ? <>
|
| 275 |
+
<Field label="模型" hint="对应 Surf Chat 网页里的模型选项">
|
| 276 |
+
<select className="input" value={f.surf_model || 'pro'} onChange={e => set('surf_model', e.target.value)}>
|
| 277 |
+
{Object.entries(models).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
|
| 278 |
+
</select>
|
| 279 |
+
</Field>
|
| 280 |
+
<Field label="思考强度"><Segmented value={f.surf_effort || 'high'} onChange={v => set('surf_effort', v)} items={[{ id: 'medium', label: '中' }, { id: 'high', label: '高' }, { id: 'ultra', label: '极高' }]} /></Field>
|
| 281 |
+
<label className="vault-check"><input type="checkbox" checked={!!f.instant} onChange={e => set('instant', e.target.checked)} />使用 Instant 快速模式(更快、更省,但不选模型、不深度思考)</label>
|
| 282 |
+
</> : <>
|
| 283 |
+
<Field label="接口地址" hint={f.mode === 'openai' ? '例如 https://…/v1/chat/completions' : f.mode === 'anthropic' ? '例如 https://api.anthropic.com/v1/messages' : '收到 POST 请求的完整地址'}><input className="input" value={f.endpoint} onChange={e => set('endpoint', e.target.value)} /></Field>
|
| 284 |
+
<Field label="模型"><input className="input" value={f.model} onChange={e => set('model', e.target.value)} /></Field>
|
| 285 |
+
{f.mode === 'custom' && <>
|
| 286 |
+
<Field label="请求头模板(JSON)" hint="可用 {{token}}"><textarea className="textarea mono" rows={3} value={f.headers_tpl} onChange={e => set('headers_tpl', e.target.value)} placeholder={'{"Authorization": "Bearer {{token}}"}'} /></Field>
|
| 287 |
+
<Field label="请求体模板(JSON)" hint="可用 {{prompt}} {{system}} {{full}} {{model}} {{token}}"><textarea className="textarea mono" rows={4} value={f.body_tpl} onChange={e => set('body_tpl', e.target.value)} placeholder={'{"message": "{{full}}"}'} /></Field>
|
| 288 |
+
<Field label="回复所在字段" hint="例如 data.reply 或 choices.0.message.content"><input className="input" value={f.reply_path} onChange={e => set('reply_path', e.target.value)} /></Field>
|
| 289 |
+
</>}
|
| 290 |
+
<label className="vault-check"><input type="checkbox" checked={f.sse} onChange={e => set('sse', e.target.checked)} />接口以流式(event-stream)返回</label>
|
| 291 |
</>}
|
| 292 |
+
<Field label="审查时的要求(可选)" hint="留空则用默认:严格的番茄责任编辑,只审查不代写。调研、出主意、起草有各自的默认要求"><textarea className="textarea" rows={3} value={f.system} onChange={e => set('system', e.target.value)} /></Field>
|
|
|
|
| 293 |
</div>
|
| 294 |
+
<div className="row end gap wrap" style={{ marginTop: 14 }}>
|
| 295 |
+
{surf && <button className="btn ghost" disabled={!!busy || !f.token_set} onClick={check} title="查账号、积分和令牌剩余时间,不花积分">{busy === 'check' ? <Spinner size={14} /> : <PlugZap size={14} />}检查连接</button>}
|
| 296 |
+
<button className="btn ghost" disabled={!!busy || (surf ? !f.token_set : !f.endpoint)} onClick={test} title="真的发一句话过去,会花少量积分">{busy === 'test' ? <Spinner size={14} /> : <Send size={14} />}发一条测试</button>
|
| 297 |
<button className="btn primary" disabled={!!busy} onClick={() => save()}>{busy === 'save' ? <Spinner size={14} /> : <Save size={14} />}保存设置</button>
|
| 298 |
</div>
|
|
|
|
| 299 |
</div>
|
| 300 |
<div className="sheet">
|
| 301 |
<div className="row between wrap gap">
|
| 302 |
+
<h2 className="sheet-title serif" style={{ margin: 0 }}>协作记录</h2>
|
| 303 |
<div className="row gap">
|
| 304 |
<Segmented value={scope} onChange={setScope} items={[{ id: 'book', label: '按作品' }, { id: 'all', label: '未关联作品' }]} />
|
| 305 |
{scope === 'book' && <ProjectPicker value={pid} onChange={setPid} />}
|
|
|
|
| 313 |
|
| 314 |
const ASK_ST: Record<string, { t: string; tone: string }> = { new: { t: '待处理', tone: 'warn' }, adopted: { t: '已采纳', tone: 'ok' }, partial: { t: '部分采纳', tone: 'accent' }, rejected: { t: '未采纳', tone: '' } }
|
| 315 |
export function AskLog({ items, error, reload, projectId, empty }: { items?: ReviewerAsk[]; error?: string | null; reload: () => void; projectId?: string; empty?: string }) {
|
| 316 |
+
const running = !!items?.some(x => x.state === 'running')
|
| 317 |
+
useEffect(() => {
|
| 318 |
+
if (!running) return
|
| 319 |
+
const t = setInterval(reload, 5000)
|
| 320 |
+
return () => clearInterval(t)
|
| 321 |
+
}, [running, reload])
|
| 322 |
if (error) return <ErrorNote error={error} onRetry={reload} />
|
| 323 |
if (!items) return <Loading />
|
| 324 |
+
if (!items.length) return <Empty title="还没有协作记录">{empty || '写作 AI 向协作 AI 派活后,问题和回复都会存在这里。'}</Empty>
|
| 325 |
+
return <div className="ask-log">{items.map(x => <AskItem key={x.ask_id} x={x} reload={reload} />)}</div>
|
| 326 |
}
|
| 327 |
+
function AskItem({ x, reload }: { x: ReviewerAsk; reload: () => void }) {
|
| 328 |
+
const toast = useToast()
|
| 329 |
+
const state = x.state || (x.ok ? 'done' : 'error')
|
| 330 |
const [open, setOpen] = useState(false)
|
| 331 |
const st = ASK_ST[x.status] || ASK_ST.new
|
| 332 |
+
const stop = async () => {
|
| 333 |
+
try { await agentApi.cancelAsk(x.ask_id, x.project_id); toast('已停止', 'ok'); reload() } catch (e: any) { toast(e.message, 'err') }
|
| 334 |
+
}
|
| 335 |
return (
|
| 336 |
+
<div className={cx('ask', state === 'error' && 'bad', state === 'running' && 'running')}>
|
| 337 |
<button className="ask-head" onClick={() => setOpen(o => !o)}>
|
| 338 |
<span className="ask-topic">{x.topic || '提问'}</span>
|
| 339 |
+
{x.task && x.task !== 'review' && <Tag>{TASK_T[x.task] || x.task}</Tag>}
|
| 340 |
+
{state === 'running' ? <Tag tone="accent"><Spinner size={11} /> 回答中</Tag>
|
| 341 |
+
: state === 'done' ? <Tag tone={st.tone}>{st.t}</Tag>
|
| 342 |
+
: <Tag tone="err">{x.error === '已停止' ? '已停止' : x.http === 401 || x.http === 403 ? '令牌失效' : x.code === 'credits_exhausted' ? '积分用完' : '请求失败'}</Tag>}
|
| 343 |
<span className="ask-meta">{x.asked_by} · {fmtAgo(x.created_at)}</span>
|
| 344 |
{open ? <ChevronUp size={15} /> : <ChevronDown size={15} />}
|
| 345 |
</button>
|
| 346 |
<p className="ask-q">{x.question}</p>
|
| 347 |
{x.attach?.length > 0 && <div className="gap-s">{x.attach.map(a => <Tag key={a}>{ATT[a.split(':')[0]] || a}{a.includes(':') ? ` ${a.split(':')[1]}` : ''}</Tag>)}</div>}
|
| 348 |
+
{state === 'running' && <div className="ask-live">
|
| 349 |
+
{x.partial_reply ? <p className="ask-partial">…{x.partial_reply.slice(-240)}</p> : <p className="muted small-note">对方正在思考,回复通常要一到几分钟。</p>}
|
| 350 |
+
<button className="link-btn muted" onClick={stop}>停止</button>
|
| 351 |
+
</div>}
|
| 352 |
{open && <>
|
| 353 |
+
{state === 'done' && <div className="ask-reply">
|
| 354 |
+
<div className="ask-label">{x.reviewer} 的回复{x.ms ? ` · ${x.ms >= 60000 ? `${Math.round(x.ms / 60000)} 分钟` : `${Math.round(x.ms / 1000)} 秒`}` : ''}{x.partial ? ' · 可能不完整' : ''}</div>
|
| 355 |
+
<Md text={x.reply || ''} />
|
| 356 |
+
</div>}
|
| 357 |
+
{state === 'error' && <div className="error-note"><span>{x.error}</span></div>}
|
| 358 |
{x.response && <div className="ask-resp"><div className="ask-label">写作 AI 的处理</div><Md text={x.response} /></div>}
|
| 359 |
+
<div className="ask-foot">
|
| 360 |
+
{x.engine && <span>{x.engine}</span>}
|
| 361 |
+
{x.continued_from && <span>接着上一次对话</span>}
|
| 362 |
+
{x.cost_usd != null && x.cost_usd > 0 && <span>计费 ${x.cost_usd.toFixed(4)}</span>}
|
| 363 |
+
{x.url && <a href={x.url} target="_blank" rel="noreferrer"><ExternalLink size={12} />在 Surf 打开这段对话</a>}
|
| 364 |
+
</div>
|
| 365 |
</>}
|
| 366 |
</div>
|
| 367 |
)
|
ui-src/src/rooms/Editor.tsx
CHANGED
|
@@ -638,7 +638,7 @@ function RefsPanel({ ctx }: { ctx: BookCtx }) {
|
|
| 638 |
)
|
| 639 |
}
|
| 640 |
|
| 641 |
-
/* ---------- AI 协作:写作由 AI 直接在工作台上完成,这里只放给它的话、留言和
|
| 642 |
function AiPanel({ ctx, detail }: { ctx: BookCtx; detail: Chapter; text: string }) {
|
| 643 |
const { bundle } = ctx
|
| 644 |
const pid = bundle.project.project_id
|
|
@@ -656,12 +656,12 @@ function AiPanel({ ctx, detail }: { ctx: BookCtx; detail: Chapter; text: string
|
|
| 656 |
<b className="panel-h">直接对 AI 说</b>
|
| 657 |
<SayToAi hint="写这一章" text={`请阅读 AI 守则和《${bundle.project.title}》的设定,写第${n}章,存为新版本。`} />
|
| 658 |
<SayToAi hint="按批注改" text={`请按批注修改第${n}章:逐条处理待改批注,存新版本,并在批注上回复改了什么。`} />
|
| 659 |
-
<SayToAi hint="请
|
| 660 |
<div className="divider" />
|
| 661 |
<RequestsBox pid={pid} cid={detail.chapter_id} />
|
| 662 |
<div className="divider" />
|
| 663 |
-
<div className="row between"><b className="panel-h">
|
| 664 |
-
<AskLog items={log.data?.items} error={log.error} reload={log.reload} empty="写作 AI
|
| 665 |
</div>
|
| 666 |
)
|
| 667 |
}
|
|
|
|
| 638 |
)
|
| 639 |
}
|
| 640 |
|
| 641 |
+
/* ---------- AI 协作:写作由 AI 直接在工作台上完成,这里只放给它的话、留言和协作记录 ---------- */
|
| 642 |
function AiPanel({ ctx, detail }: { ctx: BookCtx; detail: Chapter; text: string }) {
|
| 643 |
const { bundle } = ctx
|
| 644 |
const pid = bundle.project.project_id
|
|
|
|
| 656 |
<b className="panel-h">直接对 AI 说</b>
|
| 657 |
<SayToAi hint="写这一章" text={`请阅读 AI 守则和《${bundle.project.title}》的设定,写第${n}章,存为新版本。`} />
|
| 658 |
<SayToAi hint="按批注改" text={`请按批注修改第${n}章:逐条处理待改批注,存新版本,并在批注上回复改了什么。`} />
|
| 659 |
+
<SayToAi hint="请协作 AI 把关" text={`请把第${n}章发给协作 AI 审查,问它逻辑和人设有没有问题,读完回复再决定怎么改。`} />
|
| 660 |
<div className="divider" />
|
| 661 |
<RequestsBox pid={pid} cid={detail.chapter_id} />
|
| 662 |
<div className="divider" />
|
| 663 |
+
<div className="row between"><b className="panel-h">协作 AI 记录</b><button className="link-btn" onClick={() => go('agent/reviewer')}>全部 / 设置</button></div>
|
| 664 |
+
<AskLog items={log.data?.items} error={log.error} reload={log.reload} empty="写作 AI 向协作 AI 派活后,问答会出现在这里。" />
|
| 665 |
</div>
|
| 666 |
)
|
| 667 |
}
|
ui-src/src/styles.css
CHANGED
|
@@ -1703,3 +1703,15 @@ kbd { font-family: var(--mono); font-size: 11px; padding: 1px 5px; border-radius
|
|
| 1703 |
.room-tabs::-webkit-scrollbar { display: none; }
|
| 1704 |
.room-tabs > * { flex: 0 0 auto; white-space: nowrap; }
|
| 1705 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1703 |
.room-tabs::-webkit-scrollbar { display: none; }
|
| 1704 |
.room-tabs > * { flex: 0 0 auto; white-space: nowrap; }
|
| 1705 |
}
|
| 1706 |
+
|
| 1707 |
+
/* 协作 AI */
|
| 1708 |
+
.howto { margin: 2px 0 4px; padding-left: 20px; font-size: 12.5px; line-height: 1.8; color: var(--ink-2); }
|
| 1709 |
+
.howto code { font-size: 11.5px; padding: 1px 5px; border-radius: 4px; background: var(--bg-2); word-break: break-all; }
|
| 1710 |
+
.chk-ok { display: flex; gap: 8px; align-items: flex-start; font-size: 12.5px; line-height: 1.6; color: var(--ok); padding: 8px 10px; border-radius: var(--r-s); background: var(--ok-soft); }
|
| 1711 |
+
.chk-ok svg { flex: none; margin-top: 3px; }
|
| 1712 |
+
.ask.running { border-color: color-mix(in srgb, var(--accent) 40%, transparent); }
|
| 1713 |
+
.ask-live { display: flex; align-items: flex-end; justify-content: space-between; gap: 10px; margin-top: 6px; }
|
| 1714 |
+
.ask-partial { margin: 0; font-size: 12.5px; line-height: 1.7; color: var(--ink-3); white-space: pre-wrap; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }
|
| 1715 |
+
.ask-foot { display: flex; flex-wrap: wrap; gap: 6px 14px; margin-top: 10px; font-size: 12px; color: var(--ink-3); }
|
| 1716 |
+
.ask-foot a { display: inline-flex; align-items: center; gap: 4px; color: var(--accent); }
|
| 1717 |
+
.ask-head .tag .spinner, .ask-head .tag svg { vertical-align: -2px; }
|