diff --git a/PLAN.md b/PLAN.md
index fd439d8..0b2154d 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -53,9 +53,9 @@ branch `phase10` (2026-11-25), not yet merged: schema 36, a new
the visible changes are posting accounts, Connections, Activity, and a
CSRF token in every form.
-**Next: Phase 11, agents.** Parts 1–3 (agent users and keys, module tools
-over MCP, approvals) are built on branch `phase11`; part 4 (limits and
-visibility) is next. Phase 12 still needs who adds Supermarket's client to
+**Next: Phase 11, agents.** Parts 1–4 (agent users and keys, module tools
+over MCP, approvals, limits and visibility) are built on branch `phase11`;
+part 5 (a JSON API) can wait until someone needs it. Phase 12 still needs who adds Supermarket's client to
Authelia.
**Coming back to it (for the agent working on it):**
@@ -2620,6 +2620,28 @@ single `mcp-token`. A commit after each part.
tools that change things, and once allowed once a day, posts on its own
once, then asks again. Revoking its key stops it at once.
+**Part 4 built 2026-11-26** on `phase11`.
+- Schema 39: `agent_limits` (calls a minute, default 60; things it asks to
+ send out a day, default 50; paused, by whom) and `agent_calls` (each tool
+ call: when, the tool, ok, error or refused, the error or the start of the
+ answer, how long), kept 30 days (`job:accounts`, now on every edition).
+ The calls aren't exported.
+- Each tool call goes through a middleware on the agent's MCP server: over
+ its calls a minute, it's refused (*too many calls*) and recorded as
+ refused, which doesn't count toward the next minute's; then it's
+ recorded with how it went. Asking to send something out counts against
+ its cap per day (in the last 24 hours, approved or not); over it, the
+ agent is told to wait or ask for a higher limit.
+- *Pause* (on the agent's page, and shown on the list) refuses every call
+ at once, with 403 and why, whatever key it uses, also mid-session; *Resume*
+ undoes it. Pausing, resuming and the limits are in the audit log.
+- The agent's page shows its limits, what it asked to send out in the last
+ 24 hours, what it's waiting on (linked to Approvals), and its last 50
+ calls.
+- Fixed from part 1: each agent's MCP server was cached by its scopes, so
+ two agents with the same scopes shared one, and the tools recorded the
+ first as the writer of what both wrote. Now each agent has its own.
+
1. **Agent users and their keys.**
- An admin creates an agent on Settings → Users → *New agent*. It has a
name, a description, and the modules it's given, each *read* or
diff --git a/internal/approvals/approvals.go b/internal/approvals/approvals.go
index bc3ba16..0f05bda 100644
--- a/internal/approvals/approvals.go
+++ b/internal/approvals/approvals.go
@@ -252,3 +252,11 @@ func Allowed(d *db.DB, agent int64, class string, now time.Time) (bool, error) {
agent, class, Done, Failed, ts(now.Add(-24*time.Hour))).Scan(&n)
return n < cap, err
}
+
+// AskedSince counts what an agent asked to send out since a time, approved
+// or not: its cap per day.
+func AskedSince(d *db.DB, agent int64, since time.Time) (int, error) {
+ var n int
+ err := d.QueryRow(`SELECT count(*) FROM approvals WHERE agent_id = ? AND created_at >= ?`, agent, ts(since)).Scan(&n)
+ return n, err
+}
diff --git a/internal/db/migrations.go b/internal/db/migrations.go
index 8f35ece..e4b6ad9 100644
--- a/internal/db/migrations.go
+++ b/internal/db/migrations.go
@@ -217,6 +217,29 @@ CREATE TABLE agent_autonomy (
granted_at TEXT NOT NULL,
PRIMARY KEY (agent_id, class)
);
+`,
+ },
+ // 39
+ {
+ Note: "agents' limits and pause switch, and the calls they make",
+ SQLite: `
+CREATE TABLE agent_limits (
+ agent_id INTEGER PRIMARY KEY,
+ per_minute INTEGER NOT NULL DEFAULT 60, -- tool calls a minute
+ out_per_day INTEGER NOT NULL DEFAULT 50, -- things it asks to send out, in 24 hours
+ paused_at TEXT NOT NULL DEFAULT '', -- '' when running
+ paused_by INTEGER NOT NULL DEFAULT 0
+);
+CREATE TABLE agent_calls (
+ id INTEGER PRIMARY KEY,
+ agent_id INTEGER NOT NULL,
+ at TEXT NOT NULL,
+ tool TEXT NOT NULL,
+ outcome TEXT NOT NULL, -- ok, error, refused (over the rate)
+ detail TEXT NOT NULL DEFAULT '', -- the error, or the start of the answer
+ ms INTEGER NOT NULL DEFAULT 0
+);
+CREATE INDEX agent_calls_agent ON agent_calls(agent_id, at);
`,
},
}
diff --git a/internal/mcpserver/mcpserver.go b/internal/mcpserver/mcpserver.go
index b0201ed..c21ac68 100644
--- a/internal/mcpserver/mcpserver.go
+++ b/internal/mcpserver/mcpserver.go
@@ -32,8 +32,21 @@ type Caller struct {
// Can says whether the agent may read (act false) or change things in
// a module or scope (market, crm, …).
Can func(scope string, act bool) bool
+ // Before is asked before each tool call (a rate limit); an error
+ // refuses it. After hears how it went. Either may be nil.
+ Before func(ctx context.Context, tool string) error
+ After func(tool string, res *mcp.CallToolResult, err error, took time.Duration)
}
+// Refusal is an Authenticator's error that says why, with an HTTP status
+// (a paused agent: 403), rather than a plain 401.
+type Refusal struct {
+ Status int
+ Reason string
+}
+
+func (r *Refusal) Error() string { return r.Reason }
+
// Authenticator finds the caller of a request from its bearer key; an
// error refuses it.
type Authenticator func(r *http.Request, key string) (*Caller, error)
@@ -46,10 +59,15 @@ type Authenticator func(r *http.Request, key string) (*Caller, error)
// them, as they call what its pages call); nil for none.
func Handler(d *db.DB, version string, auth Authenticator, more func(*mcp.Server, *Caller)) http.Handler {
var mu sync.Mutex
- servers := map[string]*mcp.Server{} // by the scopes' signature: a few at most
+ // One server per agent and its scopes: tools know who calls them, and a
+ // change of scopes makes a new one.
+ servers := map[string]*mcp.Server{}
h := mcp.NewStreamableHTTPHandler(func(r *http.Request) *mcp.Server {
c, _ := r.Context().Value(callerKey{}).(*Caller)
sig := signature(c)
+ if c != nil {
+ sig = fmt.Sprintf("%d/%s", c.ID, sig)
+ }
mu.Lock()
defer mu.Unlock()
if srv, ok := servers[sig]; ok {
@@ -60,6 +78,9 @@ func Handler(d *db.DB, version string, auth Authenticator, more func(*mcp.Server
if more != nil {
more(srv, c)
}
+ if c != nil {
+ srv.AddReceivingMiddleware(watch(c))
+ }
servers[sig] = srv
return srv
}, &mcp.StreamableHTTPOptions{Stateless: true, JSONResponse: true})
@@ -71,6 +92,11 @@ func Handler(d *db.DB, version string, auth Authenticator, more func(*mcp.Server
if ok && key != "" {
c, err = auth(r, strings.TrimSpace(key))
}
+ var refusal *Refusal
+ if errors.As(err, &refusal) {
+ http.Error(w, refusal.Reason, refusal.Status)
+ return
+ }
if !ok || key == "" || err != nil || c == nil {
w.Header().Set("WWW-Authenticate", `Bearer realm="supermarket"`)
http.Error(w, "unauthorized", http.StatusUnauthorized)
@@ -82,6 +108,30 @@ func Handler(d *db.DB, version string, auth Authenticator, more func(*mcp.Server
type callerKey struct{}
+// watch asks the caller's Before and tells its After about each tool call.
+func watch(c *Caller) mcp.Middleware {
+ return func(next mcp.MethodHandler) mcp.MethodHandler {
+ return func(ctx context.Context, method string, req mcp.Request) (mcp.Result, error) {
+ p, ok := req.GetParams().(*mcp.CallToolParamsRaw)
+ if method != "tools/call" || !ok {
+ return next(ctx, method, req)
+ }
+ if c.Before != nil {
+ if err := c.Before(ctx, p.Name); err != nil {
+ return nil, err
+ }
+ }
+ start := time.Now()
+ res, err := next(ctx, method, req)
+ if c.After != nil {
+ out, _ := res.(*mcp.CallToolResult)
+ c.After(p.Name, out, err, time.Since(start))
+ }
+ return res, err
+ }
+ }
+}
+
// scopes are what tools are offered by: each, read or act.
var scopes = []string{"content", "prospects", "seo", "sites", "metrics", "market", "crm"}
diff --git a/internal/transfer/transfer.go b/internal/transfer/transfer.go
index 953701c..914a782 100644
--- a/internal/transfer/transfer.go
+++ b/internal/transfer/transfer.go
@@ -42,7 +42,7 @@ type Manifest struct {
// company's data. Secrets go in secrets.json, opened, if asked for.
var skipped = map[string]bool{
"instances": true, "locks": true, "schema_version": true, "schema_migrations": true, "secrets": true,
- "sessions": true, "links": true, "throttle": true,
+ "sessions": true, "links": true, "throttle": true, "agent_calls": true,
}
// startupSettings are settings a new install writes when it first starts:
diff --git a/internal/users/agentlimits.go b/internal/users/agentlimits.go
new file mode 100644
index 0000000..a77a415
--- /dev/null
+++ b/internal/users/agentlimits.go
@@ -0,0 +1,125 @@
+package users
+
+import (
+ "database/sql"
+ "errors"
+ "time"
+
+ "supermarket/internal/db"
+)
+
+// An agent's limits: calls a minute, things sent out a day, and whether
+// it's paused. Agents without a row have the defaults.
+
+// Default limits.
+const (
+ DefaultPerMinute = 60
+ DefaultOutPerDay = 50
+)
+
+// Limits are an agent's.
+type Limits struct {
+ PerMinute int
+ OutPerDay int
+ Paused time.Time // zero when running
+ PausedBy int64
+}
+
+// LimitsOf are an agent's limits.
+func LimitsOf(d *db.DB, agent int64) (Limits, error) {
+ l := Limits{PerMinute: DefaultPerMinute, OutPerDay: DefaultOutPerDay}
+ var paused string
+ err := d.QueryRow(`SELECT per_minute, out_per_day, paused_at, paused_by FROM agent_limits WHERE agent_id = ?`, agent).
+ Scan(&l.PerMinute, &l.OutPerDay, &paused, &l.PausedBy)
+ if errors.Is(err, sql.ErrNoRows) {
+ return l, nil
+ }
+ l.Paused = parseTS(paused)
+ return l, err
+}
+
+// SetLimits changes an agent's calls a minute and sends a day (each at
+// least 1).
+func SetLimits(d *db.DB, agent int64, perMinute, outPerDay int) error {
+ if perMinute < 1 || outPerDay < 1 {
+ return errors.New("limits are at least 1")
+ }
+ _, err := d.Exec(`INSERT INTO agent_limits (agent_id, per_minute, out_per_day) VALUES (?, ?, ?)
+ ON CONFLICT (agent_id) DO UPDATE SET per_minute = excluded.per_minute, out_per_day = excluded.out_per_day`, agent, perMinute, outPerDay)
+ return err
+}
+
+// Pause stops all of an agent's calls (by: who), or lets them go on.
+func Pause(d *db.DB, agent int64, paused bool, by int64, now time.Time) error {
+ at := ""
+ if paused {
+ at = ts(now)
+ }
+ _, err := d.Exec(`INSERT INTO agent_limits (agent_id, per_minute, out_per_day, paused_at, paused_by) VALUES (?, ?, ?, ?, ?)
+ ON CONFLICT (agent_id) DO UPDATE SET paused_at = excluded.paused_at, paused_by = excluded.paused_by`,
+ agent, DefaultPerMinute, DefaultOutPerDay, at, by)
+ return err
+}
+
+// Call is one tool call an agent made.
+type Call struct {
+ ID int64
+ Agent int64
+ At time.Time
+ Tool string
+ Outcome string // ok, error, refused
+ Detail string
+ Took time.Duration
+}
+
+// Outcomes.
+const (
+ CallOK = "ok"
+ CallError = "error"
+ CallRefused = "refused"
+)
+
+// RecordCall notes a tool call.
+func RecordCall(d *db.DB, c Call) error {
+ if r := []rune(c.Detail); len(r) > 300 {
+ c.Detail = string(r[:299]) + "…"
+ }
+ _, err := d.Exec(`INSERT INTO agent_calls (agent_id, at, tool, outcome, detail, ms) VALUES (?, ?, ?, ?, ?, ?)`,
+ c.Agent, ts(c.At), c.Tool, c.Outcome, c.Detail, c.Took.Milliseconds())
+ return err
+}
+
+// CallsSince counts an agent's calls since a time, not counting those
+// refused over the rate.
+func CallsSince(d *db.DB, agent int64, since time.Time) (int, error) {
+ var n int
+ err := d.QueryRow(`SELECT count(*) FROM agent_calls WHERE agent_id = ? AND at >= ? AND outcome <> ?`, agent, ts(since), CallRefused).Scan(&n)
+ return n, err
+}
+
+// RecentCalls are an agent's last calls, newest first.
+func RecentCalls(d *db.DB, agent int64, limit int) ([]Call, error) {
+ rows, err := d.Query(`SELECT id, agent_id, at, tool, outcome, detail, ms FROM agent_calls WHERE agent_id = ? ORDER BY id DESC LIMIT ?`, agent, limit)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []Call
+ for rows.Next() {
+ var c Call
+ var at string
+ var ms int64
+ if err := rows.Scan(&c.ID, &c.Agent, &at, &c.Tool, &c.Outcome, &c.Detail, &ms); err != nil {
+ return nil, err
+ }
+ c.At, c.Took = parseTS(at), time.Duration(ms)*time.Millisecond
+ out = append(out, c)
+ }
+ return out, rows.Err()
+}
+
+// PruneCalls forgets calls older than 30 days.
+func PruneCalls(d *db.DB, now time.Time) error {
+ _, err := d.Exec(`DELETE FROM agent_calls WHERE at < ?`, ts(now.Add(-30*24*time.Hour)))
+ return err
+}
diff --git a/internal/users/agents_test.go b/internal/users/agents_test.go
index 1cb8dd3..636f112 100644
--- a/internal/users/agents_test.go
+++ b/internal/users/agents_test.go
@@ -105,3 +105,40 @@ func TestAgentKeys(t *testing.T) {
t.Error("keys outlived the agent")
}
}
+
+func TestAgentLimitsAndCalls(t *testing.T) {
+ d := openDB(t)
+ now := time.Now()
+ a, _ := CreateAgent(d, "Bot", "", now)
+ l, _ := LimitsOf(d, a.ID)
+ if l.PerMinute != DefaultPerMinute || l.OutPerDay != DefaultOutPerDay || !l.Paused.IsZero() {
+ t.Errorf("defaults %+v", l)
+ }
+ if err := SetLimits(d, a.ID, 0, 5); err == nil {
+ t.Error("zero accepted")
+ }
+ SetLimits(d, a.ID, 10, 5)
+ Pause(d, a.ID, true, 7, now)
+ l, _ = LimitsOf(d, a.ID)
+ if l.PerMinute != 10 || l.OutPerDay != 5 || l.Paused.IsZero() || l.PausedBy != 7 {
+ t.Errorf("set %+v", l)
+ }
+ Pause(d, a.ID, false, 7, now)
+ if l, _ = LimitsOf(d, a.ID); !l.Paused.IsZero() || l.PerMinute != 10 {
+ t.Errorf("resumed %+v", l)
+ }
+ RecordCall(d, Call{Agent: a.ID, At: now.Add(-2 * time.Minute), Tool: "x", Outcome: CallOK})
+ RecordCall(d, Call{Agent: a.ID, At: now, Tool: "y", Outcome: CallError, Detail: strings.Repeat("e", 400), Took: 1500 * time.Millisecond})
+ RecordCall(d, Call{Agent: a.ID, At: now, Tool: "z", Outcome: CallRefused})
+ if n, _ := CallsSince(d, a.ID, now.Add(-time.Minute)); n != 1 {
+ t.Errorf("calls in a minute: %d", n)
+ }
+ calls, _ := RecentCalls(d, a.ID, 10)
+ if len(calls) != 3 || calls[1].Tool != "y" || calls[1].Took != 1500*time.Millisecond || len([]rune(calls[1].Detail)) != 300 {
+ t.Errorf("recent %+v", calls)
+ }
+ PruneCalls(d, now.Add(31*24*time.Hour))
+ if calls, _ = RecentCalls(d, a.ID, 10); len(calls) != 0 {
+ t.Error("not pruned")
+ }
+}
diff --git a/internal/web/activity.go b/internal/web/activity.go
index 06e6a8b..163e667 100644
--- a/internal/web/activity.go
+++ b/internal/web/activity.go
@@ -180,6 +180,7 @@ var actionLabels = map[string]string{
"key-made": "made a new key for", "key-revoked": "revoked a key of",
"asked-approval": "asked for approval to", "did-on-its-own": "did on its own:", "approved": "approved", "refused": "refused",
"allowed-on-its-own": "let an agent act on its own:", "withdrew-on-its-own": "took back what an agent may do on its own:",
+ "agent-paused": "paused the agent", "agent-resumed": "resumed the agent", "agent-limits": "changed the limits of",
"wrote-draft": "wrote a draft:", "edited-draft": "edited a draft:", "edited-change": "edited a proposed change to", "market-added": "added to the Market", "market-changed": "changed in the Market",
}
diff --git a/internal/web/agentlimits_test.go b/internal/web/agentlimits_test.go
new file mode 100644
index 0000000..987b7c9
--- /dev/null
+++ b/internal/web/agentlimits_test.go
@@ -0,0 +1,99 @@
+package web
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "supermarket/internal/content"
+ "supermarket/internal/posting"
+ "supermarket/internal/users"
+)
+
+func TestAgentPauseAndLimits(t *testing.T) {
+ s, h := newTestServer(t, nil)
+ agent, key := newAgent(t, s, "Busy", map[string]users.Access{"content": users.Edit})
+ page := "/settings/agents/" + strconv.FormatInt(agent.ID, 10)
+
+ // Its calls are listed on its page, errors too.
+ mcpCall(t, h, key, "content_drafts", map[string]any{})
+ mcpCall(t, h, key, "content_create_draft", map[string]any{"channel": "myspace", "text": "x"})
+ body := do(h, http.MethodGet, page, nil, nil).Body.String()
+ if !strings.Contains(body, "content_drafts") || !strings.Contains(body, "no channel") {
+ t.Errorf("calls: %s", body)
+ }
+
+ // Pause: every call refused at once, with why.
+ postForm(h, page+"/pause", url.Values{})
+ code, _ := mcpTools(h, key)
+ if code != http.StatusForbidden {
+ t.Errorf("paused: %d", code)
+ }
+ if body := do(h, http.MethodGet, "/settings/agents", nil, nil).Body.String(); !strings.Contains(body, "paused") {
+ t.Error("not shown as paused")
+ }
+ postForm(h, page+"/resume", url.Values{})
+ if code, _ := mcpTools(h, key); code != http.StatusOK {
+ t.Errorf("resumed: %d", code)
+ }
+
+ // Calls a minute.
+ if rec := postForm(h, page+"/limits", url.Values{"per_minute": {"0"}, "out_per_day": {"1"}}); rec.Code != http.StatusUnprocessableEntity {
+ t.Errorf("zero: %d", rec.Code)
+ }
+ postForm(h, page+"/limits", url.Values{"per_minute": {"3"}, "out_per_day": {"1"}})
+ // Two calls so far in this minute; one more is fine, the next isn't.
+ if _, isErr := mcpCall(t, h, key, "content_drafts", map[string]any{}); isErr {
+ t.Error("third call refused")
+ }
+ if text, isErr := mcpCall(t, h, key, "content_drafts", map[string]any{}); !isErr || !strings.Contains(text, "3 a minute") {
+ t.Errorf("fourth call: %v %s", isErr, text)
+ }
+ calls, _ := users.RecentCalls(s.DB, agent.ID, 1)
+ if calls[0].Outcome != users.CallRefused {
+ t.Errorf("not recorded as refused: %+v", calls[0])
+ }
+ // A minute later it may call again (the refused call doesn't count).
+ s.DB.Exec(`UPDATE agent_calls SET at = ?`, time.Now().Add(-2*time.Minute).UTC().Format("2006-01-02T15:04:05.000Z"))
+
+ // Things sent out a day: one.
+ postForm(h, page+"/limits", url.Values{"per_minute": {"100"}, "out_per_day": {"1"}})
+ company := &posting.Account{Network: posting.X, Name: "@acme", External: "acme"}
+ posting.Save(s.DB, s.Secrets, company, "t", "", time.Now())
+ posting.SetGrants(s.DB, map[int64][]int64{company.ID: {agent.ID}})
+ for i, want := range []string{"Waiting for approval", "may ask to send out 1 things a day"} {
+ text, _ := mcpCall(t, h, key, "content_create_draft", map[string]any{"channel": "x", "text": "Post " + strconv.Itoa(i)})
+ var d draftView
+ json.Unmarshal([]byte(text), &d)
+ if text, _ := mcpCall(t, h, key, "content_publish", map[string]any{"draft_id": d.ID}); !strings.Contains(text, want) {
+ t.Errorf("ask %d: %s", i, text)
+ }
+ }
+ if body := do(h, http.MethodGet, page, nil, nil).Body.String(); !strings.Contains(body, "Waiting on") || !strings.Contains(body, "asked to send out 1 of its 1") {
+ t.Errorf("agent page: %s", body)
+ }
+}
+
+// Two agents with the same scopes each have their own server: what they
+// write is theirs.
+func TestAgentsDontShareServers(t *testing.T) {
+ s, h := newTestServer(t, nil)
+ scopes := map[string]users.Access{"content": users.Edit}
+ a, ka := newAgent(t, s, "A", scopes)
+ b, kb := newAgent(t, s, "B", scopes)
+ for _, k := range []string{ka, kb} {
+ mcpCall(t, h, k, "content_create_draft", map[string]any{"channel": "x", "text": "From " + k[:8]})
+ }
+ list, _ := content.ListDrafts(s.DB, 10, content.StatusDraft)
+ by := map[string]int64{}
+ for _, d := range list {
+ by[d.Content] = d.WrittenBy
+ }
+ if by["From "+ka[:8]] != a.ID || by["From "+kb[:8]] != b.ID {
+ t.Errorf("written by %v (a %d, b %d)", by, a.ID, b.ID)
+ }
+}
diff --git a/internal/web/agents.go b/internal/web/agents.go
index dba27a7..ef644e8 100644
--- a/internal/web/agents.go
+++ b/internal/web/agents.go
@@ -1,12 +1,16 @@
package web
import (
+ "context"
"errors"
+ "fmt"
"net/http"
"strconv"
"strings"
"time"
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+
"supermarket/internal/approvals"
"supermarket/internal/audit"
"supermarket/internal/fileutil"
@@ -42,7 +46,64 @@ func (s *Server) AgentAuth(r *http.Request, key string) (*mcpserver.Caller, erro
if err != nil {
return nil, users.ErrBadKey
}
- return &mcpserver.Caller{ID: u.ID, Name: u.Name, Can: m.Can}, nil
+ lim, err := users.LimitsOf(s.DB, u.ID)
+ if err != nil {
+ return nil, err
+ }
+ if !lim.Paused.IsZero() {
+ return nil, &mcpserver.Refusal{Status: http.StatusForbidden,
+ Reason: u.Name + " is paused: an admin can resume it under Settings → Agents."}
+ }
+ id := u.ID
+ return &mcpserver.Caller{ID: u.ID, Name: u.Name, Can: m.Can,
+ Before: func(ctx context.Context, tool string) error { return s.beforeCall(id, tool) },
+ After: func(tool string, res *mcp.CallToolResult, err error, took time.Duration) {
+ s.afterCall(id, tool, res, err, took)
+ }}, nil
+}
+
+// beforeCall keeps an agent within its calls a minute, and stops a paused
+// agent's call even mid-session.
+func (s *Server) beforeCall(agent int64, tool string) error {
+ now := time.Now()
+ lim, err := users.LimitsOf(s.DB, agent)
+ if err != nil {
+ return err
+ }
+ if !lim.Paused.IsZero() {
+ return errors.New("this agent is paused: an admin can resume it under Settings → Agents")
+ }
+ n, err := users.CallsSince(s.DB, agent, now.Add(-time.Minute))
+ if err != nil {
+ return err
+ }
+ if n >= lim.PerMinute {
+ _ = users.RecordCall(s.DB, users.Call{Agent: agent, At: now, Tool: tool, Outcome: users.CallRefused,
+ Detail: fmt.Sprintf("over %d calls a minute", lim.PerMinute)})
+ return fmt.Errorf("too many calls: this agent may make %d a minute; wait a little", lim.PerMinute)
+ }
+ return nil
+}
+
+// afterCall records an agent's tool call.
+func (s *Server) afterCall(agent int64, tool string, res *mcp.CallToolResult, err error, took time.Duration) {
+ c := users.Call{Agent: agent, At: time.Now().Add(-took), Tool: tool, Outcome: users.CallOK, Took: took}
+ switch {
+ case err != nil:
+ c.Outcome, c.Detail = users.CallError, err.Error()
+ case res != nil && res.IsError:
+ c.Outcome = users.CallError
+ fallthrough
+ case res != nil:
+ if len(res.Content) > 0 {
+ if t, ok := res.Content[0].(*mcp.TextContent); ok {
+ c.Detail = strings.Join(strings.Fields(t.Text), " ")
+ }
+ }
+ }
+ if err := users.RecordCall(s.DB, c); err != nil {
+ s.Log.Warn("agents: recording a call", "err", err)
+ }
}
// hermesKey is the setting naming the local edition's built-in Hermes agent.
@@ -108,6 +169,7 @@ type agentRow struct {
Working int // keys that work now
Last *users.Key // the last used
BuiltIn bool
+ Limits users.Limits
}
func (s *Server) agentRows(now time.Time) ([]agentRow, error) {
@@ -121,6 +183,9 @@ func (s *Server) agentRows(now time.Time) ([]agentRow, error) {
continue
}
row := agentRow{TeamUser: m, Access: agentAccessText(m.Membership), BuiltIn: s.isHermes(m.ID)}
+ if row.Limits, err = users.LimitsOf(s.DB, m.ID); err != nil {
+ return nil, err
+ }
if row.Keys, err = users.Keys(s.DB, m.ID); err != nil {
return nil, err
}
@@ -276,6 +341,9 @@ type agentData struct {
Grants []grant
Allowed []approvals.Grant // what it may do on its own
Asked []approvals.Request
+ Waiting []approvals.Request // what it's waiting on
+ Calls []users.Call
+ SentDay int // what it asked to send out in the last 24 hours
Problem string
Now time.Time
}
@@ -320,6 +388,9 @@ func (s *Server) renderAgent(w http.ResponseWriter, r *http.Request, u *users.Us
d := agentData{Row: row, Grants: agentGrants(), Problem: problem, Now: now}
d.Allowed, _ = approvals.Grants(s.DB, u.ID)
d.Asked, _ = approvals.List(s.DB, "", u.ID, 20)
+ d.Waiting, _ = approvals.List(s.DB, approvals.Waiting, u.ID, 50)
+ d.Calls, _ = users.RecentCalls(s.DB, u.ID, 50)
+ d.SentDay, _ = approvals.AskedSince(s.DB, u.ID, now.Add(-24*time.Hour))
s.render(w, r, "agent", page{Title: u.Name, Nav: "settings/agents", Data: d})
return
}
@@ -397,6 +468,27 @@ func (s *Server) agentAction(w http.ResponseWriter, r *http.Request) {
redirect(w, r, back, "key-revoked")
return
}
+ case "limits":
+ pm, _ := strconv.Atoi(r.PostFormValue("per_minute"))
+ pd, _ := strconv.Atoi(r.PostFormValue("out_per_day"))
+ if err = users.SetLimits(s.DB, u.ID, pm, pd); err != nil {
+ s.renderAgent(w, r, u, "Each limit is a whole number, at least 1.", http.StatusUnprocessableEntity)
+ return
+ }
+ s.audit(r, "agent-limits", u.Name, fmt.Sprintf("%d calls a minute, %d sent out a day", pm, pd))
+ redirect(w, r, back, "saved")
+ return
+ case "pause", "resume":
+ by := int64(0)
+ if v := viewerOf(r); v.User != nil {
+ by = v.User.ID
+ }
+ paused := r.PathValue("action") == "pause"
+ if err = users.Pause(s.DB, u.ID, paused, by, now); err == nil {
+ s.audit(r, ifElse(paused, "agent-paused", "agent-resumed"), u.Name, "")
+ redirect(w, r, back, ifElse(paused, "agent-paused", "agent-resumed"))
+ return
+ }
case "disable":
if err = users.SetStatus(s.DB, u.ID, users.Disabled); err == nil {
s.audit(r, "disabled", u.Name, "an agent: its keys stop working")
diff --git a/internal/web/approvals.go b/internal/web/approvals.go
index 1202c7e..bed8d1e 100644
--- a/internal/web/approvals.go
+++ b/internal/web/approvals.go
@@ -95,6 +95,16 @@ func (s *Server) ask(ctx context.Context, c *mcpserver.Caller, r *approvals.Requ
return fmt.Sprintf("Already waiting for approval (request %d): nothing more to do; approvals_status says when it's decided.", p.ID), nil
}
now := time.Now()
+ // The cap per day on what an agent asks to send out, approved or not.
+ lim, err := users.LimitsOf(s.DB, r.Agent)
+ if err != nil {
+ return "", err
+ }
+ if n, err := approvals.AskedSince(s.DB, r.Agent, now.Add(-24*time.Hour)); err != nil {
+ return "", err
+ } else if n >= lim.OutPerDay {
+ return "", fmt.Errorf("this agent may ask to send out %d things a day, and has: try again tomorrow, or ask an admin to raise its limit", lim.OutPerDay)
+ }
ok, err := approvals.Allowed(s.DB, r.Agent, r.Class, now)
if err != nil {
return "", err
diff --git a/internal/web/server.go b/internal/web/server.go
index e6dcf74..5003c75 100644
--- a/internal/web/server.go
+++ b/internal/web/server.go
@@ -714,6 +714,8 @@ var flashes = map[string]string{
"refused": "Refused: the agent is told.",
"approved-request": "Approved, and done.",
"withdrawn-class": "Withdrawn: it asks again from now on.",
+ "agent-paused": "Paused: every call it makes is refused until you resume it.",
+ "agent-resumed": "Resumed.",
"account-removed": "Signed out: posts scheduled to it are back in Posts.",
"own-account-connected": "Connected: you can post as it, and an admin can let others.",
"deleted": "Deleted.",
diff --git a/internal/web/signin.go b/internal/web/signin.go
index 7c489ba..c8597dc 100644
--- a/internal/web/signin.go
+++ b/internal/web/signin.go
@@ -398,12 +398,10 @@ func nameSuffix(name string) string {
return ""
}
-// RunAccounts forgets ended sessions, used-up links and old counts of
-// failed sign-ins, every hour (the server edition).
+// RunAccounts forgets ended sessions, used-up links, old counts of failed
+// sign-ins, the audit log past two years and agents' calls past 30 days,
+// every hour.
func (s *Server) RunAccounts(ctx context.Context) {
- if !s.signsIn() {
- return
- }
tick := time.NewTicker(time.Hour)
defer tick.Stop()
for {
@@ -419,6 +417,9 @@ func (s *Server) RunAccounts(ctx context.Context) {
s.Log.Warn("accounts: pruning counts", "err", err)
}
s.pruneAudit(now)
+ if err := users.PruneCalls(s.DB, now); err != nil {
+ s.Log.Warn("accounts: pruning agents' calls", "err", err)
+ }
})
select {
case <-ctx.Done():
diff --git a/internal/web/static/app.css b/internal/web/static/app.css
index 51c6090..88085dc 100644
--- a/internal/web/static/app.css
+++ b/internal/web/static/app.css
@@ -525,3 +525,4 @@ ul.accounts li { display: flex; align-items: center; gap: 0.5rem; flex-wrap: wra
ul.accounts form.inline { margin: 0 0 0 auto; }
fieldset.post-as { border: 0; padding: 0; margin: 0.5rem 0; }
fieldset.post-as label { display: inline-flex; margin-right: 1rem; }
+input.tiny { width: 5.5rem; display: inline-block; }
diff --git a/internal/web/templates/agent.html b/internal/web/templates/agent.html
index 722993f..3ea4e15 100644
--- a/internal/web/templates/agent.html
+++ b/internal/web/templates/agent.html
@@ -1,8 +1,51 @@
{{define "content"}}{{template "settings-start" .}}{{with .Data}}{{$d := .}}{{$a := .Row}}
{{.}}
{{end}} +In the last 24 hours it asked to send out {{.SentDay}} of its {{$a.Limits.OutPerDay}}: posts, emails, mailing-list adds and changes to the sites, approved or not.
+| When | Tool | Result | Took |
|---|---|---|---|
| {{ago .At}} | +{{.Tool}} |
+ {{if eq .Outcome "ok"}}{{truncate 100 .Detail}}{{else if eq .Outcome "refused"}}refused {{.Detail}}{{else}}{{truncate 160 .Detail}}{{end}} | +{{.Took.Milliseconds}} ms | +
The last 50; kept for 30 days.
+ {{else}}No calls yet.
{{end}} +