| 1 | package agent |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "strings" |
| 8 | |
| 9 | "reasonix/internal/event" |
| 10 | "reasonix/internal/tool" |
| 11 | ) |
| 12 | |
| 13 | // AskTool lets the model put a structured multiple-choice question (or a few) to |
| 14 | // the user mid-task and get the answer back — for genuine forks the model can't |
| 15 | // resolve from the request or the code (which library, which approach, …) rather |
| 16 | // than guessing or asking in prose. The frontend renders selectable options, the |
| 17 | // user picks, and the choices come back as the tool result. It reaches the user |
| 18 | // through the Asker carried on the call |
| 19 | // context (CallContext); with no asker (headless runs) it returns an explicit |
| 20 | // model-assumption fallback so an autonomous run never blocks or pretends a user |
| 21 | // answered. |
| 22 | type AskTool struct{} |
| 23 | |
| 24 | func NewAskTool() *AskTool { return &AskTool{} } |
| 25 | |
| 26 | func (*AskTool) Name() string { return tool.HostAsk } |
| 27 | |
| 28 | func (*AskTool) Description() string { |
| 29 | return "Ask the user one or more multiple-choice questions when you hit a decision that is genuinely theirs to make — one you can't resolve from the request, the code, or sensible defaults. The frontend shows the options for the user to pick; their choices are returned to you. Prefer this over asking in prose for any real fork (which approach, which library, scope). Don't use it for decisions with an obvious default — pick the sensible option and proceed. Permission presets do not answer these questions for the user. Each question has a short `header` (a tab label), the `question` text, 2-4 `options` (each a `label` and optional `description`; put any recommended option first), and `multiSelect` when more than one may apply." |
| 30 | } |
| 31 | |
| 32 | func (*AskTool) Schema() json.RawMessage { |
| 33 | return json.RawMessage(`{ |
| 34 | "type":"object", |
| 35 | "properties":{ |
| 36 | "questions":{ |
| 37 | "type":"array", |
| 38 | "minItems":1, |
| 39 | "maxItems":3, |
| 40 | "description":"1-3 related questions to ask together. Same ambiguity is asked only once.", |
| 41 | "items":{ |
| 42 | "type":"object", |
| 43 | "properties":{ |
| 44 | "header":{"type":"string","description":"Very short label for the question (a tab title), e.g. \"Library\"."}, |
| 45 | "question":{"type":"string","description":"The full question to ask."}, |
| 46 | "options":{ |
| 47 | "type":"array","minItems":2,"maxItems":4, |
| 48 | "description":"The choices. Put any recommended option first.", |
| 49 | "items":{ |
| 50 | "type":"object", |
| 51 | "properties":{ |
| 52 | "label":{"type":"string","description":"The choice text (concise)."}, |
| 53 | "description":{"type":"string","description":"Optional one-line explanation of the choice."} |
| 54 | }, |
| 55 | "required":["label"] |
| 56 | } |
| 57 | }, |
| 58 | "multiSelect":{"type":"boolean","description":"Allow selecting more than one option."} |
| 59 | }, |
| 60 | "required":["question","header","options"] |
| 61 | } |
| 62 | }, |
| 63 | "decision_id":{"type":"string","description":"Required when reopening a previously accepted decision; cite the original decision_id."}, |
| 64 | "new_evidence":{"type":"string","description":"Required with decision_id when asking again after the user already accepted a consequence."} |
| 65 | }, |
| 66 | "required":["questions"] |
| 67 | }`) |
| 68 | } |
| 69 | |
| 70 | // ReadOnly is true: asking has no host side effects, so it never needs approval |
| 71 | // and stays available in plan mode (clarifying scope while planning is fine). |
| 72 | func (*AskTool) ReadOnly() bool { return true } |
| 73 | |
| 74 | func (*AskTool) Execute(ctx context.Context, args json.RawMessage) (string, error) { |
| 75 | p, err := parseAskArgs(args) |
| 76 | if err != nil { |
| 77 | return "", err |
| 78 | } |
| 79 | |
| 80 | qs := make([]event.AskQuestion, 0, len(p.Questions)) |
| 81 | for i, q := range p.Questions { |
| 82 | question := strings.TrimSpace(q.Question) |
| 83 | if question == "" || len(q.Options) < 2 { |
| 84 | return "", fmt.Errorf("question %d: a question and at least two options are required", i+1) |
| 85 | } |
| 86 | opts := make([]event.AskOption, len(q.Options)) |
| 87 | seenLabels := make(map[string]int, len(q.Options)) |
| 88 | for j, o := range q.Options { |
| 89 | label := strings.TrimSpace(o.Label) |
| 90 | if label == "" { |
| 91 | return "", fmt.Errorf("question %d option %d: label is required", i+1, j+1) |
| 92 | } |
| 93 | if prev, ok := seenLabels[label]; ok { |
| 94 | return "", fmt.Errorf("question %d option %d: duplicate label %q also used by option %d", i+1, j+1, label, prev+1) |
| 95 | } |
| 96 | seenLabels[label] = j |
| 97 | opts[j] = event.AskOption{Label: label, Description: strings.TrimSpace(o.Description)} |
| 98 | } |
| 99 | qs = append(qs, event.AskQuestion{ |
| 100 | ID: fmt.Sprintf("q%d", i+1), |
| 101 | Header: strings.TrimSpace(q.Header), |
| 102 | Prompt: question, |
| 103 | Options: opts, |
| 104 | Multi: q.MultiSelect, |
| 105 | }) |
| 106 | } |
| 107 | |
| 108 | id := strings.TrimSpace(p.DecisionID) |
| 109 | explicitID := id != "" |
| 110 | if id == "" { |
| 111 | id = decisionIDForQuestions(qs) |
| 112 | } |
| 113 | if dec, ok := existingDecision(ctx, id); ok { |
| 114 | if strings.TrimSpace(p.Evidence) == "" { |
| 115 | return fmt.Sprintf("Host reused accepted decision %s. The user already chose: %s. Continue with that decision unless you supply decision_id and new_evidence.", dec.ID, dec.Answer), nil |
| 116 | } |
| 117 | } else if !explicitID { |
| 118 | if dec, matched := matchingExistingDecision(ctx, qs); matched { |
| 119 | return fmt.Sprintf("Host reused accepted decision %s for the same ambiguity. The user already chose: %s. Continue with that decision; to reopen it, cite decision_id %s and supply new_evidence.", dec.ID, dec.Answer, dec.ID), nil |
| 120 | } |
| 121 | } else if explicitID { |
| 122 | if _, hasAcceptedDecision := firstExistingDecision(ctx); hasAcceptedDecision { |
| 123 | return "", fmt.Errorf("unknown decision_id %q; cite the original accepted decision_id and include new_evidence to reopen it", id) |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | _, _, asker, ok := CallContext(ctx) |
| 128 | if !ok || asker == nil { |
| 129 | // Headless / no interactive user: don't block an autonomous run, but make |
| 130 | // the provenance explicit so the model doesn't treat this as a user choice. |
| 131 | return "No interactive user answered. This is a model-assumption fallback, not a user answer. Proceed with your best judgment, state the assumption you made, and prefer the safest reversible option when choices differ in risk.", nil |
| 132 | } |
| 133 | |
| 134 | answers, err := asker.Ask(ctx, qs) |
| 135 | if err != nil { |
| 136 | return "", fmt.Errorf("ask: %w", err) |
| 137 | } |
| 138 | summary := formatAnswers(qs, answers) |
| 139 | rememberDecisionForQuestions(ctx, id, qs[0].Prompt, summary, qs) |
| 140 | return summary + "\n\ndecision_id: " + id, nil |
| 141 | } |
| 142 | |
| 143 | // formatAnswers renders the user's selections as a compact, model-facing summary, |
| 144 | // keyed by question header so the model can tell which answer is which. When the |
| 145 | // user picked nothing at all (the "just chat" / dismiss path), it returns an |
| 146 | // explicit stop signal instead of a per-question "(no answer)" — otherwise the |
| 147 | // model reads the empty result as license to proceed and acts unasked. |
| 148 | func formatAnswers(qs []event.AskQuestion, answers []event.AskAnswer) string { |
| 149 | pick := make(map[string][]string, len(answers)) |
| 150 | for _, a := range answers { |
| 151 | pick[a.QuestionID] = a.Selected |
| 152 | } |
| 153 | answered := 0 |
| 154 | for _, q := range qs { |
| 155 | if len(pick[q.ID]) > 0 { |
| 156 | answered++ |
| 157 | } |
| 158 | } |
| 159 | if answered == 0 { |
| 160 | return "The user dismissed the question without choosing — read this as \"don't decide for me, let's just talk.\" Do not pick an option, run a tool, or take any further action toward this; stop and wait for the user's next message." |
| 161 | } |
| 162 | var b strings.Builder |
| 163 | b.WriteString("The user answered:\n") |
| 164 | for _, q := range qs { |
| 165 | sel := pick[q.ID] |
| 166 | label := q.Header |
| 167 | if label == "" { |
| 168 | label = q.Prompt |
| 169 | } |
| 170 | if len(sel) == 0 { |
| 171 | fmt.Fprintf(&b, "- %s: (left unanswered — don't assume a choice)\n", label) |
| 172 | continue |
| 173 | } |
| 174 | fmt.Fprintf(&b, "- %s: %s\n", label, strings.Join(sel, ", ")) |
| 175 | } |
| 176 | return strings.TrimRight(b.String(), "\n") |
| 177 | } |
| 178 |