@fish-under-sea/magpie-purge 0.8.4 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -0
- package/hooks.js +142 -7
- package/lib/response.mjs +159 -0
- package/lib/rewrite.mjs +64 -0
- package/lib/routing.mjs +264 -0
- package/lib/state.mjs +9 -2
- package/lib/topology.mjs +152 -0
- package/middleware.js +53 -0
- package/package.json +19 -1
- package/page/app.js +414 -0
- package/page/index.html +179 -46
- package/page/routing-logic.js +256 -0
- package/page/style.css +1272 -1
- package/tools/build-preview.mjs +3 -1
package/README.md
CHANGED
|
@@ -221,6 +221,8 @@ magpie plugin list
|
|
|
221
221
|
| `inline` | 页面里直接贴进来的人设/技能正文,不进磁盘 |
|
|
222
222
|
| `gatewayTimeoutMs` | 钩子预算,默认 1500 ms(magpie 侧 100–10000) |
|
|
223
223
|
| `useAgentPurge` | 默认 `false`。设为 `true` 才去读 agent-purge 的 `state.json`,见下 |
|
|
224
|
+
| `stripThink` | 默认 `true`:去掉回复开头的 `<think>` 块(整包与流式都处理) |
|
|
225
|
+
| `refusalWatch` | 默认 `true`:认出「短、无内容的推脱」,只记日志,不改回复 |
|
|
224
226
|
|
|
225
227
|
### 想读 agent-purge 的设置?(默认关)
|
|
226
228
|
|
|
@@ -281,6 +283,34 @@ magpie plugin options magpie-purge '{"useAgentPurge":true}'
|
|
|
281
283
|
随快照一起下发,点开就能读,不用去磁盘翻文件。超过 8000 字符会截断并标出总长度;
|
|
282
284
|
换条目自动收起,不会把上一条的正文带过来。
|
|
283
285
|
|
|
286
|
+
## 回复侧:think 块与推脱观测(本 PR 新增)
|
|
287
|
+
|
|
288
|
+
前面的所有内容都在改**请求**(system 里的人设与技能)。这一节管**回复**,只做两件事:
|
|
289
|
+
|
|
290
|
+
1. **去掉回复开头的 think 块。** 有的模型会把 `<think>…</think>` 留在正文里,下一轮
|
|
291
|
+
跟着消息历史回去,又被当成正文接着推理。`onResponse` 处理整包,`onEvent` 处理流式;
|
|
292
|
+
流式时标签可能被切在两个 chunk 之间(`<thi` + `nk>`),所以剥离器会先攒住没确认的前缀,
|
|
293
|
+
确认不是 think 就原样吐出去——**正常的 `<div>` 之类不会被吞**。
|
|
294
|
+
2. **认出空推脱,记一行日志。** 只认「开头一句拒绝 + 通篇没有实质内容」的短回复;
|
|
295
|
+
带代码块、编号步骤、「不过我可以给你…」的一律不算。命中的写
|
|
296
|
+
`[purge] refusal opening (agent=… model=…)`,用来回答「这条到底是模型拒了,还是配置错了」。
|
|
297
|
+
|
|
298
|
+
**刻意不做的事:**
|
|
299
|
+
|
|
300
|
+
- 不重试、不改写回复内容。钩子拿到的回复已经生成,流式时甚至只有半条;重跑模型是改请求,
|
|
301
|
+
属于 `onRequest` 的活。想让模型少拒,请换人设/技能,而不是在回复层硬掰。
|
|
302
|
+
- 不因为认到推脱就替换成别的话。人设本身不承诺无条件照做(见「削弱版」一节),
|
|
303
|
+
统计归统计,干预归干预。
|
|
304
|
+
|
|
305
|
+
两个开关都能单独关:
|
|
306
|
+
|
|
307
|
+
```bash
|
|
308
|
+
magpie plugin options magpie-purge '{"stripThink":false}'
|
|
309
|
+
magpie plugin options magpie-purge '{"refusalWatch":false}'
|
|
310
|
+
```
|
|
311
|
+
|
|
312
|
+
失败一律 fail-open:剥不动、认不准,就把原文放回去,绝不让一条正常回复变坏。
|
|
313
|
+
|
|
284
314
|
## 边界(照实说,不含糊)
|
|
285
315
|
|
|
286
316
|
- 只处理**经过 magpie 网关**的 agent 请求;客户端自己写死的行为、不经过网关的流量改不到。
|
|
@@ -288,6 +318,7 @@ magpie plugin options magpie-purge '{"useAgentPurge":true}'
|
|
|
288
318
|
- 页面**不读磁盘**:所有扫描与读盘都在插件后端(`hooks.js`)里做,页面只显示快照。
|
|
289
319
|
- 不执行导入件里的任何脚本:DSH 插件包与导出包只被**判型与登记**,不当代码跑。
|
|
290
320
|
- 坏包(缺 manifest、路径带 `..`、超大文件)整个拒绝,同目录其它条目不受影响。
|
|
321
|
+
- 回复侧只做「剥 think」和「把推脱记一笔」;推脱识别是保守规则,宁可漏也不误报,更不会改回复。
|
|
291
322
|
|
|
292
323
|
## 目录
|
|
293
324
|
|
|
@@ -464,6 +495,7 @@ node tools/scan.mjs --json
|
|
|
464
495
|
|
|
465
496
|
| 版本 | 要点 |
|
|
466
497
|
| --- | --- |
|
|
498
|
+
| `0.9.0` | 合并路由定向注入(PR #3,Closes #1)与回复侧处理(PR #2):新增 `middleware.js` 两阶段供应商/模型精确注入、`onResponse`/`onEvent` 剥离回复开头 `<think>` 与空推脱观测日志;并在二级页「外观与选项」补齐官方无修改 Magpie 原生可用的 Agent / 供应商 / 模型定向规则配置与回复侧开关 |
|
|
467
499
|
| `0.8.4` | 行/事实块补上宿主同款光学:左上冷光 + 渐变高光边;状态徽标、类型标签、模式下拉也吃玻璃胶囊;玻璃下解除滚动区的 `mask-image` / `opacity`(它们会建立 backdrop root,让行里的 backdrop-filter 采不到东西) |
|
|
468
500
|
| `0.8.3` | 玻璃改成宿主材质直出:`--card` 底色 + backdrop 模糊/饱和/提亮 + 内侧高光 + 1px 渐变高光边 + 柔光;去掉左右两列大壳与所有自定义边框(不再有黑边),行/块本身就是玻璃面;控件仍是 `--fg` 10% 胶囊;占位符接 `--magpie-muted` |
|
|
469
501
|
| `0.8.2` | 玻璃观感对齐官方插件页:画布全透、卡片用 content 原值(去掉 55/70/45 的下限)、胶囊与控件改用 `--fg` 的 10%×控件数字、材质与分隔线由 `--fg` 派生;另修掉注释里写了 `page/*/style.css` 导致 `*/` 提前闭合、整段玻璃变量规则被解析器吞掉的问题 |
|
package/hooks.js
CHANGED
|
@@ -15,7 +15,10 @@ import { fileURLToPath } from 'node:url'
|
|
|
15
15
|
import { compose, rewrite, supported } from './lib/rewrite.mjs'
|
|
16
16
|
import { readState } from './lib/agentpurge.mjs'
|
|
17
17
|
import { applyPrefs, resolve as resolvePlan } from './lib/plan.mjs'
|
|
18
|
+
import { PENDING_KEY, decideRequest } from './lib/routing.mjs'
|
|
18
19
|
import { ensurePaths, loadCatalog, ownOptions, sync } from './lib/state.mjs'
|
|
20
|
+
import { appendRoutingTrace } from './lib/topology.mjs'
|
|
21
|
+
import { createStreamStripper, looksLikeRefusal, replyText, streamSlots, stripLeadingThink, stripThinkInPlace } from './lib/response.mjs'
|
|
19
22
|
|
|
20
23
|
const here = dirname(fileURLToPath(import.meta.url))
|
|
21
24
|
|
|
@@ -202,9 +205,15 @@ export function createHook(root = here, { deadlineMs = 400, rescanMs = 30_000, w
|
|
|
202
205
|
}
|
|
203
206
|
try {
|
|
204
207
|
if (!body || typeof body !== 'object' || Array.isArray(body)) return
|
|
205
|
-
|
|
206
|
-
const
|
|
207
|
-
if (
|
|
208
|
+
const reqModel = ctx?.model || body?.model || ''
|
|
209
|
+
const decision = decideRequest({ options, agent: ctx?.agent || '', model: reqModel })
|
|
210
|
+
if (decision.action === 'skip') {
|
|
211
|
+
appendRoutingTrace(P, {
|
|
212
|
+
agent: ctx?.agent || '',
|
|
213
|
+
model: reqModel,
|
|
214
|
+
action: 'skip',
|
|
215
|
+
reason: decision.reason,
|
|
216
|
+
})
|
|
208
217
|
report('skipped', 0)
|
|
209
218
|
return
|
|
210
219
|
}
|
|
@@ -213,7 +222,10 @@ export function createHook(root = here, { deadlineMs = 400, rescanMs = 30_000, w
|
|
|
213
222
|
return
|
|
214
223
|
}
|
|
215
224
|
|
|
216
|
-
const
|
|
225
|
+
const effectiveOptions =
|
|
226
|
+
options.routing?.active === true && options.mode === undefined ? { ...options, mode: 'replace' } : options
|
|
227
|
+
|
|
228
|
+
const catalog = await ensureCatalog(effectiveOptions)
|
|
217
229
|
if (!catalog) {
|
|
218
230
|
// 扫描还没跑完(超时预算):这次放行,不阻塞 agent 请求。
|
|
219
231
|
report('skipped', 0)
|
|
@@ -221,18 +233,74 @@ export function createHook(root = here, { deadlineMs = 400, rescanMs = 30_000, w
|
|
|
221
233
|
}
|
|
222
234
|
// state.json 每请求读一次(很小的文件),这样在 agent-purge 里换人设立刻生效
|
|
223
235
|
const state = readState()
|
|
224
|
-
const picked = pick(catalog,
|
|
236
|
+
const picked = pick(catalog, effectiveOptions, state, ctx?.agent)
|
|
225
237
|
if (!picked.text) {
|
|
238
|
+
appendRoutingTrace(P, {
|
|
239
|
+
agent: ctx?.agent || '',
|
|
240
|
+
model: reqModel,
|
|
241
|
+
action: 'skip',
|
|
242
|
+
reason: picked.plan?.blockedCode || 'no-text',
|
|
243
|
+
})
|
|
226
244
|
report('skipped', 0)
|
|
227
245
|
rememberSkip(catalog, picked, ctx)
|
|
228
246
|
return
|
|
229
247
|
}
|
|
248
|
+
|
|
249
|
+
if (decision.action === 'defer') {
|
|
250
|
+
body[PENDING_KEY] = {
|
|
251
|
+
text: picked.text,
|
|
252
|
+
mode: picked.plan.mode,
|
|
253
|
+
targets: decision.targets,
|
|
254
|
+
persona: picked.personaId,
|
|
255
|
+
skills: picked.skills.map((s) => s.id),
|
|
256
|
+
agent: ctx?.agent || '',
|
|
257
|
+
protocol: ctx?.protocol || '',
|
|
258
|
+
}
|
|
259
|
+
appendRoutingTrace(P, {
|
|
260
|
+
agent: ctx?.agent || '',
|
|
261
|
+
model: reqModel,
|
|
262
|
+
groupId: decision.groupId || '',
|
|
263
|
+
action: 'defer',
|
|
264
|
+
reason: decision.reason,
|
|
265
|
+
mode: picked.plan.mode,
|
|
266
|
+
persona: picked.personaId,
|
|
267
|
+
chars: picked.text.length,
|
|
268
|
+
})
|
|
269
|
+
remember({
|
|
270
|
+
at: Date.now(),
|
|
271
|
+
agent: ctx?.agent || '',
|
|
272
|
+
protocol: ctx.protocol,
|
|
273
|
+
model: reqModel,
|
|
274
|
+
mode: picked.plan.mode,
|
|
275
|
+
modeFrom: picked.plan.modeFrom,
|
|
276
|
+
persona: picked.personaId,
|
|
277
|
+
personaFrom: picked.plan.personaFrom,
|
|
278
|
+
skills: picked.skills.map((s) => s.id),
|
|
279
|
+
chars: picked.text.length,
|
|
280
|
+
deferred: true,
|
|
281
|
+
missingPin: picked.missingPin,
|
|
282
|
+
catalogVersion: catalog?.version ?? 0,
|
|
283
|
+
})
|
|
284
|
+
report('ready', picked.text.length)
|
|
285
|
+
return body
|
|
286
|
+
}
|
|
287
|
+
|
|
230
288
|
rewrite(body, ctx.protocol, picked.text, picked.plan.mode)
|
|
289
|
+
appendRoutingTrace(P, {
|
|
290
|
+
agent: ctx?.agent || '',
|
|
291
|
+
model: reqModel,
|
|
292
|
+
action: 'inject',
|
|
293
|
+
reason: decision.reason,
|
|
294
|
+
matchedKey: decision.targets?.[0]?.key || '',
|
|
295
|
+
mode: picked.plan.mode,
|
|
296
|
+
persona: picked.personaId,
|
|
297
|
+
chars: picked.text.length,
|
|
298
|
+
})
|
|
231
299
|
remember({
|
|
232
300
|
at: Date.now(),
|
|
233
301
|
agent: ctx?.agent || '',
|
|
234
302
|
protocol: ctx.protocol,
|
|
235
|
-
model:
|
|
303
|
+
model: reqModel,
|
|
236
304
|
mode: picked.plan.mode,
|
|
237
305
|
modeFrom: picked.plan.modeFrom,
|
|
238
306
|
persona: picked.personaId,
|
|
@@ -276,4 +344,71 @@ const hook = createHook(here)
|
|
|
276
344
|
|
|
277
345
|
export async function onRequest(body, ctx) {
|
|
278
346
|
return hook.onRequest(body, ctx)
|
|
279
|
-
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// ── 回复侧 ────────────────────────────────────────────────────────────────
|
|
350
|
+
// 与 onRequest 共用同一份 options,两个开关默认都开:
|
|
351
|
+
// stripThink 去掉回复开头的 think 块(流式与整包都处理)
|
|
352
|
+
// refusalWatch 认出「短、无内容的推脱」,只记一行日志,不改回复
|
|
353
|
+
//
|
|
354
|
+
// 这里刻意不重试、不改写:钩子拿到的回复已经生成(流式时甚至是半条),
|
|
355
|
+
// 想改行为请改人设/技能。失败一律 fail-open,绝不把一条正常回复弄坏。
|
|
356
|
+
const replyOpts = (ctx) => {
|
|
357
|
+
const o = ctx?.options ?? {}
|
|
358
|
+
return { stripThink: o.stripThink !== false, refusalWatch: o.refusalWatch !== false }
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
export async function onResponse(body, ctx) {
|
|
362
|
+
if (!body || typeof body !== 'object') return
|
|
363
|
+
try {
|
|
364
|
+
const { stripThink, refusalWatch } = replyOpts(ctx)
|
|
365
|
+
const failed = typeof ctx?.status === 'number' && ctx.status >= 400
|
|
366
|
+
if (refusalWatch && !failed) {
|
|
367
|
+
const visible = stripThink ? stripLeadingThink(replyText(body)) : replyText(body)
|
|
368
|
+
if (looksLikeRefusal(visible)) {
|
|
369
|
+
console.log(`[purge] refusal opening (agent=${ctx?.agent || '?'} model=${ctx?.model || '?'})`)
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
if (stripThink && stripThinkInPlace(body)) return body
|
|
373
|
+
} catch {
|
|
374
|
+
return
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
export async function onEvent(ev, ctx) {
|
|
379
|
+
if (!ev || typeof ev !== 'object') return
|
|
380
|
+
try {
|
|
381
|
+
const { stripThink, refusalWatch } = replyOpts(ctx)
|
|
382
|
+
const slots = streamSlots(ev)
|
|
383
|
+
if (!slots.length) return
|
|
384
|
+
const st = (ctx.state ??= {})
|
|
385
|
+
let changed = false
|
|
386
|
+
|
|
387
|
+
// 先看这一段的可读文本(用于拒绝识别),再做 think 剥离
|
|
388
|
+
if (!st.purge) st.purge = { decided: false, seen: '' }
|
|
389
|
+
if (refusalWatch && !st.purge.decided) {
|
|
390
|
+
for (const { obj, key } of slots) {
|
|
391
|
+
if (typeof obj[key] !== 'string') continue
|
|
392
|
+
st.purge.seen += stripLeadingThink(obj[key])
|
|
393
|
+
}
|
|
394
|
+
const seen = st.purge.seen.trim()
|
|
395
|
+
if (looksLikeRefusal(st.purge.seen) || seen.length > 300 || /[。!?\n]/.test(seen)) {
|
|
396
|
+
if (looksLikeRefusal(st.purge.seen)) {
|
|
397
|
+
console.log(`[purge] refusal opening (agent=${ctx?.agent || '?'} model=${ctx?.model || '?'} mode=stream)`)
|
|
398
|
+
}
|
|
399
|
+
st.purge.decided = true
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
if (!stripThink) return changed ? ev : undefined
|
|
404
|
+
const stripper = (st.purgeStream ??= createStreamStripper())
|
|
405
|
+
for (const { obj, key } of slots) {
|
|
406
|
+
if (typeof obj[key] !== 'string') continue
|
|
407
|
+
const u = stripper.push(obj[key])
|
|
408
|
+
if (u !== obj[key]) { obj[key] = u; changed = true }
|
|
409
|
+
}
|
|
410
|
+
return changed ? ev : undefined
|
|
411
|
+
} catch {
|
|
412
|
+
return
|
|
413
|
+
}
|
|
414
|
+
}
|
package/lib/response.mjs
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
// 回复侧的两件事,都只「看」不改写(think 块除外):
|
|
2
|
+
//
|
|
3
|
+
// 1. 去掉回复开头的 think 块,别让它留在历史里、下一轮又被当成正文;
|
|
4
|
+
// 2. 认出「短、无实质内容」的推脱,记一行日志/一条计数给页面看。
|
|
5
|
+
//
|
|
6
|
+
// 为什么不做重试:网关钩子拿到的是一条已经生成的回复(流式时甚至是半条),
|
|
7
|
+
// 重跑模型要改请求,那是 onRequest 的活;这里能做的是让「模型拒了」这件事
|
|
8
|
+
// 可观测,而不是替它重来。人设本身也不承诺无条件照做(见 personas/dafeiyu.md),
|
|
9
|
+
// 所以这里只统计、不干预——想改行为请换人设/换技能,而不是在回复层硬掰。
|
|
10
|
+
|
|
11
|
+
export const REFUSAL_HEAD = 120 // 推脱只认开头这么多字
|
|
12
|
+
export const REFUSAL_MAX = 300 // 整段超过这个长度就不是「短推脱」了
|
|
13
|
+
|
|
14
|
+
// 开头就是明确的拒绝语。宁少认不错认:宁可漏掉一条,也不要把正常回答标成拒绝。
|
|
15
|
+
const REFUSAL = [
|
|
16
|
+
/^(?:i'?m sorry|i am sorry)[,.!]?\s*(?:but\s+)?i\s*(?:can'?t|cannot|won'?t|am not able to|'m not able to)\b/i,
|
|
17
|
+
/^i\s*(?:can'?t|cannot|won'?t)\s+(?:help|assist|do|provide|write|give|create|generate)\b/i,
|
|
18
|
+
/^i'?m not (?:going to|able to|willing to)\b/i,
|
|
19
|
+
/^(?:no|nope)[,.!]?\s*i\s*(?:won'?t|can'?t|cannot)\b/i,
|
|
20
|
+
/^(?:抱歉|对不起)[,,]?\s*(?:我)?\s*(?:不能|无法|不会|没法|帮不了)/,
|
|
21
|
+
/^我?\s*(?:不能|无法|不会|没法|不可以)\s*(?:帮你|为您|提供|协助|帮助|给出|告诉|教你|写|做|完成)/,
|
|
22
|
+
/^(?:这|那|此事|这个问题)?\s*(?:超出了?|不在)\s*我(?:的)?(?:能力|职责|范围)/,
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
// 这些词表示「后面还有内容」——一旦出现,这条就不是无内容的推脱,而是解释或替代方案。
|
|
26
|
+
const OFFER = /(?:here(?:'s|’s| is| are)|i (?:can|will|could) (?:give|show|provide|help|walk|write|share)|let me|below is|作为|我可以|我能|我可以给你|以下|下面|不过|但可以|替代方案|建议你|步骤)/i
|
|
27
|
+
|
|
28
|
+
const TAG_OPEN = /^\s*<(think|thinking|thought)>/i
|
|
29
|
+
|
|
30
|
+
/** 去掉开头的一个 think 块;没有就原样返回。 */
|
|
31
|
+
export function stripLeadingThink(text) {
|
|
32
|
+
const s = String(text ?? '')
|
|
33
|
+
const m = TAG_OPEN.exec(s)
|
|
34
|
+
if (!m) return s
|
|
35
|
+
const close = new RegExp(`</${m[1]}>`, 'i')
|
|
36
|
+
const idx = s.search(close)
|
|
37
|
+
if (idx < 0) return s
|
|
38
|
+
const rest = s.slice(idx + m[1].length + 3) // 跳过 </tag>
|
|
39
|
+
return rest.replace(/^[\s\u3000]*/, '')
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 流式用的 think 剥离器:标签可能被切在两个 chunk 里(`<thi` + `nk>`),
|
|
44
|
+
* 所以要记住「还没确认的前缀」。规则很简单:
|
|
45
|
+
* 开头还没定下来 → 先攒着;确认是 think 块 → 丢掉直到闭合;确认不是 → 原样吐出。
|
|
46
|
+
*/
|
|
47
|
+
export function createStreamStripper() {
|
|
48
|
+
let carry = '' // 还没决定去留的缓冲
|
|
49
|
+
let state = 'lead' // lead(还没确定开头)| skip(在 think 块里)| pass(正常输出)
|
|
50
|
+
const OPEN = /^\s*<(think|thinking|thought)>/i
|
|
51
|
+
return {
|
|
52
|
+
push(chunk) {
|
|
53
|
+
let t = String(chunk ?? '')
|
|
54
|
+
if (state === 'pass') return t
|
|
55
|
+
carry += t
|
|
56
|
+
for (;;) {
|
|
57
|
+
if (state === 'lead') {
|
|
58
|
+
const m = OPEN.exec(carry)
|
|
59
|
+
if (m) { state = 'skip'; continue }
|
|
60
|
+
// 还可能是半个标签:前缀是它的真子串就先等
|
|
61
|
+
const probe = carry.replace(/^\s*/, '')
|
|
62
|
+
if (probe.startsWith('<') && '<think><thinking><thought>'.includes(probe)) return ''
|
|
63
|
+
state = 'pass'
|
|
64
|
+
const out = carry
|
|
65
|
+
carry = ''
|
|
66
|
+
return out
|
|
67
|
+
}
|
|
68
|
+
if (state === 'skip') {
|
|
69
|
+
const m = /^\s*<(think|thinking|thought)>/i.exec(carry)
|
|
70
|
+
if (m) {
|
|
71
|
+
const end = new RegExp(`</${m[1]}>`, 'i')
|
|
72
|
+
const idx = carry.search(end)
|
|
73
|
+
if (idx < 0) return ''
|
|
74
|
+
carry = carry.slice(idx + m[1].length + 3)
|
|
75
|
+
state = 'lead'
|
|
76
|
+
continue
|
|
77
|
+
}
|
|
78
|
+
state = 'pass'
|
|
79
|
+
continue
|
|
80
|
+
}
|
|
81
|
+
return ''
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
/** 这条回复像不像「开头一句短推脱、后面没有实质内容」。 */
|
|
89
|
+
export function looksLikeRefusal(text) {
|
|
90
|
+
const s = String(text ?? '').trim()
|
|
91
|
+
if (!s || s.length > REFUSAL_MAX) return false
|
|
92
|
+
const head = s.slice(0, REFUSAL_HEAD)
|
|
93
|
+
if (!REFUSAL.some((re) => re.test(head))) return false
|
|
94
|
+
// 认了拒绝语,但后面接着给东西(代码块、编号步骤、「我可以给你」)——不是推脱
|
|
95
|
+
if (/```/.test(s) || /(?:^|\n)\s*\d+[.、)]\s/.test(s)) return false
|
|
96
|
+
if (OFFER.test(s)) return false // 认了拒绝语,但通篇还给了替代方案/步骤——不是空推脱
|
|
97
|
+
return true
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const textOf = (content) => {
|
|
101
|
+
if (typeof content === 'string') return content
|
|
102
|
+
if (Array.isArray(content)) return content.map((p) => (typeof p === 'string' ? p : (p?.text ?? ''))).join('')
|
|
103
|
+
return ''
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 整包回复的可读文本,按 protocol 的 body 形状取。 */
|
|
107
|
+
export function replyText(body) {
|
|
108
|
+
const out = []
|
|
109
|
+
const push = (obj, k) => { if (obj && typeof obj[k] === 'string') out.push(obj[k]) }
|
|
110
|
+
if (Array.isArray(body?.content)) for (const b of body.content) if (b && b.type === 'text') push(b, 'text')
|
|
111
|
+
if (Array.isArray(body?.choices)) for (const c of body.choices) push(c?.message, 'content')
|
|
112
|
+
if (Array.isArray(body?.output)) {
|
|
113
|
+
for (const it of body.output) {
|
|
114
|
+
if (it?.type === 'message' && Array.isArray(it.content)) for (const p of it.content) if (p?.type === 'output_text') push(p, 'text')
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
if (Array.isArray(body?.candidates)) {
|
|
118
|
+
for (const c of body.candidates) if (Array.isArray(c?.content?.parts)) for (const p of c.content.parts) push(p, 'text')
|
|
119
|
+
}
|
|
120
|
+
return out.join('')
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** 就地去 think 块;返回是否改动过。 */
|
|
124
|
+
export function stripThinkInPlace(body) {
|
|
125
|
+
let changed = false
|
|
126
|
+
const fix = (obj, k) => {
|
|
127
|
+
if (obj && typeof obj[k] === 'string') {
|
|
128
|
+
const u = stripLeadingThink(obj[k])
|
|
129
|
+
if (u !== obj[k]) { obj[k] = u; changed = true }
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
if (Array.isArray(body?.content)) for (const b of body.content) if (b && b.type === 'text') fix(b, 'text')
|
|
133
|
+
if (Array.isArray(body?.choices)) for (const c of body.choices) fix(c?.message, 'content')
|
|
134
|
+
if (Array.isArray(body?.output)) {
|
|
135
|
+
for (const it of body.output) {
|
|
136
|
+
if (it?.type === 'message' && Array.isArray(it.content)) for (const p of it.content) if (p?.type === 'output_text') fix(p, 'text')
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
if (Array.isArray(body?.candidates)) {
|
|
140
|
+
for (const c of body.candidates) if (Array.isArray(c?.content?.parts)) for (const p of c.content.parts) fix(p, 'text')
|
|
141
|
+
}
|
|
142
|
+
return changed
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** 流式事件里带可见文本的槽位,按 protocol 的事件形状取。 */
|
|
146
|
+
export function streamSlots(ev) {
|
|
147
|
+
const out = []
|
|
148
|
+
if (!ev || typeof ev !== 'object') return out
|
|
149
|
+
if (ev.type === 'content_block_delta' && ev.delta?.type === 'text_delta') out.push({ obj: ev.delta, key: 'text' })
|
|
150
|
+
else if (ev.type === 'response.output_text.delta') out.push({ obj: ev, key: 'delta' })
|
|
151
|
+
else if (Array.isArray(ev.choices)) {
|
|
152
|
+
for (const c of ev.choices) if (c?.delta && typeof c.delta.content === 'string') out.push({ obj: c.delta, key: 'content' })
|
|
153
|
+
} else if (Array.isArray(ev.candidates)) {
|
|
154
|
+
for (const c of ev.candidates) if (Array.isArray(c?.content?.parts)) for (const p of c.content.parts) if (typeof p?.text === 'string') out.push({ obj: p, key: 'text' })
|
|
155
|
+
}
|
|
156
|
+
return out
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export { textOf }
|
package/lib/rewrite.mjs
CHANGED
|
@@ -46,6 +46,65 @@ const textOf = (content) => {
|
|
|
46
46
|
return ''
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
+
/**
|
|
50
|
+
* setTextOf 把一条消息的 content 换成新文本,形状跟着原来的走。
|
|
51
|
+
*
|
|
52
|
+
* 为什么不能一律写成字符串:Anthropic 的 content 块数组里可能挂着 cache_control,
|
|
53
|
+
* 直接换成字符串会把缓存标记连同块结构一起丢掉;空块数组要保留成空数组,
|
|
54
|
+
* 因为 Claude Code 用一条「内容为空、只带 output_config」的 system 消息传本轮档位。
|
|
55
|
+
*/
|
|
56
|
+
function setTextOf(msg, text) {
|
|
57
|
+
const cur = msg.content
|
|
58
|
+
if (Array.isArray(cur)) {
|
|
59
|
+
const blocks = cur.filter((b) => b && typeof b === 'object')
|
|
60
|
+
if (!blocks.length) {
|
|
61
|
+
msg.content = text
|
|
62
|
+
return
|
|
63
|
+
}
|
|
64
|
+
const out = []
|
|
65
|
+
let placed = false
|
|
66
|
+
for (const b of blocks) {
|
|
67
|
+
if (!placed && typeof b.text === 'string') {
|
|
68
|
+
out.push({ ...b, text })
|
|
69
|
+
placed = true
|
|
70
|
+
continue
|
|
71
|
+
}
|
|
72
|
+
out.push({ ...b, text: '' })
|
|
73
|
+
}
|
|
74
|
+
msg.content = placed ? out : [{ type: 'text', text }, ...out]
|
|
75
|
+
return
|
|
76
|
+
}
|
|
77
|
+
msg.content = text
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* scrubInMessages 处理「客户端把 system 也塞进了 messages」的那一份。
|
|
82
|
+
*
|
|
83
|
+
* 这是 Claude Code 走 Anthropic 协议时被注入失效的真正原因:
|
|
84
|
+
* 1. 它把身份行("You are Claude Code…")放进 messages 里的一条 {role:"system"},
|
|
85
|
+
* 而 magpie 把顶层 system 排在前面、这条排在后面;
|
|
86
|
+
* 2. DeepSeek 的 Anthropic 端点把 messages 里的 system 合到顶层 system 之后,
|
|
87
|
+
* 也就是排在注入的人设后面 —— 后说的赢,人设当场被压掉。
|
|
88
|
+
* 现场 A/B:同一份真实 Claude Code 请求体,不注入答「我是 Claude」,
|
|
89
|
+
* 注入后人设只有 2/4 次生效;把这条消息里的身份行剥掉后 4/4 稳定生效。
|
|
90
|
+
*
|
|
91
|
+
* 所以:replace 剥身份行,strict 清空正文(只留 output_config 这类非文本字段)。
|
|
92
|
+
*/
|
|
93
|
+
function scrubInMessages(body, mode, roles = ['system', 'developer']) {
|
|
94
|
+
if (!Array.isArray(body.messages)) return
|
|
95
|
+
for (const m of body.messages) {
|
|
96
|
+
if (!m || typeof m !== 'object' || !roles.includes(m.role)) continue
|
|
97
|
+
const cur = textOf(m.content)
|
|
98
|
+
if (mode === 'strict') {
|
|
99
|
+
if (cur.trim()) setTextOf(m, '')
|
|
100
|
+
continue
|
|
101
|
+
}
|
|
102
|
+
if (mode !== 'replace' || !cur.trim()) continue
|
|
103
|
+
const stripped = stripIdentity(cur)
|
|
104
|
+
if (stripped !== cur.trim()) setTextOf(m, stripped)
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
49
108
|
/** Anthropic:system 可以是字符串或块数组;块结构(含 cache_control)原地保留。 */
|
|
50
109
|
function anthropic(body, text, mode) {
|
|
51
110
|
const cur = body.system
|
|
@@ -57,6 +116,8 @@ function anthropic(body, text, mode) {
|
|
|
57
116
|
: Array.isArray(cur)
|
|
58
117
|
? cur.filter((b) => b && typeof b === 'object').map((b) => ({ ...b }))
|
|
59
118
|
: []
|
|
119
|
+
// Anthropic 的 messages 里只有 system 这一种越权角色
|
|
120
|
+
scrubInMessages(body, mode, ['system'])
|
|
60
121
|
if (mode === 'strict') {
|
|
61
122
|
body.system = [{ type: 'text', text }]
|
|
62
123
|
return
|
|
@@ -76,6 +137,9 @@ function chat(body, text, mode) {
|
|
|
76
137
|
body.messages.splice(i < 0 ? 0 : Math.min(i, body.messages.length), 0, first)
|
|
77
138
|
return
|
|
78
139
|
}
|
|
140
|
+
// 第一条之前的 system 会被 magpie 合进顶层 system(排在人设后面,剥不剥都不影响结论);
|
|
141
|
+
// 回复之后才出现的那些留在原位,magpie 原样发出去 —— 它们同样能压掉人设。
|
|
142
|
+
scrubInMessages(body, mode, ['system', 'developer'])
|
|
79
143
|
if (i < 0) {
|
|
80
144
|
msgs.unshift({ role: 'system', content: text })
|
|
81
145
|
return
|