package chat import ( "context" "errors" "github.com/samcharles93/ai-sdk/chat" "github.com/samcharles93/ai-sdk/core" "github.com/samcharles93/archie-core/modules/chat/internal/store" ) // errToolsChanged ends a turn whose offered tools a later model request may no // longer show: access was withdrawn, the policy chain went away, or a // connector stopped. The operator can send the message again with what remains. var errToolsChanged = errors.New("this conversation's tools changed or are unavailable; send the message again") // guardedProvider re-checks the turn's offered tools before every model // request. The stream client builds the wire tool schemas once, so a tool that // is no longer permitted must stop the turn rather than be omitted silently: a // request that carried it would still describe it to the model. type guardedProvider struct { chat.Provider m *Module d Deps t store.Turn offered core.ToolSet } func (p guardedProvider) ChatStream(ctx context.Context, req chat.Request) (chat.Stream, error) { ctx, err := p.refresh(ctx) if err != nil { return nil, err } return p.Provider.ChatStream(ctx, req) } func (p guardedProvider) Chat(ctx context.Context, req chat.Request) (chat.Response, error) { ctx, err := p.refresh(ctx) if err != nil { return chat.Response{}, err } return p.Provider.Chat(ctx, req) } // refresh acts as the conversation's owner now and confirms every offered tool // is still permitted and declared. A missing tool ends the turn before the // request is made, so the model never sees a stale schema or summary grow. func (p guardedProvider) refresh(ctx context.Context) (context.Context, error) { ctx, err := p.m.actingAs(ctx, p.d, p.t.Owner) if err != nil { return nil, err } current := p.m.tools(ctx, p.d, p.t) for name := range p.offered { if _, ok := current[name]; !ok { return nil, errToolsChanged } } return ctx, nil }