Conversations are the chat module's own tables. A turn is stored before it is acknowledged, runs after the turns before it in its session, and records everything it streams, so a reader replays it from a cursor. The agent uses the configured agent model, the same connector tools as a run and the dashboard's own reads; every action is judged, and one judgement holds is put to people through approvals and run once when approved. A restart fails the turns it interrupted visibly and never restarts a started action. Conversation memory is a set of notes in the memory module. The chat prompts are copied from internal/prompts (chat-system.tmpl, soul.md, session-title.md) into internal/platform/prompts while the gateway still reads them; the tool parameter redaction is copied from internal/domain/messaging/tool_parameters.go. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
264 lines
9.2 KiB
Go
264 lines
9.2 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/judgement"
|
|
)
|
|
|
|
// principal is who hard rules see acting when the chat agent calls an action.
|
|
const principal = "chat"
|
|
|
|
// 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) {
|
|
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{
|
|
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)
|
|
}),
|
|
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
|
|
}),
|
|
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
|
|
}),
|
|
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) }),
|
|
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
|
|
}),
|
|
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])
|
|
}
|