Abilities: a bound gate before every request that performs an operation
assist.WithGate puts a gate on the context and assist.Gate runs it; with none, it refuses ability_unmapped. The registry gates the operation as it resolved it right before the provider, and the HTTP provider gates again right before its POST (for Oficina, after its teams fetch). use's gate is bound to the person and the operation runRemote checked: one short read of the switches, refusing an operation that now resolves differently (operation_changed) or whose ability is off. The Oficina provider asks Store.Allowed(apps_read) before every authenticated request, its token included, so a paused connection is never used.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 files changed,
+397
−20
internal/equipo/assist/assist_test.go+7 −7internal/equipo/assist/gate.go+47 −0internal/equipo/assist/gate_test.go+140 −0internal/equipo/assist/http.go+9 −0internal/equipo/assist/oficina.go+16 −3internal/equipo/assist/oficina_test.go+8 −8internal/equipo/assist/registry.go+6 −0internal/equipo/chat/ability_map.go+39 −0internal/equipo/chat/assistant_tools.go+9 −1internal/equipo/chat/send_gate_test.go+115 −0internal/equipo/chat_wiring.go+1 −1
diff --git a/internal/equipo/assist/assist_test.go b/internal/equipo/assist/assist_test.go| index 3711d1bb..291cef07 100644 |
| --- a/internal/equipo/assist/assist_test.go |
| +++ b/internal/equipo/assist/assist_test.go |
| @@ -92,7 +92,7 @@ func TestRegistryCachesLists(t *testing.T) { |
| "bob": {{Name: "only_bob", App: "A", ReadOnly: true}}, |
| }} |
| r := NewRegistry(f) |
| - ctx := context.Background() |
| + ctx := allowAll(context.Background()) |
| out, _ := r.Look(ctx, "ann", "") |
| r.Look(ctx, "ann", "") |
| if f.lists.Load() != 1 { |
| @@ -123,7 +123,7 @@ func TestRegistryListExpires(t *testing.T) { |
| r := NewRegistry(f) |
| at := time.Date(2026, 11, 13, 9, 0, 0, 0, time.UTC) |
| r.now = func() time.Time { return at } |
| - ctx := context.Background() |
| + ctx := allowAll(context.Background()) |
| look := func(want int32) { |
| t.Helper() |
| if out, err := r.Look(ctx, "p", ""); err != nil || !strings.Contains(out, "base_apps") { |
| @@ -175,7 +175,7 @@ func TestRegistryInvoke(t *testing.T) { |
| {Name: "get", App: "C", ReadOnly: true}, |
| }}} |
| r := NewRegistry(f) |
| - ctx := context.Background() |
| + ctx := allowAll(context.Background()) |
| if _, err := r.Invoke(ctx, "p", "add", json.RawMessage(`{"title":"x"}`), "t/1/u"); err != nil { |
| t.Fatal(err) |
| } |
| @@ -212,7 +212,7 @@ func TestWriteNeedsLedgerKey(t *testing.T) { |
| }}} |
| tm := &fake{name: "team", ops: map[string][]Operation{"p": {{Name: "team_request", App: "T"}}}} |
| r := NewRegistry(f, tm) |
| - ctx := context.Background() |
| + ctx := allowAll(context.Background()) |
| for _, op := range []string{"add", "team_request"} { |
| f.got.op, tm.got.op = "", "" |
| _, err := r.Invoke(ctx, "p", op, json.RawMessage(`{"client_id":"mine"}`), "") |
| @@ -253,7 +253,7 @@ func (s *slow) List(_ context.Context, _ string) ([]Operation, error) { |
| func TestForgetDuringListDropsStaleResult(t *testing.T) { |
| s := &slow{fake: fake{name: "base"}, started: make(chan struct{}), release: make(chan struct{}), stale: true} |
| r := NewRegistry(s) |
| - ctx := context.Background() |
| + ctx := allowAll(context.Background()) |
| done := make(chan string) |
| go func() { out, _ := r.Look(ctx, "p", ""); done <- out }() |
| <-s.started |
| @@ -276,7 +276,7 @@ func (bigFake) Invoke(context.Context, string, string, json.RawMessage, string) |
| func TestRegistryCapsResult(t *testing.T) { |
| f := &bigFake{&fake{name: "b", ops: map[string][]Operation{"p": {{Name: "get", ReadOnly: true}}}}} |
| - _, err := NewRegistry(f).Invoke(context.Background(), "p", "get", nil, "") |
| + _, err := NewRegistry(f).Invoke(allowAll(context.Background()), "p", "get", nil, "") |
| var fl Failure |
| if !errors.As(err, &fl) || fl.Code != "too_large" { |
| t.Fatalf("err = %v", err) |
| @@ -335,7 +335,7 @@ func TestHTTPProvider(t *testing.T) { |
| mux.HandleFunc("GET /elsewhere", func(http.ResponseWriter, *http.Request) { hits.Add(100) }) |
| srv := httptest.NewServer(mux) |
| defer srv.Close() |
| - ctx := context.Background() |
| + ctx := allowAll(context.Background()) |
| p := NewHTTPProvider("base", hostFor(srv.URL), srv.Client()) |
| ops, err := p.List(ctx, "p") |
diff --git a/internal/equipo/assist/gate.go b/internal/equipo/assist/gate.go| new file mode 100644 |
| index 00000000..ee4e0a9b |
| --- /dev/null |
| +++ b/internal/equipo/assist/gate.go |
| @@ -0,0 +1,47 @@ |
| +package assist |
| + |
| +import "context" |
| + |
| +// The send gate (spec 2026-11-26-assistant-abilities §6.1): the last check |
| +// before an operation goes out. The caller binds it to the person and the |
| +// operation it checked; every provider calls Gate immediately before the |
| +// request that performs the operation, after any preparatory request (an |
| +// Oficina connection's teams). A call counts as in flight once its gate |
| +// has passed. |
| + |
| +// GateFunc decides whether op may be sent now. |
| +type GateFunc func(op Operation) error |
| + |
| +type gateKey struct{} |
| + |
| +// WithGate is ctx with the gate f. |
| +func WithGate(ctx context.Context, f GateFunc) context.Context { |
| + return context.WithValue(ctx, gateKey{}, f) |
| +} |
| + |
| +// Gate runs ctx's gate for op. With no gate on ctx it refuses |
| +// ability_unmapped: a missing gate fails closed. |
| +func Gate(ctx context.Context, op Operation) error { |
| + f, _ := ctx.Value(gateKey{}).(GateFunc) |
| + if f == nil { |
| + return Failure{Code: "ability_unmapped", Message: "Not available: this can't be run from here."} |
| + } |
| + return f(op) |
| +} |
| + |
| +type resolvedKey struct{} |
| + |
| +// withResolved is ctx carrying op as the registry resolved it, for the |
| +// provider's own gate check. |
| +func withResolved(ctx context.Context, op Operation) context.Context { |
| + return context.WithValue(ctx, resolvedKey{}, op) |
| +} |
| + |
| +// resolved is the operation provider's name resolved to, as the registry |
| +// resolved it, or one known by name alone. |
| +func resolved(ctx context.Context, provider, name string) Operation { |
| + if op, ok := ctx.Value(resolvedKey{}).(Operation); ok && op.Provider == provider && op.Name == name { |
| + return op |
| + } |
| + return Operation{Provider: provider, Name: name} |
| +} |
diff --git a/internal/equipo/assist/gate_test.go b/internal/equipo/assist/gate_test.go| new file mode 100644 |
| index 00000000..2206da18 |
| --- /dev/null |
| +++ b/internal/equipo/assist/gate_test.go |
| @@ -0,0 +1,140 @@ |
| +package assist |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "sync" |
| + "testing" |
| +) |
| + |
| +// allowAll is ctx with a gate that lets every operation through. |
| +func allowAll(ctx context.Context) context.Context { |
| + return WithGate(ctx, func(Operation) error { return nil }) |
| +} |
| + |
| +// With no gate on the context, nothing is sent: a missing gate fails |
| +// closed. |
| +func TestGateMissingFailsClosed(t *testing.T) { |
| + var f Failure |
| + if err := Gate(context.Background(), Operation{Name: "x"}); !errors.As(err, &f) || f.Code != "ability_unmapped" { |
| + t.Fatalf("gate without a gate: %v", err) |
| + } |
| + a := &fake{name: "base", ops: map[string][]Operation{"p": {{Name: "base_apps", ReadOnly: true}}}} |
| + if _, err := NewRegistry(a).Invoke(context.Background(), "p", "base_apps", nil, ""); err == nil || a.got.op != "" { |
| + t.Errorf("invoked without a gate: %v %q", err, a.got.op) |
| + } |
| +} |
| + |
| +// trace records, in order, each gate check and each request a provider |
| +// makes, as "gate <op>" and "<METHOD> <path>". |
| +type trace struct { |
| + mu sync.Mutex |
| + events []string |
| +} |
| + |
| +func (tr *trace) add(e string) { tr.mu.Lock(); tr.events = append(tr.events, e); tr.mu.Unlock() } |
| +func (tr *trace) all() []string { |
| + tr.mu.Lock() |
| + defer tr.mu.Unlock() |
| + return append([]string(nil), tr.events...) |
| +} |
| + |
| +type traceTransport struct { |
| + tr *trace |
| + next http.RoundTripper |
| +} |
| + |
| +func (t traceTransport) RoundTrip(r *http.Request) (*http.Response, error) { |
| + t.tr.add(r.Method + " " + r.URL.Path) |
| + return t.next.RoundTrip(r) |
| +} |
| + |
| +// Every provider's request that performs an operation comes right after |
| +// a gate check for that operation; a refusing gate means the request is |
| +// never made. |
| +func TestEveryOperationRequestGated(t *testing.T) { |
| + tr := &trace{} |
| + client := &http.Client{Transport: traceTransport{tr, http.DefaultTransport}} |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + switch { |
| + case r.URL.Path == "/api/v1/operations": |
| + _, _ = io.WriteString(w, `{"operations":[{"name":"x_read","read_only":true,"input_schema":{"type":"object"}}]}`) |
| + case r.URL.Path == "/api/v1/connection": |
| + _, _ = io.WriteString(w, `{"teams":["acme"]}`) |
| + default: |
| + _, _ = io.WriteString(w, `{"ok":true}`) |
| + } |
| + })) |
| + defer srv.Close() |
| + host := func(context.Context, string) (string, string, bool, error) { |
| + return srv.URL, "token-0123456789", true, nil |
| + } |
| + providers := []Provider{ |
| + NewHTTPProvider("base", host, client), |
| + NewOficinaProvider("oficina", &conn{origin: srv.URL, tokens: []string{"token-0123456789"}}, client, nil), |
| + } |
| + for _, p := range providers { |
| + tr.events = nil |
| + gate := func(op Operation) error { tr.add("gate " + op.Provider + "/" + op.Name); return nil } |
| + ctx := WithGate(context.Background(), gate) |
| + if _, err := NewRegistry(p).Invoke(ctx, "p", "x_read", json.RawMessage(`{}`), ""); err != nil { |
| + t.Fatalf("%s: %v", p.Name(), err) |
| + } |
| + events := tr.all() |
| + for i, e := range events { |
| + if strings.HasPrefix(e, "POST /api/v1/operations/") && (i == 0 || events[i-1] != "gate "+p.Name()+"/x_read") { |
| + t.Errorf("%s: %s not right after its gate: %v", p.Name(), e, events) |
| + } |
| + } |
| + tr.events = nil |
| + refuse := WithGate(context.Background(), func(op Operation) error { return Failure{Code: "ability_off"} }) |
| + if _, err := NewRegistry(p).Invoke(refuse, "p", "x_read", json.RawMessage(`{}`), ""); err == nil { |
| + t.Errorf("%s: a refusing gate let it run", p.Name()) |
| + } |
| + for _, e := range tr.all() { |
| + if strings.HasPrefix(e, "POST ") { |
| + t.Errorf("%s: sent %s past a refusing gate", p.Name(), e) |
| + } |
| + } |
| + } |
| +} |
| + |
| +// countingConn is a Connection that counts the tokens it hands out (each |
| +// may be a refresh). |
| +type countingConn struct { |
| + conn |
| + hosts int |
| +} |
| + |
| +func (c *countingConn) Host(ctx context.Context, person string) (string, string, bool, error) { |
| + c.mu.Lock() |
| + c.hosts++ |
| + c.mu.Unlock() |
| + return c.conn.Host(ctx, person) |
| +} |
| + |
| +// With reading apps off, the Oficina connection is never used: no token |
| +// is asked for (or refreshed), and nothing is listed or sent. |
| +func TestPausedConnectionMakesNoRequest(t *testing.T) { |
| + tr := &trace{} |
| + client := &http.Client{Transport: traceTransport{tr, http.DefaultTransport}} |
| + c := &countingConn{conn: conn{origin: "https://connect.invalid", tokens: []string{"token-0123456789"}}} |
| + off := func(context.Context, string) error { return Failure{Code: "ability_off"} } |
| + p := NewOficinaProvider("oficina", c, client, off) |
| + ctx := allowAll(context.Background()) |
| + var f Failure |
| + if _, err := p.List(ctx, "p"); !errors.As(err, &f) || f.Code != "ability_off" { |
| + t.Errorf("list: %v", err) |
| + } |
| + if _, err := p.Invoke(ctx, "p", "calendar_list", nil, ""); !errors.As(err, &f) || f.Code != "ability_off" { |
| + t.Errorf("invoke: %v", err) |
| + } |
| + if n := len(tr.all()); n != 0 || c.hosts != 0 { |
| + t.Errorf("%d requests and %d tokens with the connection paused", n, c.hosts) |
| + } |
| +} |
diff --git a/internal/equipo/assist/http.go b/internal/equipo/assist/http.go| index c9c61835..cc6f151e 100644 |
| --- a/internal/equipo/assist/http.go |
| +++ b/internal/equipo/assist/http.go |
| @@ -4,6 +4,7 @@ import ( |
| "bytes" |
| "context" |
| "encoding/json" |
| + "errors" |
| "io" |
| "net/http" |
| "net/url" |
| @@ -63,6 +64,10 @@ func (p *httpProvider) Invoke(ctx context.Context, person, operation string, inp |
| if len(bytes.TrimSpace(input)) == 0 { |
| input = json.RawMessage(`{}`) |
| } |
| + // The request that performs the operation: the gate first. |
| + if err := Gate(ctx, resolved(ctx, p.name, operation)); err != nil { |
| + return nil, err |
| + } |
| body, err := p.do(ctx, person, http.MethodPost, "/api/v1/operations/"+url.PathEscape(operation), input, key, maxBody) |
| if err != nil { |
| return nil, err |
| @@ -75,6 +80,10 @@ func (p *httpProvider) Invoke(ctx context.Context, person, operation string, inp |
| func (p *httpProvider) do(ctx context.Context, person, method, path string, in []byte, key string, limit int64) ([]byte, error) { |
| origin, token, ok, err := p.host(ctx, person) |
| + if f := (Failure{}); errors.As(err, &f) { |
| + // A refusal the host gave (an ability off), as it is. |
| + return nil, f |
| + } |
| if err != nil { |
| return nil, Failure{Code: "unavailable", Message: "The provider could not be reached."} |
| } |
diff --git a/internal/equipo/assist/oficina.go b/internal/equipo/assist/oficina.go| index 4472a1ff..68ab9cb1 100644 |
| --- a/internal/equipo/assist/oficina.go |
| +++ b/internal/equipo/assist/oficina.go |
| @@ -44,9 +44,22 @@ type oficinaProvider struct { |
| // NewOficinaProvider is the provider for the Oficina apps behind conn. |
| // Only here is a write's client_id inferred as its key (clientIDKeyed): |
| -// other HTTP providers keep needing an explicit one. |
| -func NewOficinaProvider(name string, conn Connection, client *http.Client) Provider { |
| - return &oficinaProvider{http: newHTTPProvider(name, conn.Host, client), conn: conn} |
| +// other HTTP providers keep needing an explicit one. allowed, when set, |
| +// is asked before every authenticated request (the connection read, a |
| +// token and its refresh, listing, an operation): with reading apps off |
| +// for the person, the connection is kept but never used (spec |
| +// 2026-11-26-assistant-abilities §6.1). |
| +func NewOficinaProvider(name string, conn Connection, client *http.Client, allowed func(ctx context.Context, person string) error) Provider { |
| + host := conn.Host |
| + if allowed != nil { |
| + host = func(ctx context.Context, person string) (string, string, bool, error) { |
| + if err := allowed(ctx, person); err != nil { |
| + return "", "", false, err |
| + } |
| + return conn.Host(ctx, person) |
| + } |
| + } |
| + return &oficinaProvider{http: newHTTPProvider(name, host, client), conn: conn} |
| } |
| func (p *oficinaProvider) Name() string { return p.http.name } |
diff --git a/internal/equipo/assist/oficina_test.go b/internal/equipo/assist/oficina_test.go| index 2ddf9922..2ce1c0bd 100644 |
| --- a/internal/equipo/assist/oficina_test.go |
| +++ b/internal/equipo/assist/oficina_test.go |
| @@ -43,7 +43,7 @@ func oficinaRig(t *testing.T, teams ...string) (*oficinatest.Connect, *conn, *Re |
| t.Helper() |
| fake := oficinatest.Start(t) |
| c := &conn{origin: fake.URL, tokens: []string{fake.Grant(teams...)}} |
| - return fake, c, NewRegistry(NewOficinaProvider("oficina", c, nil)) |
| + return fake, c, NewRegistry(NewOficinaProvider("oficina", c, nil, nil)) |
| } |
| // TestOficinaKeyedWrites: an agent-access write whose input requires a |
| @@ -53,7 +53,7 @@ func oficinaRig(t *testing.T, teams ...string) (*oficinatest.Connect, *conn, *Re |
| // R4: no key is inferred there. |
| func TestOficinaKeyedWrites(t *testing.T) { |
| _, _, r := oficinaRig(t, "acme") |
| - ctx := context.Background() |
| + ctx := allowAll(context.Background()) |
| want := map[string]struct { |
| key string |
| run bool |
| @@ -129,7 +129,7 @@ func TestOficinaClientIDKeyed(t *testing.T) { |
| // key, the same on a retry with that key; a read gets no client_id. |
| func TestOficinaInvoke(t *testing.T) { |
| fake, c, r := oficinaRig(t, "acme") |
| - ctx := context.Background() |
| + ctx := allowAll(context.Background()) |
| for range 2 { |
| if _, err := r.Invoke(ctx, "p", "calendar_create_event", json.RawMessage(`{"title":"Lunch","start_local":"2026-11-20T13:00"}`), "turn\x00calendar_create_event\x00h"); err != nil { |
| t.Fatal(err) |
| @@ -164,7 +164,7 @@ func TestOficinaInvoke(t *testing.T) { |
| // them in describe and must choose; nothing is sent without a team. |
| func TestOficinaTeamsToChoose(t *testing.T) { |
| fake, _, r := oficinaRig(t, "acme", "zeta") |
| - ctx := context.Background() |
| + ctx := allowAll(context.Background()) |
| op, err := r.Describe(ctx, "p", "calendar_free_busy") |
| if err != nil { |
| t.Fatal(err) |
| @@ -197,7 +197,7 @@ func TestOficinaTeamsToChoose(t *testing.T) { |
| func TestOficinaRefusesDestructiveAndExternal(t *testing.T) { |
| fake, _, r := oficinaRig(t, "acme") |
| for _, name := range []string{"docs_delete", "calls_invite"} { |
| - _, err := r.Invoke(context.Background(), "p", name, json.RawMessage(`{"id":"1","email":"a@b.c"}`), "k") |
| + _, err := r.Invoke(allowAll(context.Background()), "p", name, json.RawMessage(`{"id":"1","email":"a@b.c"}`), "k") |
| var f Failure |
| if !errors.As(err, &f) || f.Code != "not_yet" { |
| t.Errorf("%s: %v", name, err) |
| @@ -213,7 +213,7 @@ func TestOficinaRefusesDestructiveAndExternal(t *testing.T) { |
| func TestOficinaRejectedTokenRetried(t *testing.T) { |
| fake := oficinatest.Start(t) |
| c := &conn{origin: fake.URL, tokens: []string{"stale-" + strings.Repeat("x", 20), fake.Grant("acme")}} |
| - r := NewRegistry(NewOficinaProvider("oficina", c, nil)) |
| + r := NewRegistry(NewOficinaProvider("oficina", c, nil, nil)) |
| if _, err := r.Describe(context.Background(), "p", "calendar_free_busy"); err != nil { |
| t.Fatal(err) |
| } |
| @@ -227,14 +227,14 @@ func TestOficinaRejectedTokenRetried(t *testing.T) { |
| // the hook once per look; a look for something else does neither. |
| func TestOficinaHintWhenNotConnected(t *testing.T) { |
| c := &conn{none: true} |
| - r := NewRegistry(&fake{name: "base", ops: map[string][]Operation{"p": {{Name: "base_weather", App: "Weather", ReadOnly: true}}}}, NewOficinaProvider("oficina", c, nil)) |
| + r := NewRegistry(&fake{name: "base", ops: map[string][]Operation{"p": {{Name: "base_weather", App: "Weather", ReadOnly: true}}}}, NewOficinaProvider("oficina", c, nil, nil)) |
| var hooked []string |
| raised := true |
| r.OnUnconnected(func(_ context.Context, person, provider string) bool { |
| hooked = append(hooked, person+"/"+provider) |
| return raised |
| }) |
| - ctx := context.Background() |
| + ctx := allowAll(context.Background()) |
| for _, q := range []string{"", "calendar", "Docs", "meeting"} { |
| hooked = nil |
| out, err := r.Look(ctx, "p", q) |
diff --git a/internal/equipo/assist/registry.go b/internal/equipo/assist/registry.go| index 44840b58..4e95c230 100644 |
| --- a/internal/equipo/assist/registry.go |
| +++ b/internal/equipo/assist/registry.go |
| @@ -259,6 +259,12 @@ func (r *Registry) Invoke(ctx context.Context, person, operation string, input j |
| } |
| } |
| } |
| + // The gate checks the operation as resolved now, then the provider |
| + // checks again right before its request. |
| + ctx = withResolved(ctx, op) |
| + if err := Gate(ctx, op); err != nil { |
| + return nil, err |
| + } |
| out, err := p.Invoke(ctx, person, operation, input, sent) |
| if err != nil { |
| return nil, err |
diff --git a/internal/equipo/chat/ability_map.go b/internal/equipo/chat/ability_map.go| index 61453586..d03e871a 100644 |
| --- a/internal/equipo/chat/ability_map.go |
| +++ b/internal/equipo/chat/ability_map.go |
| @@ -110,3 +110,42 @@ func (s *Store) abilityRefusal(sw Switches, key string) wire.ToolResult { |
| } |
| return refused(wire.CodeAbilityOff, abilityOffText(s.abilityName(key), sw.Ask())) |
| } |
| + |
| +// AllowedFor is Allowed for one ability, as a check a provider is given |
| +// to run before its authenticated requests. |
| +func (s *Store) AllowedFor(ability string) func(ctx context.Context, person string) error { |
| + return func(ctx context.Context, person string) error { return s.Allowed(ctx, person, ability) } |
| +} |
| + |
| +// toolOperationChanged is the refusal for an operation that resolved |
| +// differently at send from the one checked. |
| +const toolOperationChanged = "Not available: the operation changed before it could be sent. Look it up again." |
| + |
| +// sendGate is the gate bound to the person and the operation runRemote |
| +// checked (bound): one short transaction reads the person's switches, and |
| +// it refuses an operation that resolved differently in provider, name, |
| +// read-only or scope (operation_changed), one no ability covers, and one |
| +// whose ability is now off. |
| +func (s *Store) sendGate(ctx context.Context, person string, bound assist.Operation) assist.GateFunc { |
| + return func(op assist.Operation) error { |
| + if op.Provider != bound.Provider || op.Name != bound.Name || op.ReadOnly != bound.ReadOnly || op.Scope != bound.Scope { |
| + return assist.Failure{Code: wire.CodeOperationChanged, Message: toolOperationChanged} |
| + } |
| + key, ok := abilityFor(op) |
| + if !ok { |
| + return assist.Failure{Code: wire.CodeAbilityUnmapped, Message: toolAbilityUnmapped} |
| + } |
| + if key == "" { |
| + return nil |
| + } |
| + sw, err := s.switchesNow(ctx, person) |
| + if err != nil { |
| + return assist.Failure{Code: "unavailable"} |
| + } |
| + if !sw.Can(key) { |
| + res := s.abilityRefusal(sw, key) |
| + return assist.Failure{Code: res.Code, Message: res.Text} |
| + } |
| + return nil |
| + } |
| +} |
diff --git a/internal/equipo/chat/assistant_tools.go b/internal/equipo/chat/assistant_tools.go| index 3438adb4..72bb45fb 100644 |
| --- a/internal/equipo/chat/assistant_tools.go |
| +++ b/internal/equipo/chat/assistant_tools.go |
| @@ -707,7 +707,8 @@ func (s *Store) runRemote(ctx context.Context, row toolCallRecord) (res wire.Too |
| return opRefused("not_asked", ""), false |
| } |
| } |
| - out, err := ops.Invoke(withCall(filtered, row), row.Person, in.Operation, in.Input, row.LedgerKey) |
| + gated := assist.WithGate(withCall(filtered, row), s.sendGate(ctx, row.Person, op)) |
| + out, err := ops.Invoke(gated, row.Person, in.Operation, in.Input, row.LedgerKey) |
| if err != nil { |
| return s.opFailed(ctx, row.Person, err), op.ReadOnly |
| } |
| @@ -747,6 +748,13 @@ func (s *Store) opFailed(ctx context.Context, person string, err error) wire.Too |
| if !errors.As(err, &f) { |
| return refused("unavailable", toolOpUnavailable) |
| } |
| + switch f.Code { |
| + case wire.CodeAbilityOff, wire.CodeAbilityUnmapped, wire.CodeOperationChanged: |
| + // The instance's own refusal, its text the instance's. |
| + if f.Message != "" { |
| + return refused(f.Code, f.Message) |
| + } |
| + } |
| if f.Code == "unknown_operation" { |
| if _, _, ok, herr := s.Host(ctx, person); herr == nil && !ok { |
| f.Code = "not_connected" |
diff --git a/internal/equipo/chat/send_gate_test.go b/internal/equipo/chat/send_gate_test.go| new file mode 100644 |
| index 00000000..cc7b5c24 |
| --- /dev/null |
| +++ b/internal/equipo/chat/send_gate_test.go |
| @@ -0,0 +1,115 @@ |
| +package chat |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/assist" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// hookProvider is an Oficina-like provider whose List and Invoke run a |
| +// test's hook first: n is the call's number. |
| +type hookProvider struct { |
| + mu sync.Mutex |
| + ops func(n int) []assist.Operation |
| + onList func(n int) |
| + onInvoke func(n int) |
| + lists int |
| + invokes atomic.Int32 |
| +} |
| + |
| +func (p *hookProvider) Name() string { return OficinaProvider } |
| +func (p *hookProvider) List(context.Context, string) ([]assist.Operation, error) { |
| + p.mu.Lock() |
| + p.lists++ |
| + n := p.lists |
| + p.mu.Unlock() |
| + if p.onList != nil { |
| + p.onList(n) |
| + } |
| + return p.ops(n), nil |
| +} |
| +func (p *hookProvider) Invoke(context.Context, string, string, json.RawMessage, string) (json.RawMessage, error) { |
| + n := int(p.invokes.Add(1)) |
| + if p.onInvoke != nil { |
| + p.onInvoke(n) |
| + } |
| + return json.RawMessage(`{"events":[]}`), nil |
| +} |
| + |
| +func calendarList(int) []assist.Operation { |
| + return []assist.Operation{{Name: "calendar_list", ReadOnly: true, Scope: "calendar:read"}} |
| +} |
| + |
| +// turnOff turns reading apps off at Base and has Equipo hear it. |
| +func turnOff(t *testing.T, h *abilitiesHarness, base *fakeBoardBase) { |
| + base.set(func(f *fakeBoardBase) { f.board.Abilities["apps_read"], f.board.Revision = false, f.board.Revision+1 }) |
| + if _, _, err := h.s.RefreshAbilities(context.Background(), abPerson); err != nil { |
| + t.Error(err) |
| + } |
| +} |
| + |
| +// The switch turned off after use was checked but before the operation |
| +// goes out (while it is described) means it isn't sent; turned off once |
| +// the gate has passed, that request completes, and the next is refused. |
| +func TestSendGate(t *testing.T) { |
| + h, base := boardBase(t) |
| + refresh(t, h) |
| + p := &hookProvider{ops: calendarList} |
| + p.onList = func(n int) { |
| + if n == 1 { |
| + turnOff(t, h, base) |
| + } |
| + } |
| + h.s.SetOperations(assist.NewRegistry(p)) |
| + res, _ := h.s.runRemote(context.Background(), useRow(abPerson, "calendar_list")) |
| + if !res.IsError || res.Code != wire.CodeAbilityOff || p.invokes.Load() != 0 { |
| + t.Errorf("off while described: %+v, sent %d", res, p.invokes.Load()) |
| + } |
| + |
| + h2, base2 := boardBase(t) |
| + refresh(t, h2) |
| + p2 := &hookProvider{ops: calendarList} |
| + p2.onInvoke = func(n int) { |
| + if n == 1 { |
| + turnOff(t, h2, base2) |
| + } |
| + } |
| + h2.s.SetOperations(assist.NewRegistry(p2)) |
| + if res, _ := h2.s.runRemote(context.Background(), useRow(abPerson, "calendar_list")); res.IsError { |
| + t.Errorf("in flight once the gate passed: %+v", res) |
| + } |
| + res, _ = h2.s.runRemote(context.Background(), useRow(abPerson, "calendar_list")) |
| + if !res.IsError || res.Code != wire.CodeAbilityOff || p2.invokes.Load() != 1 { |
| + t.Errorf("the next request: %+v, sent %d", res, p2.invokes.Load()) |
| + } |
| +} |
| + |
| +// An operation that resolves differently at send from the one checked is |
| +// refused operation_changed, and isn't sent. |
| +func TestGateBindsOperation(t *testing.T) { |
| + h, _ := boardBase(t) |
| + refresh(t, h) |
| + p := &hookProvider{} |
| + p.ops = func(n int) []assist.Operation { |
| + if n == 1 { |
| + return calendarList(n) |
| + } |
| + return []assist.Operation{{Name: "calendar_list", ReadOnly: true, Scope: "calendar:all"}} |
| + } |
| + p.onList = func(n int) { |
| + if n == 1 { |
| + // The list is stale by the time Invoke looks again. |
| + h.s.operations().Forget(abPerson) |
| + } |
| + } |
| + h.s.SetOperations(assist.NewRegistry(p)) |
| + res, _ := h.s.runRemote(context.Background(), useRow(abPerson, "calendar_list")) |
| + if !res.IsError || res.Code != wire.CodeOperationChanged || p.invokes.Load() != 0 { |
| + t.Errorf("changed at send: %+v, sent %d", res, p.invokes.Load()) |
| + } |
| +} |
diff --git a/internal/equipo/chat_wiring.go b/internal/equipo/chat_wiring.go| index e3b98a36..6931298c 100644 |
| --- a/internal/equipo/chat_wiring.go |
| +++ b/internal/equipo/chat_wiring.go |
| @@ -91,7 +91,7 @@ func (s *Store) assistRegistry(logger *slog.Logger) *assist.Registry { |
| c := s.chat.store |
| providers := []assist.Provider{assist.NewHTTPProvider("base", c.Host, nil), c.TeamProvider()} |
| if s.oficina != nil { |
| - providers = append(providers, assist.NewOficinaProvider(oficinaProvider, s.oficina, nil)) |
| + providers = append(providers, assist.NewOficinaProvider(oficinaProvider, s.oficina, nil, c.AllowedFor(wire.AbilityAppsRead))) |
| } |
| r := assist.NewRegistry(providers...) |
| r.OnUnconnected(func(ctx context.Context, person, provider string) bool { |