Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions docs/gateway.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,13 +162,14 @@ Claude Code、Codex 等客户端会在系统提示词里放固定模板句,上

内置提示词约 2KB([`internal/prompt/defaultprompt.md`](../internal/prompt/defaultprompt.md));`prompt.file` 可替换成你自己的。

2. **指纹脱敏**(`features.sanitize_blacklist_fingerprints`)清洗所有消息里的指纹串,系统提示词、用户、助手、工具消息,以及工具调用参数和推理内容都算。上游的「渠道指纹」拦截(400 + `code 11128`,`Illegal API invocation from an unapproved channel`)按大小写不敏感的连续子串匹配,网关处理这几类:
2. **指纹脱敏**(`features.sanitize_blacklist_fingerprints`)清洗消息里的指纹串。除下面单独说明的 `workspace root` 规则外,清洗范围包括系统提示词、用户、助手、工具消息,以及工具调用参数和推理内容。上游的「渠道指纹」拦截(400 + `code 11128`,`Illegal API invocation from an unapproved channel`)按大小写不敏感的连续子串匹配,网关处理这几类:
- Claude Code、Codex 的固定模板句和 `x-anthropic-billing-header` 这类键值,改一个词或整段删掉;
- 「You are … powered by / built on / created by …」这类自我介绍句,整句换成 `You are a helpful AI assistant.`;
- DeepSeek Harness 的提示词:「… DeepSeek Harness Web GUI whose URL the runtime context names.」改个语序,正文里的 `DeepSeek Harness` 缩成 `DeepSeek`;
- OhMyOpenCode 插件的 `Sisyphus-Junior - Focused executor from OhMyOpenCode`。
- OhMyOpenCode 插件的 `Sisyphus-Junior - Focused executor from OhMyOpenCode`;
- system / developer 消息内容里的独立短语 `workspace root` 改为 `root of the workspace`,忽略大小写,允许空格或制表符分隔;较长单词中的子串不改。其他角色、工具调用参数及推理内容中的该短语保留原文。

后三类规则参考了 workbuddy2api-hub、workbuddy-manager、cpa-multi-plugins 等项目的实测(见 README 致谢)。
自我介绍句、DeepSeek Harness 和 OhMyOpenCode 三类规则参考了 workbuddy2api-hub、workbuddy-manager、cpa-multi-plugins 等项目的实测(见 README 致谢)。`workspace root` 规则依据 [PR #8](https://github.com/yreidev/workbuddy2api-panel/pull/8) 作者的 DSH 请求对照实测;本仓库维护者未独立复测真实上游。

**降级重试**:请求被内容审核拦下时,网关判定为系统提示词误报,**在同一请求内**换成中性提示词重试一次;第二次仍被拦,说明是用户内容本身触发审核,如实返回给客户端。触发降级后到次日 00:00(北京时间)前,后续请求直接用中性提示词,不再先撞一次 400。降级状态只在内存里,重启清零。内容拦截不罚账号。

Expand Down
80 changes: 75 additions & 5 deletions internal/upstream/sanitize.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,11 +84,15 @@ var sanitizeRewrites = [][2]string{
},
}

