diff --git a/internal/memoryagent/budget.go b/internal/memoryagent/budget.go index e2b26bc6..f20162b1 100644 --- a/internal/memoryagent/budget.go +++ b/internal/memoryagent/budget.go @@ -240,7 +240,7 @@ func (b *Budget) reserveAmount(ctx context.Context, kind, hash string, amount fl // (Provider.inputEstimate), for SettleHolds; one with no input tokens is // none, and the attempt records no estimate. func (b *Budget) reserveWithin(ctx context.Context, kind, hash string, amount, share float64, estimate Usage) (string, error) { - if kind == "local" { + if kind == "local" || kind == "systemone" { return "", nil } if b == nil { diff --git a/internal/memoryagent/keys.go b/internal/memoryagent/keys.go index 95f57c0b..695a20d4 100644 --- a/internal/memoryagent/keys.go +++ b/internal/memoryagent/keys.go @@ -129,7 +129,7 @@ func (k *ProviderKeys) Account() map[string]string { return maps.Clone(*k.accoun // a key pasted in the wrong place. func KindName(kind string) string { switch kind { - case "deepseek", "jev", "openai", "local": + case "deepseek", "jev", "openai", "local", "systemone": return kind } return "a kind that is not deepseek or jev" @@ -307,7 +307,7 @@ func (p *Provider) modelsURL() string { return p.endpoint } route := "/chat/completions" - if p.config.Kind == "jev" { + if isDecisionKind(p.config.Kind) { route = "/systemone" } base, found := strings.CutSuffix(u.Path, route) @@ -322,7 +322,7 @@ func (p *Provider) modelsURL() string { // 1, or a JEV decision of one question. func (p *Provider) checkBody() []byte { var body any = map[string]any{"model": p.config.Model, "messages": []map[string]string{{"role": "user", "content": "ping"}}, "max_tokens": 1} - if p.config.Kind == "jev" { + if isDecisionKind(p.config.Kind) { body = map[string]any{"model": p.config.Model, "state": map[string]any{}, "questions": map[string]Question{"check": {Type: "noul", Instructions: "Is this request a check of the API key?"}}} } diff --git a/internal/memoryagent/provider.go b/internal/memoryagent/provider.go index 0bfc99cc..69c598c6 100644 --- a/internal/memoryagent/provider.go +++ b/internal/memoryagent/provider.go @@ -150,6 +150,22 @@ func isLoopbackHost(host string) bool { return host == "127.0.0.1" || host == "localhost" || host == "::1" } +func isDecisionKind(kind string) bool { + return kind == "jev" || kind == "systemone" +} + +func systemOneEndpoint(baseURL string) string { + trimmed := strings.TrimRight(baseURL, "/") + switch { + case strings.HasSuffix(trimmed, "/v1/systemone"): + return trimmed + case strings.HasSuffix(trimmed, "/v1"): + return trimmed + "/systemone" + default: + return trimmed + "/v1/systemone" + } +} + // NewProvider is the provider of config, billed to budget, whose credential // is the host's: the variable config.KeyEnv names. func NewProvider(config ModelConfig, budget *Budget) (*Provider, error) { @@ -183,6 +199,12 @@ func newProvider(config ModelConfig, budget *Budget, keys *ProviderKeys) (*Provi return nil, errors.New("JEV requires a pinned version and the official endpoint") } p.endpoint = "https://api.typesafe.ai/v1/systemone" + case "systemone": + u, err := url.Parse(config.BaseURL) + if err != nil || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.Hostname() == "" || u.Scheme != "https" && (u.Scheme != "http" || !isLoopbackHost(u.Hostname())) { + return nil, errors.New("systemone model requires an https baseURL, or http on loopback") + } + p.endpoint = systemOneEndpoint(config.BaseURL) case "deepseek": if config.Model != "deepseek-flash" || config.BaseURL != "" { return nil, errors.New("DeepSeek requires deepseek-flash and the official endpoint") @@ -219,13 +241,21 @@ func newProvider(config ModelConfig, budget *Budget, keys *ProviderKeys) (*Provi } p.endpoint = strings.TrimRight(config.BaseURL, "/") + "/chat/completions" default: - return nil, errors.New("model kind must be jev, deepseek, openai or local") + return nil, errors.New("model kind must be jev, systemone, deepseek, openai or local") } if config.TestEndpoint != "" { p.endpoint = config.TestEndpoint } - if config.Kind != "local" && (budget == nil || config.KeyEnv == "" || p.credential() == "") { - return nil, errors.New("paid model requires a budget and a nonempty credential environment variable (or an account key)") + switch config.Kind { + case "local": + case "systemone": + if config.KeyEnv != "" && p.credential() == "" { + return nil, errors.New("systemone model keyEnv is set but its credential environment variable is empty") + } + default: + if budget == nil || config.KeyEnv == "" || p.credential() == "" { + return nil, errors.New("paid model requires a budget and a nonempty credential environment variable (or an account key)") + } } return p, nil } @@ -423,8 +453,12 @@ func (p *Provider) complete(ctx context.Context, system, prompt string, jsonOnly // it refuses is invalid, retried once (send). A reply cut at its output // limit is not checked; it fails as before. func (p *Provider) completion(ctx context.Context, system, prompt string, jsonOnly bool, callLimit int, check func(string) error) (string, Usage, cacheEntry, error) { - if p.config.Kind == "jev" { - return "", Usage{}, cacheEntry{}, errors.New("JEV is a decision model, not a completer") + if isDecisionKind(p.config.Kind) { + name := p.config.Kind + if name == "jev" { + name = "JEV" + } + return "", Usage{}, cacheEntry{}, fmt.Errorf("%s is a decision model, not a completer", name) } maxTokens := 1024 if jsonOnly { @@ -553,10 +587,10 @@ func (r completionReply) text(callLimit int) (string, error) { return r.content, nil } -// MaxQuestions is the most questions one Decide call takes: 128 for JEV, -// 80 for a completer answering them. +// MaxQuestions is the most questions one Decide call takes: 128 for System One +// decision models (JEV, Karpo, etc.), 80 for a completer answering them. func (p *Provider) MaxQuestions() int { - if p.config.Kind == "jev" { + if isDecisionKind(p.config.Kind) { return 128 } return 80 @@ -576,7 +610,7 @@ func (p *Provider) Decide(ctx context.Context, state any, questions map[string]Q if len(questions) < 1 || len(questions) > maxQuestions { return nil, Usage{}, fmt.Errorf("decision requires 1–%d binary questions", maxQuestions) } - if p.config.Kind != "jev" { + if !isDecisionKind(p.config.Kind) { prompt, _ := json.Marshal(map[string]any{"state": state, "questions": questions}) // A live reply whose answers fail is invalid, retried once (R61). check := func(text string) error { @@ -689,10 +723,12 @@ func (p *Provider) parseDecision(raw []byte) (decisionReply, error) { reply := decisionReply{answers: result.Answers} if result.Usage.Input != nil && result.Usage.Output != nil { reply.usage = Usage{InputTokens: *result.Usage.Input, OutputTokens: *result.Usage.Output} - reply.usage.USD = float64(reply.usage.InputTokens) * 0.042 / 1e6 + if p.config.Kind == "jev" { + reply.usage.USD = float64(reply.usage.InputTokens) * 0.042 / 1e6 + } reply.metering = true } - if result.Model != p.config.Model || !reply.metering { + if p.config.Kind == "jev" && (result.Model != p.config.Model || !reply.metering) { return reply, errInvalidJEV } return reply, nil diff --git a/internal/memoryagent/provider_test.go b/internal/memoryagent/provider_test.go index 165a9906..bea950bb 100644 --- a/internal/memoryagent/provider_test.go +++ b/internal/memoryagent/provider_test.go @@ -1327,3 +1327,80 @@ func TestReleaseSurvivesCanceledCaller(t *testing.T) { t.Fatal("the refused call's reservation was not released", held, spent, attempts) } } + +func TestSystemOneProviderSupportsKarpoDecision(t *testing.T) { + // Karpo Decision serves POST /v1/systemone on loopback with no API key or + // paid budget required, defaults its response model name to "karpo-decision", + // and reports output_tokens: 0. + for _, suffix := range []string{"", "/v1", "/v1/systemone"} { + t.Run("endpoint"+suffix, func(t *testing.T) { + var gotPath, gotAuth string + var gotContentLength int64 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotPath = r.URL.Path + gotAuth = r.Header.Get("Authorization") + gotContentLength = r.ContentLength + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"id":"decision-01","model":"karpo-decision","answers":{"a":{"type":"noul","noul":0.84}},"usage":{"input_tokens":512,"output_tokens":0}}`)) + })) + defer srv.Close() + + p, err := NewProvider(ModelConfig{ + Kind: "systemone", + Model: "karpo-decision-31B", + BaseURL: srv.URL + suffix, + }, nil) + if err != nil { + t.Fatalf("NewProvider failed: %v", err) + } + if p.MaxQuestions() != 128 { + t.Fatalf("MaxQuestions = %d, want 128", p.MaxQuestions()) + } + if _, _, err := p.Complete(context.Background(), "s", "p"); err == nil || !strings.Contains(err.Error(), "systemone is a decision model") { + t.Fatalf("systemone Complete err = %v, want systemone decision-model error", err) + } + + answers, usage, err := p.Decide(context.Background(), "evidence", map[string]Question{"a": binary("Relevant?")}) + if err != nil { + t.Fatalf("Decide failed: %v", err) + } + if gotPath != "/v1/systemone" { + t.Fatalf("path = %q, want /v1/systemone", gotPath) + } + if gotAuth != "" { + t.Fatalf("unexpected Authorization header %q", gotAuth) + } + if gotContentLength <= 0 { + t.Fatalf("Content-Length = %d, want > 0", gotContentLength) + } + if answers["a"] != 0.84 { + t.Fatalf("answers[a] = %v, want 0.84", answers["a"]) + } + if usage.InputTokens != 512 || usage.OutputTokens != 0 || usage.USD != 0 { + t.Fatalf("usage = %+v, want input=512 output=0 USD=0", usage) + } + }) + } + + // Non-loopback HTTP is rejected; HTTPS with optional KeyEnv works. + if _, err := NewProvider(ModelConfig{Kind: "systemone", Model: "karpo-decision-31B", BaseURL: "http://example.com:18440"}, nil); err == nil { + t.Fatal("non-loopback HTTP systemone endpoint was accepted") + } + if _, err := NewProvider(ModelConfig{Kind: "systemone", Model: "karpo-decision-31B", BaseURL: "https://karpo.example", KeyEnv: "UNIT_MISSING_SYSTEMONE_KEY"}, nil); err == nil { + t.Fatal("missing credential for explicit keyEnv was accepted") + } + t.Setenv("UNIT_SYSTEMONE_KEY", "secret-token") + p, err := NewProvider(ModelConfig{Kind: "systemone", Model: "karpo-decision-31B", BaseURL: "https://karpo.example", KeyEnv: "UNIT_SYSTEMONE_KEY"}, nil) + if err != nil { + t.Fatalf("HTTPS systemone provider with keyEnv failed: %v", err) + } + var gotAuth string + p.client.Transport = transportFunc(func(req *http.Request) (*http.Response, error) { + gotAuth = req.Header.Get("Authorization") + return mockResponse(`{"model":"karpo-decision","answers":{"a":{"type":"noul","noul":0.7}}}`), nil + }) + answers, _, err := p.Decide(context.Background(), "evidence", map[string]Question{"a": binary("Relevant?")}) + if err != nil || answers["a"] != 0.7 || gotAuth != "Bearer secret-token" { + t.Fatalf("HTTPS systemone call failed: answers=%v auth=%q err=%v", answers, gotAuth, err) + } +} diff --git a/internal/memoryagent/resilience.go b/internal/memoryagent/resilience.go index a06ac295..83ce1a88 100644 --- a/internal/memoryagent/resilience.go +++ b/internal/memoryagent/resilience.go @@ -258,7 +258,7 @@ func checkResilience(config ModelConfig, hard time.Duration) error { // kind and resilience settings; hard is its hard timeout. func classPolicies(config ModelConfig, hard time.Duration) [3]classPolicy { interactive := interactiveCompletionTimeout - if config.Kind == "jev" { + if isDecisionKind(config.Kind) { interactive = interactiveDecisionTimeout } if config.AttemptTimeoutSeconds > 0 {