Phase 11, part 4: agents' limits, recent calls and a pause switch

Each agent has calls a minute and things it may ask to send out a day,
checked on every tool call and every request to send; every call is
recorded (tool, outcome, time) and the agent's page lists the last 50 and
what it's waiting on. Pause refuses all its calls at once. Also fixes each
agent's MCP server being shared with others that had the same scopes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 11:09:18 -07:00
co-authored by Claude Opus 5.5
parent 311d2e815b
commit 6bf0517163
16 changed files with 527 additions and 13 deletions
+1
View File
@@ -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",
}
+99
View File
@@ -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, "<code>content_drafts</code>") || !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)
}
}
+93 -1
View File
@@ -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")
+10
View File
@@ -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
+2
View File
@@ -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.",
+6 -5
View File
@@ -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():
+1
View File
@@ -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; }
+44 -1
View File
@@ -1,8 +1,51 @@
{{define "content"}}{{template "settings-start" .}}{{with .Data}}{{$d := .}}{{$a := .Row}}
<p><a href="/settings/agents">← Agents</a></p>
<h2>{{$a.Name}}{{if $a.BuiltIn}} <span class="pill">built in</span>{{end}}{{if eq $a.Status "disabled"}} <span class="pill">turned off</span>{{end}}</h2>
<h2>{{$a.Name}}{{if $a.BuiltIn}} <span class="pill">built in</span>{{end}}{{if eq $a.Status "disabled"}} <span class="pill">turned off</span>{{end}}{{if not $a.Limits.Paused.IsZero}} <span class="pill warn">paused</span>{{end}}</h2>
{{with .Problem}}<p class="error" role="alert">{{.}}</p>{{end}}
<section class="card" id="running">
{{if $a.Limits.Paused.IsZero}}
<form method="post" action="/settings/agents/{{$a.ID}}/pause" class="row">
<button type="submit" class="danger">Pause</button>
<span class="help">Stops all its calls at once, whatever key it uses, until it's resumed.</span>
</form>
{{else}}
<form method="post" action="/settings/agents/{{$a.ID}}/resume" class="row">
<button type="submit">Resume</button>
<span class="help">Paused {{ago $a.Limits.Paused}}{{with by $a.Limits.PausedBy}} {{.}}{{end}}: every call it makes is refused.</span>
</form>
{{end}}
<form method="post" action="/settings/agents/{{$a.ID}}/limits" class="row wrap">
<label class="small">Calls a minute <input name="per_minute" type="number" min="1" value="{{$a.Limits.PerMinute}}" class="tiny"></label>
<label class="small">Things it asks to send out, a day <input name="out_per_day" type="number" min="1" value="{{$a.Limits.OutPerDay}}" class="tiny"></label>
<button type="submit" class="secondary small">Save the limits</button>
</form>
<p class="help">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.</p>
</section>
{{if .Waiting}}
<section class="card">
<h2>Waiting on</h2>
<ul>{{range .Waiting}}<li><a href="/approvals#r-{{.ID}}">{{.Summary}}</a> <span class="muted small">asked {{ago .Created}}</span></li>{{end}}</ul>
</section>
{{end}}
<section class="card" id="calls">
<h2>Recent calls</h2>
{{if .Calls}}
<table class="list">
<thead><tr><th>When</th><th>Tool</th><th>Result</th><th class="num">Took</th></tr></thead>
<tbody>{{range .Calls}}<tr>
<td title="{{.At.Local.Format "2 Jan 2006 15:04:05"}}">{{ago .At}}</td>
<td><code>{{.Tool}}</code></td>
<td>{{if eq .Outcome "ok"}}<span class="muted small">{{truncate 100 .Detail}}</span>{{else if eq .Outcome "refused"}}<span class="pill warn">refused</span> <span class="small">{{.Detail}}</span>{{else}}<span class="error-text small">{{truncate 160 .Detail}}</span>{{end}}</td>
<td class="num small">{{.Took.Milliseconds}} ms</td>
</tr>{{end}}</tbody>
</table>
<p class="help">The last 50; kept for 30 days.</p>
{{else}}<p class="muted">No calls yet.</p>{{end}}
</section>
<form class="card" method="post" action="/settings/agents/{{$a.ID}}/save">
<label>Name <input name="name" value="{{$a.Name}}" required></label>
<label>What it's for <textarea name="description" rows="2">{{$a.Description}}</textarea></label>
+1 -1
View File
@@ -8,7 +8,7 @@
<thead><tr><th>Agent</th><th>May</th><th>Keys</th><th>Last used</th></tr></thead>
<tbody>
{{range .Rows}}<tr>
<td><a href="/settings/agents/{{.ID}}">{{.Name}}</a>{{if .BuiltIn}} <span class="pill">built in</span>{{end}}{{if eq .Status "disabled"}} <span class="pill">turned off</span>{{end}}{{with .Description}}<br><span class="muted small">{{truncate 120 .}}</span>{{end}}</td>
<td><a href="/settings/agents/{{.ID}}">{{.Name}}</a>{{if .BuiltIn}} <span class="pill">built in</span>{{end}}{{if eq .Status "disabled"}} <span class="pill">turned off</span>{{end}}{{if not .Limits.Paused.IsZero}} <span class="pill warn">paused</span>{{end}}{{with .Description}}<br><span class="muted small">{{truncate 120 .}}</span>{{end}}</td>
<td>{{.Access}}</td>
<td>{{if .Working}}{{.Working}} working{{else}}<span class="warn-text">none working</span>{{end}}</td>
<td>{{with .Last}}{{ago .Used}}{{with .UsedFrom}} <span class="muted small">from {{.}}</span>{{end}}{{else}}<span class="muted">never</span>{{end}}</td>