Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion api/llms.txt
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ An agent never acts as the Owner, even through an Owner's browser session.
roles: owner, maintainer, viewer; scopes: approvals:read; POST /api/v1/actions/approvals.list
- budget.get [read] Show the budget mode, cap, alert threshold and usage, with unverified usage marked.
roles: owner, maintainer, viewer; scopes: budget:read; POST /api/v1/actions/budget.get
- budget.set [sensitive, step-up] Change the budget mode, cap, alert threshold or rollback reserve; Owner only.
- budget.set [sensitive, step-up] Change the budget mode, cap, alert threshold, rollback reserve or provider cost sources; Owner only.
roles: owner; scopes: budget:write; POST /api/v1/actions/budget.set
- changelog.list [read] List the changelog entries of released work.
roles: owner, maintainer, reporter, viewer, agent; scopes: catalog:read; POST /api/v1/actions/changelog.list
Expand Down
9 changes: 8 additions & 1 deletion api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,13 @@ paths:
- day
- week
- month
provider_cost_sources:
items:
enum:
- anthropic
- openai
type: array
uniqueItems: true
provider_hard_cap:
type: boolean
rollback_reserve_micros:
Expand Down Expand Up @@ -430,7 +437,7 @@ paths:
security:
- bearerAuth:
- budget:write
summary: Change the budget mode, cap, alert threshold or rollback reserve; Owner only.
summary: Change the budget mode, cap, alert threshold, rollback reserve or provider cost sources; Owner only.
tags:
- budget
x-sisf-action: budget.set
Expand Down
25 changes: 17 additions & 8 deletions cmd/factoryd/roles.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/bestagentkits/sisf/adapters/agent/fake"
"github.com/bestagentkits/sisf/cmd/factoryd/wiring"
"github.com/bestagentkits/sisf/cmd/supervisor/observe"
"github.com/bestagentkits/sisf/internal/budget"
"github.com/bestagentkits/sisf/internal/dispatcher"
"github.com/bestagentkits/sisf/pkg/core"
"github.com/bestagentkits/sisf/pkg/manifest"
Expand Down Expand Up @@ -55,9 +56,11 @@ func setup(ctx context.Context, getenv func(string) string, zone core.Zone) (zon
return zoneSetup{env: env, manifest: m, store: store, clock: clock}, nil
}

