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
+8
View File
@@ -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
}
+23
View File
@@ -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);
`,
},
}
+51 -1
View File
@@ -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"}
+1 -1
View File
@@ -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:
+125
View File
@@ -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
}
+37
View File
@@ -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")
}
}
+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>