// 以下四条是上游 11128「Illegal API invocation from an unapproved channel」的渠道指纹,
// 以下五条是上游 11128「Illegal API invocation from an unapproved channel」的渠道指纹,
// 取自同类项目的真号实测(workbuddy2api-hub #61/#533/#537/#570/#574,
// ithtelab/workbuddy-manager #246/#250,mmqz/cpa-multi-plugins #46/#49):
// 大小写不敏感、连续子串匹配,改一个词或换语序即放行。
// 作用域与上面的规则一致,所有角色都改:有项目实测放在 user 或 assistant 历史里同样被拦。
//
// 作用域:身份句、品牌句、OhMyOpenCode 三条所有角色都改——有项目实测放在 user 或
// assistant 历史里同样被拦。workspace root 是唯一的例外,只改 system 级内容:
// 它在工具参数和用户原文里只是普通字面串,全通道改写会让出站请求与用户原意不符
// (review 5881990497 第二条),见 sanitizeTextForSystem。
var (
// sanitizeIdentityStartRe 自我介绍句的开头到归属动词,例如
// "You are an AI agent powered by DeepSeek Harness."、
Expand All @@ -108,6 +112,11 @@ var (
// sanitizeBrandRe 散文里的 DeepSeek Harness 和 GUI 描述句连着出现时同样命中,缩成 DeepSeek。
// 只认空格与制表符,deepseek-harness、deepseek_harness 这类路径与标识符不动。
sanitizeBrandRe = regexp.MustCompile(`(?i)DeepSeek[ \t]+Harness`)
// sanitizeWorkspaceRootRe Codex / Claude Code 系 system prompt 的特征短语 workspace root:
// 上游按它做渠道指纹,命中即 400 11-128「Illegal API invocation from an unapproved channel」。
// 2026-11-13 实测:完整 DSH system 里只此一处命中;改成语序自然的 root of the workspace 即放行。
// 只作用于 system 级内容,其余角色与工具参数原样保留(见 sanitizeTextForSystem)。
sanitizeWorkspaceRootRe = regexp.MustCompile(`(?i)\bworkspace[ \t]+root\b`)
// sanitizeOmORe OhMyOpenCode 子代理的身份串,两半各自单独出现都放行,只拆开连在一起的这一段。
sanitizeOmORe = regexp.MustCompile(`(?i)Sisyphus-Junior - Focused executor from OhMyOpenCode`)
)
Expand Down Expand Up @@ -180,14 +189,40 @@ func hasChannelFingerprint(text string) bool {
}

// sanitizeText 单段文本净化:预检不中 → 返回原串(零分配)。
//
// 不含 workspace root 替换——该短语的改写会变更字面内容,一旦作用于工具参数、
// 工具结果或用户原文,出站请求里的目录名/命令就与用户原意不符(review 5881990497
// 第二条)。它只在 system 级内容上做,见 sanitizeTextForSystem。
func sanitizeText(text string) string {
return sanitizeTextOpt(text, false)
}

// sanitizeTextForSystem system / developer 级内容的净化:与 sanitizeText 同口径,
// 额外替换 workspace root 渠道指纹。
//
// 替换位置跨在 hasFingerprint 判定两侧:system 里只出现 workspace root 时预检为假
// (该短语已从 hasChannelFingerprint 摘除),走早返回分支只做这一处替换,不会连带
// 触发 sanitizeKvRe 等剥离层——那正是 review 5881990497 第四条指出的
// {"command":"echo workspace root; cc_version=1"} 被删成无效 JSON 的成因。
// system 里另有其他指纹时走完整链,替换嵌在链里保持原有先后顺序。
func sanitizeTextForSystem(text string) string {
return sanitizeTextOpt(text, true)
}

func sanitizeTextOpt(text string, replaceWorkspaceRoot bool) string {
if !hasFingerprint(text) {
if replaceWorkspaceRoot {
text = sanitizeWorkspaceRootRe.ReplaceAllString(text, "root of the workspace")
}
return text
}
text = sanitizeOmORe.ReplaceAllString(text, "Sisyphus-Junior - Focused executor")
text = rewriteIdentitySentences(text)
// GUI 描述段要认品牌全名,先于品牌缩减。
text = sanitizeDSHGUIRe.ReplaceAllString(text, "${1} whose URL is named in the runtime context.")
if replaceWorkspaceRoot {
text = sanitizeWorkspaceRootRe.ReplaceAllString(text, "root of the workspace")
}
text = sanitizeBrandRe.ReplaceAllString(text, "DeepSeek")
for _, rw := range sanitizeRewrites {
text = strings.ReplaceAll(text, rw[0], rw[1])
Expand Down Expand Up @@ -224,9 +259,22 @@ func hasFingerprint(text string) bool {
// sanitizeContent 兼容字符串与多模态数组;只动 text part,image 等 part 不动。
// 返回净化后的值及是否发生变化。
func sanitizeContent(v any) (any, bool) {
return sanitizeContentOpt(v, false)
}

// sanitizeContentForSystem system 级消息内容的净化:额外做 workspace root 替换。
func sanitizeContentForSystem(v any) (any, bool) {
return sanitizeContentOpt(v, true)
}

func sanitizeContentOpt(v any, systemLevel bool) (any, bool) {
fn := sanitizeText
if systemLevel {
fn = sanitizeTextForSystem
}
switch c := v.(type) {
case string:
s := sanitizeText(c)
s := fn(c)
return s, s != c
case []any:
changed := false
Expand All @@ -239,7 +287,7 @@ func sanitizeContent(v any) (any, bool) {
if !ok {
continue
}
if s := sanitizeText(text); s != text {
if s := fn(text); s != text {
m["text"] = s
changed = true
}
Expand Down Expand Up @@ -282,6 +330,16 @@ func sanitizeToolCalls(v any) bool {
return changed
}

// roleIsSystemLevel 判定 system 级角色:system 及其别名 developer。
//
// normalizeRoles 在 prepareBody 里已把 developer 归一为 system,所以跑到这里时
// 通常只剩 system;此处一并认可 developer,是为了不依赖调用顺序(单测直接调
// sanitizeMessages 时也是这个口径)。
func roleIsSystemLevel(role string) bool {
r := strings.TrimSpace(role)
return strings.EqualFold(r, "system") || strings.EqualFold(r, "developer")
}

// sanitizeMessages 净化 messages 中的 content 与 tool_calls;任一命中返回 true。
func sanitizeMessages(messages []any) bool {
changed := false
Expand All @@ -290,10 +348,22 @@ func sanitizeMessages(messages []any) bool {
if !ok {
continue
}
role, _ := m["role"].(string)
// content 与 tool_calls 各自独立判断:content 可以为 null(工具调用轮),
// 早期版本在此 continue,导致这类消息的 tool_calls 完全不被净化。
//
// workspace root 只在 system 级内容上替换:其余角色(user / assistant / tool /
// 无 role)里的它是一个真实的字面串——用户给的目录名、工具回显的文件内容——
// 改了就与用户原意不符。
if c, ok := m["content"]; ok {
if nc, ch := sanitizeContent(c); ch {
var nc any
var ch bool
if roleIsSystemLevel(role) {
nc, ch = sanitizeContentForSystem(c)
} else {
nc, ch = sanitizeContent(c)
}
if ch {
m["content"] = nc
changed = true
}
Expand Down
143 changes: 143 additions & 0 deletions internal/upstream/sanitize_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -501,6 +501,149 @@ func TestChannelFingerprintScrubbedInEveryRole(t *testing.T) {
}
}

// Codex / Claude Code 系 system prompt 的 workspace root 短语:system 级内容里命中后
// 改成语序自然的 root of the workspace,语义不变,同时不再撞上游的渠道指纹。
func TestWorkspaceRootRewritten(t *testing.T) {
in := "Relative paths resolve from the workspace root; absolute paths identify files."
want := "Relative paths resolve from the root of the workspace; absolute paths identify files."
if got := systemContent(t, in); got != want {
t.Errorf("not rewritten:\n got %q\nwant %q", got, want)
}
}

// systemContent 把单段内容包成 system 消息走一遍 sanitizeMessages,返回净化后的 content。
func systemContent(t *testing.T, in string) string {
t.Helper()
msgs := []any{map[string]any{"role": "system", "content": in}}
sanitizeMessages(msgs)
got, ok := msgs[0].(map[string]any)["content"].(string)
if !ok {
t.Fatalf("content 不是字符串: %#v", msgs[0])
}
return got
}

// 大小写不敏感,空格与制表符都算分隔。
func TestWorkspaceRootCaseAndSeparator(t *testing.T) {
for _, in := range []string{
"from the workspace root here",
"from the Workspace root here",
"from the WORKSPACE ROOT here",
"from the workspace\troot here",
} {
if got := systemContent(t, in); got != "from the root of the workspace here" {
t.Errorf("%q -> %q", in, got)
}
}
}

// 词边界:只有独立的 workspace root 才动,更长单词里的子串保持原样。
func TestWorkspaceRootWordBoundary(t *testing.T) {
for _, in := range []string{
"a workspace rooter tool",
"myworkspace root probe",
"the workspaceroot is fine",
} {
if got := systemContent(t, in); got != in {
t.Errorf("should be untouched: %q -> %q", in, got)
}
}
}

// 改写结果再过一遍不再变化。
func TestWorkspaceRootIdempotent(t *testing.T) {
once := systemContent(t, "from the workspace root here")
if twice := systemContent(t, once); twice != once {
t.Errorf("not idempotent: %q -> %q", once, twice)
}
}

// 作用域:只有 system / developer 级内容替换;user、assistant、tool、无 role
// 以及工具调用的 arguments 一律逐字保留——那是用户的真实字面内容。
func TestWorkspaceRootOnlySystemLevel(t *testing.T) {
const in = `mkdir "workspace root"`
const wantIn = `mkdir "root of the workspace"`
argsJSON, err := json.Marshal(map[string]string{"cmd": in})
if err != nil {
t.Fatalf("构造工具参数失败: %v", err)
}
wantArgs := string(argsJSON)
msgs := []any{
map[string]any{"role": "system", "content": in},
map[string]any{"role": "developer", "content": in},
map[string]any{"role": "user", "content": in},
map[string]any{"role": "assistant", "content": in},
map[string]any{"role": "tool", "content": in},
map[string]any{"content": in},
map[string]any{
"role": "assistant",
"content": nil,
"tool_calls": []any{map[string]any{
"id": "c1",
"type": "function",
"function": map[string]any{
"name": "run",
"arguments": wantArgs,
},
}},
},
}
sanitizeMessages(msgs)

wantSystems := map[int]string{0: wantIn, 1: wantIn}
for i, m := range msgs {
got, _ := m.(map[string]any)["content"].(string)
if want, ok := wantSystems[i]; ok {
if got != want {
t.Errorf("msg %d 应替换: got %q want %q", i, got, want)
}
continue
}
if i == 6 {
continue // content 为 nil,arguments 单独断言
}
if got != in {
t.Errorf("msg %d 不应改动: got %q want %q", i, got, in)
}
}
fn := msgs[6].(map[string]any)["tool_calls"].([]any)[0].(map[string]any)["function"].(map[string]any)
args := fn["arguments"].(string)
if args != wantArgs {
t.Errorf("工具参数不应改动: %q", args)
}
if !json.Valid([]byte(args)) {
t.Fatalf("工具参数不是合法 JSON: %q", args)
}
}

// workspace root 不再单独把文本拖进完整净化链:review 5881990497 第四条指出,
// 只含该短语的工具参数曾被 sanitizeKvRe 删掉 cc_version=1 而变成无效 JSON。
func TestWorkspaceRootDoesNotTriggerKvStrip(t *testing.T) {
const args = `{"command":"echo workspace root; cc_version=1"}`
msgs := []any{map[string]any{
"role": "assistant",
"content": nil,
"tool_calls": []any{map[string]any{
"id": "c1",
"type": "function",
"function": map[string]any{
"name": "run",
"arguments": args,
},
}},
}}
if sanitizeMessages(msgs) {
t.Fatal("不应有任何改动")
}
got := msgs[0].(map[string]any)["tool_calls"].([]any)[0].(map[string]any)["function"].(map[string]any)["arguments"].(string)
if got != args {
t.Fatalf("arguments 被改动: %q", got)
}
if !json.Valid([]byte(got)) {
t.Fatalf("arguments 已不是合法 JSON: %q", got)
}
}

func TestContainsFoldASCII(t *testing.T) {
if !containsFoldASCII("xx DeepSeek HARNESS", "harness") || containsFoldASCII("harnes", "harness") || containsFoldASCII("", "a") {
t.Fatal("containsFoldASCII wrong")
Expand Down
Loading