// newControl builds the control zone from its setup; surfaces and decisions
// are nil for the Owner's command-line use, which serves and decides nothing.
func newControl(s zoneSetup, log *slog.Logger, surfaces *wiring.SurfaceConfig, decisions *wiring.DecisionConfig) (*wiring.Control, error) {
// newControl builds the control zone from its setup; surfaces, decisions and
// the providers' cost sources are nil for the Owner's command-line use,
// which serves, decides and reads nothing.
func newControl(s zoneSetup, log *slog.Logger, surfaces *wiring.SurfaceConfig, decisions *wiring.DecisionConfig,
providerCost map[string]budget.CostSource) (*wiring.Control, error) {
settings, err := wiring.GitHubSettingsOf(s.manifest)
if err != nil {
return nil, err
Expand All @@ -78,7 +81,7 @@ func newControl(s zoneSetup, log *slog.Logger, surfaces *wiring.SurfaceConfig, d
WebhookSecret: s.env.WebhookSecret, ApprovalKey: key, Surfaces: surfaces, Decision: decisions,
ListenAddr: listenOr(s.env.Listen, wiring.DefaultControlListen), AllowNonLoopback: s.env.AllowNonLoopback,
Probes: wiring.ZoneProbes(s.env.AppHealthURL, s.env.DispatcherHealthURL), Clock: s.clock, Logger: log,
TrustedProxies: s.env.TrustedProxies, Reconcile: s.env.Reconcile,
TrustedProxies: s.env.TrustedProxies, Reconcile: s.env.Reconcile, ProviderCost: providerCost,
})
}

Expand Down Expand Up @@ -118,7 +121,13 @@ func runControl(ctx context.Context, args []string, getenv func(string) string,
if decisions != nil {
decisions.Secrets = secretSet.Resolver
}
c, err := newControl(s, log, surfaces, decisions)
// The control zone alone holds the admin keys that read what the
// providers report was spent.
providerCost, err := wiring.ProviderCostFromEnv(getenv)
if err != nil {
return err
}
c, err := newControl(s, log, surfaces, decisions, providerCost)
if err != nil {
return err
}
Expand Down Expand Up @@ -159,7 +168,7 @@ func runPolicyApprove(ctx context.Context, args []string, getenv func(string) st
return err
}
defer func() { _ = s.store.Close() }()
c, err := newControl(s, log, nil, nil)
c, err := newControl(s, log, nil, nil, nil)
if err != nil {
return err
}
Expand Down Expand Up @@ -187,7 +196,7 @@ func runPolicyRequest(ctx context.Context, args []string, getenv func(string) st
return err
}
defer func() { _ = s.store.Close() }()
c, err := newControl(s, log, nil, nil)
c, err := newControl(s, log, nil, nil, nil)
if err != nil {
return err
}
Expand Down Expand Up @@ -216,7 +225,7 @@ func runIssueRetry(ctx context.Context, args []string, getenv func(string) strin
return err
}
defer func() { _ = s.store.Close() }()
c, err := newControl(s, log, nil, nil)
c, err := newControl(s, log, nil, nil, nil)
if err != nil {
return err
}
Expand Down
13 changes: 11 additions & 2 deletions cmd/factoryd/wiring/control.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@ type ControlConfig struct {
// Reconcile configures the polls that recover issue changes whose
// webhooks were lost.
Reconcile ReconcileConfig
// ProviderCost reads what the providers report was spent, by provider
// name, for the providers the budget settings name; see
// ProviderCostFromEnv. A named provider missing here holds capped runs.
ProviderCost map[string]budget.CostSource
}

// Control is the control zone of one factory: the HTTP server, intake, the
Expand Down Expand Up @@ -129,6 +133,8 @@ type Control struct {
// route. reportsOff is set once a pass said why it publishes none.
reports *control.ReportPublisher
reportsOff bool
// providerSpend reads the providers' spend for the budget gate.
providerSpend budget.ProviderSpendRefresher
// budget closes the reservation of a run whose issue the control zone
// blocks because the run stopped.
budget *budget.Gate
Expand Down Expand Up @@ -169,7 +175,8 @@ func NewControl(cfg ControlConfig) (*Control, error) {
c := &Control{cfg: cfg, log: cfg.Logger, backoff: map[string]retryAt{}, projected: map[core.IssueRef]int64{},
progress: &github.ProgressComment{Issues: cfg.GitHub, Self: settings.Self, Factory: m.FactoryID},
progressShown: map[core.IssueRef]string{}, redactor: redact.New(redact.Config{}),
budget: budget.NewGate(budget.Config{Clock: cfg.Clock})}
budget: budget.NewGate(budget.Config{Clock: cfg.Clock}),
providerSpend: budget.ProviderSpendRefresher{Store: budget.StateStore(cfg.Store), Sources: cfg.ProviderCost, Clock: cfg.Clock}}
c.Audit = audit.New(cfg.Store, cfg.Clock)
reconcile, err := cfg.Reconcile.withDefaults()
if err != nil {
Expand Down Expand Up @@ -310,7 +317,8 @@ func (c *Control) Run(ctx context.Context, ln net.Listener, interval time.Durati
// parks the issues whose wait for an answer is over, polling GitHub first
// when an answer may not be known yet, and blocks the issues whose run
// stopped without a candidate; when it is configured,
// the decision layer reads the edge's counters; the stored bug reports
// the decision layer reads the edge's counters; the providers' report of
// what was spent is read for the budget gate when it is due; the stored bug reports
// past their retention are pruned, and a small batch of those waiting is
// published as GitHub issues for a person to triage. Once per reconciliation
// interval it asks GitHub for the issue changes no webhook delivered. Each part runs even
Expand Down Expand Up @@ -350,6 +358,7 @@ func (c *Control) Pass(ctx context.Context) error {
c.projectProgress(ctx),
c.projectLifecycle(ctx),
c.runDecisions(ctx),
c.providerSpend.Refresh(ctx),
pruned,
// Late, so publishing reports delays none of the factory's own work.
c.publishReports(ctx),
Expand Down
47 changes: 47 additions & 0 deletions cmd/factoryd/wiring/control_provider_spend_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package wiring_test

import (
"context"
"encoding/json"
"testing"
"time"

"github.com/bestagentkits/sisf/internal/budget"
"github.com/bestagentkits/sisf/internal/testkit/harness"
"github.com/bestagentkits/sisf/pkg/core"
"github.com/bestagentkits/sisf/pkg/state"
)

// spendOf is a provider that reports a fixed spend.
type spendOf core.Micros

func (s spendOf) Spent(_ context.Context, since time.Time) (core.Micros, time.Time, error) {
return core.Micros(s), since, nil
}

// A control pass reads the spend of the providers the budget settings name
// and stores it where the agent zone's gate reads it.
func TestAControlPassReadsTheProvidersSpend(t *testing.T) {
t.Parallel()
ctx := context.Background()
f := harness.New(t, harness.Options{ProviderCost: map[string]budget.CostSource{budget.ProviderAnthropic: spendOf(3_000_000)}})
settings, _ := json.Marshal(budget.Settings{Mode: core.BudgetCapped, CapMicros: 10_000_000, Period: budget.PeriodDay,
ProviderHardCap: true, ProviderCostSources: []string{budget.ProviderAnthropic}})
if err := f.ControlStore.Update(ctx, func(ctx context.Context, tx state.Tx) error {
_, err := tx.PutKV(ctx, state.KVEntry{Namespace: budget.SettingsNamespace, Key: budget.SettingsKey, Value: settings})
return err
}); err != nil {
t.Fatal(err)
}
f.Pass()
var spend budget.ProviderSpend
if err := f.ControlStore.View(ctx, func(ctx context.Context, tx state.Tx) (err error) {
spend, _, _, err = budget.LoadProviderSpend(ctx, tx)
return err
}); err != nil {
t.Fatal(err)
}
if got := spend.Sources[budget.ProviderAnthropic].SpentMicros; got != 3_000_000 || !spend.FetchedAt.Equal(f.Clock.Now()) {
t.Fatalf("the stored provider spend: %+v, want 3 read now", spend)
}
}
50 changes: 50 additions & 0 deletions cmd/factoryd/wiring/provider_cost_env.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package wiring

import (
"strings"

"github.com/bestagentkits/sisf/internal/budget"
"github.com/bestagentkits/sisf/internal/budget/providercost"
"github.com/bestagentkits/sisf/pkg/core"
)

// The control zone's credentials for reading what the providers report
// was spent. Each admin key comes with the one workspace or project the
// factory's runs are charged to, so other work there is not counted as the
// factory's. Their names start with SISF_, which no agent environment
// accepts, so a key the control zone holds never reaches an agent.
const (
EnvAnthropicAdminKey = "SISF_ANTHROPIC_ADMIN_KEY"
EnvAnthropicCostWorkspace = "SISF_ANTHROPIC_COST_WORKSPACE"
EnvOpenAIAdminKey = "SISF_OPENAI_ADMIN_KEY"
EnvOpenAICostProject = "SISF_OPENAI_COST_PROJECT"
)

// ProviderCostFromEnv builds the providers' cost sources the environment
// configures. A key without its workspace or project, or the reverse, is
// refused rather than read across the whole organization.
func ProviderCostFromEnv(getenv func(string) string) (map[string]budget.CostSource, error) {
sources := map[string]budget.CostSource{}
pair := func(keyName, scopeName string) (core.SecretValue, string, error) {
key, scope := strings.TrimSpace(getenv(keyName)), strings.TrimSpace(getenv(scopeName))
if (key == "") != (scope == "") {
return core.SecretValue{}, "", core.NewError(core.CodeInvalidArgument, keyName+" and "+scopeName+" are set together or not at all")
}
return core.NewSecretValue([]byte(key)), scope, nil
}
key, workspace, err := pair(EnvAnthropicAdminKey, EnvAnthropicCostWorkspace)
if err != nil {
return nil, err
}
if workspace != "" {
sources[budget.ProviderAnthropic] = providercost.Anthropic{AdminKey: key, WorkspaceID: workspace}
}
key, project, err := pair(EnvOpenAIAdminKey, EnvOpenAICostProject)
if err != nil {
return nil, err
}
if project != "" {
sources[budget.ProviderOpenAI] = providercost.OpenAI{AdminKey: key, ProjectID: project}
}
return sources, nil
}
52 changes: 52 additions & 0 deletions cmd/factoryd/wiring/provider_cost_env_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package wiring_test

import (
"testing"

"github.com/bestagentkits/sisf/cmd/factoryd/wiring"
"github.com/bestagentkits/sisf/internal/budget"
"github.com/bestagentkits/sisf/pkg/agent/agentenv"
"github.com/bestagentkits/sisf/pkg/core"
)

// Each admin key needs the one workspace or project the factory's runs
// are charged to; neither is accepted alone.
func TestAProviderCostKeyNeedsTheFactorysOwnScope(t *testing.T) {
t.Parallel()
for name, vars := range map[string]map[string]string{
"anthropic key alone": {wiring.EnvAnthropicAdminKey: "k"},
"anthropic workspace alone": {wiring.EnvAnthropicCostWorkspace: "wrkspc_factory"},
"openai key alone": {wiring.EnvOpenAIAdminKey: "k"},
"openai project alone": {wiring.EnvOpenAICostProject: "proj_factory"},
} {
if _, err := wiring.ProviderCostFromEnv(envOf(vars)); !core.HasCode(err, core.CodeInvalidArgument) {
t.Errorf("%s: %v, want INVALID_ARGUMENT", name, err)
}
}
sources, err := wiring.ProviderCostFromEnv(envOf(map[string]string{
wiring.EnvAnthropicAdminKey: "k", wiring.EnvAnthropicCostWorkspace: "wrkspc_factory",
wiring.EnvOpenAIAdminKey: "k", wiring.EnvOpenAICostProject: "proj_factory",
}))
if err != nil || sources[budget.ProviderAnthropic] == nil || sources[budget.ProviderOpenAI] == nil {
t.Fatalf("both providers configured: %v, %v", sources, err)
}
if sources, err := wiring.ProviderCostFromEnv(envOf(nil)); err != nil || len(sources) != 0 {
t.Fatalf("nothing configured: %v, %v", sources, err)
}
}

// The admin keys that read the providers' spend stay in the control zone:
// no agent environment may carry them, even when an operator asks.
func TestAProviderAdminKeyNeverReachesAnAgent(t *testing.T) {
t.Parallel()
for _, name := range []string{wiring.EnvAnthropicAdminKey, wiring.EnvOpenAIAdminKey} {
if err := agentenv.Allowed(name); !core.HasCode(err, core.CodePermissionDenied) {
t.Errorf("%s may be passed to an agent: %v", name, err)
}
_, err := agentenv.Build(agentenv.Spec{Agent: "claude", Home: "/home/agent", Extra: []string{name},
LookupEnv: func(string) (string, bool) { return "secret", true }})
if !core.HasCode(err, core.CodePermissionDenied) {
t.Errorf("an agent environment carried %s: %v", name, err)
}
}
}
2 changes: 1 addition & 1 deletion docs/acceptance-matrix.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Status meanings: **present** means the file exists in this branch and its packag
| SISF-11 | `internal/policy/unapproved_policy_change_ignored_test.go` | present |
| SISF-12 | `internal/auth/sso_oauth_negative_test.go` | present (against fakes, not real Google SSO) |
| SISF-13 | `tests/acceptance/five_surface_parity_test.go` (with `cross_surface_approval_test.go` and `step_up_and_write_limits_test.go`) | present (CLI, REST, MCP, WebMCP tool path and dashboard forms against the wired control server and fake identity provider) |
| SISF-14 | `internal/budget/budget_modes_test.go` (with `internal/budget/budget_status_test.go` `TestUnverifiedUsageAndAMissingHardCapAreShown` for a provider without a hard cap; `internal/budget/unpriced_usage_test.go` and `internal/budget/unpriced_usage_store_test.go` for usage whose provider reported no cost, recorded as reported, charged when its run closes and warned about; `internal/dispatcher/run_spend_test.go`, `cmd/supervisor/stages/run_close_reported_cost_test.go` and `pkg/state/sqlstore/run_usage_test.go` for closing a run with the cost its ledger rows show, not the agent zone's record; `pkg/state/sqlstore/usage_ledger_trust_test.go` for the agent zone's rows dated by the store and booked only against its run's reservation, rows dated before a reservation not counting, verified usage refused, costs bounded and summed without overflow, negative costs counted as 0 and their run charged in full, and a row that states no cost leaving its run unpriced (`pkg/state/sqlstore/run_usage_test.go`; `internal/dispatcher/run_spend_test.go` also pins the limit that a run booking one micro is taken at its word); `internal/budget/budget_total_overflow_test.go` for totals near the store's cap filling the budget instead of wrapping; `pkg/state/sqlstore/budget_database_time_and_usage_test.go` for the PostgreSQL zone roles dated by the server's clock, refused verified usage and refused agent usage outside a reservation of its own factory, run and issue over plain SQL (runs only with `SISF_TEST_PG_DSN` set); `internal/budget/run_reservation_id_test.go`, `cmd/factoryd/wiring/control_stopped_run_reservation_test.go` and `cmd/supervisor/stages/run_close_own_reservation_test.go` for closing a run's reservation by its ID, never the one its run record names; `cmd/supervisor/stages/run_close_retry_test.go` and `cmd/supervisor/stages/run_close_due_bound_test.go` for retrying a failed close and abandoning one that can never succeed) | present |
| SISF-14 | `internal/budget/budget_modes_test.go` (with `internal/budget/budget_status_test.go` `TestUnverifiedUsageAndAMissingHardCapAreShown` for a provider without a hard cap; `internal/budget/unpriced_usage_test.go` and `internal/budget/unpriced_usage_store_test.go` for usage whose provider reported no cost, recorded as reported, charged when its run closes and warned about; `internal/dispatcher/run_spend_test.go`, `cmd/supervisor/stages/run_close_reported_cost_test.go` and `pkg/state/sqlstore/run_usage_test.go` for closing a run with the cost its ledger rows show, not the agent zone's record; `pkg/state/sqlstore/usage_ledger_trust_test.go` for the agent zone's rows dated by the store and booked only against its run's reservation, rows dated before a reservation not counting, verified usage refused, costs bounded and summed without overflow, negative costs counted as 0 and their run charged in full, and a row that states no cost leaving its run unpriced (`pkg/state/sqlstore/run_usage_test.go`; `internal/dispatcher/run_spend_test.go` also pins the limit that a run booking one micro is taken at its word); `internal/budget/budget_total_overflow_test.go` for totals near the store's cap filling the budget instead of wrapping; `pkg/state/sqlstore/budget_database_time_and_usage_test.go` for the PostgreSQL zone roles dated by the server's clock, refused verified usage and refused agent usage outside a reservation of its own factory, run and issue over plain SQL (runs only with `SISF_TEST_PG_DSN` set); `internal/budget/run_reservation_id_test.go`, `cmd/factoryd/wiring/control_stopped_run_reservation_test.go` and `cmd/supervisor/stages/run_close_own_reservation_test.go` for closing a run's reservation by its ID, never the one its run record names; `cmd/supervisor/stages/run_close_retry_test.go` and `cmd/supervisor/stages/run_close_due_bound_test.go` for retrying a failed close and abandoning one that can never succeed; `internal/budget/provider_spend_test.go`, `internal/budget/provider_spend_store_test.go`, `internal/budget/providercost/provider_cost_sources_test.go`, `cmd/factoryd/wiring/control_provider_spend_test.go` and `cmd/factoryd/wiring/provider_cost_env_test.go` for the providers' own report bounding what the agents report, written by the control zone alone, holding capped runs when stale but never a rollback, and its admin keys never reaching an agent) | present |
| SISF-15 | `tests/acceptance/two_factories_same_upstream_test.go` | present |
| SISF-16 | `internal/conformance/backend_capability_matrix_test.go` | present |
| SISF-17 | `internal/decision/no_benefit_signal_ignored_test.go` | present |
Expand Down
Loading
Loading