fix(gateway): isolate client prompt environments (#190)

Resolve client environment declarations before protocol conversion and keep a separate snapshot per request. Remove host directory, platform, workspace and Git assumptions, preserving explicit deployment defaults and official client prompts.

Validation: Windows build, go vet, 167 integration checks, and live DeepSeek requests with unknown environment fields.
This commit is contained in:
Jason Xu committed 2026-11-20 23:16:53 +08:00
1 parent e2b2a7c281
commit 8f691a0d00
11 files changed
+476 -66

No files matched your search

+5 -3
View File
@@ -212,13 +212,15 @@ L'oggetto facoltativo `models.anonymous_backoff` sospende la corsia anonima dopo
La compatibilità gratuita può inserire prompt e strumenti ufficiali OpenCode, rinominare gli strumenti sul collegamento upstream e ripristinarne i nomi nelle risposte. Riguarda anche modelli gratuiti serviti con chiave. Il gateway inoltra le chiamate, senza eseguire strumenti sul computer. System One è escluso dall'adattamento di messaggi e strumenti.
Il prompt inserito include directory, workspace, piattaforma, modello e data UTC. Normalmente descrive il computer del gateway. Per i client remoti configura il testo in `upstream.prompt_environment`:
Il prompt inserito include modello e data UTC; directory, workspace, piattaforma e stato Git del client non noti sono indicati come `unknown`. Non vengono sostituiti con l'ambiente del gateway. Per fornire questi dati esplicitamente, aggiungi il campo `client_environment`, riservato al gateway, al livello principale di ogni richiesta di inferenza:
```json
{"working_directory":"C:\\work\\project","workspace_root":"C:\\work\\project","platform":"windows","is_git_repo":true}
{"client_environment":{"working_directory":"C:\\work\\project","workspace_root":"C:\\work\\project","platform":"windows","is_git_repo":true}}
```
Inserisci l'oggetto nel campo indicato della configurazione. I percorsi sono testo e non vengono aperti. `windows` diventa `win32`; sono ammessi anche `linux` e `darwin`. Un prompt ufficiale già fornito dal client non viene sostituito. Questi valori avanzati non hanno campi dedicati nella UI: modifica e ricarica il file. Gli override arbitrari non sono stati verificati con la validazione reale dell'upstream.
Il gateway legge e rimuove questa estensione prima dell'inoltro. Riconosce anche blocchi `<env>` formattati nelle istruzioni system/developer e aggiornamenti `<environment_context>` in messaggi user dedicati; prevale l'ultimo aggiornamento user. Quando viene inserito un prompt, l'ordine di priorità è: `client_environment` esplicito, dichiarazioni riconosciute del client, `upstream.prompt_environment` configurato, ambiente sconosciuto. Ogni fonte fornisce uno stato completo: i campi mancanti non vengono integrati da fonti con priorità inferiore e la directory di lavoro non implica la radice del workspace. Lo stato appartiene alla singola richiesta, senza cache tra richieste o sessioni. Invia l'ambiente con ogni richiesta, direttamente o nella cronologia della conversazione.
I percorsi vengono validati come testo senza accesso al filesystem. `windows` diventa `win32`; sono ammessi anche `linux` e `darwin`. Per un valore predefinito del deployment, inserisci i quattro campi interni dell'esempio in `upstream.prompt_environment`, modifica il file di configurazione e ricaricalo; questi valori avanzati non hanno campi dedicati nella UI. Un prompt ufficiale già fornito dal client viene preservato. I valori di ambiente `unknown` sono stati accettati in richieste reali a `deepseek-v4.1-flash-free`; altri modelli e corsie restano da verificare.
Il ragionamento accetta `minimal`, `low`, `medium`, `high`, `xhigh`, `max`, `none`, `auto` o un valore vuoto. Il livello esplicito del client ha precedenza. `none` rimuove le impostazioni. `auto` usa un limite recentemente verificato soltanto per modelli gratuiti Zen/anonimi e non estende la portata dei test. La scoperta richiede test attivi, può consumare quota con più richieste e scade dopo due ore. Nessun livello viene dedotto per Go, modelli a pagamento o capacità non verificate.
+5 -3
View File
@@ -214,13 +214,15 @@ An optional `models.anonymous_backoff` object pauses the anonymous lane after re
Free-model compatibility can inject the official OpenCode system prompt and tool definitions, rename client tools on the wire, and restore their names in responses. This also affects free models served by keys. The gateway relays tool calls; it does not execute tools on the host. System One is excluded from message/tool shaping.
The injected prompt includes a working directory, workspace, platform, model, and UTC date. By default these describe the gateway host. Set `upstream.prompt_environment` to supply compatibility text for remote clients:
The injected prompt includes the model and UTC date, and reports unknown client directory, workspace, platform, or Git status as `unknown`. It never substitutes the gateway host's environment. To supply these facts explicitly, add the gateway-only `client_environment` field at the top level of each inference request:
```json
{"working_directory":"C:\\work\\project","workspace_root":"C:\\work\\project","platform":"windows","is_git_repo":true}
{"client_environment":{"working_directory":"C:\\work\\project","workspace_root":"C:\\work\\project","platform":"windows","is_git_repo":true}}
```
Merge that object into `upstream.prompt_environment`. Paths are text, not accessed by this setting. `windows` normalizes to `win32`; `linux` and `darwin` are also accepted. A client-supplied official prompt is not replaced. There are no dedicated UI fields for these advanced values; edit the file and reload it. Arbitrary environment overrides have not been verified against upstream validation.
The gateway consumes and removes this extension before forwarding. It also recognizes formatted `<env>` blocks in system/developer instructions and standalone user `<environment_context>` updates; the latest user update wins. When injecting a prompt, source priority is explicit `client_environment`, recognized client declarations, configured `upstream.prompt_environment`, then unknown. Each source supplies a complete snapshot: missing fields are not filled from lower-priority sources, and a working directory does not imply a workspace root. Each request owns its snapshot; there is no environment cache across requests or sessions. Send the environment with every request, directly or in its conversation history.
Paths are validated as text without filesystem access. `windows` normalizes to `win32`; `linux` and `darwin` are also accepted. To set a deployment fallback, place the four inner fields above in `upstream.prompt_environment`, edit the configuration file, and reload it; these advanced values have no dedicated UI fields. A client-supplied official prompt is still preserved. Unknown environment values have been accepted in live `deepseek-v4.1-flash-free` requests; other models and lanes remain unverified.
Reasoning accepts `minimal`, `low`, `medium`, `high`, `xhigh`, `max`, `none`, `auto`, or an empty value. Explicit client effort takes precedence. `none` removes reasoning settings. `auto` uses a recently validated effort ceiling only for eligible free Zen/anonymous models; it does not expand probe scope. Automatic discovery needs active probes, may make several billable/quota-consuming requests, and expires after two hours. Go/paid models and unverified levels get no inferred override.
+5 -3
View File
@@ -212,13 +212,15 @@ Gửi `x-session-id` để tách hội thoại rõ ràng. Header phiên OpenCode
Tương thích mô hình miễn phí có thể chèn prompt/công cụ chính thức OpenCode, đổi tên công cụ trên đường truyền và khôi phục tên trong phản hồi. Mô hình miễn phí dùng key cũng chịu xử lý này. Gateway chỉ chuyển tiếp lời gọi, không chạy công cụ trên máy. System One không đi qua chỉnh dạng tin nhắn/công cụ.
Prompt chèn thêm có thư mục, workspace, nền tảng, mô hình và ngày UTC; mặc định mô tả máy gateway. Có thể đặt văn bản tương thích cho client từ xa trong `upstream.prompt_environment`:
Prompt chèn thêm có mô hình và ngày UTC; thư mục, workspace, nền tảng hoặc trạng thái Git chưa biết của client được ghi là `unknown`. Gateway không thay bằng môi trường của máy chủ. Để cung cấp rõ các thông tin này, thêm trường `client_environment` dành riêng cho gateway ở cấp cao nhất của mỗi yêu cầu suy luận:
```json
{"working_directory":"C:\\work\\project","workspace_root":"C:\\work\\project","platform":"windows","is_git_repo":true}
{"client_environment":{"working_directory":"C:\\work\\project","workspace_root":"C:\\work\\project","platform":"windows","is_git_repo":true}}
```
Ghép đối tượng vào trường trên. Đường dẫn chỉ là văn bản, không được truy cập do thiết lập này. `windows` thành `win32`; cũng chấp nhận `linux`, `darwin`. Prompt chính thức client đã gửi không bị thay. UI chưa có trường riêng cho giá trị nâng cao này; sửa và nạp lại tệp. Giá trị ghi đè tùy ý chưa được xác minh với kiểm tra thực tế của upstream.
Gateway đọc rồi xóa trường mở rộng này trước khi chuyển tiếp. Gateway cũng nhận diện khối `<env>` đúng định dạng trong chỉ dẫn system/developer và bản cập nhật `<environment_context>` trong tin nhắn user riêng; bản cập nhật user cuối cùng được ưu tiên. Khi chèn prompt, thứ tự nguồn là `client_environment` rõ ràng, khai báo client được nhận diện, cấu hình `upstream.prompt_environment`, rồi đến trạng thái chưa biết. Mỗi nguồn cung cấp một bản chụp đầy đủ: trường thiếu không được bổ sung từ nguồn có ưu tiên thấp hơn, và thư mục làm việc không đồng nghĩa với thư mục gốc workspace. Bản chụp chỉ thuộc yêu cầu hiện tại, không được lưu đệm giữa các yêu cầu hay phiên. Gửi môi trường trong mỗi yêu cầu, trực tiếp hoặc qua lịch sử hội thoại.
Đường dẫn chỉ được kiểm tra như văn bản, không truy cập hệ thống tệp. `windows` thành `win32`; cũng chấp nhận `linux`, `darwin`. Để đặt giá trị mặc định cho bản triển khai, đưa bốn trường bên trong của ví dụ vào `upstream.prompt_environment`, sửa và nạp lại tệp cấu hình; UI chưa có trường riêng cho các giá trị nâng cao này. Prompt chính thức client đã gửi vẫn được giữ nguyên. Các giá trị môi trường `unknown` đã được chấp nhận trong yêu cầu thực tế tới `deepseek-v4.1-flash-free`; các mô hình và kênh khác vẫn chưa được xác minh.
Mức suy luận nhận `minimal`, `low`, `medium`, `high`, `xhigh`, `max`, `none`, `auto` hoặc rỗng. Mức client chỉ định rõ có ưu tiên. `none` bỏ thiết lập suy luận. `auto` dùng mức trần mới được xác minh cho mô hình miễn phí Zen/ẩn danh, không mở rộng phạm vi thử. Khám phá tự động cần bật thử chủ động, có thể dùng nhiều yêu cầu tiêu hao hạn mức và hết hiệu lực sau hai giờ. Không suy đoán mức cho Go, mô hình trả phí hay khả năng chưa xác minh.
+5 -3
View File
@@ -214,13 +214,15 @@ OAuth 另有规则:请求选择 OAuth 路由后,只使用该 Tier 已确认
免费模型兼容逻辑会按需注入官方 OpenCode 系统提示词和工具定义,改写线上工具名,并在响应中还原客户端名称。使用 Key 的免费模型也可能经过整形。网关只转发工具调用,不会在本机执行工具;System One 不经过消息/工具整形。
注入提示词包含目录、工作区、平台、模型与 UTC 日期,默认描述网关主机。远程客户端可配置兼容文本:
注入提示词包含模型与 UTC 日期;未知的客户端目录、工作区、平台及 Git 状态标记为 `unknown`,不会使用网关主机环境替代。可在每个推理请求顶层添加仅供网关使用的 `client_environment` 字段,明确提供这些信息:
```json
{"working_directory":"C:\\work\\project","workspace_root":"C:\\work\\project","platform":"windows","is_git_repo":true}
{"client_environment":{"working_directory":"C:\\work\\project","workspace_root":"C:\\work\\project","platform":"windows","is_git_repo":true}}
```
将此对象合并到 `upstream.prompt_environment`。目录仅作为文本使用,不会由此访问;`windows` 规范为 `win32`,还支持 `linux`、`darwin`。客户端已提供的官方提示词不被覆盖。界面没有这些高级字段,需编辑配置并重载;任意环境覆盖值尚未经过真实上游校验。
网关读取后会移除此扩展字段再转发请求。也可识别 system/developer 指令中格式明确的 `<env>` 块,以及独立 user 消息中的 `<environment_context>` 更新;后者以最后一次更新为准。注入提示词时,来源优先级为显式 `client_environment`、已识别的客户端声明、配置中的 `upstream.prompt_environment`、未知。每个来源作为完整快照使用,缺失字段不会从低优先级来源补齐,工作目录也不等于工作区根目录。快照仅属于当前请求,不跨请求或会话缓存;每次请求都需直接或通过会话历史携带环境信息。
路径仅作文本校验,不访问文件系统;`windows` 规范为 `win32`,还支持 `linux`、`darwin`。如需部署级默认值,将上例的四个内层字段放入 `upstream.prompt_environment`,编辑配置文件并重载;界面没有这些高级字段。客户端已提供的官方提示词仍不被覆盖。环境值为 `unknown` 的真实 `deepseek-v4.1-flash-free` 请求已获上游接受;其他模型及通道尚未验证。
思考强度接受 `minimal`、`low`、`medium`、`high`、`xhigh`、`max`、`none`、`auto` 或空值,客户端明确指定的强度优先。`none` 移除 reasoning 设置。`auto` 仅使用近期为免费 Zen/匿名模型验证的强度上限,不扩大探测范围;自动发现需开启主动探测,可能发送多次消耗额度的请求,结果两小时后过期。Go/付费模型及未验证强度不会被推算。
+405
View File
@@ -0,0 +1,405 @@
package gateway
import (
"context"
"encoding/xml"
"errors"
"fmt"
"io"
"net/http"
"strings"
"unicode"
"opencode2api/internal/config"
wire "opencode2api/internal/protocol"
)
const maxClientEnvironmentValueLength = 4096
type clientEnvironmentContextKey struct{}
// withClientEnvironment consumes the gateway-only extension before routing or
// protocol conversion. A request owns one complete snapshot: partial client
// data must not inherit unrelated fields from the deployment configuration.
func (g *Gateway) withClientEnvironment(r *http.Request, payload map[string]any, protocol wire.Protocol) (*http.Request, bool, error) {
var environment config.PromptEnvironmentConfig
raw, explicit := payload["client_environment"]
if explicit {
var err error
environment, err = decodeClientEnvironment(raw)
if err != nil {
return r, false, err
}
delete(payload, "client_environment")
} else if native, found := nativeClientEnvironment(payload, protocol); found {
environment = native
} else {
environment = copyPromptEnvironment(g.cfg.Upstream.PromptEnvironment)
}
ctx := context.WithValue(r.Context(), clientEnvironmentContextKey{}, environment)
return r.WithContext(ctx), explicit, nil
}
// requestEnvironment returns the immutable snapshot shared by this request's
// retries and routes. Internal callers without an ingress snapshot use only
// the explicit deployment configuration, never the gateway host environment.
func (g *Gateway) requestEnvironment(ctx context.Context) *config.PromptEnvironmentConfig {
if environment, ok := ctx.Value(clientEnvironmentContextKey{}).(config.PromptEnvironmentConfig); ok {
return &environment
}
environment := copyPromptEnvironment(g.cfg.Upstream.PromptEnvironment)
return &environment
}
func copyPromptEnvironment(environment *config.PromptEnvironmentConfig) config.PromptEnvironmentConfig {
if environment == nil {
return config.PromptEnvironmentConfig{}
}
copy := *environment
if environment.IsGitRepo != nil {
gitRepo := *environment.IsGitRepo
copy.IsGitRepo = &gitRepo
}
return copy
}
func decodeClientEnvironment(raw any) (config.PromptEnvironmentConfig, error) {
var environment config.PromptEnvironmentConfig
fields, ok := raw.(map[string]any)
if !ok {
return environment, errors.New("client_environment must be an object")
}
for name, value := range fields {
switch name {
case "working_directory", "workspace_root", "platform":
text, ok := value.(string)
if !ok {
return environment, fmt.Errorf("client_environment.%s must be a string", name)
}
switch name {
case "working_directory":
environment.WorkingDirectory = text
case "workspace_root":
environment.WorkspaceRoot = text
case "platform":
environment.Platform = text
}
case "is_git_repo":
gitRepo, ok := value.(bool)
if !ok {
return environment, errors.New("client_environment.is_git_repo must be a boolean")
}
environment.IsGitRepo = &gitRepo
default:
return environment, errors.New("client_environment contains an unsupported field")
}
}
err := normalizeClientEnvironment(&environment)
return environment, err
}
func normalizeClientEnvironment(environment *config.PromptEnvironmentConfig) error {
for name, value := range map[string]string{
"working_directory": environment.WorkingDirectory,
"workspace_root": environment.WorkspaceRoot,
"platform": environment.Platform,
} {
if len(value) > maxClientEnvironmentValueLength {
return fmt.Errorf("client_environment.%s must not exceed 4096 bytes", name)
}
for _, character := range value {
if unicode.IsControl(character) || character == '\u2028' || character == '\u2029' || character == '<' || character == '>' {
return fmt.Errorf("client_environment.%s must not contain control characters, line separators, or angle brackets", name)
}
}
}
if err := environment.Normalize(); err != nil {
return errors.New(strings.Replace(err.Error(), "upstream.prompt_environment.", "client_environment.", 1))
}
return nil
}
// nativeClientEnvironment reads declarations from instruction channels and
// standalone Codex environment updates. It never inspects assistant messages,
// tool results, or arbitrary prose for paths. Conflicting/malformed native
// declarations count as an unknown client snapshot, blocking config fallback.
func nativeClientEnvironment(payload map[string]any, protocol wire.Protocol) (config.PromptEnvironmentConfig, bool) {
var environment config.PromptEnvironmentConfig
found, valid := false, true
addInstructions := func(content any) {
for _, text := range clientEnvironmentTexts(content) {
candidate, present, wellFormed := parseEnvironmentBlocks(text)
if !present {
continue
}
found = true
if !wellFormed || !mergeClientEnvironment(&environment, candidate) {
valid = false
}
}
}
var latest config.PromptEnvironmentConfig
updated := false
addUser := func(content any) {
texts := clientEnvironmentTexts(content)
if blocks, ok := content.([]any); ok && len(blocks) != len(texts) {
return // Mixed images/tool results are not standalone declarations.
}
update, present, wellFormed := parseCodexEnvironment(strings.Join(texts, "\n"))
if present {
// A later explicit Codex update replaces the earlier environment,
// including fields it does not supply; no session state is retained.
latest, updated = config.PromptEnvironmentConfig{}, true
if wellFormed {
latest = update
}
}
}
field := "messages"
switch protocol {
case wire.Chat:
case wire.Anthropic:
addInstructions(payload["system"])
case wire.Responses:
addInstructions(payload["instructions"])
field = "input"
if input, ok := payload[field].(string); ok {
addUser(input)
}
default:
return environment, false
}
messages, _ := payload[field].([]any)
for _, raw := range messages {
message, ok := raw.(map[string]any)
if !ok {
continue
}
kind, _ := message["type"].(string)
if kind != "" && kind != "message" {
continue
}
switch message["role"] {
case "system", "developer":
addInstructions(message["content"])
case "user":
addUser(message["content"])
}
}
if updated {
return latest, true
}
if !valid {
return config.PromptEnvironmentConfig{}, true
}
return environment, found
}
// clientEnvironmentTexts deliberately excludes nested tool_result content in
// Anthropic user messages. Only direct text/input_text blocks are declarations.
func clientEnvironmentTexts(content any) []string {
if text, ok := content.(string); ok {
return []string{text}
}
blocks, _ := content.([]any)
var texts []string
for _, raw := range blocks {
block, ok := raw.(map[string]any)
if !ok || block["type"] != "text" && block["type"] != "input_text" {
continue
}
if text, ok := block["text"].(string); ok {
texts = append(texts, text)
}
}
return texts
}
func parseEnvironmentBlocks(text string) (config.PromptEnvironmentConfig, bool, bool) {
var environment config.PromptEnvironmentConfig
found, inside, valid := false, false, true
var fence byte
fenceLength := 0
for line := range strings.Lines(text) {
line = strings.TrimSpace(line)
// Literal examples in Markdown are not client declarations.
if !inside && len(line) >= 3 && (line[0] == '`' || line[0] == '~') {
length := 1
for length < len(line) && line[length] == line[0] {
length++
}
if fence == 0 && length >= 3 {
fence, fenceLength = line[0], length
continue
}
if line[0] == fence && length >= fenceLength && strings.TrimSpace(line[length:]) == "" {
fence = 0
continue
}
}
if fence != 0 {
continue
}
switch line {
case "<env>":
if inside {
valid = false
}
found, inside = true, true
case "</env>":
if !inside {
valid = false
}
found, inside = true, false
default:
if !inside {
continue
}
label, value, ok := strings.Cut(line, ":")
if !ok {
continue
}
var field string
switch label {
case "Working directory":
field = "working_directory"
case "Workspace root folder":
field = "workspace_root"
case "Is directory a git repo":
field = "is_git_repo"
case "Platform":
field = "platform"
default:
continue
}
if !addNativeEnvironmentValue(&environment, field, strings.TrimSpace(value)) {
valid = false
}
}
}
return environment, found, valid && !inside
}
func parseCodexEnvironment(text string) (config.PromptEnvironmentConfig, bool, bool) {
var environment config.PromptEnvironmentConfig
text = strings.TrimSpace(text)
if !strings.HasPrefix(text, "<environment_context>") {
return environment, false, true
}
if !strings.HasSuffix(text, "</environment_context>") {
return environment, true, false
}
decoder := xml.NewDecoder(strings.NewReader(text))
if _, err := decoder.Token(); err != nil { // The exact opening tag was checked above.
return environment, true, false
}
for {
token, err := decoder.Token()
if err != nil {
return environment, true, false
}
switch item := token.(type) {
case xml.StartElement:
field := item.Name.Local
if field == "cwd" {
field = "working_directory"
}
if item.Name.Space != "" || field != "working_directory" && field != "workspace_root" && field != "platform" && field != "is_git_repo" {
if err := decoder.Skip(); err != nil {
return environment, true, false
}
continue
}
if len(item.Attr) != 0 {
return environment, true, false
}
var value strings.Builder
for {
part, err := decoder.Token()
if err != nil {
return environment, true, false
}
if _, ended := part.(xml.EndElement); ended {
break
}
characters, ok := part.(xml.CharData)
if !ok || value.Len()+len(characters) > maxClientEnvironmentValueLength {
return environment, true, false
}
value.Write(characters)
}
if !addNativeEnvironmentValue(&environment, field, value.String()) {
return environment, true, false
}
case xml.EndElement:
_, err := decoder.Token()
return environment, true, err == io.EOF
case xml.CharData:
if strings.TrimSpace(string(item)) != "" {
return environment, true, false
}
default:
return environment, true, false
}
}
}
func addNativeEnvironmentValue(environment *config.PromptEnvironmentConfig, field, value string) bool {
if len(value) > maxClientEnvironmentValueLength {
return false
}
for _, character := range value {
if unicode.IsControl(character) || character == '\u2028' || character == '\u2029' || character == '<' || character == '>' {
return false
}
}
value = strings.TrimSpace(value)
if value == "" || strings.EqualFold(value, "unknown") {
return true
}
var candidate config.PromptEnvironmentConfig
switch field {
case "working_directory":
candidate.WorkingDirectory = value
case "workspace_root":
candidate.WorkspaceRoot = value
case "platform":
candidate.Platform = value
case "is_git_repo":
var gitRepo bool
switch strings.ToLower(value) {
case "yes", "true":
gitRepo = true
case "no", "false":
default:
return false
}
candidate.IsGitRepo = &gitRepo
}
return normalizeClientEnvironment(&candidate) == nil && mergeClientEnvironment(environment, candidate)
}
// mergeClientEnvironment combines consistent native declarations, not config
// defaults. Different known values make the complete snapshot ambiguous.
func mergeClientEnvironment(environment *config.PromptEnvironmentConfig, candidate config.PromptEnvironmentConfig) bool {
for _, pair := range [][2]*string{
{&environment.WorkingDirectory, &candidate.WorkingDirectory},
{&environment.WorkspaceRoot, &candidate.WorkspaceRoot},
{&environment.Platform, &candidate.Platform},
} {
if *pair[0] != "" && *pair[1] != "" && *pair[0] != *pair[1] {
return false
}
if *pair[1] != "" {
*pair[0] = *pair[1]
}
}
if candidate.IsGitRepo != nil {
if environment.IsGitRepo != nil && *environment.IsGitRepo != *candidate.IsGitRepo {
return false
}
gitRepo := *candidate.IsGitRepo
environment.IsGitRepo = &gitRepo
}
return true
}
+27
View File
@@ -281,6 +281,12 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc {
wire.WriteError(w, external, http.StatusBadRequest, "request body must be a JSON object", "invalid_request_error", "")
return
}
var strippedEnvironment bool
r, strippedEnvironment, err = g.withClientEnvironment(r, payload, external)
if err != nil {
wire.WriteError(w, external, http.StatusBadRequest, err.Error(), "invalid_request_error", "client_environment")
return
}
model := jsonutil.StringAt(payload, "model")
meta := telemetry.MetaFromRequest(r)
if meta != nil {
@@ -346,6 +352,14 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc {
wire.WriteError(w, external, http.StatusBadRequest, "this model uses System One decisions, not chat; send state and typed questions to /v1/systemone", "invalid_request_error", "model")
return
}
if strippedEnvironment {
// This path forwards raw bytes rather than converting payload.
body, err = jsonutil.Marshal(payload)
if err != nil {
wire.WriteError(w, external, http.StatusBadRequest, "request body could not be encoded", "invalid_request_error", "")
return
}
}
g.forwardSystemOne(w, r, body, payload, model, route)
return
}
@@ -565,6 +579,19 @@ func (g *Gateway) handleSystemOne(w http.ResponseWriter, r *http.Request) {
wire.WriteError(w, wire.SystemOne, http.StatusBadRequest, "request body must be a JSON object", "invalid_request_error", "")
return
}
var strippedEnvironment bool
r, strippedEnvironment, err = g.withClientEnvironment(r, payload, wire.SystemOne)
if err != nil {
wire.WriteError(w, wire.SystemOne, http.StatusBadRequest, err.Error(), "invalid_request_error", "client_environment")
return
}
if strippedEnvironment {
body, err = jsonutil.Marshal(payload)
if err != nil {
wire.WriteError(w, wire.SystemOne, http.StatusBadRequest, "request body could not be encoded", "invalid_request_error", "")
return
}
}
model := jsonutil.StringAt(payload, "model")
if meta := telemetry.MetaFromRequest(r); meta != nil {
meta.Model = model
+7 -30
View File
@@ -2,11 +2,7 @@ package gateway
import (
_ "embed"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"opencode2api/internal/config"
@@ -41,40 +37,18 @@ Use the skill tool to load a skill when a task matches its description.
</skill>
</available_skills>`
var (
opencodeEnvOnce sync.Once
opencodeWorkDir string
)
// opencodeEnvironment renders the <env> block the CLI puts after its base
// prompt. Configured values replace the host defaults without changing the
// field names or order; the host directory is resolved once per process.
// prompt. Only values supplied for this request describe the client; missing
// facts remain unknown without inspecting or describing the gateway's host.
func opencodeEnvironment(model string, environment *config.PromptEnvironmentConfig) string {
opencodeEnvOnce.Do(func() {
directory := ""
if current, err := os.Getwd(); err == nil {
directory = filepath.Clean(strings.TrimSpace(current))
}
if directory == "" || directory == "." {
directory = "/workspace"
}
opencodeWorkDir = directory
})
apiModel := strings.TrimSpace(strings.TrimPrefix(model, "opencode/"))
if apiModel == "" {
apiModel = "unknown"
}
platform := runtime.GOOS
if platform == "windows" {
platform = "win32"
}
directory := opencodeWorkDir
workspace := directory
gitRepo := "yes"
directory, workspace, platform, gitRepo := "unknown", "unknown", "unknown", "unknown"
if environment != nil {
if environment.WorkingDirectory != "" {
directory = environment.WorkingDirectory
workspace = directory
}
if environment.WorkspaceRoot != "" {
workspace = environment.WorkspaceRoot
@@ -82,8 +56,11 @@ func opencodeEnvironment(model string, environment *config.PromptEnvironmentConf
if environment.Platform != "" {
platform = environment.Platform
}
if environment.IsGitRepo != nil && !*environment.IsGitRepo {
if environment.IsGitRepo != nil {
gitRepo = "no"
if *environment.IsGitRepo {
gitRepo = "yes"
}
}
}
return strings.Join([]string{
+1 -1
View File
@@ -239,7 +239,7 @@ func (g *Gateway) rotationAttempt(parent context.Context, w http.ResponseWriter,
resp, err = g.oauthAttempt(ctx, route, bodies[config.TierGo], ids, attempt, attempt-1, 0)
} else {
var body []byte
body, toolRenames, shaped = g.shapeKeyBody(bodies[config.TierGo], route, config.TierGo)
body, toolRenames, shaped = g.shapeKeyBody(ctx, bodies[config.TierGo], route, config.TierGo)
setRequestShape(parent, shaped, toolRenames)
cursor := g.goNodes.CursorFor(ids.Session)
var node *upstreamNode
+10 -17
View File
@@ -3,7 +3,6 @@ package gateway
import (
_ "embed"
"encoding/json"
"runtime"
"strings"
"sync"
@@ -188,41 +187,35 @@ func officialToolset(protocol wire.Protocol, v1 bool, platform string) []any {
return tools
}
// v2ShellDescription renders the configured platform's shell description,
// retaining the host-based behavior when no platform override is supplied.
// v2ShellDescription renders the client's supplied platform without inferring
// its environment from the gateway host when the platform is unknown.
func v2ShellDescription(base, platform string) string {
if platform == "" {
platform = runtime.GOOS
if platform != "windows" {
return base
}
}
switch platform {
case "win32", "windows":
return strings.Replace(base, "on Linux using bash", "on Windows using powershell", 1)
case "darwin":
return strings.Replace(base, "on Linux using bash", "on macOS using bash", 1)
default:
case "linux":
return base
default:
return strings.Replace(base, "on Linux using bash", "in the client's shell environment", 1)
}
}
// v1BashDescription applies the same platform rewrite to the 1.x bash
// definition, which states its OS and shell inline.
func v1BashDescription(base, platform string) string {
if platform == "" {
platform = runtime.GOOS
if platform != "windows" {
return base
}
}
switch platform {
case "win32", "windows":
base = strings.Replace(base, "Executes a given bash command", "Executes a given shell command", 1)
return strings.Replace(base, "OS: linux, Shell: bash", "OS: windows, Shell: powershell", 1)
case "darwin":
return strings.Replace(base, "OS: linux, Shell: bash", "OS: darwin, Shell: bash", 1)
default:
case "linux":
return base
default:
base = strings.Replace(base, "Executes a given bash command", "Executes a given shell command", 1)
return strings.Replace(base, "OS: linux, Shell: bash", "OS: unknown, Shell: unknown", 1)
}
}
+5 -5
View File
@@ -507,7 +507,7 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
preparedBodies := make([][]byte, len(upstreams))
toolRenames := make([]*wire.ToolRenames, len(upstreams))
for i, baseURL := range upstreams {
preparedBodies[i], toolRenames[i] = prepareAnonymousBody(rawBody, protocol, models.IsV1Upstream(baseURL), g.cfg.Upstream.PromptEnvironment)
preparedBodies[i], toolRenames[i] = prepareAnonymousBody(rawBody, protocol, models.IsV1Upstream(baseURL), g.requestEnvironment(ctx))
}
for proxies < limit {
if ctx.Err() != nil {
@@ -915,7 +915,7 @@ func (g *Gateway) dumpOutboundBodies(route models.Route, bodies map[config.Tier]
// shaped body, the tool renames to restore in the response, and whether the
// body changed so the gateway can collapse the SSE stream a non-streaming
// client receives back.
func (g *Gateway) shapeKeyBody(body []byte, route models.Route, tier config.Tier) ([]byte, *wire.ToolRenames, bool) {
func (g *Gateway) shapeKeyBody(ctx context.Context, body []byte, route models.Route, tier config.Tier) ([]byte, *wire.ToolRenames, bool) {
if !g.catalog.IsFreeModel(route.ID) {
return body, nil, false
}
@@ -923,7 +923,7 @@ func (g *Gateway) shapeKeyBody(body []byte, route models.Route, tier config.Tier
if tier == config.TierGo {
baseURL = g.cfg.Upstream.Go
}
shaped, renames := prepareAnonymousBody(body, route.ProtocolFor(tier), models.IsV1Upstream(baseURL), g.cfg.Upstream.PromptEnvironment)
shaped, renames := prepareAnonymousBody(body, route.ProtocolFor(tier), models.IsV1Upstream(baseURL), g.requestEnvironment(ctx))
return shaped, renames, !bytes.Equal(shaped, body)
}
@@ -955,7 +955,7 @@ func (g *Gateway) doSelectedKeyUpstream(ctx context.Context, route models.Route,
if len(body) == 0 {
return nil, fmt.Errorf("no prepared %s request body", override.Tier), 0
}
shaped, toolRenames, changed := g.shapeKeyBody(body, route, override.Tier)
shaped, toolRenames, changed := g.shapeKeyBody(ctx, body, route, override.Tier)
if changed {
body = shaped
}
@@ -1047,7 +1047,7 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies
if len(body) == 0 {
return nil, fmt.Errorf("no prepared %s request body", route.Tier), 0
}
shaped, toolRenames, changed := g.shapeKeyBody(body, route, route.Tier)
shaped, toolRenames, changed := g.shapeKeyBody(ctx, body, route, route.Tier)
if changed {
body = shaped
}
+1 -1
View File
@@ -241,7 +241,7 @@ func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Rout
prepared := make([][]byte, len(upstreams))
renames := make([]*wire.ToolRenames, len(upstreams))
for index, baseURL := range upstreams {
prepared[index], renames[index] = prepareAnonymousBody(rawBody, protocol, models.IsV1Upstream(baseURL), g.cfg.Upstream.PromptEnvironment)
prepared[index], renames[index] = prepareAnonymousBody(rawBody, protocol, models.IsV1Upstream(baseURL), g.requestEnvironment(ctx))
}
// A 429 is scoped to the exit that carried it, so the request keeps
// rotating exits until the configured attempt budget is spent; only then