feat(plugin): add optional executor usage attribution

This commit is contained in:
sususu98
2026-11-17 17:56:16 +08:00
parent 593df3274c
commit 687caf786b
15 changed files with 627 additions and 42 deletions

View File

@@ -229,6 +229,15 @@ func (h *delegatedInterceptorHost) ExecutePluginExecutor(ctx context.Context, pl
return h.pluginHost.ExecutePluginExecutor(ctx, pluginID, req, opts)
}
// ExecutePluginExecutorWithAttribution delegates direct plugin-executor
// dispatch and returns optional plugin usage attribution.
func (h *delegatedInterceptorHost) ExecutePluginExecutorWithAttribution(ctx context.Context, pluginID string, req coreexecutor.Request, opts coreexecutor.Options) (coreexecutor.Response, *pluginapi.UsageAttribution, error) {
if h.pluginHost == nil {
return coreexecutor.Response{}, nil, fmt.Errorf("plugin executor host is unavailable")
}
return h.pluginHost.ExecutePluginExecutorWithAttribution(ctx, pluginID, req, opts)
}
// ExecutePluginExecutorStream delegates streaming plugin-executor dispatch.
func (h *delegatedInterceptorHost) ExecutePluginExecutorStream(ctx context.Context, pluginID string, req coreexecutor.Request, opts coreexecutor.Options) (*coreexecutor.StreamResult, error) {
if h.pluginHost == nil {
@@ -237,6 +246,15 @@ func (h *delegatedInterceptorHost) ExecutePluginExecutorStream(ctx context.Conte
return h.pluginHost.ExecutePluginExecutorStream(ctx, pluginID, req, opts)
}
// ExecutePluginExecutorStreamWithAttribution delegates streaming plugin-executor
// dispatch and returns optional plugin usage attribution.
func (h *delegatedInterceptorHost) ExecutePluginExecutorStreamWithAttribution(ctx context.Context, pluginID string, req coreexecutor.Request, opts coreexecutor.Options) (*coreexecutor.StreamResult, *pluginapi.UsageAttribution, error) {
if h.pluginHost == nil {
return nil, nil, fmt.Errorf("plugin executor host is unavailable")
}
return h.pluginHost.ExecutePluginExecutorStreamWithAttribution(ctx, pluginID, req, opts)
}
// CountPluginExecutor delegates token counting to the internal plugin host.
func (h *delegatedInterceptorHost) CountPluginExecutor(ctx context.Context, pluginID string, req coreexecutor.Request, opts coreexecutor.Options) (coreexecutor.Response, error) {
if h.pluginHost == nil {

View File

@@ -298,12 +298,24 @@ func TestDelegatedInterceptorHostImplementsPluginExecutorHost(t *testing.T) {
if !ok || executorHost == nil {
t.Fatal("delegated host does not implement PluginExecutorHost; plugin executor routes would 502")
}
if _, okAttr := any(wrapped).(interface {
ExecutePluginExecutorWithAttribution(context.Context, string, coreexecutor.Request, coreexecutor.Options) (coreexecutor.Response, *pluginapi.UsageAttribution, error)
ExecutePluginExecutorStreamWithAttribution(context.Context, string, coreexecutor.Request, coreexecutor.Options) (*coreexecutor.StreamResult, *pluginapi.UsageAttribution, error)
}); !okAttr {
t.Fatal("delegated host does not expose plugin executor attribution methods")
}
// Nil-pluginHost delegates must return an explicit unavailable error rather
// than panic, matching the handler's unavailable-host contract.
safeWrapped := &delegatedInterceptorHost{primary: custom, pluginHost: nil}
if _, err := safeWrapped.ExecutePluginExecutor(context.Background(), "p", coreexecutor.Request{}, coreexecutor.Options{}); err == nil {
t.Fatal("ExecutePluginExecutor with nil plugin host = nil error, want unavailable")
}
if _, _, err := safeWrapped.ExecutePluginExecutorWithAttribution(context.Background(), "p", coreexecutor.Request{}, coreexecutor.Options{}); err == nil {
t.Fatal("ExecutePluginExecutorWithAttribution with nil plugin host = nil error, want unavailable")
}
if _, _, err := safeWrapped.ExecutePluginExecutorStreamWithAttribution(context.Background(), "p", coreexecutor.Request{}, coreexecutor.Options{}); err == nil {
t.Fatal("ExecutePluginExecutorStreamWithAttribution with nil plugin host = nil error, want unavailable")
}
}
// TestDelegatedInterceptorHostNilPluginHostIsSafe ensures the delegated host is

View File

@@ -284,14 +284,15 @@ func newExecutorAdapterRegistration(h *Host, record capabilityRecord, provider s
return executorRegistration{
provider: provider,
adapter: &executorAdapter{
host: h,
pluginID: record.id,
path: record.path,
version: record.version,
provider: provider,
executor: executor,
inputFormats: normalizeExecutorFormats(record.plugin.Capabilities.ExecutorInputFormats),
outputFormats: normalizeExecutorFormats(record.plugin.Capabilities.ExecutorOutputFormats),
host: h,
pluginID: record.id,
path: record.path,
version: record.version,
provider: provider,
usageExecutorType: helps.PluginExecutorType(record.id),
executor: executor,
inputFormats: normalizeExecutorFormats(record.plugin.Capabilities.ExecutorInputFormats),
outputFormats: normalizeExecutorFormats(record.plugin.Capabilities.ExecutorOutputFormats),
},
}
}
@@ -569,14 +570,15 @@ func (h *Host) modelProvidersForPlugin(pluginID string) []string {
}
type executorAdapter struct {
host *Host
pluginID string
path string
version string
provider string
executor pluginapi.ProviderExecutor
inputFormats []sdktranslator.Format
outputFormats []sdktranslator.Format
host *Host
pluginID string
path string
version string
provider string
usageExecutorType string
executor pluginapi.ProviderExecutor
inputFormats []sdktranslator.Format
outputFormats []sdktranslator.Format
}
func (a *executorAdapter) Identifier() string {
@@ -586,6 +588,16 @@ func (a *executorAdapter) Identifier() string {
return a.provider
}
func (a *executorAdapter) UsageExecutorType() string {
if a == nil {
return ""
}
if a.usageExecutorType != "" {
return a.usageExecutorType
}
return helps.PluginExecutorType(a.pluginID)
}
type preparedExecutorCall struct {
req coreexecutor.Request
opts coreexecutor.Options
@@ -982,9 +994,14 @@ func sendExecutorPluginStreamChunk(ctx context.Context, out chan<- pluginapi.Exe
}
}
func (a *executorAdapter) Execute(ctx context.Context, auth *coreauth.Auth, req coreexecutor.Request, opts coreexecutor.Options) (resp coreexecutor.Response, err error) {
func (a *executorAdapter) Execute(ctx context.Context, auth *coreauth.Auth, req coreexecutor.Request, opts coreexecutor.Options) (coreexecutor.Response, error) {
resp, _, err := a.executeWithAttribution(ctx, auth, req, opts)
return resp, err
}
func (a *executorAdapter) executeWithAttribution(ctx context.Context, auth *coreauth.Auth, req coreexecutor.Request, opts coreexecutor.Options) (resp coreexecutor.Response, attribution *pluginapi.UsageAttribution, err error) {
if a == nil || a.executor == nil || a.host.isPluginFused(a.pluginID) || !a.host.pluginIdentityCurrent(a.pluginID, a.path, a.version) {
return coreexecutor.Response{}, fmt.Errorf("plugin executor %s is unavailable", a.Identifier())
return coreexecutor.Response{}, nil, fmt.Errorf("plugin executor %s is unavailable", a.Identifier())
}
var reporter *helps.UsageReporter
@@ -1000,6 +1017,7 @@ func (a *executorAdapter) Execute(ctx context.Context, auth *coreauth.Auth, req
if recovered := recover(); recovered != nil {
a.host.fusePlugin(a.pluginID, "Executor.Execute", recovered)
resp = coreexecutor.Response{}
attribution = nil
err = fmt.Errorf("plugin executor %s panic: %v", a.Identifier(), recovered)
if reporter != nil {
reporter.PublishFailure(ctx, err)
@@ -1013,7 +1031,7 @@ func (a *executorAdapter) Execute(ctx context.Context, auth *coreauth.Auth, req
prepared, errPrepare := a.prepareExecutorCall(req, opts)
if errPrepare != nil {
return coreexecutor.Response{}, errPrepare
return coreexecutor.Response{}, nil, errPrepare
}
if reporter != nil {
@@ -1023,10 +1041,11 @@ func (a *executorAdapter) Execute(ctx context.Context, auth *coreauth.Auth, req
pluginResp, errExecute := a.executor.Execute(ctx, buildExecutorRequest(a.host, a.provider, auth, prepared.req, prepared.opts))
if errExecute != nil {
return coreexecutor.Response{}, errExecute
return coreexecutor.Response{}, nil, errExecute
}
if reporter != nil {
reporter.ApplyPluginExecutorAttribution(a.pluginID, pluginResp.Attribution)
reporter.RecordFirstPacket()
detail := helps.ParsePluginExecutorResponseUsage(prepared.outputFormat.String(), pluginResp.Payload)
reporter.Publish(ctx, detail)
@@ -1037,12 +1056,17 @@ func (a *executorAdapter) Execute(ctx context.Context, auth *coreauth.Auth, req
Payload: a.translateExecutorResponse(ctx, prepared, pluginResp.Payload, false, nil),
Metadata: cloneAnyMap(pluginResp.Metadata),
Headers: cloneHeader(pluginResp.Headers),
}, nil
}, pluginResp.Attribution, nil
}
func (a *executorAdapter) ExecuteStream(ctx context.Context, auth *coreauth.Auth, req coreexecutor.Request, opts coreexecutor.Options) (result *coreexecutor.StreamResult, err error) {
func (a *executorAdapter) ExecuteStream(ctx context.Context, auth *coreauth.Auth, req coreexecutor.Request, opts coreexecutor.Options) (*coreexecutor.StreamResult, error) {
result, _, err := a.executeStreamWithAttribution(ctx, auth, req, opts)
return result, err
}
func (a *executorAdapter) executeStreamWithAttribution(ctx context.Context, auth *coreauth.Auth, req coreexecutor.Request, opts coreexecutor.Options) (result *coreexecutor.StreamResult, attribution *pluginapi.UsageAttribution, err error) {
if a == nil || a.executor == nil || a.host.isPluginFused(a.pluginID) || !a.host.pluginIdentityCurrent(a.pluginID, a.path, a.version) {
return nil, fmt.Errorf("plugin executor %s is unavailable", a.Identifier())
return nil, nil, fmt.Errorf("plugin executor %s is unavailable", a.Identifier())
}
var reporter *helps.UsageReporter
@@ -1058,6 +1082,7 @@ func (a *executorAdapter) ExecuteStream(ctx context.Context, auth *coreauth.Auth
if recovered := recover(); recovered != nil {
a.host.fusePlugin(a.pluginID, "Executor.ExecuteStream", recovered)
result = nil
attribution = nil
err = fmt.Errorf("plugin executor %s stream panic: %v", a.Identifier(), recovered)
if reporter != nil {
reporter.PublishFailure(ctx, err)
@@ -1071,7 +1096,7 @@ func (a *executorAdapter) ExecuteStream(ctx context.Context, auth *coreauth.Auth
prepared, errPrepare := a.prepareExecutorCall(req, opts)
if errPrepare != nil {
return nil, errPrepare
return nil, nil, errPrepare
}
if reporter != nil {
@@ -1081,14 +1106,17 @@ func (a *executorAdapter) ExecuteStream(ctx context.Context, auth *coreauth.Auth
pluginResp, errExecuteStream := a.executor.ExecuteStream(ctx, buildExecutorRequest(a.host, a.provider, auth, prepared.req, prepared.opts))
if errExecuteStream != nil {
return nil, errExecuteStream
return nil, nil, errExecuteStream
}
if reporter != nil {
reporter.ApplyPluginExecutorAttribution(a.pluginID, pluginResp.Attribution)
}
chunks := a.observeAndTranslateExecutorStream(ctx, prepared, pluginResp.Chunks, reporter)
return &coreexecutor.StreamResult{
Headers: cloneHeader(pluginResp.Headers),
Chunks: chunks,
}, nil
}, pluginResp.Attribution, nil
}
func (a *executorAdapter) observeAndTranslateExecutorStream(ctx context.Context, prepared preparedExecutorCall, in <-chan pluginapi.ExecutorStreamChunk, reporter *helps.UsageReporter) <-chan coreexecutor.StreamChunk {

View File

@@ -1308,3 +1308,118 @@ func waitPluginUsageRecord(t *testing.T, ch <-chan pluginapi.UsageRecord) plugin
return pluginapi.UsageRecord{}
}
}
func TestExecutorAdapterPropagatesAttributionAndPluginExecutorType(t *testing.T) {
plugin := newTestUsageCapturePlugin("")
registerTestUsagePlugin(t, "test-executor-adapter-plugin-type", plugin)
executorRecord := normalizeTestCapabilityRecord(capabilityRecord{id: "custom-plugin-id"})
host := newHostWithRecords(executorRecord)
exec := &fakeExecutor{
identifier: "plugin-provider",
execute: func(ctx context.Context, req pluginapi.ExecutorRequest) (pluginapi.ExecutorResponse, error) {
return pluginapi.ExecutorResponse{
Payload: []byte(`{"id":"chatcmpl-1","choices":[{"message":{"role":"assistant","content":"ok"}}],"usage":{"prompt_tokens":1,"completion_tokens":2,"total_tokens":3}}`),
Metadata: map[string]any{"k": "v"},
Attribution: &pluginapi.UsageAttribution{
AuthIndex: " idx-1 ",
AuthType: " oauth ",
Source: " acct@example.com ",
},
}, nil
},
executeStream: func(ctx context.Context, req pluginapi.ExecutorRequest) (pluginapi.ExecutorStreamResponse, error) {
ch := make(chan pluginapi.ExecutorStreamChunk, 1)
ch <- pluginapi.ExecutorStreamChunk{Payload: []byte("data: [DONE]\n\n")}
close(ch)
return pluginapi.ExecutorStreamResponse{
Headers: http.Header{"Content-Type": []string{"text/event-stream"}},
Attribution: &pluginapi.UsageAttribution{
AuthIndex: "idx-stream",
AuthType: "api_key",
Source: "stream-acct",
},
Chunks: ch,
}, nil
},
}
executorRecord.plugin.Capabilities.Executor = exec
executorRecord.plugin.Capabilities.ExecutorInputFormats = []string{"openai"}
executorRecord.plugin.Capabilities.ExecutorOutputFormats = []string{"openai"}
host = newHostWithRecords(executorRecord)
adapter := newExecutorAdapterForRecordForTest(host, executorRecord, exec,
[]sdktranslator.Format{sdktranslator.FormatOpenAI},
[]sdktranslator.Format{sdktranslator.FormatOpenAI},
)
req := coreexecutor.Request{
Model: "test-model",
Payload: []byte(`{"model":"test-model","messages":[{"role":"user","content":"hi"}]}`),
}
opts := coreexecutor.Options{
SourceFormat: sdktranslator.FormatOpenAI,
ResponseFormat: sdktranslator.FormatOpenAI,
}
_, attr, errExec := host.ExecutePluginExecutorWithAttribution(context.Background(), "custom-plugin-id", req, opts)
if errExec != nil {
t.Fatalf("ExecutePluginExecutorWithAttribution error = %v", errExec)
}
if attr == nil ||
attr.AuthIndex != " idx-1 " ||
attr.AuthType != " oauth " ||
attr.Source != " acct@example.com " {
t.Fatalf("attr = %+v", attr)
}
streamRes, streamAttr, errStream := host.ExecutePluginExecutorStreamWithAttribution(context.Background(), "custom-plugin-id", req, opts)
if errStream != nil {
t.Fatalf("ExecutePluginExecutorStreamWithAttribution error = %v", errStream)
}
if streamAttr == nil ||
streamAttr.AuthIndex != "idx-stream" ||
streamAttr.AuthType != "api_key" ||
streamAttr.Source != "stream-acct" {
t.Fatalf("streamAttr = %+v", streamAttr)
}
for range streamRes.Chunks {
}
// Verify auth-backed executions report "plugin:<id>", preserve auth credentials, and apply source attribution.
auth := &coreauth.Auth{
ID: "auth-1",
Provider: "plugin-provider",
FileName: "auth-1.json",
Attributes: map[string]string{coreauth.AttributeAuthKind: "oauth"},
}
if _, errAuthExec := adapter.Execute(context.Background(), auth, req, opts); errAuthExec != nil {
t.Fatalf("Execute(auth!=nil) error = %v", errAuthExec)
}
rec := plugin.waitRecord(t, 2*time.Second)
if rec.ExecutorType != "plugin:custom-plugin-id" ||
rec.Provider != "plugin-provider" ||
rec.AuthID != "auth-1" ||
rec.AuthIndex != auth.EnsureIndex() ||
rec.AuthType != "oauth" ||
rec.Source != "acct@example.com" {
t.Fatalf("auth-backed Execute rec = %+v", rec)
}
authStreamRes, errAuthStream := adapter.ExecuteStream(context.Background(), auth, req, opts)
if errAuthStream != nil {
t.Fatalf("ExecuteStream(auth!=nil) error = %v", errAuthStream)
}
for range authStreamRes.Chunks {
}
streamRec := plugin.waitRecord(t, 2*time.Second)
if streamRec.ExecutorType != "plugin:custom-plugin-id" ||
streamRec.Provider != "plugin-provider" ||
streamRec.AuthID != "auth-1" ||
streamRec.AuthIndex != auth.EnsureIndex() ||
streamRec.AuthType != "oauth" ||
streamRec.Source != "stream-acct" {
t.Fatalf("auth-backed ExecuteStream rec = %+v", streamRec)
}
}

View File

@@ -84,20 +84,32 @@ func (h *Host) PluginExecutorRequestToFormat(pluginID string, req coreexecutor.R
// ExecutePluginExecutor executes a request with the named plugin executor without changing the requested model.
func (h *Host) ExecutePluginExecutor(ctx context.Context, pluginID string, req coreexecutor.Request, opts coreexecutor.Options) (coreexecutor.Response, error) {
resp, _, err := h.ExecutePluginExecutorWithAttribution(ctx, pluginID, req, opts)
return resp, err
}
// ExecutePluginExecutorWithAttribution executes a request with the named plugin executor and returns optional plugin attribution.
func (h *Host) ExecutePluginExecutorWithAttribution(ctx context.Context, pluginID string, req coreexecutor.Request, opts coreexecutor.Options) (coreexecutor.Response, *pluginapi.UsageAttribution, error) {
adapter, errAdapter := h.executorAdapterForPlugin(pluginID)
if errAdapter != nil {
return coreexecutor.Response{}, errAdapter
return coreexecutor.Response{}, nil, errAdapter
}
return adapter.Execute(ctx, (*coreauth.Auth)(nil), req, opts)
return adapter.executeWithAttribution(ctx, (*coreauth.Auth)(nil), req, opts)
}
// ExecutePluginExecutorStream executes a streaming request with the named plugin executor without changing the requested model.
func (h *Host) ExecutePluginExecutorStream(ctx context.Context, pluginID string, req coreexecutor.Request, opts coreexecutor.Options) (*coreexecutor.StreamResult, error) {
result, _, err := h.ExecutePluginExecutorStreamWithAttribution(ctx, pluginID, req, opts)
return result, err
}
// ExecutePluginExecutorStreamWithAttribution executes a streaming request with the named plugin executor and returns optional plugin attribution.
func (h *Host) ExecutePluginExecutorStreamWithAttribution(ctx context.Context, pluginID string, req coreexecutor.Request, opts coreexecutor.Options) (*coreexecutor.StreamResult, *pluginapi.UsageAttribution, error) {
adapter, errAdapter := h.executorAdapterForPlugin(pluginID)
if errAdapter != nil {
return nil, errAdapter
return nil, nil, errAdapter
}
return adapter.ExecuteStream(ctx, (*coreauth.Auth)(nil), req, opts)
return adapter.executeStreamWithAttribution(ctx, (*coreauth.Auth)(nil), req, opts)
}
// CountPluginExecutor executes a count-tokens request with the named plugin executor without changing the requested model.

View File

@@ -33,12 +33,17 @@ func (a *rpcPluginAdapter) ExecuteStream(ctx context.Context, req pluginapi.Exec
out <- chunk
}
close(out)
return pluginapi.ExecutorStreamResponse{Headers: resp.Headers, Chunks: out}, nil
return pluginapi.ExecutorStreamResponse{
Headers: resp.Headers,
Chunks: out,
Attribution: resp.Attribution,
}, nil
}
// Async streaming plugins can return before they finish emitting chunks, so keep callbacks alive until the stream ends.
return pluginapi.ExecutorStreamResponse{
Headers: resp.Headers,
Chunks: cleanupWhenStreamDone(ctx, chunks, cleanup),
Headers: resp.Headers,
Chunks: cleanupWhenStreamDone(ctx, chunks, cleanup),
Attribution: resp.Attribution,
}, nil
}

View File

@@ -125,3 +125,78 @@ func waitForStreamCallbackPlugin(t *testing.T, client *streamCallbackPluginClien
t.Fatal("plugin stream method was not called")
}
}
type staticStreamClient struct {
resp rpcExecutorStreamResponse
}
func (c *staticStreamClient) Call(_ context.Context, method string, _ []byte) ([]byte, error) {
if method != pluginabi.MethodExecutorExecuteStream {
return nil, fmt.Errorf("unexpected method %s", method)
}
return marshalRPCResult(c.resp)
}
func (c *staticStreamClient) Shutdown() {}
func TestRPCExecuteStreamPropagatesAttribution(t *testing.T) {
wantAttr := &pluginapi.UsageAttribution{
AuthIndex: "idx-stream-1",
AuthType: "oauth",
Source: "acct-stream@example.com",
}
t.Run("inline chunks", func(t *testing.T) {
host := New()
adapter := &rpcPluginAdapter{
id: "stream-attr",
host: host,
client: &staticStreamClient{
resp: rpcExecutorStreamResponse{
Headers: http.Header{"Content-Type": []string{"text/event-stream"}},
Chunks: []pluginapi.ExecutorStreamChunk{{Payload: []byte("data: ok\n\n")}},
Attribution: wantAttr,
},
},
}
res, errStream := adapter.ExecuteStream(context.Background(), pluginapi.ExecutorRequest{Stream: true})
if errStream != nil {
t.Fatalf("ExecuteStream() error = %v", errStream)
}
if res.Attribution == nil || *res.Attribution != *wantAttr {
t.Fatalf("res.Attribution = %+v, want %+v", res.Attribution, wantAttr)
}
for range res.Chunks {
}
})
t.Run("async stream", func(t *testing.T) {
host := New()
adapter := &rpcPluginAdapter{
id: "stream-attr-async",
host: host,
client: &staticStreamClient{
resp: rpcExecutorStreamResponse{
Headers: http.Header{"Content-Type": []string{"text/event-stream"}},
Attribution: wantAttr,
},
},
}
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
res, errStream := adapter.ExecuteStream(ctx, pluginapi.ExecutorRequest{Stream: true})
if errStream != nil {
t.Fatalf("ExecuteStream() error = %v", errStream)
}
t.Cleanup(func() {
cancel()
for range res.Chunks {
}
})
if res.Attribution == nil || *res.Attribution != *wantAttr {
t.Fatalf("res.Attribution = %+v, want %+v", res.Attribution, wantAttr)
}
})
}

View File

@@ -72,8 +72,9 @@ type rpcIdentifierResponse struct {
}
type rpcExecutorStreamResponse struct {
Headers http.Header `json:"headers,omitempty"`
Chunks []pluginapi.ExecutorStreamChunk `json:"chunks,omitempty"`
Headers http.Header `json:"headers,omitempty"`
Chunks []pluginapi.ExecutorStreamChunk `json:"chunks,omitempty"`
Attribution *pluginapi.UsageAttribution `json:"attribution,omitempty"`
}
type rpcAuthLoginStartRequest struct {

View File

@@ -26,6 +26,7 @@ import (
cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth"
cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor"
"github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage"
"github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginapi"
log "github.com/sirupsen/logrus"
)
@@ -169,6 +170,40 @@ func (r *UsageReporter) SetStream(stream bool) {
r.stream = stream
}
// PluginExecutorType returns the canonical usage executor label for a plugin ID.
func PluginExecutorType(pluginID string) string {
if id := strings.TrimSpace(pluginID); id != "" {
return "plugin:" + id
}
return ""
}
// ApplyPluginExecutorAttribution populates executorType and optional upstream credential
// attribution fields for direct plugin executor dispatches and auth-backed plugin executors.
// Already-populated AuthIndex and AuthType values (e.g. from coreauth.Auth) are preserved.
func (r *UsageReporter) ApplyPluginExecutorAttribution(executorPluginID string, attr *pluginapi.UsageAttribution) {
if r == nil {
return
}
if r.executorType == "" {
if executorType := PluginExecutorType(executorPluginID); executorType != "" {
r.executorType = executorType
}
}
if attr == nil {
return
}
if v := strings.TrimSpace(attr.AuthIndex); v != "" && r.authIndex == "" {
r.authIndex = v
}
if v := strings.TrimSpace(attr.AuthType); v != "" && r.authType == "" {
r.authType = v
}
if v := strings.TrimSpace(attr.Source); v != "" {
r.source = v
}
}
// SetSessionHierarchy sets the explicit session and parent session identifiers.
// Callers should invoke this method before Publish or EnsurePublished on the request thread.
func (r *UsageReporter) SetSessionHierarchy(sessionID, parentSessionID string) {
@@ -347,10 +382,19 @@ func (r *UsageReporter) ResponseModel() string {
return r.responseModel
}
type usageExecutorTypeProvider interface {
UsageExecutorType() string
}
func ExecutorTypeName(executor any) string {
if executor == nil {
return ""
}
if custom, ok := executor.(usageExecutorTypeProvider); ok && custom != nil {
if name := strings.TrimSpace(custom.UsageExecutorType()); name != "" {
return name
}
}
executorType := reflect.TypeOf(executor)
for executorType.Kind() == reflect.Pointer {
executorType = executorType.Elem()

View File

@@ -26,6 +26,7 @@ import (
cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth"
cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor"
"github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage"
"github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginapi"
)
func TestParseOpenAIUsageChatCompletions(t *testing.T) {
@@ -2196,3 +2197,51 @@ func TestImageDetailsCloneStringsFromReusableBuffer(t *testing.T) {
t.Fatalf("ObserveOpenAIStream ImageDetails corrupted after buffer overwrite: %+v", d.ImageDetails)
}
}
type customUsageExecutorType struct{}
func (*customUsageExecutorType) Identifier() string { return "custom-prov" }
func (*customUsageExecutorType) UsageExecutorType() string { return "plugin:custom-prov" }
func TestUsageReporterApplyPluginExecutorAttribution(t *testing.T) {
ctx := usage.WithAPIKey(context.Background(), "sk-client-fallback")
reporter := NewUsageReporter(ctx, "my-plugin", "gpt-5.4", nil)
reporter.ApplyPluginExecutorAttribution("my-plugin", nil)
before := reporter.buildRecord(usage.Detail{TotalTokens: 1}, false)
if before.ExecutorType != "plugin:my-plugin" {
t.Fatalf("before.ExecutorType = %q, want %q", before.ExecutorType, "plugin:my-plugin")
}
if before.Source != "sk-client-fallback" {
t.Fatalf("before.Source = %q, want client fallback", before.Source)
}
reporter.ApplyPluginExecutorAttribution("my-plugin", &pluginapi.UsageAttribution{
AuthIndex: " idx-1 ",
AuthType: " oauth ",
Source: " acct@example.com ",
})
// Subsequent calls must not overwrite already-populated auth attribution fields.
reporter.ApplyPluginExecutorAttribution("my-plugin", &pluginapi.UsageAttribution{
AuthIndex: "idx-2",
AuthType: "api_key",
})
after := reporter.buildRecord(usage.Detail{TotalTokens: 2}, false)
if after.Provider != "my-plugin" ||
after.ExecutorType != "plugin:my-plugin" ||
after.AuthIndex != "idx-1" ||
after.AuthType != "oauth" ||
after.Source != "acct@example.com" {
t.Fatalf("after record = %+v", after)
}
execReporter := NewExecutorUsageReporter(context.Background(), &customUsageExecutorType{}, "gpt-5.4", nil)
execRec := execReporter.buildRecord(usage.Detail{TotalTokens: 1}, false)
if execRec.ExecutorType != "plugin:custom-prov" {
t.Fatalf("execRec.ExecutorType = %q, want %q", execRec.ExecutorType, "plugin:custom-prov")
}
if PluginExecutorType("") != "" || PluginExecutorType(" ") != "" || PluginExecutorType(" my-plugin ") != "plugin:my-plugin" {
t.Fatalf("unexpected PluginExecutorType values")
}
}

View File

@@ -30,6 +30,11 @@ type pluginExecutorFormatResolver interface {
PluginExecutorRequestToFormat(string, coreexecutor.Request, coreexecutor.Options) sdktranslator.Format
}
type pluginExecutorAttributionHost interface {
ExecutePluginExecutorWithAttribution(context.Context, string, coreexecutor.Request, coreexecutor.Options) (coreexecutor.Response, *pluginapi.UsageAttribution, error)
ExecutePluginExecutorStreamWithAttribution(context.Context, string, coreexecutor.Request, coreexecutor.Options) (*coreexecutor.StreamResult, *pluginapi.UsageAttribution, error)
}
// ExecuteWithAuthManager executes a non-streaming request via the core auth manager.
// This path is the only supported execution route.
func (h *BaseAPIHandler) ExecuteWithAuthManager(ctx context.Context, handlerType, modelName string, rawJSON []byte, alt string) ([]byte, http.Header, *interfaces.ErrorMessage) {
@@ -222,10 +227,20 @@ func (h *BaseAPIHandler) executeWithPluginExecutor(ctx context.Context, entryPro
var reporter *helps.UsageReporter
if !execOptions.InternalSource {
reporter = helps.NewUsageReporter(execCtx, executorPluginID, modelName, nil)
reporter.ApplyPluginExecutorAttribution(executorPluginID, nil)
reporter.SetTranslatedReasoningEffort(req.Payload, entryProtocol)
reporter.StartResponseTTFT()
}
resp, errExecute := host.ExecutePluginExecutor(execCtx, executorPluginID, req, opts)
var (
resp coreexecutor.Response
attribution *pluginapi.UsageAttribution
errExecute error
)
if attrHost, ok := host.(pluginExecutorAttributionHost); ok && attrHost != nil {
resp, attribution, errExecute = attrHost.ExecutePluginExecutorWithAttribution(execCtx, executorPluginID, req, opts)
} else {
resp, errExecute = host.ExecutePluginExecutor(execCtx, executorPluginID, req, opts)
}
if errExecute != nil {
if reporter != nil && !nestedTracker.hasNestedExecution() {
reporter.PublishFailure(execCtx, errExecute)
@@ -235,6 +250,7 @@ func (h *BaseAPIHandler) executeWithPluginExecutor(ctx context.Context, entryPro
return nil, nil, errMsg
}
if reporter != nil && !nestedTracker.hasNestedExecution() {
reporter.ApplyPluginExecutorAttribution(executorPluginID, attribution)
reporter.RecordFirstPacket()
detail := parsePluginExecutorResponseUsage(responseProtocol, resp.Payload)
reporter.Publish(execCtx, detail)

View File

@@ -752,11 +752,13 @@ func TestHandlerPluginExecutorSkipsOuterFailureWhenPluginCallsHostModelExecute(t
type mockPluginUsageHost struct {
handlerDirectExecutorRouteHost
execResp coreexecutor.Response
execErr error
execFunc func(context.Context, string, coreexecutor.Request, coreexecutor.Options) (coreexecutor.Response, error)
streamResult *coreexecutor.StreamResult
streamFunc func(context.Context, string, coreexecutor.Request, coreexecutor.Options) (*coreexecutor.StreamResult, error)
execResp coreexecutor.Response
execAttribution *pluginapi.UsageAttribution
execErr error
execFunc func(context.Context, string, coreexecutor.Request, coreexecutor.Options) (coreexecutor.Response, error)
streamResult *coreexecutor.StreamResult
streamAttribution *pluginapi.UsageAttribution
streamFunc func(context.Context, string, coreexecutor.Request, coreexecutor.Options) (*coreexecutor.StreamResult, error)
}
func (h *mockPluginUsageHost) ExecutePluginExecutor(ctx context.Context, pluginID string, req coreexecutor.Request, opts coreexecutor.Options) (coreexecutor.Response, error) {
@@ -772,6 +774,14 @@ func (h *mockPluginUsageHost) ExecutePluginExecutor(ctx context.Context, pluginI
return h.execResp, nil
}
func (h *mockPluginUsageHost) ExecutePluginExecutorWithAttribution(ctx context.Context, pluginID string, req coreexecutor.Request, opts coreexecutor.Options) (coreexecutor.Response, *pluginapi.UsageAttribution, error) {
resp, err := h.ExecutePluginExecutor(ctx, pluginID, req, opts)
if err != nil {
return coreexecutor.Response{}, nil, err
}
return resp, h.execAttribution, nil
}
func (h *mockPluginUsageHost) ExecutePluginExecutorStream(ctx context.Context, pluginID string, req coreexecutor.Request, opts coreexecutor.Options) (*coreexecutor.StreamResult, error) {
h.lastPluginID = pluginID
h.lastRequest = req
@@ -782,6 +792,14 @@ func (h *mockPluginUsageHost) ExecutePluginExecutorStream(ctx context.Context, p
return h.streamResult, nil
}
func (h *mockPluginUsageHost) ExecutePluginExecutorStreamWithAttribution(ctx context.Context, pluginID string, req coreexecutor.Request, opts coreexecutor.Options) (*coreexecutor.StreamResult, *pluginapi.UsageAttribution, error) {
streamResult, err := h.ExecutePluginExecutorStream(ctx, pluginID, req, opts)
if err != nil {
return nil, nil, err
}
return streamResult, h.streamAttribution, nil
}
func advanceMonotonicClock() time.Duration {
start := time.Now()
for {
@@ -932,3 +950,105 @@ func TestHandlerPluginExecutorPublishesFirstPacketFallbackTTFTStream(t *testing.
t.Fatalf("record.TTFT = %v, want > 0 for first-packet fallback", record.TTFT)
}
}
func TestHandlerPluginExecutorPublishesAttributionNonStream(t *testing.T) {
targetPluginID := "custom-attr-nonstream-plugin"
plugin := newCapturePluginExecutorUsagePlugin(targetPluginID)
registerUsagePluginForTest(t, "test-plugin-executor-attr-nonstream", plugin)
originalModel := "gpt-4o"
openAIResponseBody := []byte(`{"id":"chatcmpl-1","choices":[{"message":{"role":"assistant","content":"hello"}}],"usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15}}`)
mockHost := &mockPluginUsageHost{
execResp: coreexecutor.Response{
Payload: openAIResponseBody,
},
execAttribution: &pluginapi.UsageAttribution{
AuthIndex: "idx-1",
AuthType: "oauth",
Source: "acct@example.com",
},
}
mockHost.hasRouters = true
mockHost.route = func(ctx context.Context, req pluginapi.ModelRouteRequest) (pluginapi.ModelRouteResponse, bool) {
return pluginapi.ModelRouteResponse{Handled: true, TargetKind: pluginapi.ModelRouteTargetExecutor, Target: targetPluginID}, true
}
handler := NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, nil)
handler.SetModelRouterHost(mockHost)
ctx := usage.WithAPIKey(context.Background(), "sk-downstream-key")
_, _, errMsg := handler.ExecuteWithAuthManager(ctx, "openai", originalModel, []byte(fmt.Sprintf(`{"model":%q}`, originalModel)), "")
if errMsg != nil {
t.Fatalf("ExecuteWithAuthManager() error = %+v", errMsg)
}
record := plugin.waitRecord(t)
if record.Provider != targetPluginID ||
record.ExecutorType != "plugin:"+targetPluginID ||
record.AuthIndex != "idx-1" ||
record.AuthType != "oauth" ||
record.Source != "acct@example.com" {
t.Fatalf("record attribution = %+v", record)
}
}
func TestHandlerPluginExecutorPublishesAttributionStreamAndFailureExecutorType(t *testing.T) {
targetPluginID := "custom-attr-stream-plugin"
plugin := newCapturePluginExecutorUsagePlugin(targetPluginID)
registerUsagePluginForTest(t, "test-plugin-executor-attr-stream", plugin)
originalModel := "gpt-4o"
mockHost := &mockPluginUsageHost{
streamAttribution: &pluginapi.UsageAttribution{
AuthIndex: "idx-stream",
AuthType: "oauth",
Source: "stream@example.com",
},
streamFunc: func(ctx context.Context, pluginID string, req coreexecutor.Request, opts coreexecutor.Options) (*coreexecutor.StreamResult, error) {
chunks := make(chan coreexecutor.StreamChunk, 2)
chunks <- coreexecutor.StreamChunk{Payload: []byte("data: {\"id\":\"chatcmpl-1\",\"choices\":[{\"delta\":{\"content\":\"hi\"}}]}\n\n")}
chunks <- coreexecutor.StreamChunk{Payload: []byte("data: {\"id\":\"chatcmpl-1\",\"choices\":[],\"usage\":{\"prompt_tokens\":6,\"completion_tokens\":4,\"total_tokens\":10}}\n\n")}
close(chunks)
return &coreexecutor.StreamResult{
Chunks: chunks,
}, nil
},
}
mockHost.hasRouters = true
mockHost.route = func(ctx context.Context, req pluginapi.ModelRouteRequest) (pluginapi.ModelRouteResponse, bool) {
return pluginapi.ModelRouteResponse{Handled: true, TargetKind: pluginapi.ModelRouteTargetExecutor, Target: targetPluginID}, true
}
handler := NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, nil)
handler.SetModelRouterHost(mockHost)
dataChan, _, errChan := handler.ExecuteStreamWithAuthManager(context.Background(), "openai", originalModel, []byte(fmt.Sprintf(`{"model":%q,"stream":true}`, originalModel)), "")
for range dataChan {
}
for err := range errChan {
if err != nil {
t.Fatalf("stream error = %+v", err)
}
}
record := plugin.waitRecord(t)
if record.Provider != targetPluginID ||
record.ExecutorType != "plugin:"+targetPluginID ||
record.AuthIndex != "idx-stream" ||
record.AuthType != "oauth" ||
record.Source != "stream@example.com" {
t.Fatalf("stream record attribution = %+v", record)
}
// Failure paths must still report plugin:<id> executorType.
mockHost.execErr = errors.New("upstream error")
_, _, failErr := handler.ExecuteWithAuthManager(context.Background(), "openai", originalModel, []byte(fmt.Sprintf(`{"model":%q}`, originalModel)), "")
if failErr == nil {
t.Fatal("expected error from ExecuteWithAuthManager")
}
failRecord := plugin.waitRecord(t)
if !failRecord.Failed || failRecord.ExecutorType != "plugin:"+targetPluginID {
t.Fatalf("failRecord = %+v, want Failed=true ExecutorType=%q", failRecord, "plugin:"+targetPluginID)
}
}

View File

@@ -118,10 +118,20 @@ func (h *BaseAPIHandler) streamWithPluginExecutor(ctx context.Context, entryProt
var reporter *helps.UsageReporter
if !execOptions.InternalSource {
reporter = helps.NewUsageReporter(execCtx, executorPluginID, modelName, nil)
reporter.ApplyPluginExecutorAttribution(executorPluginID, nil)
reporter.SetTranslatedReasoningEffort(req.Payload, entryProtocol)
reporter.StartResponseTTFT()
}
streamResult, errStream := host.ExecutePluginExecutorStream(execCtx, executorPluginID, req, opts)
var (
streamResult *coreexecutor.StreamResult
attribution *pluginapi.UsageAttribution
errStream error
)
if attrHost, ok := host.(pluginExecutorAttributionHost); ok && attrHost != nil {
streamResult, attribution, errStream = attrHost.ExecutePluginExecutorStreamWithAttribution(execCtx, executorPluginID, req, opts)
} else {
streamResult, errStream = host.ExecutePluginExecutorStream(execCtx, executorPluginID, req, opts)
}
if errStream != nil {
if reporter != nil && !nestedTracker.hasNestedExecution() {
reporter.PublishFailure(execCtx, errStream)
@@ -144,6 +154,9 @@ func (h *BaseAPIHandler) streamWithPluginExecutor(ctx context.Context, entryProt
close(errChan)
return nil, nil, errChan
}
if reporter != nil && !nestedTracker.hasNestedExecution() {
reporter.ApplyPluginExecutorAttribution(executorPluginID, attribution)
}
passthroughHeadersEnabled := executionPassthroughHeaders(h.CurrentConfig(), execOptions.InternalSource)
interceptorHost := h.interceptorHost()

View File

@@ -1319,6 +1319,17 @@ type ExecutorRequest struct {
HTTPClient HostHTTPClient `json:"-"`
}
// UsageAttribution reports optional upstream credential identity
// resolved by a plugin executor when no built-in credential was selected upfront.
type UsageAttribution struct {
// AuthIndex identifies the selected credential index.
AuthIndex string `json:"auth_index,omitempty"`
// AuthType identifies the selected credential type (e.g. "oauth", "api_key").
AuthType string `json:"auth_type,omitempty"`
// Source identifies the upstream account, project, or credential label.
Source string `json:"source,omitempty"`
}
// ExecutorResponse returns a non-streaming executor result.
type ExecutorResponse struct {
// Payload contains the raw response body.
@@ -1327,6 +1338,8 @@ type ExecutorResponse struct {
Headers http.Header
// Metadata is an extension bag for executor-specific response data.
Metadata map[string]any
// Attribution reports optional upstream credential identity for usage tracking.
Attribution *UsageAttribution `json:"attribution,omitempty"`
}
// ExecutorStreamResponse returns a streaming executor result.
@@ -1335,6 +1348,8 @@ type ExecutorStreamResponse struct {
Headers http.Header
// Chunks yields streaming payload chunks until the channel closes.
Chunks <-chan ExecutorStreamChunk
// Attribution reports optional upstream credential identity for usage tracking.
Attribution *UsageAttribution `json:"attribution,omitempty"`
}
// ExecutorStreamChunk carries one streaming payload chunk or an error.

View File

@@ -1118,3 +1118,65 @@ func TestHostAuthModelsTypes(t *testing.T) {
t.Fatalf("decoded response = %#v, want %#v", decodedResp, resp)
}
}
func TestUsageAttributionAndExecutorResponsesJSON(t *testing.T) {
attr := UsageAttribution{
AuthIndex: "idx-1",
AuthType: "oauth",
Source: "acct@example.com",
}
raw, errMarshal := json.Marshal(attr)
if errMarshal != nil {
t.Fatalf("marshal UsageAttribution error = %v", errMarshal)
}
var decodedMap map[string]string
if errUnmarshalMap := json.Unmarshal(raw, &decodedMap); errUnmarshalMap != nil {
t.Fatalf("unmarshal UsageAttribution map error = %v", errUnmarshalMap)
}
for key, want := range map[string]string{
"auth_index": attr.AuthIndex,
"auth_type": attr.AuthType,
"source": attr.Source,
} {
if decodedMap[key] != want {
t.Fatalf("decodedMap[%q] = %q, want %q (raw=%s)", key, decodedMap[key], want, raw)
}
}
var decoded UsageAttribution
if errUnmarshal := json.Unmarshal(raw, &decoded); errUnmarshal != nil {
t.Fatalf("unmarshal UsageAttribution error = %v", errUnmarshal)
}
if decoded != attr {
t.Fatalf("decoded = %+v, want %+v", decoded, attr)
}
resp := ExecutorResponse{
Payload: []byte(`{"ok":true}`),
Headers: http.Header{"Content-Type": []string{"application/json"}},
Attribution: &attr,
}
respBytes, errRespMarshal := json.Marshal(resp)
if errRespMarshal != nil {
t.Fatalf("marshal ExecutorResponse error = %v", errRespMarshal)
}
var decodedResp ExecutorResponse
if errRespUnmarshal := json.Unmarshal(respBytes, &decodedResp); errRespUnmarshal != nil {
t.Fatalf("unmarshal ExecutorResponse error = %v", errRespUnmarshal)
}
if decodedResp.Attribution == nil || *decodedResp.Attribution != attr {
t.Fatalf("decodedResp.Attribution = %+v, want %+v", decodedResp.Attribution, attr)
}
streamJSON := []byte(`{"attribution":{"auth_index":"idx-stream","auth_type":"oauth","source":"stream-u"}}`)
var decodedStream ExecutorStreamResponse
if errStreamUnmarshal := json.Unmarshal(streamJSON, &decodedStream); errStreamUnmarshal != nil {
t.Fatalf("unmarshal ExecutorStreamResponse error = %v", errStreamUnmarshal)
}
if decodedStream.Attribution == nil ||
decodedStream.Attribution.AuthIndex != "idx-stream" ||
decodedStream.Attribution.AuthType != "oauth" ||
decodedStream.Attribution.Source != "stream-u" {
t.Fatalf("decodedStream = %+v", decodedStream)
}
}