diff --git a/internal/runtime/executor/codex_executor_execute.go b/internal/runtime/executor/codex_executor_execute.go index fae2f32201..4800725d80 100644 --- a/internal/runtime/executor/codex_executor_execute.go +++ b/internal/runtime/executor/codex_executor_execute.go @@ -194,11 +194,18 @@ func (e *CodexExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, re } sanitizeOpenAIResponsesReasoningEncryptedContentWithCompatModelAndBaseURLDoc(ctx, "codex executor", doc, isCompat, targetModel, baseURL) + sessionInstructions, errSession := helps.PrepareCodexSessionInstructions(ctx, doc, req, opts, nil, nil, isCompactionSummary) + if errSession != nil { + return resp, errSession + } url := strings.TrimSuffix(baseURL, "/") + "/responses" httpReq, upstreamBody, err := e.cacheHelperDoc(ctx, from, url, req, doc, auth, opts.Headers) if err != nil { return resp, err } + if errFinal := sessionInstructions.CheckFinal(upstreamBody); errFinal != nil { + return resp, errFinal + } body = upstreamBody upstreamModel := strings.TrimSpace(doc.Get("model").String()) if upstreamModel != "" && upstreamModel != baseModel { @@ -225,7 +232,7 @@ func (e *CodexExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, re URL: url, Method: http.MethodPost, Headers: httpReq.Header.Clone(), - Body: upstreamBody, + Body: sessionInstructions.LogBody(upstreamBody), Provider: e.Identifier(), AuthID: authID, AuthLabel: authLabel, @@ -481,6 +488,7 @@ func (e *CodexExecutor) executeCompact(ctx context.Context, auth *cliproxyauth.A helps.NormalizeCodexToolSchemasDoc(doc) optimizeMultiAgentV2 := helps.OptimizeCodexMultiAgentV2RequestForAuthDoc(doc, ctx, opts.Headers, e.cfg, auth, isCompat) + helps.StripCodexSessionInstructionMarker(doc, from) url := strings.TrimSuffix(baseURL, "/") + "/responses/compact" httpReq, upstreamBody, err := e.cacheHelperDoc(ctx, from, url, req, doc, auth, opts.Headers) if err != nil { diff --git a/internal/runtime/executor/codex_executor_request.go b/internal/runtime/executor/codex_executor_request.go index 1acd7d7949..b731bf61ca 100644 --- a/internal/runtime/executor/codex_executor_request.go +++ b/internal/runtime/executor/codex_executor_request.go @@ -196,6 +196,9 @@ func (e *CodexExecutor) cacheHelperDoc(ctx context.Context, from sdktranslator.F if doc != nil { rawJSON = doc.Bytes() } + if errMarker := helps.ValidateCodexSessionInstructionMarker(rawJSON, from); errMarker != nil { + return nil, nil, errMarker + } wireBody := rawJSON if e.cfg != nil && e.cfg.Codex.UpstreamRequestCompression && auth != nil && !codexAuthUsesAPIKey(auth) && !codexUseSIWCForRequest(ctx, auth, headers) && diff --git a/internal/runtime/executor/codex_executor_stream.go b/internal/runtime/executor/codex_executor_stream.go index fb7b7e5b56..5f7b72ef62 100644 --- a/internal/runtime/executor/codex_executor_stream.go +++ b/internal/runtime/executor/codex_executor_stream.go @@ -122,11 +122,18 @@ func (e *CodexExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Au } sanitizeOpenAIResponsesReasoningEncryptedContentWithCompatModelAndBaseURLDoc(ctx, "codex executor", doc, isCompat, targetModel, baseURL) + sessionInstructions, errSession := helps.PrepareCodexSessionInstructions(ctx, doc, req, opts, nil, nil, codexCompactionSummaryFromContext(ctx)) + if errSession != nil { + return nil, errSession + } url := strings.TrimSuffix(baseURL, "/") + "/responses" httpReq, upstreamBody, err := e.cacheHelperDoc(ctx, from, url, req, doc, auth, opts.Headers) if err != nil { return nil, err } + if errFinal := sessionInstructions.CheckFinal(upstreamBody); errFinal != nil { + return nil, errFinal + } body = upstreamBody upstreamModel := strings.TrimSpace(doc.Get("model").String()) if upstreamModel != "" && upstreamModel != baseModel { @@ -153,7 +160,7 @@ func (e *CodexExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Au URL: url, Method: http.MethodPost, Headers: httpReq.Header.Clone(), - Body: upstreamBody, + Body: sessionInstructions.LogBody(upstreamBody), Provider: e.Identifier(), AuthID: authID, AuthLabel: authLabel, diff --git a/internal/runtime/executor/codex_executor_tokens.go b/internal/runtime/executor/codex_executor_tokens.go index e65d9a18f5..5270b2657d 100644 --- a/internal/runtime/executor/codex_executor_tokens.go +++ b/internal/runtime/executor/codex_executor_tokens.go @@ -42,6 +42,7 @@ func (e *CodexExecutor) CountTokens(ctx context.Context, auth *cliproxyauth.Auth helps.SetStringIfDifferentDoc(doc, "model", baseModel) _ = doc.Delete("previous_response_id") + helps.StripCodexSessionInstructionMarker(doc, from) _ = doc.Delete("generate") _ = doc.Delete("prompt_cache_retention") _ = doc.Delete("safety_identifier") diff --git a/internal/runtime/executor/codex_session_instructions_test.go b/internal/runtime/executor/codex_session_instructions_test.go new file mode 100644 index 0000000000..475e0e7ae2 --- /dev/null +++ b/internal/runtime/executor/codex_session_instructions_test.go @@ -0,0 +1,277 @@ +package executor + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/MoeForge/moego/ojson" + "github.com/gorilla/websocket" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + core "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +func managedInstructionsOptions(t *testing.T) core.Options { + return core.Options{ + SourceFormat: sdktranslator.FormatOpenAIResponse, + Headers: http.Header{"Session-Id": {t.Name()}}, + Metadata: map[string]any{core.CallerScopeMetadataKey: "test-caller", core.ExecutionSessionMetadataKey: t.Name()}, + } +} + +func TestCodexSessionInstructionsHTTP(t *testing.T) { + for _, tc := range []struct { + name string + auth func(string) *cliproxyauth.Auth + }{{"oauth", codexOAuthTestAuth}, {"api-key", codexAPIKeyTestAuth}} { + t.Run(tc.name, func(t *testing.T) { + tcAuth := tc.auth + server, captured, _ := newCodexHostedImageTestServer(t, "http") + cfg := &config.Config{} + cfg.Payload.Override = []config.PayloadRule{{ + Models: []config.PayloadModelRule{{Name: "*", Match: []map[string]any{{"input.0.content.0.text": " A ", "instructions": "override"}}}}, + Params: map[string]any{"input.0.content.0.text": "configured", "instructions": "configured"}, + }} + exec := NewCodexExecutor(cfg) + opts := managedInstructionsOptions(t) + for i, tc := range []struct { + body, baseline, instructions string + count int + }{ + {`{"input":"hi","instructions":" A ","client_metadata":{"cpa_session_instructions":"start","other":"keep"}}`, " A ", "", 2}, + {`{"input":"hi","instructions":" A ","client_metadata":{"cpa_session_instructions":"reuse"}}`, " A ", "", 2}, + {`{"input":"hi","instructions":"A","client_metadata":{"cpa_session_instructions":"reuse"}}`, " A ", "A", 2}, + {`{"input":"hi","client_metadata":{"cpa_session_instructions":"reuse"}}`, " A ", "", 2}, + {`{"input":"hi","instructions":null,"client_metadata":{"cpa_session_instructions":"reuse"}}`, " A ", "", 2}, + {`{"input":"hi","instructions":"","client_metadata":{"cpa_session_instructions":"reuse"}}`, " A ", "", 2}, + {`{"input":[{"type":"message","role":"developer","content":[{"type":"input_text","text":" A "}]},{"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}],"client_metadata":{"cpa_session_instructions":"reuse"}}`, " A ", "", 2}, + {`{"input":"hi","instructions":"override","client_metadata":{"cpa_session_instructions":"reuse"}}`, "configured", "configured", 2}, + {`{"input":"hi","instructions":" A "}`, "hi", " A ", 1}, + } { + req := core.Request{Model: "gpt-5.4", Payload: []byte(tc.body)} + if i%2 == 0 { + if _, errExecute := exec.Execute(t.Context(), tcAuth(server.URL), req, opts); errExecute != nil { + t.Fatal(errExecute) + } + } else { + res, errStream := exec.ExecuteStream(t.Context(), tcAuth(server.URL), req, opts) + if errStream != nil { + t.Fatal(errStream) + } + for chunk := range res.Chunks { + if chunk.Err != nil { + t.Fatal(chunk.Err) + } + } + } + body := ojson.NewDoc((<-captured).body) + if body.Get("input.0.content.0.text").String() != tc.baseline || body.Get("input.#").Int() != int64(tc.count) || body.Get("instructions").String() != tc.instructions || body.Get("client_metadata.cpa_session_instructions").Exists() { + t.Fatalf("turn %d: unexpected upstream request: %s", i, body.Bytes()) + } + if i == 0 && body.Get("client_metadata.other").String() != "keep" { + t.Fatal("unrelated client metadata was removed") + } + } + req := core.Request{Model: "gpt-5.4", Payload: []byte(`{"instructions":"B","input":[],"client_metadata":{"cpa_session_instructions":"reuse"}}`)} + check := func(req core.Request, opts core.Options, status int) { + t.Helper() + _, errExecute := exec.Execute(t.Context(), tcAuth(server.URL), req, opts) + var errStatus interface{ StatusCode() int } + if !errors.As(errExecute, &errStatus) || errStatus.StatusCode() != status { + t.Fatalf("expected %d, got %v", status, errExecute) + } + select { + case <-captured: + t.Fatal("invalid request reached upstream") + default: + } + } + other := managedInstructionsOptions(t) + other.Metadata[core.CallerScopeMetadataKey] = "different-caller" + check(req, other, http.StatusConflict) + delete(other.Metadata, core.CallerScopeMetadataKey) + check(req, other, http.StatusBadRequest) + req.Payload = []byte(`{"instructions":"B","input":[],"previous_response_id":"r0","client_metadata":{"cpa_session_instructions":"start"}}`) + check(req, opts, http.StatusConflict) + unreconstructed := opts + unreconstructed.OriginalRequest = req.Payload + req.Payload = []byte(`{"instructions":"B","input":[],"client_metadata":{"cpa_session_instructions":"reuse"}}`) + check(req, unreconstructed, http.StatusConflict) + req.Payload = []byte(`{"input":[],"client_metadata":{"other":"ok"},"client_metadata":{"cpa_session_instructions":"reuse"}}`) + check(req, opts, http.StatusBadRequest) + }) + } +} + +func newManagedInstructionsWSServer(t *testing.T) (*httptest.Server, <-chan []byte) { + t.Helper() + captured := make(chan []byte, 10) + upgrader := websocket.Upgrader{} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, errUpgrade := upgrader.Upgrade(w, r, nil) + if errUpgrade != nil { + t.Error(errUpgrade) + return + } + defer func() { + if errClose := conn.Close(); errClose != nil { + t.Log(errClose) + } + }() + for i := 0; ; i++ { + _, frame, errRead := conn.ReadMessage() + if errRead != nil { + return + } + captured <- frame + for _, event := range []string{"response.created", "response.completed"} { + msg := fmt.Sprintf(`{"type":%q,"response":{"id":"r%d","status":"completed","output":[]}}`, event, i) + if errWrite := conn.WriteMessage(websocket.TextMessage, []byte(msg)); errWrite != nil { + return + } + } + } + })) + t.Cleanup(server.Close) + return server, captured +} + +func TestCodexSessionInstructionsWebsocket(t *testing.T) { + for _, mode := range []string{"stream", "nonstream", "duplex", "filtered-prefix", "filtered-parent"} { + t.Run(mode, func(t *testing.T) { + server, captured := newManagedInstructionsWSServer(t) + cfg := &config.Config{Codex: config.CodexConfig{ResponseSteering: mode == "duplex"}} + if mode == "filtered-prefix" { + cfg.Payload.Override = []config.PayloadRule{{Models: []config.PayloadModelRule{{Name: "*"}}, Params: map[string]any{"input.0.content.0.text": "filtered"}}} + } else if mode == "filtered-parent" { + cfg.Payload.Override = []config.PayloadRule{{Models: []config.PayloadModelRule{{Name: "*", Match: []map[string]any{{"previous_response_id": "r0"}}}}, Params: map[string]any{"previous_response_id": "configured"}}} + } + exec := NewCodexWebsocketsExecutor(cfg) + exec.store = &codexWebsocketSessionStore{sessions: make(map[string]*codexWebsocketSession)} + defer exec.CloseExecutionSession(t.Name()) + opts := managedInstructionsOptions(t) + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + input := make(chan core.WebsocketInput, 1) + var duplex *core.StreamResult + if mode == "duplex" { + ctx = core.WithWebsocketInput(core.WithDownstreamWebsocket(ctx), input) + } + auth := codexAPIKeyTestAuth(server.URL) + turn := func(payload string, opts core.Options, reject bool) { + t.Helper() + req := core.Request{Model: "gpt-5.4", Payload: []byte(payload)} + var err error + switch { + case mode == "nonstream": + _, err = exec.Execute(ctx, auth, req, opts) + case mode == "duplex": + if duplex == nil { + duplex, err = exec.ExecuteStream(ctx, auth, req, opts) + } else { + input <- core.WebsocketInput{Payload: req.Payload} + } + if err == nil { + for chunk := range duplex.Chunks { + if chunk.Err != nil { + t.Fatal(chunk.Err) + } + kind := ojson.GetBytes(chunk.Payload, "type").String() + if kind == "error" { + if !reject || ojson.GetBytes(chunk.Payload, "error.code").String() != "previous_response_not_found" { + t.Fatalf("unexpected error %s", chunk.Payload) + } + return + } + if kind == "response.completed" { + if reject { + t.Fatal("invalid delta reached upstream") + } + return + } + } + t.Fatal("duplex stream ended early") + } + default: + var result *core.StreamResult + result, err = exec.ExecuteStream(ctx, auth, req, opts) + if err == nil { + for chunk := range result.Chunks { + if chunk.Err != nil { + t.Fatal(chunk.Err) + } + } + } + } + if reject { + if !core.IsUpstreamWebsocketTurnError(err) { + t.Fatalf("want full replay error, got %v", err) + } + } else if err != nil { + t.Fatal(err) + } + } + turn(`{"type":"response.create","input":"root","instructions":"A","client_metadata":{"cpa_session_instructions":"start"}}`, opts, false) + root := ojson.NewDoc(<-captured) + wantPrefix := "A" + if mode == "filtered-prefix" { + wantPrefix = "filtered" + } + if root.Get("input.0.role").String() != "developer" || root.Get("input.0.content.0.text").String() != wantPrefix || root.Get("instructions").String() != "" || root.Get("client_metadata.cpa_session_instructions").Exists() { + t.Fatalf("root was not rewritten: %s", root.Bytes()) + } + delta := `{"type":"response.append","input":"next","client_metadata":{"cpa_session_instructions":"reuse"},"instructions":"B"}` + unsafe := mode == "filtered-prefix" || mode == "filtered-parent" + turn(delta, opts, unsafe) + if !unsafe { + body := ojson.NewDoc(<-captured) + if body.Get("previous_response_id").String() != "r0" || body.Get("input.#").Int() != 1 || body.Get("input.0.role").String() != "user" || body.Get("instructions").String() != "B" || body.Get("client_metadata.cpa_session_instructions").Exists() { + t.Fatalf("delta was incorrectly rewritten: %s", body.Bytes()) + } + turn(`{"type":"response.append","input":"unmarked"}`, opts, false) + body = ojson.NewDoc(<-captured) + if body.Get("previous_response_id").String() != "r1" || body.Get("input.#").Int() != 1 || body.Get("instructions").String() != "" { + t.Fatalf("unmarked delta did not inherit managed chain: %s", body.Bytes()) + } + if mode != "duplex" { + other := managedInstructionsOptions(t) + other.Metadata[core.CallerScopeMetadataKey] = "different-caller" + turn(`{"type":"response.create","previous_response_id":"r2","input":"cross caller"}`, other, true) + other = managedInstructionsOptions(t) + other.Headers.Set("Session-Id", "different-logical-session") + turn(`{"type":"response.create","previous_response_id":"r2","input":"cross session"}`, other, true) + } + } + turn(`{"type":"response.create","previous_response_id":"unknown","input":"next"}`, opts, true) + if mode == "stream" { + sess := exec.getOrCreateSession(t.Name()) + sess.connMu.Lock() + original := sess.conn + sess.connMu.Unlock() + exec.invalidateUpstreamConnWithoutDisconnectNotify(sess, original, "test_reconnect", nil) + turn(`{"type":"response.create","previous_response_id":"r2","input":"next"}`, opts, true) + turn(`{"type":"response.create","input":"replay","client_metadata":{"cpa_session_instructions":"reuse"}}`, opts, false) + body := ojson.NewDoc(<-captured) + if body.Get("input.0.content.0.text").String() != "A" || body.Get("previous_response_id").Exists() { + t.Fatalf("full replay did not restore the baseline: %s", body.Bytes()) + } + } + select { + case frame := <-captured: + t.Fatalf("unexpected send: %s", strings.TrimSpace(string(frame))) + default: + } + cancel() + if duplex != nil { + for range duplex.Chunks { + } + } + }) + } +} diff --git a/internal/runtime/executor/codex_websockets_duplex.go b/internal/runtime/executor/codex_websockets_duplex.go index 8f49f3fa2a..7854d0d98f 100644 --- a/internal/runtime/executor/codex_websockets_duplex.go +++ b/internal/runtime/executor/codex_websockets_duplex.go @@ -76,6 +76,7 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( var unacknowledgedSteers []codexSteerSubmission acceptedSteers := make(map[string]codexAcceptedSteer) current := initial + var currentSessionReceipt helps.CodexInstructionReceipt responseID := "" latestTurnResponseID := "" responseSettings := make(map[string]*codexWebsocketPrepared) @@ -403,10 +404,11 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( } createDoc := ojson.NewDoc(payload) _ = createDoc.Set("model", model) - if (isAppend || hasLocalCompactionParent) && !createDoc.Get("instructions").Exists() { - metadataMu.Lock() - parentSettings := responseSettings[prevID] - metadataMu.Unlock() + metadataMu.Lock() + parentSettings := responseSettings[prevID] + metadataMu.Unlock() + managed := helps.HasCodexSessionInstructionMarker(createDoc, opts.SourceFormat) || (parentSettings != nil && parentSettings.sessionInstructions.Managed()) + if (isAppend || hasLocalCompactionParent) && !managed && !createDoc.Get("instructions").Exists() { // Inherit normalized settings before user rules, not the previous final body. var instructions string if parentSettings != nil { @@ -574,11 +576,24 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( consumedPayload = nil return true } - prepared, errPrepare := e.prepareCodexWebsocketStream(streamCtx, auth, nextReq, nextOpts) + prepared, errPrepare := e.prepareCodexWebsocketStream(streamCtx, auth, nextReq, nextOpts, sess) if errPrepare != nil { + if cliproxyexecutor.IsUpstreamWebsocketTurnError(errPrepare) { + return rejectPreviousResponseNotFound(eventID) + } + if status := helps.CodexSessionInstructionErrorStatus(errPrepare); status != 0 { + errType := "invalid_request_error" + if status >= 500 { + errType = "server_error" + } + return emitDuplexError(status, errType, "", "", errPrepare.Error(), eventID) + } fail(errPrepare) return false } + if errConn := prepared.sessionInstructions.OnConnection(conn); errConn != nil { + return rejectPreviousResponseNotFound(eventID) + } if prepared.wsURL != initial.wsURL { fail(cliproxyexecutor.NewUpstreamWebsocketReplayRequiredError()) return false @@ -590,6 +605,7 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( fail(fmt.Errorf("too many outstanding response.create requests")) return false } + prepared.sessionReceipt = sess.sessionInstructions.Sent(conn, prepared.sessionInstructions) pending = append(pending, prepared) consumedPayload = nil // pending owns it now, including a possibly partial write metadataMu.Unlock() @@ -601,7 +617,7 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( return false } helps.RecordAPIWebsocketRequest(streamCtx, e.cfg, helps.UpstreamRequestLog{ - URL: initial.wsURL, Method: "WEBSOCKET", Body: payload, Provider: e.Identifier(), AuthID: auth.ID, + URL: initial.wsURL, Method: "WEBSOCKET", Body: prepared.sessionInstructions.LogBody(payload), Provider: e.Identifier(), AuthID: auth.ID, }) if errWrite := writeCodexWebsocketMessage(sess, conn, payload); errWrite != nil { fail(mapCodexWebsocketWriteError(sess, conn, errWrite)) @@ -698,6 +714,7 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( continue } steerDoc := ojson.NewDoc(steerReq.Payload) + helps.StripCodexSessionInstructionMarker(steerDoc, opts.SourceFormat) if codexUseSIWCForRequest(ctx, auth, steerHeaders) { thinking.StripConfigurationUpdatesDoc(steerDoc) } @@ -707,6 +724,12 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( parent := strings.Clone(steerDoc.Get("previous_response_id").String()) steerEventID := strings.Clone(steerDoc.Get("event_id").String()) payload = steerDoc.Bytes() + if errMarker := helps.ValidateCodexSessionInstructionMarker(payload, opts.SourceFormat); errMarker != nil { + if !reject(errMarker.Error()) { + return + } + continue + } metadataMu.Lock() settings := responseSettings[parent] metadataMu.Unlock() @@ -718,6 +741,12 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( settings = responseSettings[parent] metadataMu.Unlock() } + if sess.sessionInstructions.Armed() && (settings == nil || !settings.sessionInstructions.AllowsControl(payload, steerReq, steerOpts)) { + if !rejectPreviousResponseNotFound(steerEventID) { + return + } + continue + } metadataMu.Lock() unacknowledgedSteers = append(unacknowledgedSteers, codexSteerSubmission{parent: parent, eventID: steerEventID}) consumedPayload = nil @@ -912,6 +941,11 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( } } waitingParent = "" + currentSessionReceipt = helps.CodexInstructionReceipt{} + if len(pending) == 1 && !responseActive && !automaticActive && len(unacknowledgedSteers) == 0 && len(acceptedSteers) == 0 { + currentSessionReceipt = pending[0].sessionReceipt + currentSessionReceipt.Observe(payload) + } automaticActive = !firstResponse && len(pending) == 0 if len(pending) > 0 { current, pending = pending[0], pending[1:] @@ -1088,6 +1122,9 @@ func (e *CodexWebsocketsExecutor) streamCodexDuplex( endedID = ojson.GetBytesNoCopy(payload, "response_id").String() } metadataMu.Lock() + if responseActive && endedID != "" && endedID == responseID { + currentSessionReceipt.Observe(payload) + } if endedID == "" && !responseActive { // An id-less failure that ended the running response. endedID = responseID diff --git a/internal/runtime/executor/codex_websockets_execute.go b/internal/runtime/executor/codex_websockets_execute.go index e1b44ebbcd..aa394b791f 100644 --- a/internal/runtime/executor/codex_websockets_execute.go +++ b/internal/runtime/executor/codex_websockets_execute.go @@ -121,27 +121,6 @@ func (e *CodexWebsocketsExecutor) Execute(ctx context.Context, auth *cliproxyaut if useSIWC { applyCodexSIWCWebsocketBodyRulesDoc(doc, hasExplicitInstructions, cliproxyexecutor.Options{KeepTopLevelEffort: thinking.HasThinkingSuffix(req.Model)}) } - helps.FinalizePayloadDoc(ctx, doc) - body = doc.Bytes() - upstreamModel := strings.TrimSpace(doc.Get("model").String()) - if upstreamModel != "" && upstreamModel != baseModel { - reporter.SetUpstreamModel(upstreamModel) - } - reporter.SetTranslatedReasoningEffort(body, to.String()) - wsHeaders = applyCodexWebsocketHeaders(ctx, wsHeaders, auth, apiKey, e.cfg, nativeRequest, opts.Headers) - applyCodexRoutingHint(ctx, wsHeaders, auth, upstreamModel, body, opts.Headers) - applyModelHeaderOverrides(wsHeaders, upstreamModel) - if errValidate := helps.ValidateCodexHostedImageGenerationDoc(doc, wsHeaders, e.cfg, !useSIWC && !codexAuthUsesAPIKey(auth)); errValidate != nil { - return resp, errValidate - } - - var authID, authLabel, authType, authValue string - if auth != nil { - authID = auth.ID - authLabel = auth.Label - authType, authValue = auth.AccountInfo() - } - executionSessionID := executionSessionIDFromOptions(opts) var sess *codexWebsocketSession isEphemeralSession := false @@ -162,12 +141,43 @@ func (e *CodexWebsocketsExecutor) Execute(ctx context.Context, auth *cliproxyaut sess = newEphemeralCodexWebsocketSession() } + sessionInstructions, errSession := e.prepareSessionInstructions(ctx, doc, auth, req, opts, sess, wsURL, useSIWC) + if errSession != nil { + return resp, errSession + } + helps.FinalizePayloadDoc(ctx, doc) + body = doc.Bytes() + if errMarker := helps.ValidateCodexSessionInstructionMarker(body, from); errMarker != nil { + return resp, errMarker + } + if errFinal := sessionInstructions.CheckFinal(body); errFinal != nil { + return resp, errFinal + } + upstreamModel := strings.TrimSpace(doc.Get("model").String()) + if upstreamModel != "" && upstreamModel != baseModel { + reporter.SetUpstreamModel(upstreamModel) + } + reporter.SetTranslatedReasoningEffort(body, to.String()) + wsHeaders = applyCodexWebsocketHeaders(ctx, wsHeaders, auth, apiKey, e.cfg, nativeRequest, opts.Headers) + applyCodexRoutingHint(ctx, wsHeaders, auth, upstreamModel, body, opts.Headers) + applyModelHeaderOverrides(wsHeaders, upstreamModel) + if errValidate := helps.ValidateCodexHostedImageGenerationDoc(doc, wsHeaders, e.cfg, !useSIWC && !codexAuthUsesAPIKey(auth)); errValidate != nil { + return resp, errValidate + } + + var authID, authLabel, authType, authValue string + if auth != nil { + authID = auth.ID + authLabel = auth.Label + authType, authValue = auth.AccountInfo() + } + wsReqBody := frameCodexWebsocketRequestBody(body) wsReqLog := helps.UpstreamRequestLog{ URL: wsURL, Method: "WEBSOCKET", Headers: wsHeaders.Clone(), - Body: wsReqBody, + Body: sessionInstructions.LogBody(wsReqBody), Provider: e.Identifier(), AuthID: authID, AuthLabel: authLabel, @@ -181,9 +191,12 @@ func (e *CodexWebsocketsExecutor) Execute(ctx context.Context, auth *cliproxyaut var respHS *http.Response var errDial error dialCtx := ctx - if cliproxyexecutor.RequiredUpstreamWebsocket(ctx) { + if cliproxyexecutor.RequiredUpstreamWebsocket(ctx) || sessionInstructions.ConnectionBound() { conn, closer = existingWebsocketSessionConn(sess, authID, wsURL, executionProxyURL(ctx, sess.effectiveConfig(authID, e.cfg), auth), useSIWC) if conn == nil { + if errConn := sessionInstructions.OnConnection(nil); errConn != nil { + return resp, errConn + } return resp, cliproxyexecutor.NewUpstreamWebsocketReplayRequiredError() } } else { @@ -209,6 +222,9 @@ func (e *CodexWebsocketsExecutor) Execute(ctx context.Context, auth *cliproxyaut } return resp, errDial } + if errConn := sessionInstructions.OnConnection(conn); errConn != nil { + return resp, errConn + } if errBind := sess.bindExecutionLifecycle(opts, conn, closer, req.Model); errBind != nil { unlockSession() closeWebsocketAfterBindFailure(sess, conn, closer) @@ -235,6 +251,7 @@ func (e *CodexWebsocketsExecutor) Execute(ctx context.Context, auth *cliproxyaut } restoreMultiAgentV2 := !multiAgentV2Conflict && (optimizeMultiAgentV2 || sess.isMultiAgentV2Optimized(conn)) + sessionReceipt := sess.sessionInstructions.Sent(conn, sessionInstructions) cliproxyexecutor.MarkUpstreamAttempt(ctx) if errSend := writeCodexWebsocketMessage(sess, conn, wsReqBody); errSend != nil { errSend = mapCodexWebsocketWriteError(sess, conn, errSend) @@ -253,6 +270,10 @@ func (e *CodexWebsocketsExecutor) Execute(ctx context.Context, auth *cliproxyaut return resp, errSend } + if errConn := sessionInstructions.OnConnection(nil); errConn != nil { + return resp, errConn + } + // Retry once with a fresh websocket connection. This is mainly to handle // upstream closing the socket between sequential requests within the same // execution session. @@ -274,7 +295,7 @@ func (e *CodexWebsocketsExecutor) Execute(ctx context.Context, auth *cliproxyaut URL: wsURL, Method: "WEBSOCKET", Headers: wsHeaders.Clone(), - Body: wsReqBodyRetry, + Body: sessionInstructions.LogBody(wsReqBodyRetry), Provider: e.Identifier(), AuthID: authID, AuthLabel: authLabel, @@ -283,6 +304,7 @@ func (e *CodexWebsocketsExecutor) Execute(ctx context.Context, auth *cliproxyaut }) recordAPIWebsocketHandshake(ctx, e.cfg, respHSRetry) reporter.StartResponseTTFT() + sessionReceipt = sess.sessionInstructions.Sent(conn, sessionInstructions) cliproxyexecutor.MarkUpstreamAttempt(ctx) if errSendRetry := writeCodexWebsocketMessage(sess, conn, wsReqBodyRetry); errSendRetry == nil { wsReqBody = wsReqBodyRetry @@ -368,6 +390,7 @@ func (e *CodexWebsocketsExecutor) Execute(ctx context.Context, auth *cliproxyaut return resp, streamErr } + sessionReceipt.Observe(payload) payload = normalizeCodexWebsocketCompletion(payload) eventType := ojson.GetBytesNoCopy(payload, "type").String() if helps.HasMeaningfulCodexOutputDelta(payload) { diff --git a/internal/runtime/executor/codex_websockets_executor.go b/internal/runtime/executor/codex_websockets_executor.go index 199bb2d8f7..8a94b50907 100644 --- a/internal/runtime/executor/codex_websockets_executor.go +++ b/internal/runtime/executor/codex_websockets_executor.go @@ -11,8 +11,10 @@ import ( "github.com/MoeForge/moego/ojson" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" log "github.com/sirupsen/logrus" ) @@ -270,6 +272,14 @@ func (e *CodexWebsocketsExecutor) InterruptExecutionSession(ctx context.Context, if !authEnabled { return fmt.Errorf("websocket credential is no longer enabled") } + if ojson.GetBytesNoCopy(payload, "client_metadata").Exists() { + doc := ojson.NewDoc(payload) + helps.StripCodexSessionInstructionMarker(doc, sdktranslator.FormatOpenAIResponse) + payload = doc.Bytes() + if errMarker := helps.ValidateCodexSessionInstructionMarker(payload, sdktranslator.FormatOpenAIResponse); errMarker != nil { + return errMarker + } + } if errWrite := writeCodexWebsocketMessage(sess, conn, payload); errWrite != nil { return errWrite } diff --git a/internal/runtime/executor/codex_websockets_request.go b/internal/runtime/executor/codex_websockets_request.go index 5322cf4c51..4efdaf53ba 100644 --- a/internal/runtime/executor/codex_websockets_request.go +++ b/internal/runtime/executor/codex_websockets_request.go @@ -18,6 +18,18 @@ import ( sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) +func (e *CodexWebsocketsExecutor) prepareSessionInstructions(ctx context.Context, doc *ojson.Doc, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, sess *codexWebsocketSession, wsURL string, useSIWC bool) (helps.CodexInstructionTurn, error) { + if sess == nil || opts.SourceFormat != sdktranslator.FormatOpenAIResponse { + return helps.PrepareCodexSessionInstructions(ctx, doc, req, opts, nil, nil, false) + } + authID := "" + if auth != nil { + authID = auth.ID + } + conn, _ := existingWebsocketSessionConn(sess, authID, wsURL, executionProxyURL(ctx, sess.effectiveConfig(authID, e.cfg), auth), useSIWC) + return helps.PrepareCodexSessionInstructions(ctx, doc, req, opts, &sess.sessionInstructions, conn, false) +} + func applyCodexPromptCacheHeaders(from sdktranslator.Format, req cliproxyexecutor.Request, rawJSON []byte) ([]byte, http.Header) { body, headers, _ := applyCodexPromptCacheHeadersWithContext(context.Background(), from, req, rawJSON) return body, headers diff --git a/internal/runtime/executor/codex_websockets_session.go b/internal/runtime/executor/codex_websockets_session.go index e0a634057a..949ce32ae4 100644 --- a/internal/runtime/executor/codex_websockets_session.go +++ b/internal/runtime/executor/codex_websockets_session.go @@ -12,6 +12,7 @@ import ( "github.com/MoeForge/moego/ojson" "github.com/gorilla/websocket" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" log "github.com/sirupsen/logrus" @@ -50,7 +51,8 @@ func (c *websocketConnectionCloser) Close() error { } type codexWebsocketSession struct { - sessionID string + sessionInstructions helps.CodexInstructionChain + sessionID string reqMu sync.Mutex diff --git a/internal/runtime/executor/codex_websockets_stream.go b/internal/runtime/executor/codex_websockets_stream.go index 6e1e1963bd..4d4c107525 100644 --- a/internal/runtime/executor/codex_websockets_stream.go +++ b/internal/runtime/executor/codex_websockets_stream.go @@ -59,32 +59,6 @@ func (e *CodexWebsocketsExecutor) ExecuteStream(ctx context.Context, auth *clipr reporter := helps.NewExecutorUsageReporter(ctx, e, baseModel, auth) defer reporter.TrackFailure(ctx, &err) - prepared, err := e.prepareCodexWebsocketStream(ctx, auth, req, opts) - if err != nil { - return nil, err - } - if prepared.upstreamModel != "" && prepared.upstreamModel != baseModel { - reporter.SetUpstreamModel(prepared.upstreamModel) - } - from := prepared.from - responseFormat := prepared.responseFormat - to := prepared.to - preserveNativeOutput := prepared.preserveNativeOutput - originalPayload := prepared.originalPayload - clientBody := prepared.clientBody - wsURL := prepared.wsURL - wsHeaders := prepared.wsHeaders - useSIWC := prepared.useSIWC - replayScope := prepared.replayScope - optimizeMultiAgentV2 := prepared.optimizeMultiAgentV2 - multiAgentV2Conflict := prepared.multiAgentV2Conflict - reporter.SetTranslatedReasoningEffort(clientBody, to.String()) - - var authID, authLabel, authType, authValue string - authID = auth.ID - authLabel = auth.Label - authType, authValue = auth.AccountInfo() - executionSessionID := executionSessionIDFromOptions(opts) var sess *codexWebsocketSession isEphemeralSession := false @@ -111,12 +85,39 @@ func (e *CodexWebsocketsExecutor) ExecuteStream(ctx context.Context, auth *clipr } } + prepared, err := e.prepareCodexWebsocketStream(ctx, auth, req, opts, sess) + if err != nil { + unlockStreamSession() + return nil, codexWebsocketTurnEventID(err, req.Payload) + } + if prepared.upstreamModel != "" && prepared.upstreamModel != baseModel { + reporter.SetUpstreamModel(prepared.upstreamModel) + } + from := prepared.from + responseFormat := prepared.responseFormat + to := prepared.to + preserveNativeOutput := prepared.preserveNativeOutput + originalPayload := prepared.originalPayload + clientBody := prepared.clientBody + wsURL := prepared.wsURL + wsHeaders := prepared.wsHeaders + useSIWC := prepared.useSIWC + replayScope := prepared.replayScope + optimizeMultiAgentV2 := prepared.optimizeMultiAgentV2 + multiAgentV2Conflict := prepared.multiAgentV2Conflict + reporter.SetTranslatedReasoningEffort(clientBody, to.String()) + + var authID, authLabel, authType, authValue string + authID = auth.ID + authLabel = auth.Label + authType, authValue = auth.AccountInfo() + wsReqBody := frameCodexWebsocketRequestBody(clientBody) wsReqLog := helps.UpstreamRequestLog{ URL: wsURL, Method: "WEBSOCKET", Headers: wsHeaders.Clone(), - Body: wsReqBody, + Body: prepared.sessionInstructions.LogBody(wsReqBody), Provider: e.Identifier(), AuthID: authID, AuthLabel: authLabel, @@ -130,10 +131,13 @@ func (e *CodexWebsocketsExecutor) ExecuteStream(ctx context.Context, auth *clipr var respHS *http.Response var errDial error dialCtx := ctx - if cliproxyexecutor.RequiredUpstreamWebsocket(ctx) { + if cliproxyexecutor.RequiredUpstreamWebsocket(ctx) || prepared.sessionInstructions.ConnectionBound() { conn, closer = existingWebsocketSessionConn(sess, authID, wsURL, executionProxyURL(ctx, sess.effectiveConfig(authID, e.cfg), auth), useSIWC) if conn == nil { unlockStreamSession() + if errConn := prepared.sessionInstructions.OnConnection(nil); errConn != nil { + return nil, codexWebsocketTurnEventID(errConn, originalPayload) + } if cliproxyexecutor.DownstreamWebsocket(ctx) && sess != nil { sess.activeMu.Lock() lost := cliproxyexecutor.IsUpstreamWebsocketTurnError(sess.terminalErr) @@ -179,6 +183,10 @@ func (e *CodexWebsocketsExecutor) ExecuteStream(ctx context.Context, auth *clipr unlockStreamSession() return nil, errDial } + if errConn := prepared.sessionInstructions.OnConnection(conn); errConn != nil { + unlockStreamSession() + return nil, codexWebsocketTurnEventID(errConn, originalPayload) + } if errBind := sess.bindExecutionLifecycle(opts, conn, closer, req.Model); errBind != nil { unlockStreamSession() closeWebsocketAfterBindFailure(sess, conn, closer) @@ -204,6 +212,7 @@ func (e *CodexWebsocketsExecutor) ExecuteStream(ctx context.Context, auth *clipr return nil, codexWebsocketTurnEventID(errLoss, originalPayload) } } + prepared.sessionReceipt = sess.sessionInstructions.Sent(conn, prepared.sessionInstructions) cliproxyexecutor.MarkUpstreamAttempt(ctx) if errSend := writeCodexWebsocketMessage(sess, conn, wsReqBody); errSend != nil { errSend = mapCodexWebsocketWriteError(sess, conn, errSend) @@ -238,6 +247,12 @@ func (e *CodexWebsocketsExecutor) ExecuteStream(ctx context.Context, auth *clipr return nil, errSend } + if errConn := prepared.sessionInstructions.OnConnection(nil); errConn != nil { + sess.clearActive(conn, readCh) + unlockStreamSession() + return nil, codexWebsocketTurnEventID(errConn, originalPayload) + } + // Retry once with a new websocket connection for the same execution session. connRetry, closerRetry, respHSRetry, errDialRetry := e.ensureUpstreamConnWithSIWC(ctx, auth, sess, authID, wsURL, wsHeaders, useSIWC) if errDialRetry != nil || connRetry == nil { @@ -262,7 +277,7 @@ func (e *CodexWebsocketsExecutor) ExecuteStream(ctx context.Context, auth *clipr URL: wsURL, Method: "WEBSOCKET", Headers: wsHeaders.Clone(), - Body: wsReqBodyRetry, + Body: prepared.sessionInstructions.LogBody(wsReqBodyRetry), Provider: e.Identifier(), AuthID: authID, AuthLabel: authLabel, @@ -271,6 +286,7 @@ func (e *CodexWebsocketsExecutor) ExecuteStream(ctx context.Context, auth *clipr }) recordAPIWebsocketHandshake(ctx, e.cfg, respHSRetry) reporter.StartResponseTTFT() + prepared.sessionReceipt = sess.sessionInstructions.Sent(conn, prepared.sessionInstructions) cliproxyexecutor.MarkUpstreamAttempt(ctx) if errSendRetry := writeCodexWebsocketMessage(sess, conn, wsReqBodyRetry); errSendRetry != nil { errSendRetry = mapCodexWebsocketWriteError(sess, conn, errSendRetry) @@ -510,6 +526,7 @@ func (e *CodexWebsocketsExecutor) ExecuteStream(ctx context.Context, auth *clipr break } + prepared.sessionReceipt.Observe(payload) eventType := ojson.GetBytesNoCopy(payload, "type").String() isTerminalEvent := eventType == "response.completed" || eventType == "response.done" || eventType == "response.incomplete" || eventType == "response.failed" || eventType == "error" if helps.HasMeaningfulCodexOutputDelta(payload) { @@ -774,6 +791,7 @@ func (e *CodexWebsocketsExecutor) ExecuteStream(ctx context.Context, auth *clipr return } + prepared.sessionReceipt.Observe(payload) eventType := ojson.GetBytesNoCopy(payload, "type").String() isTerminalEvent := eventType == "response.completed" || eventType == "response.done" || eventType == "response.incomplete" || eventType == "response.failed" || eventType == "error" if helps.HasMeaningfulCodexOutputDelta(payload) { @@ -877,13 +895,15 @@ type codexWebsocketPrepared struct { replayScope codexReasoningReplayScope optimizeMultiAgentV2 bool multiAgentV2Conflict bool + sessionInstructions helps.CodexInstructionTurn + sessionReceipt helps.CodexInstructionReceipt // Immutable pre-payload JSON value for duplex inheritance; never rebuild from clientBody. // An empty Go string means absent, not an explicitly empty JSON string. unconfiguredInstructions string } -func (e *CodexWebsocketsExecutor) prepareCodexWebsocketStream(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) (*codexWebsocketPrepared, error) { +func (e *CodexWebsocketsExecutor) prepareCodexWebsocketStream(ctx context.Context, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, sessions ...*codexWebsocketSession) (*codexWebsocketPrepared, error) { if errPrev := rejectSyntheticCompactionPreviousResponseID(ctx, req.Payload); errPrev != nil { return nil, errPrev } @@ -978,8 +998,22 @@ func (e *CodexWebsocketsExecutor) prepareCodexWebsocketStream(ctx context.Contex if useSIWC { applyCodexSIWCWebsocketBodyRulesDoc(doc, hasExplicitInstructions, cliproxyexecutor.Options{KeepTopLevelEffort: thinking.HasThinkingSuffix(req.Model)}) } + var sess *codexWebsocketSession + if len(sessions) > 0 { + sess = sessions[0] + } + sessionInstructions, errSession := e.prepareSessionInstructions(ctx, doc, auth, req, opts, sess, wsURL, useSIWC) + if errSession != nil { + return nil, errSession + } helps.FinalizePayloadDoc(ctx, doc) body = doc.Bytes() + if errMarker := helps.ValidateCodexSessionInstructionMarker(body, from); errMarker != nil { + return nil, errMarker + } + if errFinal := sessionInstructions.CheckFinal(body); errFinal != nil { + return nil, errFinal + } upstreamModel := strings.TrimSpace(doc.Get("model").String()) wsHeaders = applyCodexWebsocketHeaders(ctx, wsHeaders, auth, apiKey, e.cfg, preserveNativeOutput, opts.Headers) applyCodexRoutingHint(ctx, wsHeaders, auth, upstreamModel, body, opts.Headers) @@ -1002,6 +1036,7 @@ func (e *CodexWebsocketsExecutor) prepareCodexWebsocketStream(ctx context.Contex replayScope: replayScope, optimizeMultiAgentV2: optimizeMultiAgentV2, multiAgentV2Conflict: multiAgentV2Conflict, + sessionInstructions: sessionInstructions, unconfiguredInstructions: unconfiguredInstructions, }, nil diff --git a/internal/runtime/executor/helps/codex_session_instructions.go b/internal/runtime/executor/helps/codex_session_instructions.go new file mode 100644 index 0000000000..12d130d7c7 --- /dev/null +++ b/internal/runtime/executor/helps/codex_session_instructions.go @@ -0,0 +1,493 @@ +package helps + +import ( + "context" + "errors" + "net/http" + "strings" + "sync" + "time" + "unicode/utf8" + + "github.com/MoeForge/moego/ojson" + "github.com/gorilla/websocket" + "github.com/router-for-me/CLIProxyAPI/v8/internal/kvstore" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/session" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +const ( + codexSessionInstructionMarker = "cpa_session_instructions" + codexSessionInstructionPath = "client_metadata." + codexSessionInstructionMarker + codexSessionInstructionTTL = 24 * time.Hour + codexSessionInstructionMaxBytes = 32 << 10 + codexSessionInstructionMaxSessions = 512 +) + +type codexSessionInstructionError struct { + status int + message string +} + +func (e *codexSessionInstructionError) Error() string { return e.message } +func (e *codexSessionInstructionError) StatusCode() int { return e.status } +func (*codexSessionInstructionError) IsRequestScoped() bool { return true } + +var ( + errCodexSessionInstructionMissing = &codexSessionInstructionError{http.StatusConflict, "session instructions are missing or expired; use start with full input and a new session ID"} + errCodexSessionInstructionStore = &codexSessionInstructionError{http.StatusServiceUnavailable, "session instructions storage is unavailable"} + errCodexSessionInstructionStart = &codexSessionInstructionError{http.StatusBadRequest, "session instructions start requires non-empty instructions to establish a baseline"} +) + +type codexSessionInstructionEntry struct { + text string + expires time.Time +} + +type codexSessionInstructionStore struct { + current func() (kvstore.KVClient, bool, error) + now func() time.Time + mu sync.Mutex + entries map[string]codexSessionInstructionEntry +} + +var codexSessionInstructions = codexSessionInstructionStore{current: kvstore.CurrentKVClient, now: time.Now} + +// load never falls back after an enabled KV fails. A start with a candidate uses +// SET NX, and the loser reads the winner without changing its expiration. +func (s *codexSessionInstructionStore) load(ctx context.Context, key, candidate string) (string, error) { + client, enabled, errClient := s.current() + if errClient != nil || (enabled && client == nil) { + return "", errCodexSessionInstructionStore + } + if enabled { + if candidate != "" { + won, errSet := client.KVSetNX(ctx, key, []byte(candidate), codexSessionInstructionTTL) + if errSet != nil { + return "", errCodexSessionInstructionStore + } + if won { + return candidate, nil + } + } + value, found, errGet := client.KVGet(ctx, key) + if errGet != nil { + return "", errCodexSessionInstructionStore + } + if !found { + return "", errCodexSessionInstructionMissing + } + if len(value) == 0 || len(value) > codexSessionInstructionMaxBytes || !utf8.Valid(value) { + return "", errCodexSessionInstructionStore + } + return string(value), nil + } + + s.mu.Lock() + defer s.mu.Unlock() + now := s.now() + if entry, ok := s.entries[key]; ok { + if now.Before(entry.expires) { + return entry.text, nil + } + delete(s.entries, key) + } + if candidate == "" { + return "", errCodexSessionInstructionMissing + } + if len(s.entries) >= codexSessionInstructionMaxSessions { + for id, entry := range s.entries { + if !now.Before(entry.expires) { + delete(s.entries, id) + } + } + if len(s.entries) >= codexSessionInstructionMaxSessions { + return "", errCodexSessionInstructionStore + } + } + if s.entries == nil { + s.entries = make(map[string]codexSessionInstructionEntry) + } + s.entries[key] = codexSessionInstructionEntry{strings.Clone(candidate), now.Add(codexSessionInstructionTTL)} + return candidate, nil +} + +func codexInstructionKey(req cliproxyexecutor.Request, opts cliproxyexecutor.Options) string { + caller, _ := opts.Metadata[cliproxyexecutor.CallerScopeMetadataKey].(string) + if caller == "" { + caller, _ = req.Metadata[cliproxyexecutor.CallerScopeMetadataKey].(string) + } + caller = strings.TrimSpace(caller) + if caller == "" || len(caller) > 256 { + return "" + } + var sessionID string + for name, values := range opts.Headers { + if !strings.EqualFold(name, "Session-Id") && !strings.EqualFold(name, "Session_id") && !strings.EqualFold(name, "X-Session-Id") { + continue + } + for _, value := range values { + id := session.NormalizeExplicitID(value) + if id == "" || (sessionID != "" && id != sessionID) { + return "" + } + sessionID = id + } + } + if sessionID == "" { + return "" + } + return "cpa:codex:session-instructions:v1:" + kvstore.HashKeyPart(caller) + ":" + kvstore.HashKeyPart(sessionID) +} + +func CodexSessionInstructionErrorStatus(err error) int { + var sessionErr *codexSessionInstructionError + if errors.As(err, &sessionErr) { + return sessionErr.status + } + return 0 +} + +func HasCodexSessionInstructionMarker(doc *ojson.Doc, from sdktranslator.Format) bool { + return doc != nil && from == sdktranslator.FormatOpenAIResponse && doc.Get(codexSessionInstructionPath).Exists() +} + +func codexSessionMarker(root ojson.Result) (marker ojson.Result, ambiguous bool) { + metadataCount, markerCount := 0, 0 + root.ForEach(func(key, value ojson.Result) bool { + if key.String() == "client_metadata" { + metadataCount++ + if value.IsObject() { + value.ForEach(func(k, v ojson.Result) bool { + if k.String() == codexSessionInstructionMarker { + marker, markerCount = v, markerCount+1 + } + return true + }) + } + } + return true + }) + return marker, markerCount > 1 || (markerCount > 0 && metadataCount > 1) +} + +// StripCodexSessionInstructionMarker is also used for control and summary frames, +// which may never read or create a session baseline. +func StripCodexSessionInstructionMarker(doc *ojson.Doc, from sdktranslator.Format) { + if HasCodexSessionInstructionMarker(doc, from) { + _ = doc.Delete(codexSessionInstructionPath) + } +} + +func ValidateCodexSessionInstructionMarker(body []byte, from sdktranslator.Format) error { + if from == sdktranslator.FormatOpenAIResponse && ojson.GetBytesNoCopy(body, "client_metadata").Exists() { + if marker, _ := codexSessionMarker(ojson.GetBytesNoCopy(body, "@this")); marker.Exists() { + return &codexSessionInstructionError{http.StatusBadRequest, "outbound payload contains the reserved session instructions marker"} + } + } + return nil +} + +func codexInstructionFieldsUnique(root ojson.Result, fields ...string) bool { + var seen uint32 + unique := true + root.ForEach(func(key, _ ojson.Result) bool { + for i, field := range fields { + if key.String() == field { + bit := uint32(1) << i + if seen&bit != 0 { + unique = false + return false + } + seen |= bit + break + } + } + return true + }) + return unique +} + +// PrepareCodexSessionInstructions runs after built-in payload transformations and +// before payload rules. A nil chain means the consumer has no upstream WS proof. +func PrepareCodexSessionInstructions(ctx context.Context, doc *ojson.Doc, req cliproxyexecutor.Request, opts cliproxyexecutor.Options, chain *CodexInstructionChain, conn *websocket.Conn, summary bool) (CodexInstructionTurn, error) { + var turn CodexInstructionTurn + if opts.SourceFormat != sdktranslator.FormatOpenAIResponse { + return turn, nil + } + StripCodexSessionInstructionMarker(doc, opts.SourceFormat) + if summary { + return turn, nil + } + raw := ojson.GetBytesNoCopy(req.Payload, "@this") + var marker ojson.Result + if raw.Get("client_metadata").Exists() { + var ambiguous bool + marker, ambiguous = codexSessionMarker(raw) + if ambiguous { + return turn, codexSessionInstructionPayload() + } + } + mode := marker.String() + if marker.Exists() && (marker.Type != ojson.String || (mode != "start" && mode != "reuse")) { + return turn, &codexSessionInstructionError{http.StatusBadRequest, "cpa_session_instructions must be start or reuse"} + } + armed, last := chain.parent(conn) + if mode == "" && !armed { + return turn, nil + } + kind := strings.TrimSpace(raw.Get("type").String()) + if (kind != "" && kind != "response.create" && kind != "response.append") || + !codexInstructionFieldsUnique(raw, "type", "previous_response_id", "instructions", "input") { + return turn, codexSessionInstructionPayload() + } + parent := strings.TrimSpace(raw.Get("previous_response_id").String()) + incremental := parent != "" || kind == "response.append" + if !incremental && len(opts.OriginalRequest) > 0 { + original := ojson.GetBytesNoCopy(opts.OriginalRequest, "@this") + if strings.TrimSpace(original.Get("previous_response_id").String()) != "" || strings.TrimSpace(original.Get("type").String()) == "response.append" { + return turn, codexSessionInstructionsReplay() + } + } + turn.key = codexInstructionKey(req, opts) + turn.checkParent = true + if incremental { + // An implicit append can only target the last proven response on this socket. + if parent == "" { + parent = last.id + } + if parent == "" || parent != last.id || turn.key != last.key || (last.managed && last.digest == "") || (mode != "" && !last.managed) { + return turn, codexSessionInstructionsReplay() + } + turn.parent, turn.conn = parent, conn + if doc.Get("previous_response_id").String() != parent { + _ = doc.Set("previous_response_id", parent) + } + if last.managed { + mode = "reuse" + } + } + if mode == "" { + return turn, nil + } + if turn.key == "" { + return turn, &codexSessionInstructionError{http.StatusBadRequest, "session instructions require an authenticated caller and an explicit session ID header"} + } + turn.managed = true + value := raw.Get("instructions") + if inherited := cliproxyexecutor.InheritedWebsocketInstructions(ctx); inherited != "" && value.Raw == inherited { + value = ojson.Result{} + } + if value.Exists() && value.Type != ojson.Null && (value.Type != ojson.String || len(value.String()) > codexSessionInstructionMaxBytes) { + return turn, &codexSessionInstructionError{http.StatusBadRequest, "instructions must be a string of at most 32 KiB or null in session instructions mode"} + } + current := "" + if value.Type == ojson.String { + current = value.String() + } + if !incremental { + input := doc.Get("input") + if input.Exists() && !input.IsArray() { + return turn, &codexSessionInstructionError{http.StatusBadRequest, "session instructions require Responses string or array input"} + } + } + candidate := "" + if mode == "start" && !incremental { + candidate = current + } + baseline, errLoad := codexSessionInstructions.load(ctx, turn.key, candidate) + if errLoad != nil { + if mode == "start" && candidate == "" && errors.Is(errLoad, errCodexSessionInstructionMissing) { + return turn, errCodexSessionInstructionStart + } + return turn, errLoad + } + turn.digest = kvstore.HashKeyPart(baseline) + if incremental && last.digest != turn.digest { + return turn, codexSessionInstructionsReplay() + } + if current == baseline { + current = "" + } + if errSet := doc.Set("instructions", current); errSet != nil { + return turn, codexSessionInstructionPayload() + } + if !incremental && !codexSessionInstructionPrefix(doc.Get("input.0"), turn.digest) { + prefix := ojson.NewDocString(`[{"type":"message","role":"developer","content":[{"type":"input_text","text":""}]}]`) + _ = prefix.Set("0.content.0.text", baseline) + input := doc.Get("input") + merged := prefix.String() + if input.Get("#").Int() > 0 { + merged = merged[:len(merged)-1] + "," + input.Raw[1:] + } + if errSet := doc.SetRaw("input", merged); errSet != nil { + return turn, codexSessionInstructionPayload() + } + } + return turn, nil +} + +func codexSessionInstructionPayload() error { + return &codexSessionInstructionError{http.StatusBadRequest, "invalid session instructions payload"} +} + +func codexSessionInstructionsReplay() error { + return &cliproxyexecutor.UpstreamWebsocketTurnError{FullContextRequired: true} +} + +func codexSessionInstructionPrefix(item ojson.Result, digest string) bool { + if !codexInstructionFieldsUnique(item, "type", "role", "content") { + return false + } + typ := item.Get("type") + if (typ.Exists() && typ.String() != "message") || item.Get("role").String() != "developer" { + return false + } + text := item.Get("content") + if text.IsArray() { + if text.Get("#").Int() != 1 || text.Get("0.type").String() != "input_text" || + !codexInstructionFieldsUnique(text.Get("0"), "type", "text") { + return false + } + text = text.Get("0.text") + } + return text.Type == ojson.String && kvstore.HashKeyPart(text.String()) == digest +} + +// CodexInstructionTurn carries only proof metadata, never baseline text. +type CodexInstructionTurn struct { + key, digest, parent string + conn *websocket.Conn + managed, checkParent bool +} + +// CheckFinal observes actual configured business fields without rewriting them. +func (t *CodexInstructionTurn) CheckFinal(body []byte) error { + if !t.checkParent { + return nil + } + root := ojson.GetBytesNoCopy(body, "@this") + if !codexInstructionFieldsUnique(root, "previous_response_id", "input", "type", "instructions") || + root.Get("previous_response_id").String() != t.parent { + return codexSessionInstructionsReplay() + } + if t.managed && t.parent == "" && !codexSessionInstructionPrefix(root.Get("input.0"), t.digest) { + t.digest = "" + } + return nil +} + +func (t CodexInstructionTurn) ConnectionBound() bool { return t.conn != nil } + +func (t CodexInstructionTurn) OnConnection(conn *websocket.Conn) error { + if t.conn != nil && t.conn != conn { + return codexSessionInstructionsReplay() + } + return nil +} + +// LogBody keeps restored baseline text out of upstream request diagnostics. +func (t CodexInstructionTurn) LogBody(body []byte) []byte { + if t.managed { + return nil + } + return body +} + +func (t CodexInstructionTurn) Managed() bool { return t.managed } + +func (t CodexInstructionTurn) AllowsControl(body []byte, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) bool { + return codexInstructionFieldsUnique(ojson.GetBytesNoCopy(body, "@this"), "type", "previous_response_id") && + (!t.managed || (t.key != "" && t.key == codexInstructionKey(req, opts))) +} + +// CodexInstructionChain retains only the most recent reliably correlated success. +// Once a managed frame is sent, unmarked deltas cannot bypass verification by +// changing scope, targeting an old ID, or switching physical connections. +type CodexInstructionChain struct { + mu sync.Mutex + armed bool + serial uint64 + last codexInstructionParent +} + +type codexInstructionParent struct { + conn *websocket.Conn + id, key, digest string + managed bool +} + +func (c *CodexInstructionChain) parent(conn *websocket.Conn) (bool, codexInstructionParent) { + if c == nil { + return false, codexInstructionParent{} + } + c.mu.Lock() + defer c.mu.Unlock() + if conn == nil || c.last.conn != conn { + return c.armed, codexInstructionParent{} + } + return c.armed, c.last +} + +func (c *CodexInstructionChain) Armed() bool { + armed, _ := c.parent(nil) + return armed +} + +// Sent forgets the previous proof as another turn takes its place. The serial +// prevents a late completion from winning over a more recently submitted turn. +func (c *CodexInstructionChain) Sent(conn *websocket.Conn, turn CodexInstructionTurn) CodexInstructionReceipt { + c.mu.Lock() + defer c.mu.Unlock() + if !c.armed && !turn.managed { + return CodexInstructionReceipt{} + } + c.armed = true + c.serial++ + c.last = codexInstructionParent{} + return CodexInstructionReceipt{chain: c, serial: c.serial, sent: codexInstructionParent{conn: conn, key: turn.key, digest: turn.digest, managed: turn.managed}, parent: turn.parent} +} + +type CodexInstructionReceipt struct { + chain *CodexInstructionChain + serial uint64 + sent codexInstructionParent + parent string + invalid bool +} + +func (r *CodexInstructionReceipt) Observe(payload []byte) { + if r.chain == nil || r.invalid { + return + } + kind := CodexResponseEventType(payload) + switch kind { + case "response.created": + id := ojson.GetBytesNoCopy(payload, "response.id") + if r.sent.id != "" || id.Type != ojson.String || id.String() == "" || len(id.String()) > 256 || !r.matchesParent(payload) { + r.invalid = true + return + } + r.sent.id = strings.Clone(id.String()) + case "response.completed", "response.done": + id := ojson.GetBytesNoCopy(payload, "response.id") + if r.sent.id == "" || id.Type != ojson.String || r.sent.id != id.String() || !r.matchesParent(payload) { + return + } + status := ojson.GetBytesNoCopy(payload, "response.status").String() + if status != "" && status != "completed" { + return + } + r.chain.mu.Lock() + if r.chain.serial == r.serial { + r.chain.last = r.sent + } + r.chain.mu.Unlock() + } +} + +func (r *CodexInstructionReceipt) matchesParent(payload []byte) bool { + echo := ojson.GetBytesNoCopy(payload, "response.previous_response_id") + return !echo.Exists() || echo.String() == r.parent +} diff --git a/internal/runtime/executor/helps/codex_session_instructions_test.go b/internal/runtime/executor/helps/codex_session_instructions_test.go new file mode 100644 index 0000000000..e51d4a1354 --- /dev/null +++ b/internal/runtime/executor/helps/codex_session_instructions_test.go @@ -0,0 +1,105 @@ +package helps + +import ( + "context" + "errors" + "fmt" + "sync" + "testing" + "time" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/kvstore" +) + +type sessionInstructionTestKV struct { + kvstore.KVClient + mu sync.Mutex + values map[string][]byte + gets, writes int + ttl time.Duration + err error +} + +func (kv *sessionInstructionTestKV) KVGet(_ context.Context, key string) ([]byte, bool, error) { + kv.mu.Lock() + defer kv.mu.Unlock() + kv.gets++ + value, ok := kv.values[key] + return value, ok, kv.err +} + +func (kv *sessionInstructionTestKV) KVSetNX(_ context.Context, key string, value []byte, ttl time.Duration) (bool, error) { + kv.mu.Lock() + defer kv.mu.Unlock() + kv.writes++ + kv.ttl = ttl + if kv.err != nil { + return false, kv.err + } + if _, ok := kv.values[key]; ok { + return false, nil + } + kv.values[key] = value + return true, nil +} + +func TestCodexSessionInstructionStore(t *testing.T) { + now := time.Unix(12345, 0) + kv := &sessionInstructionTestKV{values: make(map[string][]byte)} + mode := false + store := codexSessionInstructionStore{ + now: func() time.Time { return now }, + current: func() (kvstore.KVClient, bool, error) { return kv, mode, nil }, + } + const key = "session" + load := func(candidate string) (string, error) { return store.load(t.Context(), key, candidate) } + if got, err := load(" A "); err != nil || got != " A " { + t.Fatalf("start: %q %v", got, err) + } + now = now.Add(23 * time.Hour) + if got, err := load("B"); err != nil || got != " A " { + t.Fatalf("fixed baseline: %q %v", got, err) + } + now = now.Add(time.Hour) + if got, err := load(""); got != "" || !errors.Is(err, errCodexSessionInstructionMissing) { + t.Fatalf("expired reuse: %q %v", got, err) + } + if got, err := load("B"); err != nil || got != "B" { + t.Fatalf("new start: %q %v", got, err) + } + mode = true + kv.err = errors.New("sensitive error") + if got, err := load(""); got != "" || !errors.Is(err, errCodexSessionInstructionStore) { + t.Fatalf("enabled KV failure fell back to memory: %q %v", got, err) + } + if got, err := load("candidate"); got != "" || !errors.Is(err, errCodexSessionInstructionStore) { + t.Fatalf("failed SET NX fell back to memory: %q %v", got, err) + } + kv.err = nil + if got, err := load(""); got != "" || !errors.Is(err, errCodexSessionInstructionMissing) || kv.writes != 1 { + t.Fatalf("reuse wrote or fell back to memory: %q %v", got, err) + } + const workers = 20 + var wg sync.WaitGroup + results := make(chan string, workers) + for i := 0; i < workers; i++ { + wg.Go(func() { + got, err := load(fmt.Sprint(i)) + if err != nil { + t.Error(err) + } + results <- got + }) + } + wg.Wait() + close(results) + winner := string(kv.values[key]) + for got := range results { + if got == "" || got != winner { + t.Errorf("concurrent start got %q, want winner %q", got, winner) + } + } + if kv.writes != workers+1 || kv.ttl != 24*time.Hour { + t.Fatalf("SET NX count=%d ttl=%v", kv.writes, kv.ttl) + } +} diff --git a/sdk/api/handlers/openai/openai_responses_websocket.go b/sdk/api/handlers/openai/openai_responses_websocket.go index c798aa253e..9fad03913b 100644 --- a/sdk/api/handlers/openai/openai_responses_websocket.go +++ b/sdk/api/handlers/openai/openai_responses_websocket.go @@ -1029,6 +1029,11 @@ func (h *OpenAIResponsesAPIHandler) ResponsesWebsocket(c *gin.Context) { var cliCancel handlers.APIHandlerCancelFunc cliCtx, cliCancel = h.GetContextWithCancel(h, c, turnExecutionParent) cliCtx = cliproxyexecutor.WithDownstreamWebsocket(cliCtx) + if !nativeWebsocketPassthrough && !ojson.GetBytesNoCopy(payload, "instructions").Exists() { + if inherited := ojson.GetBytesNoCopy(requestJSON, "instructions"); inherited.Exists() { + cliCtx = cliproxyexecutor.WithInheritedWebsocketInstructions(cliCtx, strings.Clone(inherited.Raw)) + } + } cliCtx = cliproxyexecutor.WithLocalWebsocketTurnTracker(cliCtx) cliCtx = cliproxyexecutor.WithWebsocketInputEpoch(cliCtx, &inputEpoch, msgEpoch) if duplexInput != nil { diff --git a/sdk/cliproxy/executor/websocket.go b/sdk/cliproxy/executor/websocket.go index 4c1f084d15..31ee3ec56f 100644 --- a/sdk/cliproxy/executor/websocket.go +++ b/sdk/cliproxy/executor/websocket.go @@ -72,6 +72,20 @@ func IsUpstreamWebsocketTurnError(err error) bool { return errors.As(err, &turnErr) } +type inheritedWebsocketInstructionsKey struct{} + +// WithInheritedWebsocketInstructions distinguishes legacy transcript inheritance +// from instructions supplied by the current frame. Only opt-in consumers use it. +func WithInheritedWebsocketInstructions(ctx context.Context, raw string) context.Context { + return context.WithValue(ctx, inheritedWebsocketInstructionsKey{}, raw) +} + +// InheritedWebsocketInstructions returns the JSON value added by transcript rebuilding. +func InheritedWebsocketInstructions(ctx context.Context) string { + raw, _ := ctx.Value(inheritedWebsocketInstructionsKey{}).(string) + return raw +} + type websocketInputLossState struct { epoch *atomic.Uint64 messageEpoch uint64