| 1 | package assist |
| 2 | |
| 3 | import "context" |
| 4 | |
| 5 | // The send gate (spec 2026-11-26-assistant-abilities §6.1): the last check |
| 6 | // before an operation goes out. The caller binds it to the person and the |
| 7 | // operation it checked; every provider calls Gate immediately before the |
| 8 | // request that performs the operation, after any preparatory request (an |
| 9 | // Oficina connection's teams). A call counts as in flight once its gate |
| 10 | // has passed. |
| 11 | |
| 12 | // Refusal is the instance's own refusal of an operation (an ability off, |
| 13 | // none mapped, the operation changed, no copy of the board), told to the |
| 14 | // model in the instance's words. Only the instance makes one: a |
| 15 | // provider's error is always a Failure, and can't use these codes. |
| 16 | type Refusal struct{ Code, Message string } |
| 17 | |
| 18 | func (r Refusal) Error() string { return "assist: refused: " + r.Code } |
| 19 | |
| 20 | // instanceCodes are the codes only the instance's refusals carry. |
| 21 | var instanceCodes = map[string]bool{"ability_off": true, "ability_unmapped": true, "operation_changed": true} |
| 22 | |
| 23 | // GateFunc decides whether op may be sent now. |
| 24 | type GateFunc func(op Operation) error |
| 25 | |
| 26 | type gateKey struct{} |
| 27 | |
| 28 | // WithGate is ctx with the gate f. |
| 29 | func WithGate(ctx context.Context, f GateFunc) context.Context { |
| 30 | return context.WithValue(ctx, gateKey{}, f) |
| 31 | } |
| 32 | |
| 33 | // Gate runs ctx's gate for op. With no gate on ctx it refuses |
| 34 | // ability_unmapped: a missing gate fails closed. |
| 35 | func Gate(ctx context.Context, op Operation) error { |
| 36 | f, _ := ctx.Value(gateKey{}).(GateFunc) |
| 37 | if f == nil { |
| 38 | return Refusal{Code: "ability_unmapped", Message: "Not available: this can't be run from here."} |
| 39 | } |
| 40 | return f(op) |
| 41 | } |
| 42 | |
| 43 | type resolvedKey struct{} |
| 44 | |
| 45 | // withResolved is ctx carrying op as the registry resolved it, for the |
| 46 | // provider's own gate check. |
| 47 | func withResolved(ctx context.Context, op Operation) context.Context { |
| 48 | return context.WithValue(ctx, resolvedKey{}, op) |
| 49 | } |
| 50 | |
| 51 | // resolved is the operation provider's name resolved to, as the registry |
| 52 | // resolved it, or one known by name alone. |
| 53 | func resolved(ctx context.Context, provider, name string) Operation { |
| 54 | if op, ok := ctx.Value(resolvedKey{}).(Operation); ok && op.Provider == provider && op.Name == name { |
| 55 | return op |
| 56 | } |
| 57 | return Operation{Provider: provider, Name: name} |
| 58 | } |
| 59 | |