Sessions carry an owner; every chat route serves only the caller's own conversations (others are 404). Each turn and each approved held action acts as its owner's principal, checked against the access rules before judgement, so an operator's chat can't do what the operator can't. Chat is open to any signed-in person, and the stream sends chat updates only to the owner. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
317 lines
12 KiB
Go
317 lines
12 KiB
Go
package chat
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"encoding/json/jsontext"
|
|
"errors"
|
|
"fmt"
|
|
"regexp"
|
|
"slices"
|
|
"strings"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/samcharles93/ai-sdk/core"
|
|
|
|
"github.com/samcharles93/archie-core/internal/platform/prompts"
|
|
"github.com/samcharles93/archie-core/modules/chat/internal/store"
|
|
"github.com/samcharles93/archie-core/modules/connectors"
|
|
"github.com/samcharles93/archie-core/modules/governance"
|
|
"github.com/samcharles93/archie-core/modules/judgement"
|
|
)
|
|
|
|
// principal is who hard rules see acting when the chat agent calls an action.
|
|
const principal = "chat"
|
|
|
|
// actingAs is ctx carrying the principal of owner, the person whose
|
|
// conversation it is, as a request they made would carry it. It is read from
|
|
// the owner's current memberships, so a turn never acts with access its owner
|
|
// has since lost.
|
|
func (m *Module) actingAs(ctx context.Context, d Deps, owner string) (context.Context, error) {
|
|
if owner == "" {
|
|
return nil, errors.New("the conversation has no owner to act as")
|
|
}
|
|
p, err := d.People.PrincipalFor(ctx, governance.IdentityID(owner))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read who the conversation acts as: %w", err)
|
|
}
|
|
return governance.WithActor(governance.WithOrg(governance.WithPrincipal(ctx, p), p.Org), owner), nil
|
|
}
|
|
|
|
// allowed refuses what the principal in ctx may not do through the
|
|
// dashboard, so a tool never reaches further than the person chatting.
|
|
func (m *Module) allowed(ctx context.Context, d Deps, action governance.Action, kind governance.ResourceKind, id string) error {
|
|
p, ok := governance.PrincipalFromContext(ctx)
|
|
if !ok {
|
|
return errors.New("no one to act as")
|
|
}
|
|
decision := d.Access.Authorize(ctx, p, action, governance.Resource{Kind: kind, ID: id, Org: p.Org}, governance.AccessContext{})
|
|
switch {
|
|
case decision.Allowed:
|
|
return nil
|
|
case errors.Is(decision.Err, governance.ErrChainUnavailable):
|
|
return errors.New("access policies are unavailable; try again shortly")
|
|
}
|
|
return fmt.Errorf("you may not %s %s %s", action, kind, id)
|
|
}
|
|
|
|
// guarded is tool with its run refused unless the principal may take action
|
|
// on a resource of kind.
|
|
func (m *Module) guarded(d Deps, action governance.Action, kind governance.ResourceKind, tool *core.Tool) *core.Tool {
|
|
run := tool.Execute
|
|
tool.Execute = func(ctx context.Context, input string) (string, error) {
|
|
if err := m.allowed(ctx, d, action, kind, ""); err != nil {
|
|
return "", err
|
|
}
|
|
return run(ctx, input)
|
|
}
|
|
return tool
|
|
}
|
|
|
|
// unsafeToolChars are those a model API refuses in a tool name.
|
|
var unsafeToolChars = regexp.MustCompile(`[^a-zA-Z0-9_-]`)
|
|
|
|
func toolName(connector, name string) string {
|
|
return unsafeToolChars.ReplaceAllString(connector+"_"+name, "_")
|
|
}
|
|
|
|
// tools is what the agent may call on turn t: every connector lookup, action
|
|
// and MCP tool a run may call, and the dashboard's own reads.
|
|
func (m *Module) tools(d Deps, t store.Turn) core.ToolSet {
|
|
set := core.ToolSet{}
|
|
for _, decl := range d.Toolbox.Declarations() {
|
|
name := toolName(decl.Connector, decl.Name)
|
|
set[name] = &core.Tool{
|
|
Name: name, Description: decl.Description, Parameters: []byte(decl.Schema),
|
|
Execute: func(ctx context.Context, input string) (string, error) {
|
|
return m.call(ctx, d, t, decl, jsontext.Value(input))
|
|
},
|
|
}
|
|
}
|
|
for _, tool := range m.builtins(d, t) {
|
|
set[tool.Name] = tool
|
|
}
|
|
return set
|
|
}
|
|
|
|
func toolSummaries(set core.ToolSet) []prompts.ChatTool {
|
|
out := make([]prompts.ChatTool, 0, len(set))
|
|
for _, t := range set {
|
|
out = append(out, prompts.ChatTool{Name: t.Name, Description: t.Description})
|
|
}
|
|
slices.SortFunc(out, func(a, b prompts.ChatTool) int { return strings.Compare(a.Name, b.Name) })
|
|
return out
|
|
}
|
|
|
|
// call runs a lookup, or judges an action and runs it only as decided. An
|
|
// action judgement holds is put to people and comes back to the agent as
|
|
// waiting for approval rather than as a failure.
|
|
func (m *Module) call(ctx context.Context, d Deps, t store.Turn, decl connectors.Declaration, input jsontext.Value) (string, error) {
|
|
need := governance.ActionRun
|
|
if decl.Kind == connectors.KindLookup {
|
|
need = governance.ActionRead
|
|
}
|
|
if err := m.allowed(ctx, d, need, governance.KindConnector, decl.Connector); err != nil {
|
|
return "", err
|
|
}
|
|
tool, ok := d.Toolbox.Tool(decl.Connector)
|
|
if !ok {
|
|
return "", fmt.Errorf("%q isn't running", decl.Connector)
|
|
}
|
|
if decl.Kind == connectors.KindLookup {
|
|
out, found, err := tool.Lookup(ctx, decl.Name, input)
|
|
switch {
|
|
case err != nil:
|
|
return "", err
|
|
case !found:
|
|
return "not found", nil
|
|
}
|
|
return out, nil
|
|
}
|
|
key := uuid.NewString()
|
|
decision, err := d.Judge.Assess(ctx, judgement.Request{
|
|
RunID: t.ID, Key: key, Connector: decl.Connector, Action: decl.Name, Input: input, Workflow: principal,
|
|
})
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
out, err := d.Judge.Execute(ctx, decision, input, key)
|
|
switch {
|
|
case errors.Is(err, judgement.ErrHeld):
|
|
return m.hold(ctx, d, t, decision)
|
|
case errors.Is(err, connectors.ErrOutcomeUnknown):
|
|
return "", fmt.Errorf("the action was started and its outcome is unknown; it may have taken effect, so don't run it again: %w", err)
|
|
case err != nil:
|
|
return "", err
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// hold puts an action judgement held to the first step of its escalation
|
|
// path and shows the request in the conversation.
|
|
func (m *Module) hold(ctx context.Context, d Deps, t store.Turn, decision judgement.Decision) (string, error) {
|
|
path, err := d.Settings.EscalationPath(ctx, decision.Owner(), decision.Level == judgement.Escalate)
|
|
if err != nil {
|
|
return "", fmt.Errorf("find who approves %s %s: %w", decision.Action.Connector, decision.Action.Name, err)
|
|
}
|
|
key := waitKey(decision.Key)
|
|
request, err := d.Approver.Ask(ctx, t.ID, key, decision, path)
|
|
if err != nil {
|
|
return "", fmt.Errorf("ask for approval: %w", err)
|
|
}
|
|
rawDecision, err := json.Marshal(decision)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
rawPath, err := json.Marshal(path)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if _, err := m.store.PutAction(ctx, m.orgID, store.Action{
|
|
ID: uuid.New(), TurnID: t.ID, Key: key, Decision: rawDecision, RequestID: request.ID,
|
|
Path: rawPath, StepDue: request.StepDeadline,
|
|
}); err != nil {
|
|
return "", err
|
|
}
|
|
m.record(ctx, t.ID, kindApproval, Approval{
|
|
RequestID: request.ID, Action: decision.Action.Connector + " " + decision.Action.Name,
|
|
Summary: request.Summary, Level: decision.Level.String(), Deadline: request.StepDeadline,
|
|
})
|
|
return fmt.Sprintf("held at %s for approval and not run: %s. The operator answers on the approval card in this conversation; don't call it again.",
|
|
decision.Level, heldBecause(decision)), nil
|
|
}
|
|
|
|
// heldBecause lists what held a decision back, for the agent.
|
|
func heldBecause(d judgement.Decision) string {
|
|
var parts []string
|
|
for _, v := range d.Verdicts {
|
|
if v.Advisory || v.Ceiling != d.Level {
|
|
continue
|
|
}
|
|
for _, f := range v.Findings {
|
|
parts = append(parts, v.Guard+": "+f.Text)
|
|
}
|
|
}
|
|
if len(parts) == 0 {
|
|
return "no guard allowed it to run unattended"
|
|
}
|
|
return strings.Join(parts, "; ")
|
|
}
|
|
|
|
// waitKey is the key an approval answer comes back under.
|
|
func waitKey(key string) string { return "approval:" + key }
|
|
|
|
// builtins are the dashboard reads the agent may make: runs, pending
|
|
// approvals, what it remembers, and opening a page for the operator.
|
|
func (m *Module) builtins(d Deps, t store.Turn) []*core.Tool {
|
|
return []*core.Tool{
|
|
m.guarded(d, governance.ActionRead, governance.KindRun, typedTool("run_list", "List the most recent workflow runs, newest first, with their state and error.",
|
|
`{"type":"object","properties":{"limit":{"type":"integer","minimum":1,"maximum":100}}}`,
|
|
func(ctx context.Context, in struct {
|
|
Limit int `json:"limit"`
|
|
},
|
|
) (any, error) {
|
|
if in.Limit <= 0 || in.Limit > 100 {
|
|
in.Limit = 20
|
|
}
|
|
return d.Runs.Recent(ctx, m.orgID, in.Limit)
|
|
})),
|
|
m.guarded(d, governance.ActionRead, governance.KindRun, typedTool("run_get", "Read one workflow run with its result.",
|
|
`{"type":"object","properties":{"id":{"type":"string","format":"uuid"}},"required":["id"]}`,
|
|
func(ctx context.Context, in struct {
|
|
ID uuid.UUID `json:"id"`
|
|
},
|
|
) (any, error) {
|
|
run, ok, err := d.Runs.Run(ctx, m.orgID, in.ID)
|
|
if err != nil || !ok {
|
|
return "no such run", err
|
|
}
|
|
return run, nil
|
|
})),
|
|
m.guarded(d, governance.ActionRead, governance.KindApproval, typedTool("approval_list", "List the approval requests waiting for an answer.", `{"type":"object","properties":{}}`,
|
|
func(ctx context.Context, _ struct{}) (any, error) {
|
|
pending, err := d.Approver.Pending(ctx)
|
|
views := make([]any, 0, len(pending))
|
|
for _, p := range pending {
|
|
views = append(views, p.View())
|
|
}
|
|
return views, err
|
|
})),
|
|
m.guarded(d, governance.ActionRead, governance.KindSettings, typedTool("memory_list", "List the facts you remember across conversations, with their ids.", `{"type":"object","properties":{}}`,
|
|
func(ctx context.Context, _ struct{}) (any, error) { return d.Memory.Notes(ctx) })),
|
|
m.guarded(d, governance.ActionUpdate, governance.KindSettings, typedTool("memory_save", "Remember a durable fact the operator told you, for later conversations. One fact per call, in a sentence.",
|
|
`{"type":"object","properties":{"text":{"type":"string"}},"required":["text"]}`,
|
|
func(ctx context.Context, in struct {
|
|
Text string `json:"text"`
|
|
},
|
|
) (any, error) {
|
|
n, err := d.Memory.Remember(ctx, in.Text)
|
|
return "remembered as " + n.ID.String(), err
|
|
})),
|
|
m.guarded(d, governance.ActionUpdate, governance.KindSettings, typedTool("memory_forget", "Forget a remembered fact by its id.",
|
|
`{"type":"object","properties":{"id":{"type":"string","format":"uuid"}},"required":["id"]}`,
|
|
func(ctx context.Context, in struct {
|
|
ID uuid.UUID `json:"id"`
|
|
},
|
|
) (any, error) {
|
|
ok, err := d.Memory.Forget(ctx, in.ID)
|
|
if !ok {
|
|
return "nothing is remembered under that id", err
|
|
}
|
|
return "forgotten", err
|
|
})),
|
|
typedTool("dashboard_navigate", "Offer the operator a link to a dashboard page, such as /runs/ID or /classes.",
|
|
`{"type":"object","properties":{"path":{"type":"string"},"label":{"type":"string"}},"required":["path"]}`,
|
|
func(ctx context.Context, in Navigation) (any, error) {
|
|
if !dashboardPath(in.Path) {
|
|
return nil, fmt.Errorf("%q isn't a dashboard page", in.Path)
|
|
}
|
|
if in.Label == "" {
|
|
in.Label = in.Path
|
|
}
|
|
m.record(ctx, t.ID, kindNavigate, in)
|
|
return "offered the operator a link to " + in.Path, nil
|
|
}),
|
|
}
|
|
}
|
|
|
|
// typedTool is a tool whose input decodes into In and whose result is text,
|
|
// or JSON when it isn't a string.
|
|
func typedTool[In any](name, description, schema string, run func(context.Context, In) (any, error)) *core.Tool {
|
|
return core.NewTool(name, description, jsontext.Value(schema), func(ctx context.Context, input string) (string, error) {
|
|
var in In
|
|
if strings.TrimSpace(input) != "" {
|
|
if err := json.Unmarshal([]byte(input), &in); err != nil {
|
|
return "", fmt.Errorf("read the input: %w", err)
|
|
}
|
|
}
|
|
out, err := run(ctx, in)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if text, ok := out.(string); ok {
|
|
return text, nil
|
|
}
|
|
raw, err := json.Marshal(out)
|
|
return string(raw), err
|
|
})
|
|
}
|
|
|
|
// dashboardPages are the dashboard's top-level pages.
|
|
var dashboardPages = []string{
|
|
"composer", "runs", "unmatched", "events", "classes", "people", "controls",
|
|
"extensions", "sources", "triggers", "credentials", "settings",
|
|
}
|
|
|
|
var pageID = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._:-]*$`)
|
|
|
|
// dashboardPath accepts a top-level page or one item under it, and nothing
|
|
// that could leave the dashboard.
|
|
func dashboardPath(path string) bool {
|
|
parts := strings.Split(strings.TrimPrefix(path, "/"), "/")
|
|
if !strings.HasPrefix(path, "/") || len(parts) > 2 || !slices.Contains(dashboardPages, parts[0]) {
|
|
return false
|
|
}
|
|
return len(parts) == 1 || pageID.MatchString(parts[1])
|
|
}
|