package agent import ( "context" "encoding/json" "errors" "fmt" "strings" "github.com/andrew/superbrain/internal/ai" ) // ErrCompileRejected means the model could not (or refused to) express the // request as a task. The message is safe to show the user verbatim. type ErrCompileRejected struct{ Reason string } func (e *ErrCompileRejected) Error() string { return "compile rejected: " + e.Reason } // compileSystem is the compiler contract. The model gets a closed schema, // worked examples, and an explicit refusal path — it never gets to invent // actions. Everything it returns is re-validated by ValidateSpec; the // prompt is convenience, the validator is the boundary. const compileSystem = `You are Superbrain's automation compiler. Convert the user's request into ONE automation task, or refuse. Reply with ONLY a JSON object, no prose: {"name": "", "spec": } on success {"error": ""} when the request cannot be expressed. Spec schema: { "condition": { "type": "url_watch" | "signal", "url": absolute http(s) URL to poll (url_watch only), "question": what to look for on the page, <=500 chars (url_watch only), "op": "any" | "lt" | "lte" | "gt" | "gte" | "eq" | "contains", "threshold": number for lt/lte/gt/gte, "text": string for eq/contains, "keyword": optional keyword filter (signal only) }, "action": { "type": "notify" | "email" | "bookmark", "channelId": existing notification channel id (notify only; you do NOT know ids - put "" and the user picks one), "to": recipient email (email only), "title": message/bookmark title, "body": message body, "url": URL to save (bookmark only) }, "pollMinutes": 15..10080 (default 60), "once": true for one-shot deals, false for ongoing watches } What Superbrain can actually do — anything else MUST be refused: - url_watch: fetch a PUBLIC web page on a schedule and answer one question about it (prices, availability, a phrase). It cannot log in, search engines, book anything, or chain multiple sites. Multi-step requests (e.g. "watch flights AND then search hotels") must be refused with an explanation that one watch per task is supported today. - signal: fire when the user's existing mailbox watchers produce a new signal, optionally filtered by keyword. - Actions: notify (an existing channel), email (one message to one fixed recipient), bookmark (save one URL for the user). Examples: - "when the denver-indy round trip on https://flights.example/q/123 drops below 400, email david@email.com" -> {"name":"Flights DEN-IND under $400","spec":{"condition":{"type":"url_watch","url":"https://flights.example/q/123","question":"What is the cheapest round-trip flight price shown, in USD?","op":"lt","threshold":400},"action":{"type":"email","channelId":"","to":"david@email.com","title":"Flight deal: DEN-IND under $400","body":"A round-trip flight dropped below $400."},"pollMinutes":60,"once":true}} - "tell me when my inbox gets an invoice" -> {"name":"Invoice signals","spec":{"condition":{"type":"signal","keyword":"invoice"},"action":{"type":"notify","channelId":""},"pollMinutes":15,"once":false}} - "book me a hotel" -> {"error":"Superbrain cannot book anything; it can watch a public page and notify you."} Rules: prefer once=true for deals and once=false for ongoing watches; pollMinutes>=15 (60 unless the user asks for faster); never invent URLs the user did not provide — if a watch target is missing, refuse and ask for it; keep names under 80 characters.` // Compile turns one natural-language request into a validated task // proposal. The result is NOT persisted — the user confirms it through the // regular task-creation endpoint, which validates again. func Compile(ctx context.Context, text string) (name string, spec Spec, err error) { text = strings.TrimSpace(text) if text == "" { return "", Spec{}, errors.New("empty request") } if len([]rune(text)) > 2000 { return "", Spec{}, errors.New("request too long (max 2000 characters)") } reply, err := ai.Complete(ctx, compileSystem, text) if err != nil { return "", Spec{}, err } raw, err := ai.ExtractJSON(reply) if err != nil { return "", Spec{}, fmt.Errorf("model reply was not JSON: %w", err) } var out struct { Name string `json:"name"` Spec *Spec `json:"spec"` Error string `json:"error"` } if err := json.Unmarshal(raw, &out); err != nil { return "", Spec{}, fmt.Errorf("model reply did not match the compiler schema: %w", err) } if out.Error != "" { return "", Spec{}, &ErrCompileRejected{Reason: out.Error} } if out.Spec == nil { return "", Spec{}, &ErrCompileRejected{Reason: "the model returned neither a task nor an explanation"} } name = strings.TrimSpace(out.Name) if name == "" { name = "Automation" } if len([]rune(name)) > 120 { name = string([]rune(name)[:120]) } // The validator, not the model, decides what a task is. if err := ValidateSpec(out.Spec); err != nil { return "", Spec{}, &ErrCompileRejected{Reason: "the proposed task failed validation: " + err.Error()} } // A compiled notify action never knows channel ids; the UI fills it in. return name, *out.Spec, nil }