mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 08:02:53 +00:00
fix: align the v2 free-tier shape with OpenCode 2.0.32
- Use the genuine patchText description and keep the Linux/bash shell sentence. - Preserve the client's child session id separately from the affinity. - Scope the anonymous parent session id like every other derived identity. - Append beta=true only on v2 Anthropic lanes and parse the query safely. - Remove the redundant v1 project renderer and duplicate anthropic-version. - Revert the formatting-only churn in opencode_tools.json and update lane docs.
This commit is contained in:
1 parent
8899749008
commit
f0f064f31d
11 files changed
+111
-129
No files matched your search
@@ -262,7 +262,7 @@ See [config.example.json](config.example.json) for a complete starting configura
|
||||
| `prefer` | `go`; accepts `go` or `zen`. |
|
||||
| `upstream.zen` | `https://opencode.ai/zen`. |
|
||||
| `upstream.go` | `https://opencode.ai/zen/go`. |
|
||||
| `upstream.anonymous` | `https://opencode.ai/inference`; the anonymous lane's fallback after `/zen`. |
|
||||
| `upstream.anonymous` | `https://opencode.ai/inference`; tried first by the anonymous lane, which falls back to `/zen`. |
|
||||
| `proxies` | Falls back to `["direct"]` when both proxy sources are empty. |
|
||||
| `proxyfile` | Optional; relative paths resolve beside the configuration file. |
|
||||
| `models.refresh_seconds` | `300`; minimum 1. |
|
||||
|
||||
+1
-1
@@ -266,7 +266,7 @@ Xem [config.example.json](config.example.json) để có một cấu hình khở
|
||||
| `prefer` | `go`; nhận `go` hoặc `zen`. |
|
||||
| `upstream.zen` | `https://opencode.ai/zen`. |
|
||||
| `upstream.go` | `https://opencode.ai/zen/go`. |
|
||||
| `upstream.anonymous` | `https://opencode.ai/inference`; upstream dự phòng của kênh ẩn danh sau `/zen`. |
|
||||
| `upstream.anonymous` | `https://opencode.ai/inference`; kênh ẩn danh thử trước, dự phòng về `/zen`. |
|
||||
| `proxies` | Rơi về `["direct"]` khi cả hai nguồn proxy đều rỗng. |
|
||||
| `proxyfile` | Không bắt buộc; đường dẫn tương đối được phân giải cạnh file cấu hình. |
|
||||
| `models.refresh_seconds` | `300`; tối thiểu 1. |
|
||||
|
||||
+1
-1
@@ -262,7 +262,7 @@ Key 初始化时均衡分配到代理。真实流量可以触发代理检查、K
|
||||
| `prefer` | `go`;可选 `go`、`zen`。 |
|
||||
| `upstream.zen` | `https://opencode.ai/zen`。 |
|
||||
| `upstream.go` | `https://opencode.ai/zen/go`。 |
|
||||
| `upstream.anonymous` | `https://opencode.ai/inference`;匿名通道在 `/zen` 之后的回退上游。 |
|
||||
| `upstream.anonymous` | `https://opencode.ai/inference`;匿名通道优先使用,失败后回退到 `/zen`。 |
|
||||
| `proxies` | 两个代理来源都为空时,使用 `["direct"]`。 |
|
||||
| `proxyfile` | 可选;相对路径基于配置文件所在目录解析。 |
|
||||
| `models.refresh_seconds` | `300`;最小为 1。 |
|
||||
|
||||
@@ -75,9 +75,9 @@ type UpstreamConfig struct {
|
||||
// CLI shape. The WebUI also reads the plan's quota from its /v1/usage.
|
||||
Go string `json:"go"`
|
||||
// Anonymous is the v2 /inference origin of the keyless free tier. The
|
||||
// anonymous lane tries the v1 /zen origin (models.V1Base, not Zen) first
|
||||
// and falls back to this one, which is skipped when it equals the v1
|
||||
// origin. Empty means https://opencode.ai/inference.
|
||||
// anonymous lane tries this origin first and falls back to the v1 /zen
|
||||
// origin (models.V1Base, not Zen), which is the only upstream used when
|
||||
// this one equals the v1 origin. Empty means https://opencode.ai/inference.
|
||||
Anonymous string `json:"anonymous"`
|
||||
}
|
||||
|
||||
|
||||
@@ -8,8 +8,8 @@
|
||||
// 1.x User-Agent, the x-opencode-request header, a git-commit-shaped project
|
||||
// and, on the free tier, the single "read" tool. The v2 lane is the /inference
|
||||
// origin (upstream.anonymous) and the Go plan's /zen/go origin, which expect
|
||||
// the OpenCode 2.x CLI shape. The anonymous free tier tries the v1 origin
|
||||
// first and falls back to the configured v2 /inference origin.
|
||||
// the OpenCode 2.x CLI shape. The anonymous free tier tries the configured v2
|
||||
// /inference origin first and falls back to the v1 origin.
|
||||
package gateway
|
||||
|
||||
import (
|
||||
|
||||
@@ -21,11 +21,7 @@
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"path",
|
||||
"oldString",
|
||||
"newString"
|
||||
],
|
||||
"required": ["path", "oldString", "newString"],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
@@ -38,9 +34,7 @@
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"code"
|
||||
],
|
||||
"required": ["code"],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
@@ -67,9 +61,7 @@
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"pattern"
|
||||
],
|
||||
"required": ["pattern"],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
@@ -105,9 +97,7 @@
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"pattern"
|
||||
],
|
||||
"required": ["pattern"],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
@@ -142,10 +132,7 @@
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"label",
|
||||
"description"
|
||||
],
|
||||
"required": ["label", "description"],
|
||||
"type": "object"
|
||||
},
|
||||
"type": "array"
|
||||
@@ -155,20 +142,14 @@
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"question",
|
||||
"header",
|
||||
"options"
|
||||
],
|
||||
"required": ["question", "header", "options"],
|
||||
"type": "object"
|
||||
},
|
||||
"minItems": 1,
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"questions"
|
||||
],
|
||||
"required": ["questions"],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
@@ -192,14 +173,12 @@
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"path"
|
||||
],
|
||||
"required": ["path"],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"shell": {
|
||||
"description": "Execute a shell command and return its output. Quote file paths containing spaces or special characters. Prefer dedicated tools over shell commands when possible. When output is large, the full result is saved to a file and a truncated preview is returned. Rely on automatic truncation unless filtering the output is more useful. Commands accept an optional timeout, background commands have no timeout by default. Background commands return immediately, and you will be notified when they complete.",
|
||||
"description": "Execute a shell command and return its output. Commands run on Linux using bash. Quote file paths containing spaces or special characters. Prefer dedicated tools over shell commands when possible. When output is large, the full result is saved to a file and a truncated preview is returned. Rely on automatic truncation unless filtering the output is more useful. Commands accept an optional timeout, background commands have no timeout by default. Background commands return immediately, and you will be notified when they complete.",
|
||||
"parameters": {
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
@@ -221,9 +200,7 @@
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"command"
|
||||
],
|
||||
"required": ["command"],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
@@ -237,9 +214,7 @@
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id"
|
||||
],
|
||||
"required": ["id"],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
@@ -274,11 +249,7 @@
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"agent",
|
||||
"description",
|
||||
"prompt"
|
||||
],
|
||||
"required": ["agent", "description", "prompt"],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
@@ -289,11 +260,7 @@
|
||||
"properties": {
|
||||
"format": {
|
||||
"description": "The format to return the content in. Defaults to markdown.",
|
||||
"enum": [
|
||||
"text",
|
||||
"markdown",
|
||||
"html"
|
||||
],
|
||||
"enum": ["text", "markdown", "html"],
|
||||
"type": "string"
|
||||
},
|
||||
"timeout": {
|
||||
@@ -307,9 +274,7 @@
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"url"
|
||||
],
|
||||
"required": ["url"],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
@@ -323,9 +288,7 @@
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"query"
|
||||
],
|
||||
"required": ["query"],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
@@ -343,27 +306,22 @@
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"path",
|
||||
"content"
|
||||
],
|
||||
"required": ["path", "content"],
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"patch": {
|
||||
"description": "Use the `patch` tool to edit files. Your patch language is a stripped‑down, file‑oriented diff format designed to be easy to parse and safe to apply. You can think of it as a high‑level envelope:\n\n*** Begin Patch\n[ one or more file sections ]\n*** End Patch\n\nWithin that envelope, you get a sequence of file operations.\nYou MUST include a header to specify the action you are taking.\nEach operation starts with one of three headers:\n\n*** Add File: <path> - create a new file. Every following line is a + line (the initial contents).\n*** Delete File: <path> - remove an existing file. Nothing follows.\n*** Update File: <path> - patch an existing file in place (optionally with a rename).\n\nExample patch:\n\n```\n*** Begin Patch\n*** Add File: hello.txt\n+Hello world\n*** Update File: src/app.py\n*** Move to: src/main.py\n@@ def greet():\n-print(\"Hi\")\n+print(\"Hello, world!\")\n*** Delete File: obsolete.txt\n*** End Patch\n```\n\nIt is important to remember:\n\n- You must include a header with your intended action (Add/Delete/Update)\n- You must prefix new lines with `+` even when creating a new file",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"patchText": {
|
||||
"type": "string",
|
||||
"description": "The full patch text describing add, update, and delete operations to perform."
|
||||
"description": "The full patch text describing add, update, and delete operations",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"patchText"
|
||||
],
|
||||
"additionalProperties": false
|
||||
"required": ["patchText"],
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -105,8 +105,8 @@ func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult
|
||||
if g.cfg.Anonymous {
|
||||
cursor := g.anonymous.CursorFor(ids.Session)
|
||||
if node := cursor.Next(); node != nil {
|
||||
// Prefer the v1 lane (/zen) before falling back to the v2
|
||||
// /inference origin.
|
||||
// Try the anonymous upstreams in preference order: the v2
|
||||
// /inference origin before the v1 fallback.
|
||||
for _, baseURL := range g.anonymousUpstreams() {
|
||||
lanes = append(lanes, lane{anonymousZenKey, "anonymous", baseURL, g.inferenceClient(node.proxy, baseURL, model)})
|
||||
}
|
||||
|
||||
@@ -265,8 +265,8 @@ func (g *Gateway) refreshAnonymousTier(ctx context.Context, base string) []strin
|
||||
var models []string
|
||||
var status int
|
||||
var err error
|
||||
// List models on the v1 origin first, then fall back to the
|
||||
// configured v2 /inference origin (see anonymousUpstreams).
|
||||
// List models on the configured v2 /inference origin first, then fall
|
||||
// back to the v1 origin (see anonymousUpstreams).
|
||||
for _, upstream := range g.anonymousUpstreams() {
|
||||
models, status, err = modelcatalog.FetchModels(refreshCtx, node.proxy.client, upstream, anonymousZenKey)
|
||||
if err == nil || isProxyFailure(err) {
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"slices"
|
||||
"sort"
|
||||
@@ -293,14 +294,14 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodie
|
||||
// doAnonymousUpstream walks the session's anonymous proxy cursor. Each static
|
||||
// proxy is tried at most once; rotating #pool proxies may be drawn again until
|
||||
// Retry.MaxAttempts proxies were used. For each proxy it tries the upstreams in
|
||||
// anonymousUpstreams order: the v1 lane (models.V1Base) before the v2
|
||||
// /inference upstream (Upstream.Anonymous). Any failure, including an HTTP
|
||||
// error response, advances to the next upstream or proxy; a proxy-route
|
||||
// failure, or a proxy marked unhealthy, skips that proxy's remaining
|
||||
// upstreams. Only a successful response ends the anonymous phase; exhausting
|
||||
// the proxy cursor returns control to the preferred authenticated tiers. It
|
||||
// returns the last response (body still open), else the last error, plus the
|
||||
// number of attempts made.
|
||||
// anonymousUpstreams order: the configured v2 /inference upstream
|
||||
// (Upstream.Anonymous) before the v1 lane (models.V1Base). Any failure,
|
||||
// including an HTTP error response, advances to the next upstream or proxy; a
|
||||
// proxy-route failure, or a proxy marked unhealthy, skips that proxy's
|
||||
// remaining upstreams. Only a successful response ends the anonymous phase;
|
||||
// exhausting the proxy cursor returns control to the preferred authenticated
|
||||
// tiers. It returns the last response (body still open), else the last error,
|
||||
// plus the number of attempts made.
|
||||
func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (*http.Response, error, int) {
|
||||
var lastResponse *http.Response
|
||||
var lastErr error
|
||||
@@ -421,10 +422,9 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
|
||||
}
|
||||
|
||||
// anonymousUpstreams returns the ordered base URLs for the keyless free tier:
|
||||
// the v1 origin (models.V1Base) is tried first, and the configured v2
|
||||
// /inference origin (Upstream.Anonymous) is kept as a fallback. Only the v1
|
||||
// origin is returned when Upstream.Anonymous is empty or names that same
|
||||
// origin.
|
||||
// the configured v2 /inference origin (Upstream.Anonymous) is tried first, and
|
||||
// the v1 origin (models.V1Base) is kept as a fallback. Only the v1 origin is
|
||||
// returned when Upstream.Anonymous is empty or names that same origin.
|
||||
func (g *Gateway) anonymousUpstreams() []string {
|
||||
v1 := strings.TrimRight(models.V1Base, "/")
|
||||
primary := strings.TrimRight(g.cfg.Upstream.Anonymous, "/")
|
||||
@@ -1223,13 +1223,15 @@ func (g *Gateway) recordUpstreamAttempt(ctx context.Context, route models.Route,
|
||||
|
||||
// upstreamRequest builds the POST for one attempt: baseURL plus the protocol's
|
||||
// /v1/... route, carrying body. The header set follows the lane: setV1Headers
|
||||
// when models.IsV1Upstream(baseURL), setV2Headers otherwise. key is sent as
|
||||
// x-api-key (with anthropic-version) on the Anthropic protocol and as a Bearer
|
||||
// token on every other one; the anonymous lane passes anonymousZenKey.
|
||||
// when models.IsV1Upstream(baseURL), setV2Headers otherwise. Anthropic
|
||||
// endpoints on a v2 lane gain beta=true, matching the 2.x client; the 1.x lane
|
||||
// keeps its shape. key is sent as x-api-key (with anthropic-version) on the
|
||||
// Anthropic protocol and as a Bearer token on every other one; the anonymous
|
||||
// lane passes anonymousZenKey.
|
||||
func upstreamRequest(ctx context.Context, baseURL string, protocol wire.Protocol, body []byte, ids identity.RequestIDs, key string) (*http.Request, error) {
|
||||
endpoint := strings.TrimRight(baseURL, "/") + wire.Path(protocol)
|
||||
if protocol == wire.Anthropic && !strings.Contains(endpoint, "beta=true") {
|
||||
endpoint += "?beta=true"
|
||||
if protocol == wire.Anthropic && !models.IsV1Upstream(baseURL) {
|
||||
endpoint = withAnthropicBeta(endpoint)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
@@ -1253,6 +1255,22 @@ func upstreamRequest(ctx context.Context, baseURL string, protocol wire.Protocol
|
||||
return req, nil
|
||||
}
|
||||
|
||||
// withAnthropicBeta marks an Anthropic endpoint as beta the way the OpenCode
|
||||
// 2.x client does, preserving any query a configured base URL already carries.
|
||||
func withAnthropicBeta(endpoint string) string {
|
||||
parsed, err := url.Parse(endpoint)
|
||||
if err != nil {
|
||||
return endpoint
|
||||
}
|
||||
query := parsed.Query()
|
||||
if query.Get("beta") == "true" {
|
||||
return endpoint
|
||||
}
|
||||
query.Set("beta", "true")
|
||||
parsed.RawQuery = query.Encode()
|
||||
return parsed.String()
|
||||
}
|
||||
|
||||
// setV1Headers renders the v1 lane's header set, that of an OpenCode 1.19.3
|
||||
// model request on its opencode provider, as captured from the official
|
||||
// release: the AI SDK User-Agent of the package serving the protocol, both
|
||||
@@ -1272,7 +1290,7 @@ func setV1Headers(header http.Header, protocol wire.Protocol, body []byte, ids i
|
||||
message = identity.AscendingID("msg", time.Now())
|
||||
}
|
||||
header.Set("x-opencode-request", message)
|
||||
header.Set("x-opencode-project", v1ProjectID(ids.Project))
|
||||
header.Set("x-opencode-project", projectID(ids.Project))
|
||||
if ids.ParentSession != "" {
|
||||
parent := identity.CanonicalSessionID(ids.ParentSession)
|
||||
header.Set("x-opencode-parent-session-id", parent)
|
||||
@@ -1286,12 +1304,14 @@ func setV1Headers(header http.Header, protocol wire.Protocol, body []byte, ids i
|
||||
}
|
||||
|
||||
// setV2Headers renders the OpenCode 2.x CLI header set the v2 gates
|
||||
// fingerprint: the "opencode/<channel>/<version>/cli" User-Agent, every
|
||||
// session header (x-opencode-session, x-opencode-session-id,
|
||||
// x-session-affinity, X-Session-Id) set to the same descending-encoded id,
|
||||
// and a bare 40-character hex x-opencode-project. The v2 gate rejects
|
||||
// x-opencode-request and canonical prj_* project ids with 403 FreeTierError,
|
||||
// so neither is sent. Anthropic requests carry a fixed anthropic-beta set.
|
||||
// fingerprint: the "opencode/<channel>/<version>/cli" User-Agent, the
|
||||
// client's child session as x-opencode-session-id, the conversation affinity
|
||||
// (the canonical parent when one is present) as x-opencode-session,
|
||||
// x-session-affinity and X-Session-Id, and a bare 40-character hex
|
||||
// x-opencode-project. The v2 gate rejects x-opencode-request and canonical
|
||||
// prj_* project ids with 403 FreeTierError, so neither is sent. Anthropic
|
||||
// requests carry a fixed anthropic-beta set; upstreamRequest adds
|
||||
// anthropic-version and the beta query.
|
||||
func setV2Headers(header http.Header, protocol wire.Protocol, ids identity.RequestIDs) {
|
||||
header.Set("Accept", "application/json, text/event-stream")
|
||||
header.Set("x-opencode-client", "cli")
|
||||
@@ -1302,14 +1322,17 @@ func setV2Headers(header http.Header, protocol wire.Protocol, ids identity.Reque
|
||||
header.Set("x-opencode-parent-session-id", parent)
|
||||
header.Set("x-parent-session-id", parent)
|
||||
}
|
||||
childSession := ids.ChildSession
|
||||
if childSession == "" {
|
||||
childSession = ids.Session
|
||||
}
|
||||
header.Set("x-session-affinity", rootSession)
|
||||
header.Set("X-Session-Id", rootSession)
|
||||
header.Set("x-opencode-session", rootSession)
|
||||
header.Set("x-opencode-session-id", ids.Session)
|
||||
header.Set("x-opencode-session-id", childSession)
|
||||
header.Set("User-Agent", httpx.V2UserAgent())
|
||||
header.Set("x-opencode-project", v2ProjectID(ids.Project))
|
||||
header.Set("x-opencode-project", projectID(ids.Project))
|
||||
if protocol == wire.Anthropic {
|
||||
header.Set("anthropic-version", "2023-06-01")
|
||||
header.Set("anthropic-beta", "interleaved-thinking-2025-05-14")
|
||||
}
|
||||
}
|
||||
@@ -1328,21 +1351,10 @@ func v1ProviderUtils(protocol wire.Protocol) string {
|
||||
}
|
||||
}
|
||||
|
||||
// gitCommitPattern matches the git root commit hash OpenCode 1.x uses as its
|
||||
// project id.
|
||||
// gitCommitPattern matches the git root commit hash OpenCode uses as its
|
||||
// project id on both lanes.
|
||||
var gitCommitPattern = regexp.MustCompile(`^[0-9a-f]{40}$`)
|
||||
|
||||
// v1ProjectID renders the project header the way the OpenCode 1.x client
|
||||
// does: the git root commit hash of the project, or "global" outside a git
|
||||
// repository. A genuine value from a v1 client is kept verbatim; any other
|
||||
// project is hashed into the commit shape (see v2ProjectID).
|
||||
func v1ProjectID(project string) string {
|
||||
if project == "global" || gitCommitPattern.MatchString(project) {
|
||||
return project
|
||||
}
|
||||
return v2ProjectID(project)
|
||||
}
|
||||
|
||||
// v1AnthropicBetaRequest holds the Messages body fields the AI SDK
|
||||
// anthropic provider derives beta flags from. Fields whose JSON type varies
|
||||
// stay raw so one unexpected value cannot hide the others.
|
||||
@@ -1485,13 +1497,13 @@ func anthropicSupportsStructuredOutput(model string) bool {
|
||||
return strings.Contains(model, "claude-")
|
||||
}
|
||||
|
||||
// v2ProjectID renders the project header in the shape the OpenCode 2.x CLI
|
||||
// sends to the v2 gates: a bare 40-character lowercase hex id, here the first
|
||||
// 20 bytes of a domain-separated SHA-256 of the project. The value itself is
|
||||
// not checked upstream, only its shape, but hashing keeps one project mapped
|
||||
// to one stable upstream project id. v1ProjectID reuses it to fit a
|
||||
// non-genuine project into the git commit shape.
|
||||
func v2ProjectID(project string) string {
|
||||
// projectID renders the project header in the shape both lanes use: the
|
||||
// genuine git root commit hash or "global" is kept verbatim, and any other
|
||||
// project is hashed into the same 40-character lowercase hex shape. The value
|
||||
// itself is not checked upstream, only its shape, but hashing keeps one
|
||||
// project mapped to one stable upstream project id and masks a caller's
|
||||
// prj_*-style project, which the v2 gate rejects.
|
||||
func projectID(project string) string {
|
||||
if project == "global" || gitCommitPattern.MatchString(project) {
|
||||
return project
|
||||
}
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
// carry the v1 lane's x-opencode-request header. The identity that matters
|
||||
// upstream is therefore the pair (x-opencode-session, x-opencode-session-id):
|
||||
// Session is the conversation-affinity key and must keep the descending layout
|
||||
// minted by CanonicalSessionID.
|
||||
// minted by CanonicalSessionID; ChildSession preserves the client's own
|
||||
// x-opencode-session-id when it differs, as it does for a subagent.
|
||||
package identity
|
||||
|
||||
import (
|
||||
@@ -22,13 +23,16 @@ import (
|
||||
)
|
||||
|
||||
// RequestIDs carries the identity headers the upstream free tier inspects.
|
||||
// Session is sent as both x-opencode-session and x-opencode-session-id.
|
||||
// Message is the user message id the v1 lane receives as x-opencode-request;
|
||||
// the v2 lane rejects that header. Request only identifies the request inside
|
||||
// the gateway. Project is rendered per lane by the gateway (prj_* on the v1
|
||||
// lane, bare 40-hex on the v2 lane).
|
||||
// Session is the conversation-affinity key sent as x-opencode-session; the
|
||||
// v2 lane sends ChildSession, the client's own x-opencode-session-id, as
|
||||
// x-opencode-session-id so a subagent keeps its child id while affinity stays
|
||||
// on the parent. The v1 lane sends Session as both headers. Message is the
|
||||
// user message id the v1 lane receives as x-opencode-request; the v2 lane
|
||||
// rejects that header. Request only identifies the request inside the
|
||||
// gateway. Project is rendered per lane by the gateway.
|
||||
type RequestIDs struct {
|
||||
Session string
|
||||
ChildSession string
|
||||
Request string
|
||||
Message string
|
||||
Project string
|
||||
@@ -68,6 +72,10 @@ func DeriveRequestIDs(r *http.Request, body map[string]any, scope string) Reques
|
||||
signal = RandomID("fallback", 16)
|
||||
}
|
||||
session := scopedSessionID(scope, signal)
|
||||
childSession := r.Header.Get("x-opencode-session-id")
|
||||
if childSession != "" {
|
||||
childSession = scopedSessionID(scope, childSession)
|
||||
}
|
||||
projectSignal := jsonutil.FirstString(r.Header.Get("x-opencode-project"), jsonutil.StringAt(body, "metadata", "project_id"))
|
||||
if projectSignal == "" {
|
||||
// Without a client project every caller would otherwise share one
|
||||
@@ -81,8 +89,12 @@ func DeriveRequestIDs(r *http.Request, body map[string]any, scope string) Reques
|
||||
r.Header.Get("x-parent-session-id"),
|
||||
jsonutil.StringAt(body, "metadata", "parent_session_id"),
|
||||
)
|
||||
if parentSession != "" {
|
||||
parentSession = scopedSessionID(scope, parentSession)
|
||||
}
|
||||
return RequestIDs{
|
||||
Session: session,
|
||||
ChildSession: childSession,
|
||||
Request: RandomID("req", 16),
|
||||
Message: UserMessageID(r, body, session),
|
||||
Project: projectSignal,
|
||||
|
||||
@@ -26,7 +26,7 @@ const (
|
||||
GoDocsURL = "https://raw.githubusercontent.com/anomalyco/opencode/dev/packages/web/src/content/docs/go.mdx"
|
||||
// V1Base is the v1 lane's origin: the /zen console (serving /zen/v1/*) that
|
||||
// expects the OpenCode 1.x request shape. It is the default keyed Zen
|
||||
// upstream, and the anonymous lane tries it before the v2 /inference
|
||||
// upstream and the anonymous lane's fallback after the v2 /inference
|
||||
// origin. It also serves the models listing.
|
||||
V1Base = "https://opencode.ai/zen"
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user