package bot import ( "context" "encoding/json" "fmt" "os" "regexp" "strings" "time" ) // Recipe schema v1 (docs/bot-recipes.md): a bot's behaviour as data — an // ordered list of trigger→action rules from a bounded, admin-auditable palette // (docs/bots.md § Governance), executed by Engine. Declarative bots need no // code, and the palette is the capability boundary: an action the schema // doesn't name cannot be expressed, so a recipe can never escalate a bot // beyond what the operator can read off this file. // // Sibling schema, deliberately not unified: docs/conversation-scripts.md // (client-executed onboarding flows). Recipes are sidecar-executed. type Recipe struct { Rules []Rule `json:"rules"` } // Rule is one trigger→action pair. Rules are evaluated in order; the first // rule whose trigger matches acts, and the rest are skipped. type Rule struct { // On is the trigger: "message" (an incoming chat message) or "changelog" // (new entries in the instance's embedded changelog — a custom deploy // watcher; the retired default Announcer used this). On string `json:"on"` // Message-trigger refinements. Match is who the rule listens to: // "trigger" (default) fires only when the bot is addressed — a DM, or a // group @mention; "any" fires on every message the bot can read — the // loud, consent-gated watcher mode (docs/bots.md § Consent). Keyword // (case-insensitive substring) and Regex (RE2) further gate the text; // both set means both must match. Match string `json:"match,omitempty"` Keyword string `json:"keyword,omitempty"` Regex string `json:"regex,omitempty"` // Action is what a matched rule does: "commands" (answer the deterministic // command floor; non-commands fall through to later rules), "reply" (post // Text, with {name} replaced by the sender's name), or "announce" (post // fresh changelog entries — changelog trigger only). Action string `json:"action"` Text string `json:"text,omitempty"` // Every is the changelog poll interval (Go duration, default 5m). Every string `json:"every,omitempty"` re *regexp.Regexp every time.Duration } // RecipePathFor mirrors the .state.json convention: the recipe rides next to // the session file it configures. func RecipePathFor(sessionPath string) string { return sessionPath + ".recipe.json" } // DefaultRecipe is a bot with no recipe file: when addressed, answer the // command floor, and let the model take anything that isn't a command — // exactly the Node sidecar's behaviour with and without an ANTHROPIC_API_KEY // (the model rule falls through harmlessly when there's no key). func DefaultRecipe() *Recipe { return &Recipe{Rules: []Rule{ {On: "message", Action: "commands"}, {On: "message", Action: "model"}, }} } // usesModel reports whether any rule can produce a model-generated reply — the // signal for the AI badge (a bot with a key but no model rule, like a // changelog watcher or a template-only bot, is deterministic and badges BOT). func (r *Recipe) usesModel() bool { for _, rule := range r.Rules { if rule.On == "message" && rule.Action == "model" { return true } } return false } // LoadRecipe reads and validates a recipe file. A missing file returns // (nil, nil) — "no recipe" is a normal state (the caller falls back to // DefaultRecipe). Anything else fails closed: a recipe that doesn't validate // must stop the bot, never silently degrade to different behaviour. func LoadRecipe(path string) (*Recipe, error) { raw, err := os.ReadFile(path) if os.IsNotExist(err) { return nil, nil } if err != nil { return nil, err } var r Recipe if err := json.Unmarshal(raw, &r); err != nil { return nil, fmt.Errorf("bad recipe %s: %w", path, err) } if err := r.validate(); err != nil { return nil, fmt.Errorf("bad recipe %s: %w", path, err) } return &r, nil } // validate enforces the palette. Unknown triggers, actions, or fields that // don't belong together are errors — the schema is the capability boundary, // so nothing unrecognised may pass. func (r *Recipe) validate() error { if len(r.Rules) == 0 { return fmt.Errorf("no rules") } changelogs := 0 for i := range r.Rules { rule := &r.Rules[i] switch rule.On { case "message": switch rule.Match { case "", "trigger", "any": default: return fmt.Errorf("rule %d: unknown match %q", i, rule.Match) } switch rule.Action { case "commands", "model": if rule.Text != "" { return fmt.Errorf("rule %d: %s takes no text", i, rule.Action) } case "reply": if rule.Text == "" { return fmt.Errorf("rule %d: reply needs text", i) } default: return fmt.Errorf("rule %d: unknown message action %q", i, rule.Action) } if rule.Regex != "" { re, err := regexp.Compile(rule.Regex) if err != nil { return fmt.Errorf("rule %d: %w", i, err) } rule.re = re } if rule.Every != "" { return fmt.Errorf("rule %d: every belongs to changelog rules", i) } case "changelog": changelogs++ if changelogs > 1 { return fmt.Errorf("rule %d: at most one changelog rule (one announce state per bot)", i) } if rule.Action != "announce" { return fmt.Errorf("rule %d: unknown changelog action %q", i, rule.Action) } if rule.Match != "" || rule.Keyword != "" || rule.Regex != "" || rule.Text != "" { return fmt.Errorf("rule %d: changelog rules take only every", i) } rule.every = 5 * time.Minute if rule.Every != "" { d, err := time.ParseDuration(rule.Every) if err != nil || d <= 0 { return fmt.Errorf("rule %d: bad every %q", i, rule.Every) } rule.every = d } default: return fmt.Errorf("rule %d: unknown trigger %q", i, rule.On) } } return nil } // Watches reports whether any rule reads beyond addressed messages — the flag // that carries the watcher consent weight (docs/bots.md § Consent). func (r *Recipe) Watches() bool { for _, rule := range r.Rules { if rule.On == "message" && rule.Match == "any" { return true } } return false } // handler folds the message rules into the Runtime's Handler seam. First // matching rule acts. A "commands" rule that was addressed but got a // non-command lets later rules try; if nothing else acts, an addressed // message falls back to the no-AI hint (only without a model — with one, a // failed model call stays silent, like the Node runtime). func (r *Recipe) handler(botName string, aiEnabled bool) func(*ThreadCtx, Incoming) (Reply, bool) { strip := mentionStripper(botName) return func(tc *ThreadCtx, in Incoming) (Reply, bool) { sawCommands := false for _, rule := range r.Rules { if rule.On != "message" { continue } if rule.Match != "any" && !in.Triggered { continue } text := strip(in.Text) if rule.Keyword != "" && !strings.Contains(strings.ToLower(in.Text), strings.ToLower(rule.Keyword)) { continue } if rule.re != nil && !rule.re.MatchString(in.Text) { continue } switch rule.Action { case "commands": if rep, ok := RunCommand(text, aiEnabled); ok { return rep, true } sawCommands = true // not a command — later rules may still act case "reply": return Reply{Text: strings.ReplaceAll(rule.Text, "{name}", in.Sender)}, true case "model": if rep, ok := tc.ModelReply(); ok { return rep, true } // No brain, or the call failed — later rules may still act. } } if sawCommands && in.Triggered && !aiEnabled { return Reply{Text: degradeText}, true } return Reply{}, false } } // Engine runs one bot from its recipe: the live Runtime with the folded // message rules, plus a poller per changelog rule. This is the whole of // `lchat bot run` for one identity. type Engine struct { Base string Session *Session SessionPath string // for the announce state file (StatePathFor) Recipe *Recipe // AIKey is the ANTHROPIC_API_KEY (empty = deterministic-only: model rules // fall through, the bot badges BOT, and nothing ever leaves the box). AIKey string // Charters marks this identity as the sidecar's charter host — it runs // member bots and offers the create_bot tool (docs/member-bots.md; elected // in botcmd's runBotRun, exactly one per sidecar). Charters bool // Ready, if set, is forwarded to the Runtime (called once the bot is live). Ready func() Logf func(format string, args ...any) } func (e *Engine) Run(ctx context.Context) error { for _, rule := range e.Recipe.Rules { if rule.On != "changelog" { continue } a := &Announcer{Base: e.Base, Session: e.Session, StatePath: StatePathFor(e.SessionPath), Logf: e.Logf} go a.Run(ctx, rule.every) } // The AI brain is live only when the recipe can actually use it: a bot with // a key but no model rule (the Announcer, a template-only watcher) is // deterministic and must badge BOT, not AI. aiKey := "" if e.Recipe.usesModel() { aiKey = e.AIKey } rt := &Runtime{ Base: e.Base, Session: e.Session, Handler: e.Recipe.handler(e.Session.Name, aiKey != ""), AIKey: aiKey, Charters: e.Charters, Ready: e.Ready, Logf: e.Logf, } return rt.Run(ctx) }