// shape.go 免费车道(OpenCode)的请求整形:官方系统提示 + 工具改名 + 官方工具集。 // // 移植自 dsh-our-free-model 的 src/o2a/(opencode2api Go 实现的 JS 移植), // 只保留 chat 线(本网关的免费层只暴露 /v1/chat/completions)。每条事实都有 // 实测依据,见 dsh 仓库 docs/free-lane-wire.md: // - 请求体必须带官方 CLI 系统提示(base + + skills); // - 调用方工具必须全部改名成不透明的 clint_; // - 必须补齐官方 13 个工具定义(read/shell 两个是闸门直接读的); // - 绝不下发 tool_choice:"none";流式补 stream_options.include_usage, // 调用方没给上限时补 max_completion_tokens:32000。 package freemodel import ( "crypto/sha256" _ "embed" "encoding/hex" "encoding/json" "fmt" "runtime" "strings" "time" ) //go:embed assets/opencode_prompt_v2.txt var openCodePromptBase string //go:embed assets/opencode_tools.json var openCodeToolsJSON []byte const ( officialPromptMarker = "You are opencode, an interactive CLI tool" clientToolPrefix = "clint_" completionLimit = 32000 ) const officialSkills = `Skills provide specialized instructions and workflows for specific tasks. Use the skill tool to load a skill when a task matches its description. customize-opencode Use ONLY when the user is editing or creating opencode's own configuration: opencode.json, opencode.jsonc, files under .opencode/, or files under ~/.config/opencode/. Also use when creating or fixing opencode agents, subagents, skills, plugins, MCP servers, or permission rules. Do not use for the user's own application code, or for any project that is not configuring opencode itself. <built-in> ` // v2OfficialToolOrder 官方工具的固定顺序(JSON key 顺序不保证)。 var v2OfficialToolOrder = []string{ "edit", "execute", "glob", "grep", "question", "read", "shell", "skill", "subagent", "webfetch", "websearch", "write", "patch", } // officialClientAliases 客户端常见工具名 → 官方工具名(折叠比较)。 var officialClientAliases = map[string]string{ "edit": "edit", "glob": "glob", "grep": "grep", "question": "question", "askuserquestion": "question", "read": "read", "view": "read", "shell": "shell", "bash": "shell", "skill": "skill", "subagent": "subagent", "agent": "subagent", "task": "subagent", "webfetch": "webfetch", "fetch": "webfetch", "websearch": "websearch", "write": "write", "patch": "patch", "applypatch": "patch", } var officialTools map[string]map[string]any func init() { officialTools = map[string]map[string]any{} var parsed map[string]struct { Description string `json:"description"` Parameters map[string]any `json:"parameters"` } if json.Unmarshal(openCodeToolsJSON, &parsed) == nil { for name, def := range parsed { if def.Description == "" || def.Parameters == nil { continue } officialTools[name] = map[string]any{ "description": def.Description, "parameters": def.Parameters, } } } } // officialTool 渲染一个官方工具(chat 形状带 strict:false)。 func officialTool(name string) map[string]any { description := "Agent tool " + name parameters := map[string]any{"type": "object", "properties": map[string]any{}} if def, ok := officialTools[name]; ok { if d, ok := def["description"].(string); ok { description = d } if p, ok := def["parameters"].(map[string]any); ok { parameters = deepCopyMap(p) } } if name == "shell" && runtime.GOOS == "windows" { description = strings.ReplaceAll(description, "on Linux using bash", "on Windows using powershell") } return map[string]any{ "type": "function", "function": map[string]any{ "name": name, "description": description, "parameters": parameters, "strict": false, }, } } func deepCopyMap(in map[string]any) map[string]any { raw, _ := json.Marshal(in) var out map[string]any _ = json.Unmarshal(raw, &out) return out } // foldToolName 小写并去掉分隔符,用于别名比较。 func foldToolName(name string) string { var b strings.Builder for _, r := range strings.ToLower(name) { switch r { case '_', '.', '-', ' ', '\t', '\r', '\n': continue } b.WriteRune(r) } return b.String() } func officialForClientName(name string) string { return officialClientAliases[foldToolName(name)] } // clientToolWireName 生成不透明 wire 名:clint_ + sha256(name)[:12]。 func clientToolWireName(name string, used map[string]bool) string { sum := sha256.Sum256([]byte(name)) base := clientToolPrefix + hex.EncodeToString(sum[:])[:12] if !used[base] { used[base] = true return base } for suffix := 2; ; suffix++ { tag := fmt.Sprintf("_%d", suffix) candidate := base if len(candidate)+len(tag) > 64 { candidate = candidate[:64-len(tag)] } candidate += tag if !used[candidate] { used[candidate] = true return candidate } } } // renameMap wire 名 → 客户端原名。 type renameMap struct { byClient map[string]string byWire map[string]string byCase map[string]string byShape map[string]string } func newRenameMap() *renameMap { return &renameMap{ byClient: map[string]string{}, byWire: map[string]string{}, byCase: map[string]string{}, byShape: map[string]string{}, } } func (m *renameMap) add(client, wire string) { if client == "" || wire == "" || client == wire { return } if _, ok := m.byClient[client]; ok { return } if _, ok := m.byWire[wire]; ok { return } m.byClient[client] = wire m.byWire[wire] = client m.bindFolded(m.byCase, strings.ToLower(client), client) m.bindFolded(m.byShape, foldToolName(client), client) } func (m *renameMap) bindFolded(index map[string]string, key, client string) { if key == "" { return } if existing, ok := index[key]; !ok { index[key] = client } else if existing != client { index[key] = "" } } func (m *renameMap) wireOf(client string) (string, bool) { w, ok := m.byClient[client] return w, ok } // resolve 上游回来的名字 → 客户端原名。 func (m *renameMap) resolve(wire string) string { if m == nil || wire == "" { return wire } if exact, ok := m.byWire[wire]; ok { return exact } client := wire if strings.HasPrefix(client, clientToolPrefix) { client = strings.TrimPrefix(client, clientToolPrefix) if client == "" { return wire } } if _, ok := m.byClient[client]; ok { return client } if folded, ok := m.byCase[strings.ToLower(client)]; ok && folded != "" { return folded } if folded, ok := m.byShape[foldToolName(client)]; ok && folded != "" { return folded } return client } // applyFingerprint 对 chat 请求体做完整整形,返回改名表(响应侧还原用)。 func applyFingerprint(body map[string]any, model, session string) *renameMap { if body == nil { return newRenameMap() } if isTitleRequest(body) { return newRenameMap() } injectOfficialPrompt(body, model) renames, injected := shapeTools(body) if len(injected) > 0 { noteInjectedTools(body, injected) } if choice, ok := body["tool_choice"].(string); ok && choice == "none" { delete(body, "tool_choice") } if choice, ok := body["tool_choice"].(map[string]any); ok { if t, _ := choice["type"].(string); t == "none" { delete(body, "tool_choice") } } ensureChatUsage(body) ensureV2CompletionLimit(body) return renames } // isTitleRequest 与 dsh 同一判定:没有工具、1-3 轮纯 user/system、且带标题标记。 // 这类请求整形反而会被上游 403/429。 func isTitleRequest(body map[string]any) bool { if tools, ok := body["tools"].([]any); ok && len(tools) > 0 { return false } if functions, ok := body["functions"].([]any); ok && len(functions) > 0 { return false } if _, ok := body["tool_choice"]; ok { return false } messages, _ := body["messages"].([]any) if len(messages) == 0 || len(messages) > 3 { return false } var text strings.Builder for _, raw := range messages { msg, _ := raw.(map[string]any) if msg == nil { return false } role, _ := msg["role"].(string) if role != "user" && role != "system" && role != "developer" { return false } text.WriteString(textOf(msg["content"])) text.WriteString("\n") } lower := strings.ToLower(text.String()) markers := []string{ "generate a title", "write a title", "create a title", "come up with a title", "conversation title", "summarize this conversation", "summarize the conversation", } for _, marker := range markers { if strings.Contains(lower, marker) { return true } } return false } // injectOfficialPrompt 把官方 CLI 提示注入首条 system/developer 消息。 func injectOfficialPrompt(body map[string]any, model string) { prompt := officialSystemPrompt(model) if prompt == "" { return } messages, _ := body["messages"].([]any) anchor := -1 for i, raw := range messages { msg, _ := raw.(map[string]any) if msg == nil { continue } role, _ := msg["role"].(string) if role != "system" && role != "developer" { continue } if carriesOpenCodePrompt(msg["content"]) { return } if anchor == -1 { anchor = i } } if anchor == -1 { body["messages"] = append([]any{map[string]any{"role": "system", "content": prompt}}, messages...) return } msg := messages[anchor].(map[string]any) switch content := msg["content"].(type) { case []any: msg["content"] = append([]any{map[string]any{"type": "text", "text": prompt}}, content...) case string: if strings.TrimSpace(content) == "" { msg["content"] = prompt } else { msg["content"] = prompt + "\n\n" + content } default: msg["content"] = prompt } messages[anchor] = msg body["messages"] = messages } func officialSystemPrompt(model string) string { if strings.TrimSpace(openCodePromptBase) == "" { return "" } return openCodePromptBase + officialEnvironment(model) + "\n" + officialSkills } func officialEnvironment(model string) string { apiModel := strings.TrimPrefix(strings.TrimSpace(model), "opencode/") if apiModel == "" { apiModel = "unknown" } platform := runtime.GOOS if platform == "windows" { platform = "win32" } now := time.Now().UTC() date := fmt.Sprintf("%s %s %02d %d", now.Format("Mon"), now.Format("Jan"), now.Day(), now.Year()) return fmt.Sprintf("You are powered by the model named %s. The exact model ID is opencode/%s\n"+ "Here is some useful information about the environment you are running in:\n"+ "\n Working directory: /workspace\n Workspace root folder: /workspace\n"+ " Is directory a git repo: yes\n Platform: %s\n Today's date: %s\n", apiModel, apiModel, platform, date) } func textOf(value any) string { switch v := value.(type) { case string: return v case []any: var b strings.Builder for _, item := range v { b.WriteString(textOf(item)) } return b.String() case map[string]any: if t, ok := v["text"].(string); ok { return t } if c, ok := v["content"]; ok { return textOf(c) } } return "" } func carriesOpenCodePrompt(value any) bool { switch v := value.(type) { case string: return strings.Contains(v, officialPromptMarker) case []any: for _, item := range v { if carriesOpenCodePrompt(item) { return true } } case map[string]any: if t, ok := v["text"].(string); ok && strings.Contains(t, officialPromptMarker) { return true } if c, ok := v["content"]; ok { return carriesOpenCodePrompt(c) } } return false } // shapeTools 改名调用方工具并补齐官方 13 工具集。 func shapeTools(body map[string]any) (*renameMap, []string) { renames := newRenameMap() used := map[string]bool{} officialUsed := map[string]bool{} items, _ := body["tools"].([]any) if functions, ok := body["functions"].([]any); ok { items = append(items, convertLegacyFunctions(functions, renames, used)...) delete(body, "functions") } // 已逐字带官方定义的声明视为官方声明,不重命名也不重复补。 keep := map[string]bool{} for _, raw := range items { if name := renamableToolName(raw); name != "" && carriesOfficialDefinition(raw, name) { keep[name] = true officialUsed[name] = true } } declaredClientTools := 0 for _, raw := range items { if renamableToolName(raw) != "" { declaredClientTools++ } } shaped := make([]any, 0, len(items)+len(v2OfficialToolOrder)) for _, raw := range items { name := renamableToolName(raw) if name == "" { shaped = append(shaped, raw) continue } if keep[name] || strings.HasPrefix(name, clientToolPrefix) { shaped = append(shaped, raw) continue } if official := officialForClientName(name); official != "" && !officialUsed[official] { if _, exists := officialTools[official]; exists { officialUsed[official] = true renames.add(name, official) shaped = append(shaped, withToolName(raw, official)) continue } } wireName, ok := renames.wireOf(name) if !ok { wireName = clientToolWireName(name, used) renames.add(name, wireName) } if wireName != name { shaped = append(shaped, withToolName(raw, wireName)) } else { shaped = append(shaped, raw) } } injected := make([]string, 0) for _, name := range v2OfficialToolOrder { if officialUsed[name] { continue } shaped = append(shaped, officialTool(name)) injected = append(injected, name) officialUsed[name] = true } body["tools"] = shaped rewriteToolReferences(body, renames) if declaredClientTools > 0 { known := map[string]bool{} for name := range officialUsed { known[name] = true } for wire := range renames.byWire { known[wire] = true } sanitizeToolHistory(body, known) dropDanglingToolChoice(body, known) } return renames, injected } func renamableToolName(entry any) string { tool, _ := entry.(map[string]any) if tool == nil { return "" } fn, _ := tool["function"].(map[string]any) if fn == nil { return "" } name, _ := fn["name"].(string) return strings.TrimSpace(name) } func carriesOfficialDefinition(entry any, name string) bool { tool, _ := entry.(map[string]any) fn, _ := tool["function"].(map[string]any) official := officialTool(name) ofn, _ := official["function"].(map[string]any) if fn == nil || ofn == nil { return false } if fn["description"] != ofn["description"] { return false } a, _ := json.Marshal(fn["parameters"]) b, _ := json.Marshal(ofn["parameters"]) return string(a) == string(b) } func withToolName(entry any, name string) any { tool, _ := entry.(map[string]any) if tool == nil { return entry } clone := make(map[string]any, len(tool)) for k, v := range tool { clone[k] = v } fn, _ := clone["function"].(map[string]any) fnClone := make(map[string]any, len(fn)+1) for k, v := range fn { fnClone[k] = v } fnClone["name"] = name clone["function"] = fnClone return clone } func convertLegacyFunctions(functions []any, renames *renameMap, used map[string]bool) []any { out := make([]any, 0, len(functions)) for _, raw := range functions { fn, _ := raw.(map[string]any) if fn == nil { continue } name, _ := fn["name"].(string) if name == "" { continue } wireName, ok := renames.wireOf(name) if !ok { wireName = clientToolWireName(name, used) renames.add(name, wireName) } params := fn["parameters"] if params == nil { params = map[string]any{"type": "object", "properties": map[string]any{}} } converted := map[string]any{ "type": "function", "function": map[string]any{ "name": wireName, "description": fn["description"], "parameters": params, }, } if strict, ok := fn["strict"]; ok { converted["function"].(map[string]any)["strict"] = strict } out = append(out, converted) } return out } func rewriteToolReferences(body map[string]any, renames *renameMap) { if len(renames.byClient) == 0 { return } resolve := func(container map[string]any) (string, bool) { name, _ := container["name"].(string) if name == "" { return "", false } wire, ok := renames.wireOf(name) if !ok || wire == name { return "", false } return wire, true } if choice, ok := body["tool_choice"].(map[string]any); ok { if fn, ok := choice["function"].(map[string]any); ok { if wire, ok := resolve(fn); ok { fn["name"] = wire } } else if wire, ok := resolve(choice); ok { choice["name"] = wire } } if fc, ok := body["function_call"].(map[string]any); ok { if wire, ok := resolve(fc); ok { fc["name"] = wire } } messages, _ := body["messages"].([]any) for _, raw := range messages { msg, _ := raw.(map[string]any) if msg == nil { continue } if fc, ok := msg["function_call"].(map[string]any); ok { if wire, ok := resolve(fc); ok { fc["name"] = wire } } calls, _ := msg["tool_calls"].([]any) for _, rawCall := range calls { call, _ := rawCall.(map[string]any) fn, _ := call["function"].(map[string]any) if fn == nil { continue } if wire, ok := resolve(fn); ok { fn["name"] = wire } } } } // sanitizeToolHistory 丢掉历史里「本轮 wire 不提供」的工具调用及其配对结果。 func sanitizeToolHistory(body map[string]any, known map[string]bool) { messages, _ := body["messages"].([]any) if messages == nil { return } droppedCalls := map[string]bool{} droppedFunctions := map[string]bool{} out := make([]any, 0, len(messages)) for _, raw := range messages { msg, _ := raw.(map[string]any) if msg == nil { out = append(out, raw) continue } drop := false if role, _ := msg["role"].(string); role == "tool" { if id, _ := msg["tool_call_id"].(string); droppedCalls[id] { continue } } if role, _ := msg["role"].(string); role == "function" { if name, _ := msg["name"].(string); droppedFunctions[name] { continue } } if calls, ok := msg["tool_calls"].([]any); ok { kept := make([]any, 0, len(calls)) for _, rawCall := range calls { call, _ := rawCall.(map[string]any) fn, _ := call["function"].(map[string]any) name, _ := fn["name"].(string) if name == "" { continue } if known[name] { kept = append(kept, call) continue } if official := officialForClientName(name); official != "" && known[official] { fn["name"] = official kept = append(kept, call) continue } if id, _ := call["id"].(string); id != "" { droppedCalls[id] = true } } if len(kept) == 0 { delete(msg, "tool_calls") if !rowHasContent(msg) { drop = true } } else if len(kept) != len(calls) { msg["tool_calls"] = kept } } if fc, ok := msg["function_call"].(map[string]any); ok { name, _ := fc["name"].(string) if official := officialForClientName(name); official != "" && known[official] { fc["name"] = official } else if !known[name] { if name != "" { droppedFunctions[name] = true } delete(msg, "function_call") if !rowHasContent(msg) { drop = true } } } if !drop { out = append(out, msg) } } body["messages"] = out } func rowHasContent(msg map[string]any) bool { for _, key := range []string{"content", "reasoning_content", "reasoning"} { switch v := msg[key].(type) { case string: if v != "" { return true } case []any: if len(v) > 0 { return true } case map[string]any: if len(v) > 0 { return true } case nil: default: return true } } return false } func dropDanglingToolChoice(body map[string]any, known map[string]bool) { choice, ok := body["tool_choice"].(map[string]any) if !ok { return } name := "" if fn, ok := choice["function"].(map[string]any); ok { name, _ = fn["name"].(string) } else { name, _ = choice["name"].(string) } if name != "" && !known[name] { delete(body, "tool_choice") } } func noteInjectedTools(body map[string]any, names []string) { quoted := make([]string, len(names)) for i, name := range names { quoted[i] = "`" + name + "`" } note := "The tools " + strings.Join(quoted, ", ") + " are part of the host CLI's own toolset and are placeholders in this session; they do nothing here. Use the other tools you have been given instead." appendSystemContext(body, note) } func appendSystemContext(body map[string]any, note string) { messages, _ := body["messages"].([]any) if len(messages) > 0 { if first, ok := messages[0].(map[string]any); ok { if role, _ := first["role"].(string); role == "system" || role == "developer" { switch content := first["content"].(type) { case string: first["content"] = content + "\n\n" + note return case []any: first["content"] = append(content, map[string]any{"type": "text", "text": note}) return } first["content"] = note return } } } body["messages"] = append([]any{map[string]any{"role": "system", "content": note}}, messages...) } func ensureChatUsage(body map[string]any) { if stream, _ := body["stream"].(bool); !stream { return } if opts, ok := body["stream_options"].(map[string]any); ok { if include, _ := opts["include_usage"].(bool); !include { opts["include_usage"] = true } return } body["stream_options"] = map[string]any{"include_usage": true} } func ensureV2CompletionLimit(body map[string]any) { if _, ok := body["max_completion_tokens"]; ok { return } if _, ok := body["max_tokens"]; ok { return } body["max_completion_tokens"] = completionLimit }