// Package identity derives stable session identities and unique request IDs. package identity import ( "crypto/rand" "crypto/sha256" "encoding/hex" "encoding/json" "fmt" "net/http" "opencode2api/internal/jsonutil" ) type RequestIDs struct { Session string Request string Project string ParentSession string } func DeriveRequestIDs(r *http.Request, body map[string]any) RequestIDs { signal := jsonutil.FirstString( r.Header.Get("x-opencode-session"), r.Header.Get("x-session-affinity"), r.Header.Get("X-Session-Id"), r.Header.Get("x-session-id"), r.Header.Get("conversation-id"), jsonutil.StringAt(body, "conversation_id"), jsonutil.StringAt(body, "metadata", "session_id"), ) if signal == "" { // Using the first user turn keeps a multi-turn conversation stable as its // history grows while separating conversations with different beginnings. signal = conversationSeed(body) } if signal == "" { signal = jsonutil.StringAt(body, "previous_response_id") } if signal == "" || signal == `{}` { signal = RandomID("fallback", 16) } session := StableID("ses", signal) projectSignal := jsonutil.FirstString(r.Header.Get("x-opencode-project"), jsonutil.StringAt(body, "metadata", "project_id")) if projectSignal == "" { projectSignal = "opencode2api:default-project" } parentSession := jsonutil.FirstString( r.Header.Get("x-parent-session-id"), jsonutil.StringAt(body, "metadata", "parent_session_id"), ) return RequestIDs{ Session: session, Request: RandomID("req", 16), Project: StableID("prj", projectSignal), ParentSession: parentSession, } } func conversationSeed(body map[string]any) string { if input, ok := body["input"].(string); ok && input != "" { return input } for _, field := range []string{"messages", "input"} { for _, raw := range jsonutil.SliceAt(body, field) { item, ok := raw.(map[string]any) if !ok || jsonutil.StringAt(item, "role") != "user" { continue } encoded, _ := json.Marshal(item["content"]) if len(encoded) > 0 && string(encoded) != "null" { return string(encoded) } } } return "" } func StableID(prefix, value string) string { sum := sha256.Sum256([]byte(prefix + "\x00" + value)) return prefix + "_" + hex.EncodeToString(sum[:12]) } func RandomID(prefix string, size int) string { buf := make([]byte, size) if _, err := rand.Read(buf); err != nil { panic(fmt.Sprintf("crypto/rand failed: %v", err)) } return prefix + "_" + hex.EncodeToString(buf) }