Files
archie/internal/app/archiemessaging/org_channels.go
T

311 lines
11 KiB
Go

package archiemessaging
import (
"context"
"encoding/json"
"errors"
"fmt"
"slices"
"time"
"github.com/samcharles93/archie-core/internal/channels"
"github.com/samcharles93/archie-core/internal/channels/telegram"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
"github.com/samcharles93/archie-core/internal/secret"
"github.com/samcharles93/archie-core/internal/taskstate"
)
// telegramCredential is the credential binding service an org's Telegram bot
// token is bound under.
const telegramCredential = "telegram"
// credentialBindingsKind is the control-plane resource holding the bindings.
const credentialBindingsKind = "credential-bindings"
// orgChannelSource is where the Messaging Service learns which orgs run a
// channel and how they are bound. *controlplanerpc.Client satisfies the first
// two; the principals come from the State Store's access contract.
type orgChannelSource interface {
ChannelOrgs(ctx context.Context) ([]controlplanerpc.OrgChannel, error)
Query(ctx context.Context, kind string, decode func([]byte) error) (int64, bool, error)
}
// orgChannelDeps is everything an org's channels need beyond the instance's.
type orgChannelDeps struct {
Source orgChannelSource
Principals access.PrincipalSource
}
// orgChannelPlan is one org's channel as its settings, binding and agent
// currently resolve.
type orgChannelPlan struct {
org string
token string
allowed []int64
show bool
agent access.Principal
}
// same reports whether next needs no rebuild of the running channel.
func (p orgChannelPlan) same(next orgChannelPlan) bool {
return p.token == next.token && slices.Equal(p.allowed, next.allowed) && p.agent.IdentityID == next.agent.IdentityID
}
// orgChannelLoop keeps one channel per org that has settings, a bound bot token
// and an agent of its own, until ctx ends.
func (s *Service) orgChannelLoop(ctx context.Context) {
ticker := time.NewTicker(s.reconcileInterval)
defer ticker.Stop()
for {
if err := s.syncOrgChannels(ctx); err != nil {
s.log.WarnContext(ctx, "org channels not synced", "err", err)
}
select {
case <-ctx.Done():
return
case <-ticker.C:
}
}
}
// syncOrgChannels builds, replaces or stops each org's channel to match what
// the orgs currently hold. A channel that no longer resolves is stopped: an org
// whose binding or agent went away must not keep a bot running.
func (s *Service) syncOrgChannels(ctx context.Context) error {
orgs, err := s.orgs.Source.ChannelOrgs(ctx)
if err != nil {
return err
}
bindings, err := s.telegramBindings(ctx)
if err != nil {
return err
}
wanted := map[string]orgChannelPlan{}
for _, entry := range orgs {
plan, err := s.planOrgChannel(ctx, entry, bindings[entry.Org])
if err != nil {
s.log.WarnContext(ctx, "org channel not run", "org", entry.Org, "reason", err)
continue
}
wanted[entry.Org] = plan
}
for owner, plan := range wanted {
s.applyOrgChannel(ctx, owner, plan)
}
for _, instance := range s.instances() {
if _, still := wanted[instance.owner]; instance.owner != storecontract.DefaultOrgID && !still {
if err := s.setChannelState(instance, nil); err != nil {
s.log.WarnContext(ctx, "org channel not stopped", "org", instance.owner, "err", err)
}
s.status.Declare(instance.name, false, false)
}
}
s.signalPublish()
return nil
}
// planOrgChannel resolves one org's settings to a channel it may run. The
// agent must belong to the org: the settings are the org's to write, so the
// identity they name is checked here rather than trusted.
func (s *Service) planOrgChannel(ctx context.Context, entry controlplanerpc.OrgChannel, binding secret.SecretRef) (orgChannelPlan, error) {
settings := entry.Settings
switch {
case settings.Agent == "":
return orgChannelPlan{}, errors.New("no agent named")
case len(settings.Telegram.AllowedUserIDs) == 0:
return orgChannelPlan{}, errors.New("no allowed telegram users")
case binding == (secret.SecretRef{}):
return orgChannelPlan{}, fmt.Errorf("no credential binding %q", telegramCredential)
}
principal, err := s.orgs.Principals.PrincipalFor(ctx, identity.IdentityID(settings.Agent))
if err != nil {
return orgChannelPlan{}, fmt.Errorf("resolve agent: %w", err)
}
if string(principal.Org) != entry.Org || !principal.Kind.Agent() {
return orgChannelPlan{}, errors.New("agent is not an agent of this org")
}
token, err := s.secrets.Resolve(binding)
if err != nil {
return orgChannelPlan{}, fmt.Errorf("resolve token: %w", err)
}
if token == "" {
return orgChannelPlan{}, errors.New("token resolved empty")
}
return orgChannelPlan{org: entry.Org, token: token, allowed: settings.Telegram.AllowedUserIDs, show: settings.ShowToolCalls, agent: principal}, nil
}
// telegramBindings maps each org to the secret its Telegram bot token is bound
// to. Bindings are the instance's to grant, so they are read from the system
// org's document.
func (s *Service) telegramBindings(ctx context.Context) (map[string]secret.SecretRef, error) {
var documents []struct {
Service string `json:"service"`
Org string `json:"org"`
Secret struct {
Engine string `json:"engine"`
Key string `json:"key"`
} `json:"secret"`
}
if _, _, err := s.orgs.Source.Query(ctx, credentialBindingsKind, func(value []byte) error { return json.Unmarshal(value, &documents) }); err != nil {
return nil, err
}
out := map[string]secret.SecretRef{}
for _, document := range documents {
if document.Service == telegramCredential {
out[document.Org] = secret.SecretRef{Engine: document.Secret.Engine, Key: document.Secret.Key}
}
}
return out, nil
}
// applyOrgChannel starts owner's channel, or replaces it when its plan changed.
func (s *Service) applyOrgChannel(ctx context.Context, owner string, plan orgChannelPlan) {
if instance := s.orgInstance(owner); instance != nil {
s.applyExistingOrgChannel(ctx, instance, plan)
return
}
instance := &channelInstance{
name: owner + "/" + telegramCredential, kind: telegramCredential, owner: owner,
chat: actingChat{ChatContract: s.chat, as: plan.agent}, plan: &plan,
notify: make(chan struct{}, 1),
}
instance.channel = s.buildOrgTelegram(plan)
s.addChannel(ctx, instance)
}
func (s *Service) applyExistingOrgChannel(ctx context.Context, instance *channelInstance, plan orgChannelPlan) {
previous := instance.currentPlan()
instance.mu.Lock()
running := instance.channel != nil
instance.mu.Unlock()
if running && previous.same(plan) {
if previous.show != plan.show {
s.setOrgShowToolCalls(instance, plan.show)
instance.setPlan(plan, s.chat)
}
return
}
instance.setPlan(plan, s.chat)
if err := s.setChannelState(instance, s.buildOrgTelegram(plan)); err != nil {
s.log.WarnContext(ctx, "org channel not restarted", "org", plan.org, "err", err)
return
}
s.status.Declare(instance.name, true, false)
}
func (s *Service) setOrgShowToolCalls(instance *channelInstance, show bool) {
if g, ok := instance.current().(*telegram.Gateway); ok {
g.SetShowToolCalls(show)
}
}
// buildOrgTelegram builds an org's bot. It carries none of the instance
// operator's seams: no settings command, update service or version report, so
// an org's chat users reach nothing but chat.
func (s *Service) buildOrgTelegram(plan orgChannelPlan) channels.Channel {
tg := telegram.New(plan.token, plan.allowed, s.log.With("org", plan.org))
tg.SetShowToolCalls(plan.show)
return tg
}
func (c *channelInstance) currentPlan() orgChannelPlan {
c.mu.Lock()
defer c.mu.Unlock()
if c.plan == nil {
return orgChannelPlan{}
}
return *c.plan
}
// setPlan records the plan the instance runs and the chat it speaks through.
func (c *channelInstance) setPlan(plan orgChannelPlan, gateway messaging.ChatContract) {
c.mu.Lock()
defer c.mu.Unlock()
c.plan = &plan
c.chat = actingChat{ChatContract: gateway, as: plan.agent}
}
func (s *Service) orgInstance(owner string) *channelInstance {
for _, instance := range s.instances() {
if instance.owner == owner && instance.kind == telegramCredential {
return instance
}
}
return nil
}
// addChannel registers a channel composed after startup and supervises it.
func (s *Service) addChannel(ctx context.Context, instance *channelInstance) {
s.chMu.Lock()
s.channels = append(s.channels, instance)
s.chMu.Unlock()
s.status.Add(instance.name, instance.name, instance.current() != nil)
instance.mu.Lock()
instance.supervised = true
instance.mu.Unlock()
s.wg.Add(1)
go s.runChannel(ctx, instance)
}
// instances returns the composed channels, including those added since start.
func (s *Service) instances() []*channelInstance {
s.chMu.RLock()
defer s.chMu.RUnlock()
return slices.Clone(s.channels)
}
// actingChat speaks to the Gateway as an org's agent, so every call lands in
// that org. Every method of the contract is wrapped: one left bare would act
// for no one, which the Gateway reads as the system org.
type actingChat struct {
messaging.ChatContract
as access.Principal
}
func (a actingChat) act(ctx context.Context) context.Context { return access.WithPrincipal(ctx, a.as) }
func (a actingChat) Snapshot(ctx context.Context) (messaging.ChatSnapshot, error) {
return a.ChatContract.Snapshot(a.act(ctx))
}
func (a actingChat) GetSession(ctx context.Context, id string) (messaging.SessionContext, bool, error) {
return a.ChatContract.GetSession(a.act(ctx), id)
}
func (a actingChat) RecentMessages(ctx context.Context, id string, limit int) ([]messaging.Message, error) {
return a.ChatContract.RecentMessages(a.act(ctx), id, limit)
}
func (a actingChat) RecentTurns(ctx context.Context, id string, limit int) ([]messaging.TurnRecord, error) {
return a.ChatContract.RecentTurns(a.act(ctx), id, limit)
}
func (a actingChat) Route(ctx context.Context, in messaging.Inbound) (messaging.ChatReply, error) {
return a.ChatContract.Route(a.act(ctx), in)
}
func (a actingChat) Stream(ctx context.Context, in messaging.Inbound) (<-chan messaging.ChatEvent, error) {
return a.ChatContract.Stream(a.act(ctx), in)
}
func (a actingChat) Cancel(ctx context.Context, id string) (messaging.ChatCancellation, error) {
return a.ChatContract.Cancel(a.act(ctx), id)
}
func (a actingChat) StopTasks(ctx context.Context, origin string, taskID int64) ([]int64, error) {
return a.ChatContract.StopTasks(a.act(ctx), origin, taskID)
}
func (a actingChat) ApplyTaskAction(ctx context.Context, origin string, taskID int64, action taskstate.Action, payload taskactions.ActionPayload) (messaging.TaskActionResult, error) {
return a.ChatContract.ApplyTaskAction(a.act(ctx), origin, taskID, action, payload)
}
func (a actingChat) ApplyOperatorTaskAction(ctx context.Context, actor taskactions.Actor, taskID int64, action taskstate.Action, payload taskactions.ActionPayload) (messaging.TaskActionResult, error) {
return a.ChatContract.ApplyOperatorTaskAction(a.act(ctx), actor, taskID, action, payload)
}