bots-garden/mini-mepublic Fork
⑂ 1cfe23f
Commits
⬇ Clone ▾
git clone https://git.rickub.com/bots-garden/mini-me.git
git clone ssh://git@rickub.com/bots-garden/mini-me.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP

♻️ Quality: no smell left in the decision blocks' code

- installRouter: one blockInstaller per decision block
- config: the decision blocks' validate() share decisionchecks.go
  (problem, firstError, prefixed, dotted, matcherError, deciderQuestions)
- decide: state templates (state.go) and result pieces (resultstate.go)
  split out; JudgeResult uses bestPiece
- engine: readBlockDecider / compileMatcher shared by the three
  constructors (decisionblocks.go); startAddress + anotherAddressAnswers
- llamastart: ensureModel → requestLoad, waitLoaded, loadOutcome

Same behaviour, same error messages; qlty smells 221 → 210.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
agent committed 2026-11-28T11:14:34+01:00 Browse files
1cfe23f parent: 291b7a6
modified decision_wiring.go +70 -38
@@ -38,56 +38,88 @@ func runDecisionPrompt(ctx context.Context, e *engine.Engine, prompt string, out
3838 // for it.
3939 func installRouter() error {
4040 routing = ""
41- if settings := config.Cfg.SkillRouting; settings.Enabled() {
42- r, err := engine.NewRouter(settings)
41+ for _, install := range []blockInstaller{installSkillRouter, installToolRouter, installDecisionContext, installDecisionTool, installDecisionResult} {
42+ column, err := install()
4343 if err != nil {
4444 return err
4545 }
46- decide.SetRouter(r)
47- routing = fmt.Sprintf(" | routing: %s/%s ≥ %.2f", r.Client.Provider, r.Client.Model, r.MinConfidence)
46+ routing += column
4847 }
49- if settings := config.Cfg.ToolRouting; settings.Enabled() {
50- r, err := engine.NewToolRouter(settings)
51- if err != nil {
52- return err
53- }
54- decide.SetToolRouter(r)
55- routing += fmt.Sprintf(" | tool routing: %s/%s, %d group(s), drop < %.2f", r.Client.Provider, r.Client.Model, len(r.Groups), r.DropBelow)
48+ return nil
49+}
50+
51+// blockInstaller installs one decision block of the config and returns its
52+// banner column, "" when the block is off.
53+type blockInstaller func() (string, error)
54+
55+func installSkillRouter() (string, error) {
56+ settings := config.Cfg.SkillRouting
57+ if !settings.Enabled() {
58+ return "", nil
59+ }
60+ r, err := engine.NewRouter(settings)
61+ if err != nil {
62+ return "", err
5663 }
64+ decide.SetRouter(r)
65+ return fmt.Sprintf(" | routing: %s/%s ≥ %.2f", r.Client.Provider, r.Client.Model, r.MinConfidence), nil
66+}
67+
68+func installToolRouter() (string, error) {
69+ settings := config.Cfg.ToolRouting
70+ if !settings.Enabled() {
71+ return "", nil
72+ }
73+ r, err := engine.NewToolRouter(settings)
74+ if err != nil {
75+ return "", err
76+ }
77+ decide.SetToolRouter(r)
78+ return fmt.Sprintf(" | tool routing: %s/%s, %d group(s), drop < %.2f", r.Client.Provider, r.Client.Model, len(r.Groups), r.DropBelow), nil
79+}
80+
81+func installDecisionContext() (string, error) {
5782 engine.SetContextAsker(nil)
58- if settings := config.Cfg.DecisionContext; settings.Enabled() {
59- a, err := engine.NewContextAsker(settings)
60- if err != nil {
61- return err
62- }
63- engine.SetContextAsker(a)
64- routing += fmt.Sprintf(" | decision context: %s/%s, %d question(s), %d instruction(s)", a.Client.Provider, a.Client.Model, len(a.Questions), len(a.Options.Then))
83+ settings := config.Cfg.DecisionContext
84+ if !settings.Enabled() {
85+ return "", nil
6586 }
87+ a, err := engine.NewContextAsker(settings)
88+ if err != nil {
89+ return "", err
90+ }
91+ engine.SetContextAsker(a)
92+ return fmt.Sprintf(" | decision context: %s/%s, %d question(s), %d instruction(s)", a.Client.Provider, a.Client.Model, len(a.Questions), len(a.Options.Then)), nil
93+}
94+
95+func installDecisionTool() (string, error) {
6696 engine.SetToolJudge(nil)
67- if settings := config.Cfg.DecisionTool; settings.Enabled() {
68- j, err := engine.NewToolJudge(settings)
69- if err != nil {
70- return err
71- }
72- engine.SetToolJudge(j)
73- matcher := settings.Matcher
74- if matcher == "" {
75- matcher = "every tool"
76- }
77- routing += fmt.Sprintf(" | decision tool: %s/%s on %s, %d rule(s)", j.Client.Provider, j.Client.Model, matcher, len(j.Rules))
97+ settings := config.Cfg.DecisionTool
98+ if !settings.Enabled() {
99+ return "", nil
78100 }
79- j, err := installAnswerCheck()
101+ j, err := engine.NewToolJudge(settings)
80102 if err != nil {
81- return err
103+ return "", err
82104 }
83- if j != nil {
84- matcher := config.Cfg.DecisionResult.Matcher
85- if matcher == "" {
86- matcher = "every tool"
87- }
88- routing += fmt.Sprintf(" | decision result: %s/%s on %s, %d rule(s)", j.Client.Provider, j.Client.Model, matcher, len(j.Rules))
105+ engine.SetToolJudge(j)
106+ return fmt.Sprintf(" | decision tool: %s/%s on %s, %d rule(s)", j.Client.Provider, j.Client.Model, matcherLabel(settings.Matcher), len(j.Rules)), nil
107+}
108+
109+func installDecisionResult() (string, error) {
110+ j, err := installAnswerCheck()
111+ if err != nil || j == nil {
112+ return "", err
89113 }
90- return nil
114+ return fmt.Sprintf(" | decision result: %s/%s on %s, %d rule(s)", j.Client.Provider, j.Client.Model, matcherLabel(config.Cfg.DecisionResult.Matcher), len(j.Rules)), nil
115+}
116+
117+// matcherLabel names a block's tools in the banner.
118+func matcherLabel(matcher string) string {
119+ if matcher == "" {
120+ return "every tool"
121+ }
122+ return matcher
91123 }
92124
93125 // routing is the banner's column for skill and tool routing, "" when off.
@@ -38,56 +38,88 @@ func runDecisionPrompt(ctx context.Context, e *engine.Engine, prompt string, out
38 // for it.38 // for it.
39 func installRouter() error {39 func installRouter() error {
40 routing = ""40 routing = ""
41- if settings := config.Cfg.SkillRouting; settings.Enabled() {41+ for _, install := range []blockInstaller{installSkillRouter, installToolRouter, installDecisionContext, installDecisionTool, installDecisionResult} {
42- r, err := engine.NewRouter(settings)42+ column, err := install()
43 if err != nil {43 if err != nil {
44 return err44 return err
45 }45 }
46- decide.SetRouter(r)46+ routing += column
47- routing = fmt.Sprintf(" | routing: %s/%s ≥ %.2f", r.Client.Provider, r.Client.Model, r.MinConfidence)
48 }47 }
49- if settings := config.Cfg.ToolRouting; settings.Enabled() {48+ return nil
50- r, err := engine.NewToolRouter(settings)49+}
51- if err != nil {50+
52- return err51+// blockInstaller installs one decision block of the config and returns its
53- }52+// banner column, "" when the block is off.
54- decide.SetToolRouter(r)53+type blockInstaller func() (string, error)
55- routing += fmt.Sprintf(" | tool routing: %s/%s, %d group(s), drop < %.2f", r.Client.Provider, r.Client.Model, len(r.Groups), r.DropBelow)54+
55+func installSkillRouter() (string, error) {
56+ settings := config.Cfg.SkillRouting
57+ if !settings.Enabled() {
58+ return "", nil
59+ }
60+ r, err := engine.NewRouter(settings)
61+ if err != nil {
62+ return "", err
56 }63 }
64+ decide.SetRouter(r)
65+ return fmt.Sprintf(" | routing: %s/%s ≥ %.2f", r.Client.Provider, r.Client.Model, r.MinConfidence), nil
66+}
67+
68+func installToolRouter() (string, error) {
69+ settings := config.Cfg.ToolRouting
70+ if !settings.Enabled() {
71+ return "", nil
72+ }
73+ r, err := engine.NewToolRouter(settings)
74+ if err != nil {
75+ return "", err
76+ }
77+ decide.SetToolRouter(r)
78+ return fmt.Sprintf(" | tool routing: %s/%s, %d group(s), drop < %.2f", r.Client.Provider, r.Client.Model, len(r.Groups), r.DropBelow), nil
79+}
80+
81+func installDecisionContext() (string, error) {
57 engine.SetContextAsker(nil)82 engine.SetContextAsker(nil)
58- if settings := config.Cfg.DecisionContext; settings.Enabled() {83+ settings := config.Cfg.DecisionContext
59- a, err := engine.NewContextAsker(settings)84+ if !settings.Enabled() {
60- if err != nil {85+ return "", nil
61- return err
62- }
63- engine.SetContextAsker(a)
64- routing += fmt.Sprintf(" | decision context: %s/%s, %d question(s), %d instruction(s)", a.Client.Provider, a.Client.Model, len(a.Questions), len(a.Options.Then))
65 }86 }
87+ a, err := engine.NewContextAsker(settings)
88+ if err != nil {
89+ return "", err
90+ }
91+ engine.SetContextAsker(a)
92+ return fmt.Sprintf(" | decision context: %s/%s, %d question(s), %d instruction(s)", a.Client.Provider, a.Client.Model, len(a.Questions), len(a.Options.Then)), nil
93+}
94+
95+func installDecisionTool() (string, error) {
66 engine.SetToolJudge(nil)96 engine.SetToolJudge(nil)
67- if settings := config.Cfg.DecisionTool; settings.Enabled() {97+ settings := config.Cfg.DecisionTool
68- j, err := engine.NewToolJudge(settings)98+ if !settings.Enabled() {
69- if err != nil {99+ return "", nil
70- return err
71- }
72- engine.SetToolJudge(j)
73- matcher := settings.Matcher
74- if matcher == "" {
75- matcher = "every tool"
76- }
77- routing += fmt.Sprintf(" | decision tool: %s/%s on %s, %d rule(s)", j.Client.Provider, j.Client.Model, matcher, len(j.Rules))
78 }100 }
79- j, err := installAnswerCheck()101+ j, err := engine.NewToolJudge(settings)
80 if err != nil {102 if err != nil {
81- return err103+ return "", err
82 }104 }
83- if j != nil {105+ engine.SetToolJudge(j)
84- matcher := config.Cfg.DecisionResult.Matcher106+ return fmt.Sprintf(" | decision tool: %s/%s on %s, %d rule(s)", j.Client.Provider, j.Client.Model, matcherLabel(settings.Matcher), len(j.Rules)), nil
85- if matcher == "" {107+}
86- matcher = "every tool"108+
87- }109+func installDecisionResult() (string, error) {
88- routing += fmt.Sprintf(" | decision result: %s/%s on %s, %d rule(s)", j.Client.Provider, j.Client.Model, matcher, len(j.Rules))110+ j, err := installAnswerCheck()
111+ if err != nil || j == nil {
112+ return "", err
89 }113 }
90- return nil114+ return fmt.Sprintf(" | decision result: %s/%s on %s, %d rule(s)", j.Client.Provider, j.Client.Model, matcherLabel(config.Cfg.DecisionResult.Matcher), len(j.Rules)), nil
115+}
116+
117+// matcherLabel names a block's tools in the banner.
118+func matcherLabel(matcher string) string {
119+ if matcher == "" {
120+ return "every tool"
121+ }
122+ return matcher
91 }123 }
92 124
93 // routing is the banner's column for skill and tool routing, "" when off.125 // routing is the banner's column for skill and tool routing, "" when off.
added internal/config/decisionchecks.go +86 -0
new file mode 100644
@@ -0,0 +1,86 @@
1+package config
2+
3+import (
4+ "errors"
5+ "fmt"
6+ "os"
7+ "regexp"
8+ "strings"
9+
10+ "mm/internal/decide"
11+)
12+
13+// What the decision blocks (decisionContext, decisionTool, decisionResult)
14+// check alike: a list of problems reported in order, and a decider file that
15+// exists, reads and has questions to ask.
16+
17+// problem is err when bad is true, nil otherwise — one line of a block's
18+// list of checks.
19+func problem(bad bool, msg string) error {
20+ if !bad {
21+ return nil
22+ }
23+ return errors.New(msg)
24+}
25+
26+// firstError returns the first non-nil error of a block's checks, in order.
27+//
28+// err := firstError(problem(d.Timeout < 0, "x.timeout must be >= 0"), matcherError("x.matcher", d.Matcher))
29+func firstError(errs ...error) error {
30+ for _, err := range errs {
31+ if err != nil {
32+ return err
33+ }
34+ }
35+ return nil
36+}
37+
38+// prefixed puts key and ": " before err; nil stays nil.
39+func prefixed(key string, err error) error {
40+ if err == nil {
41+ return nil
42+ }
43+ return fmt.Errorf("%s: %w", key, err)
44+}
45+
46+// dotted puts block and "." before err (an error that starts with the key it
47+// is about, such as "rules[0].action …"); nil stays nil.
48+func dotted(block string, err error) error {
49+ if err == nil {
50+ return nil
51+ }
52+ return fmt.Errorf("%s.%w", block, err)
53+}
54+
55+// matcherError reports a matcher that does not compile; "" is every tool.
56+func matcherError(key, matcher string) error {
57+ if matcher == "" {
58+ return nil
59+ }
60+ _, err := regexp.Compile(matcher)
61+ return prefixed(key, err)
62+}
63+
64+// deciderQuestions reads a block's decider file and returns its questions:
65+// the file must exist, read as a decider, and ask at least one question.
66+//
67+// questions, err := deciderQuestions("decisionTool", d.Decider)
68+func deciderQuestions(block, path string) ([]decide.Question, error) {
69+ key := block + ".decider"
70+ if _, err := os.Stat(path); err != nil {
71+ return nil, prefixed(key, err)
72+ }
73+ decider, err := ReadDecider(path)
74+ if err == nil && (decider.Decision == nil || len(decider.Decision.Questions) == 0) {
75+ err = fmt.Errorf("%s has no decision.questions to ask", path)
76+ }
77+ if err != nil {
78+ return nil, prefixed(key, err)
79+ }
80+ return decider.Decision.Questions, nil
81+}
82+
83+// blankError reports an empty value.
84+func blankError(value, msg string) error {
85+ return problem(strings.TrimSpace(value) == "", msg)
86+}
new file mode 100644
@@ -0,0 +1,86 @@
1+package config
2+
3+import (
4+ "errors"
5+ "fmt"
6+ "os"
7+ "regexp"
8+ "strings"
9+
10+ "mm/internal/decide"
11+)
12+
13+// What the decision blocks (decisionContext, decisionTool, decisionResult)
14+// check alike: a list of problems reported in order, and a decider file that
15+// exists, reads and has questions to ask.
16+
17+// problem is err when bad is true, nil otherwise — one line of a block's
18+// list of checks.
19+func problem(bad bool, msg string) error {
20+ if !bad {
21+ return nil
22+ }
23+ return errors.New(msg)
24+}
25+
26+// firstError returns the first non-nil error of a block's checks, in order.
27+//
28+// err := firstError(problem(d.Timeout < 0, "x.timeout must be >= 0"), matcherError("x.matcher", d.Matcher))
29+func firstError(errs ...error) error {
30+ for _, err := range errs {
31+ if err != nil {
32+ return err
33+ }
34+ }
35+ return nil
36+}
37+
38+// prefixed puts key and ": " before err; nil stays nil.
39+func prefixed(key string, err error) error {
40+ if err == nil {
41+ return nil
42+ }
43+ return fmt.Errorf("%s: %w", key, err)
44+}
45+
46+// dotted puts block and "." before err (an error that starts with the key it
47+// is about, such as "rules[0].action …"); nil stays nil.
48+func dotted(block string, err error) error {
49+ if err == nil {
50+ return nil
51+ }
52+ return fmt.Errorf("%s.%w", block, err)
53+}
54+
55+// matcherError reports a matcher that does not compile; "" is every tool.
56+func matcherError(key, matcher string) error {
57+ if matcher == "" {
58+ return nil
59+ }
60+ _, err := regexp.Compile(matcher)
61+ return prefixed(key, err)
62+}
63+
64+// deciderQuestions reads a block's decider file and returns its questions:
65+// the file must exist, read as a decider, and ask at least one question.
66+//
67+// questions, err := deciderQuestions("decisionTool", d.Decider)
68+func deciderQuestions(block, path string) ([]decide.Question, error) {
69+ key := block + ".decider"
70+ if _, err := os.Stat(path); err != nil {
71+ return nil, prefixed(key, err)
72+ }
73+ decider, err := ReadDecider(path)
74+ if err == nil && (decider.Decision == nil || len(decider.Decision.Questions) == 0) {
75+ err = fmt.Errorf("%s has no decision.questions to ask", path)
76+ }
77+ if err != nil {
78+ return nil, prefixed(key, err)
79+ }
80+ return decider.Decision.Questions, nil
81+}
82+
83+// blankError reports an empty value.
84+func blankError(value, msg string) error {
85+ return problem(strings.TrimSpace(value) == "", msg)
86+}
modified internal/config/decisioncontext.go +18 -23
@@ -3,7 +3,6 @@ package config
33 import (
44 "errors"
55 "fmt"
6- "os"
76 "path/filepath"
87 "slices"
98 "strings"
@@ -156,32 +155,28 @@ func (d DecisionContextConfig) validate(isDecider bool) error {
156155 if !d.Enabled() {
157156 return nil
158157 }
159- switch {
160- case isDecider:
161- return errors.New("decision and decisionContext cannot be used together: a decider has no chat model to give the answers to")
162- case d.MinConfidence < 0 || d.MinConfidence > 1:
163- return errors.New("decisionContext.minConfidence must be between 0 and 1")
164- case d.Timeout < 0:
165- return errors.New("decisionContext.timeout must be >= 0")
166- case !slices.Contains([]string{DecisionAnswersLines, DecisionAnswersJSON, DecisionAnswersNone}, d.Answers):
167- return fmt.Errorf("decisionContext.answers must be lines, json or none, not %q", d.Answers)
168- case d.Answers == DecisionAnswersNone && len(d.Then) == 0:
169- return errors.New("decisionContext: answers: none and no then: entry — nothing would ever be injected")
158+ if err := firstError(
159+ problem(isDecider, "decision and decisionContext cannot be used together: a decider has no chat model to give the answers to"),
160+ problem(d.MinConfidence < 0 || d.MinConfidence > 1, "decisionContext.minConfidence must be between 0 and 1"),
161+ problem(d.Timeout < 0, "decisionContext.timeout must be >= 0"),
162+ answersError(d.Answers),
163+ problem(d.Answers == DecisionAnswersNone && len(d.Then) == 0, "decisionContext: answers: none and no then: entry — nothing would ever be injected"),
164+ ); err != nil {
165+ return err
170166 }
171- if _, err := os.Stat(d.Decider); err != nil {
172- return fmt.Errorf("decisionContext.decider: %w", err)
173- }
174- decider, err := ReadDecider(d.Decider)
167+ questions, err := deciderQuestions("decisionContext", d.Decider)
175168 if err != nil {
176- return fmt.Errorf("decisionContext.decider: %w", err)
177- }
178- if decider.Decision == nil || len(decider.Decision.Questions) == 0 {
179- return fmt.Errorf("decisionContext.decider: %s has no decision.questions to ask", d.Decider)
169+ return err
180170 }
181- if err := decide.CheckInstructions(decider.Decision.Questions, d.Then); err != nil {
182- return fmt.Errorf("decisionContext.then: %w", err)
171+ return prefixed("decisionContext.then", decide.CheckInstructions(questions, d.Then))
172+}
173+
174+// answersError reports a decisionContext.answers value that is not known.
175+func answersError(answers string) error {
176+ if slices.Contains([]string{DecisionAnswersLines, DecisionAnswersJSON, DecisionAnswersNone}, answers) {
177+ return nil
183178 }
184- return nil
179+ return fmt.Errorf("decisionContext.answers must be lines, json or none, not %q", answers)
185180 }
186181
187182 // resolveContextDecider makes decisionContext.decider absolute against the
@@ -3,7 +3,6 @@ package config
3 import (3 import (
4 "errors"4 "errors"
5 "fmt"5 "fmt"
6- "os"
7 "path/filepath"6 "path/filepath"
8 "slices"7 "slices"
9 "strings"8 "strings"
@@ -156,32 +155,28 @@ func (d DecisionContextConfig) validate(isDecider bool) error {
156 if !d.Enabled() {155 if !d.Enabled() {
157 return nil156 return nil
158 }157 }
159- switch {158+ if err := firstError(
160- case isDecider:159+ problem(isDecider, "decision and decisionContext cannot be used together: a decider has no chat model to give the answers to"),
161- return errors.New("decision and decisionContext cannot be used together: a decider has no chat model to give the answers to")160+ problem(d.MinConfidence < 0 || d.MinConfidence > 1, "decisionContext.minConfidence must be between 0 and 1"),
162- case d.MinConfidence < 0 || d.MinConfidence > 1:161+ problem(d.Timeout < 0, "decisionContext.timeout must be >= 0"),
163- return errors.New("decisionContext.minConfidence must be between 0 and 1")162+ answersError(d.Answers),
164- case d.Timeout < 0:163+ problem(d.Answers == DecisionAnswersNone && len(d.Then) == 0, "decisionContext: answers: none and no then: entry — nothing would ever be injected"),
165- return errors.New("decisionContext.timeout must be >= 0")164+ ); err != nil {
166- case !slices.Contains([]string{DecisionAnswersLines, DecisionAnswersJSON, DecisionAnswersNone}, d.Answers):165+ return err
167- return fmt.Errorf("decisionContext.answers must be lines, json or none, not %q", d.Answers)
168- case d.Answers == DecisionAnswersNone && len(d.Then) == 0:
169- return errors.New("decisionContext: answers: none and no then: entry — nothing would ever be injected")
170 }166 }
171- if _, err := os.Stat(d.Decider); err != nil {167+ questions, err := deciderQuestions("decisionContext", d.Decider)
172- return fmt.Errorf("decisionContext.decider: %w", err)
173- }
174- decider, err := ReadDecider(d.Decider)
175 if err != nil {168 if err != nil {
176- return fmt.Errorf("decisionContext.decider: %w", err)169+ return err
177- }
178- if decider.Decision == nil || len(decider.Decision.Questions) == 0 {
179- return fmt.Errorf("decisionContext.decider: %s has no decision.questions to ask", d.Decider)
180 }170 }
181- if err := decide.CheckInstructions(decider.Decision.Questions, d.Then); err != nil {171+ return prefixed("decisionContext.then", decide.CheckInstructions(questions, d.Then))
182- return fmt.Errorf("decisionContext.then: %w", err)172+}
173+
174+// answersError reports a decisionContext.answers value that is not known.
175+func answersError(answers string) error {
176+ if slices.Contains([]string{DecisionAnswersLines, DecisionAnswersJSON, DecisionAnswersNone}, answers) {
177+ return nil
183 }178 }
184- return nil179+ return fmt.Errorf("decisionContext.answers must be lines, json or none, not %q", answers)
185 }180 }
186 181
187 // resolveContextDecider makes decisionContext.decider absolute against the182 // resolveContextDecider makes decisionContext.decider absolute against the
modified internal/config/decisionresult.go +20 -45
@@ -3,10 +3,8 @@ package config
33 import (
44 "errors"
55 "fmt"
6- "os"
76 "path/filepath"
87 "regexp"
9- "strings"
108 "time"
119
1210 "mm/internal/decide"
@@ -174,57 +172,34 @@ func (d DecisionResultConfig) validate(isDecider bool) error {
174172 if !d.Enabled() {
175173 return nil
176174 }
177- switch {
178- case isDecider:
179- return errors.New("decision and decisionResult cannot be used together: a decider calls no tool")
180- case d.Timeout < 0:
181- return errors.New("decisionResult.timeout must be >= 0")
182- case d.OutputChars < 0:
183- return errors.New("decisionResult.outputChars must be >= 0")
184- case len(d.Rules) == 0:
185- return errors.New("decisionResult.rules: at least one rule is needed")
186- }
187- if d.Matcher != "" {
188- if _, err := regexp.Compile(d.Matcher); err != nil {
189- return fmt.Errorf("decisionResult.matcher: %w", err)
190- }
191- }
192- if err := decide.CheckResultState(d.State); err != nil {
193- return fmt.Errorf("decisionResult.state: %w", err)
194- }
195- if err := d.Pieces.validate(); err != nil {
196- return fmt.Errorf("decisionResult.pieces.%w", err)
197- }
198- if _, err := os.Stat(d.Decider); err != nil {
199- return fmt.Errorf("decisionResult.decider: %w", err)
200- }
201- decider, err := ReadDecider(d.Decider)
175+ if err := firstError(
176+ problem(isDecider, "decision and decisionResult cannot be used together: a decider calls no tool"),
177+ problem(d.Timeout < 0, "decisionResult.timeout must be >= 0"),
178+ problem(d.OutputChars < 0, "decisionResult.outputChars must be >= 0"),
179+ problem(len(d.Rules) == 0, "decisionResult.rules: at least one rule is needed"),
180+ matcherError("decisionResult.matcher", d.Matcher),
181+ prefixed("decisionResult.state", decide.CheckResultState(d.State)),
182+ dotted("decisionResult.pieces", d.Pieces.validate()),
183+ ); err != nil {
184+ return err
185+ }
186+ questions, err := deciderQuestions("decisionResult", d.Decider)
202187 if err != nil {
203- return fmt.Errorf("decisionResult.decider: %w", err)
204- }
205- if decider.Decision == nil || len(decider.Decision.Questions) == 0 {
206- return fmt.Errorf("decisionResult.decider: %s has no decision.questions to ask", d.Decider)
188+ return err
207189 }
208- if err := decide.CheckResultRules(decider.Decision.Questions, d.Rules); err != nil {
209- return fmt.Errorf("decisionResult.%w", err)
210- }
211- return nil
190+ return dotted("decisionResult", decide.CheckResultRules(questions, d.Rules))
212191 }
213192
214193 func (p *DecisionPiecesConfig) validate() error {
215194 if p == nil {
216195 return nil
217196 }
218- if strings.TrimSpace(p.Keep) == "" {
219- return errors.New("keep must not be empty: it says which paragraphs are judged")
220- }
221- if _, err := regexp.Compile(p.Keep); err != nil {
222- return fmt.Errorf("keep: %w", err)
223- }
224- if p.Long <= 0 || p.Around <= 0 || p.Max <= 0 {
225- return errors.New("long, around and max must be > 0")
226- }
227- return nil
197+ _, compileErr := regexp.Compile(p.Keep)
198+ return firstError(
199+ blankError(p.Keep, "keep must not be empty: it says which paragraphs are judged"),
200+ prefixed("keep", compileErr),
201+ problem(p.Long <= 0 || p.Around <= 0 || p.Max <= 0, "long, around and max must be > 0"),
202+ )
228203 }
229204
230205 // resolveResultDecider makes decisionResult.decider absolute against the
@@ -3,10 +3,8 @@ package config
3 import (3 import (
4 "errors"4 "errors"
5 "fmt"5 "fmt"
6- "os"
7 "path/filepath"6 "path/filepath"
8 "regexp"7 "regexp"
9- "strings"
10 "time"8 "time"
11 9
12 "mm/internal/decide"10 "mm/internal/decide"
@@ -174,57 +172,34 @@ func (d DecisionResultConfig) validate(isDecider bool) error {
174 if !d.Enabled() {172 if !d.Enabled() {
175 return nil173 return nil
176 }174 }
177- switch {175+ if err := firstError(
178- case isDecider:176+ problem(isDecider, "decision and decisionResult cannot be used together: a decider calls no tool"),
179- return errors.New("decision and decisionResult cannot be used together: a decider calls no tool")177+ problem(d.Timeout < 0, "decisionResult.timeout must be >= 0"),
180- case d.Timeout < 0:178+ problem(d.OutputChars < 0, "decisionResult.outputChars must be >= 0"),
181- return errors.New("decisionResult.timeout must be >= 0")179+ problem(len(d.Rules) == 0, "decisionResult.rules: at least one rule is needed"),
182- case d.OutputChars < 0:180+ matcherError("decisionResult.matcher", d.Matcher),
183- return errors.New("decisionResult.outputChars must be >= 0")181+ prefixed("decisionResult.state", decide.CheckResultState(d.State)),
184- case len(d.Rules) == 0:182+ dotted("decisionResult.pieces", d.Pieces.validate()),
185- return errors.New("decisionResult.rules: at least one rule is needed")183+ ); err != nil {
186- }184+ return err
187- if d.Matcher != "" {185+ }
188- if _, err := regexp.Compile(d.Matcher); err != nil {186+ questions, err := deciderQuestions("decisionResult", d.Decider)
189- return fmt.Errorf("decisionResult.matcher: %w", err)
190- }
191- }
192- if err := decide.CheckResultState(d.State); err != nil {
193- return fmt.Errorf("decisionResult.state: %w", err)
194- }
195- if err := d.Pieces.validate(); err != nil {
196- return fmt.Errorf("decisionResult.pieces.%w", err)
197- }
198- if _, err := os.Stat(d.Decider); err != nil {
199- return fmt.Errorf("decisionResult.decider: %w", err)
200- }
201- decider, err := ReadDecider(d.Decider)
202 if err != nil {187 if err != nil {
203- return fmt.Errorf("decisionResult.decider: %w", err)188+ return err
204- }
205- if decider.Decision == nil || len(decider.Decision.Questions) == 0 {
206- return fmt.Errorf("decisionResult.decider: %s has no decision.questions to ask", d.Decider)
207 }189 }
208- if err := decide.CheckResultRules(decider.Decision.Questions, d.Rules); err != nil {190+ return dotted("decisionResult", decide.CheckResultRules(questions, d.Rules))
209- return fmt.Errorf("decisionResult.%w", err)
210- }
211- return nil
212 }191 }
213 192
214 func (p *DecisionPiecesConfig) validate() error {193 func (p *DecisionPiecesConfig) validate() error {
215 if p == nil {194 if p == nil {
216 return nil195 return nil
217 }196 }
218- if strings.TrimSpace(p.Keep) == "" {197+ _, compileErr := regexp.Compile(p.Keep)
219- return errors.New("keep must not be empty: it says which paragraphs are judged")198+ return firstError(
220- }199+ blankError(p.Keep, "keep must not be empty: it says which paragraphs are judged"),
221- if _, err := regexp.Compile(p.Keep); err != nil {200+ prefixed("keep", compileErr),
222- return fmt.Errorf("keep: %w", err)201+ problem(p.Long <= 0 || p.Around <= 0 || p.Max <= 0, "long, around and max must be > 0"),
223- }202+ )
224- if p.Long <= 0 || p.Around <= 0 || p.Max <= 0 {
225- return errors.New("long, around and max must be > 0")
226- }
227- return nil
228 }203 }
229 204
230 // resolveResultDecider makes decisionResult.decider absolute against the205 // resolveResultDecider makes decisionResult.decider absolute against the
modified internal/config/decisiontool.go +11 -29
@@ -3,9 +3,7 @@ package config
33 import (
44 "errors"
55 "fmt"
6- "os"
76 "path/filepath"
8- "regexp"
97 "strings"
108 "time"
119
@@ -182,36 +180,20 @@ func (d DecisionToolConfig) validate(isDecider bool) error {
182180 if !d.Enabled() {
183181 return nil
184182 }
185- switch {
186- case isDecider:
187- return errors.New("decision and decisionTool cannot be used together: a decider calls no tool")
188- case d.Timeout < 0:
189- return errors.New("decisionTool.timeout must be >= 0")
190- case len(d.Rules) == 0:
191- return errors.New("decisionTool.rules: at least one rule is needed")
183+ if err := firstError(
184+ problem(isDecider, "decision and decisionTool cannot be used together: a decider calls no tool"),
185+ problem(d.Timeout < 0, "decisionTool.timeout must be >= 0"),
186+ problem(len(d.Rules) == 0, "decisionTool.rules: at least one rule is needed"),
187+ matcherError("decisionTool.matcher", d.Matcher),
188+ prefixed("decisionTool.state", decide.CheckState(d.State)),
189+ ); err != nil {
190+ return err
192191 }
193- if d.Matcher != "" {
194- if _, err := regexp.Compile(d.Matcher); err != nil {
195- return fmt.Errorf("decisionTool.matcher: %w", err)
196- }
197- }
198- if err := decide.CheckState(d.State); err != nil {
199- return fmt.Errorf("decisionTool.state: %w", err)
200- }
201- if _, err := os.Stat(d.Decider); err != nil {
202- return fmt.Errorf("decisionTool.decider: %w", err)
203- }
204- decider, err := ReadDecider(d.Decider)
192+ questions, err := deciderQuestions("decisionTool", d.Decider)
205193 if err != nil {
206- return fmt.Errorf("decisionTool.decider: %w", err)
194+ return err
207195 }
208- if decider.Decision == nil || len(decider.Decision.Questions) == 0 {
209- return fmt.Errorf("decisionTool.decider: %s has no decision.questions to ask", d.Decider)
210- }
211- if err := decide.CheckRules(decider.Decision.Questions, d.Rules); err != nil {
212- return fmt.Errorf("decisionTool.%w", err)
213- }
214- return nil
196+ return dotted("decisionTool", decide.CheckRules(questions, d.Rules))
215197 }
216198
217199 // resolveToolGateDecider makes decisionTool.decider absolute against the
@@ -3,9 +3,7 @@ package config
3 import (3 import (
4 "errors"4 "errors"
5 "fmt"5 "fmt"
6- "os"
7 "path/filepath"6 "path/filepath"
8- "regexp"
9 "strings"7 "strings"
10 "time"8 "time"
11 9
@@ -182,36 +180,20 @@ func (d DecisionToolConfig) validate(isDecider bool) error {
182 if !d.Enabled() {180 if !d.Enabled() {
183 return nil181 return nil
184 }182 }
185- switch {183+ if err := firstError(
186- case isDecider:184+ problem(isDecider, "decision and decisionTool cannot be used together: a decider calls no tool"),
187- return errors.New("decision and decisionTool cannot be used together: a decider calls no tool")185+ problem(d.Timeout < 0, "decisionTool.timeout must be >= 0"),
188- case d.Timeout < 0:186+ problem(len(d.Rules) == 0, "decisionTool.rules: at least one rule is needed"),
189- return errors.New("decisionTool.timeout must be >= 0")187+ matcherError("decisionTool.matcher", d.Matcher),
190- case len(d.Rules) == 0:188+ prefixed("decisionTool.state", decide.CheckState(d.State)),
191- return errors.New("decisionTool.rules: at least one rule is needed")189+ ); err != nil {
190+ return err
192 }191 }
193- if d.Matcher != "" {192+ questions, err := deciderQuestions("decisionTool", d.Decider)
194- if _, err := regexp.Compile(d.Matcher); err != nil {
195- return fmt.Errorf("decisionTool.matcher: %w", err)
196- }
197- }
198- if err := decide.CheckState(d.State); err != nil {
199- return fmt.Errorf("decisionTool.state: %w", err)
200- }
201- if _, err := os.Stat(d.Decider); err != nil {
202- return fmt.Errorf("decisionTool.decider: %w", err)
203- }
204- decider, err := ReadDecider(d.Decider)
205 if err != nil {193 if err != nil {
206- return fmt.Errorf("decisionTool.decider: %w", err)194+ return err
207 }195 }
208- if decider.Decision == nil || len(decider.Decision.Questions) == 0 {196+ return dotted("decisionTool", decide.CheckRules(questions, d.Rules))
209- return fmt.Errorf("decisionTool.decider: %s has no decision.questions to ask", d.Decider)
210- }
211- if err := decide.CheckRules(decider.Decision.Questions, d.Rules); err != nil {
212- return fmt.Errorf("decisionTool.%w", err)
213- }
214- return nil
215 }197 }
216 198
217 // resolveToolGateDecider makes decisionTool.decider absolute against the199 // resolveToolGateDecider makes decisionTool.decider absolute against the
modified internal/decide/result.go +18 -90
@@ -2,7 +2,6 @@ package decide
22
33 import (
44 "fmt"
5- "regexp"
65 "slices"
76 "strings"
87 )
@@ -57,82 +56,6 @@ func CheckResultRules(questions []Question, rules []ResultRule) error {
5756 return CheckRules(questions, gate)
5857 }
5958
60-// knownResultPlaceholder is the form each placeholder of a result state
61-// must have: a call's, plus {output} and {output.tail}.
62-var knownResultPlaceholder = regexp.MustCompile(`^\{(cwd|tool|input(\.[A-Za-z0-9_-]+)?|output|output\.tail)\}$`)
63-
64-// CheckResultState reports a placeholder a result state cannot fill.
65-//
66-// decide.CheckResultState("Command: {input.command}\nOutput:\n{output.tail}") // nil
67-func CheckResultState(template string) error {
68- for _, p := range placeholder.FindAllString(template, -1) {
69- if !knownResultPlaceholder.MatchString(p) {
70- return fmt.Errorf("unknown placeholder %s ({cwd}, {tool}, {input}, {input.<field>}, {output}, {output.tail})", p)
71- }
72- }
73- return nil
74-}
75-
76-// RenderResultState fills a result state for one output (or one piece of
77-// it): {output} is its first chars characters, {output.tail} its last ones
78-// (a cut is marked with […]), "(no output)" when it is empty.
79-//
80-// decide.RenderResultState("Command: {input.command}\nOutput:\n{output.tail}", "/w", "bash", in, "…FAILED", 2000)
81-func RenderResultState(template, cwd, tool string, input any, output string, chars int) string {
82- output = strings.TrimSpace(output)
83- head, tail := output, output
84- if output == "" {
85- head, tail = noOutput, noOutput
86- }
87- if runes := []rune(output); len(runes) > chars {
88- head = string(runes[:chars]) + "\n[…]"
89- tail = "[…]\n" + string(runes[len(runes)-chars:])
90- }
91- return render(template, cwd, tool, input, map[string]string{"output": head, "output.tail": tail})
92-}
93-
94-// PieceOptions says which parts of an output are worth asking about.
95-type PieceOptions struct {
96- Keep *regexp.Regexp // a paragraph is kept when it matches
97- Long int // a kept paragraph longer than this is cut…
98- Around int // …to this many characters on each side of the match
99- Max int // at most this many pieces
100-}
101-
102-// Pieces returns the paragraphs of text that Keep matches, a long one cut
103-// around its first match — a decider judges a text as a whole, and one
104-// hidden sentence drowns in a long page (0.44 whole, 0.93 alone, ticket 132).
105-// No match, no piece: the output costs no call.
106-//
107-// decide.Pieces(page, decide.PieceOptions{Keep: regexp.MustCompile(`(?i)\bagents?\b`), Long: 500, Around: 200, Max: 10})
108-func Pieces(text string, o PieceOptions) []string {
109- var out []string
110- for _, paragraph := range paragraphBreak.Split(text, -1) {
111- loc := o.Keep.FindStringIndex(paragraph)
112- if loc == nil {
113- continue
114- }
115- piece := strings.TrimSpace(paragraph)
116- if len(piece) > o.Long {
117- start, end := max(0, loc[0]-o.Around), min(len(paragraph), loc[1]+o.Around)
118- piece = strings.TrimSpace(validUTF8(paragraph[start:end]))
119- }
120- out = append(out, piece)
121- if len(out) == o.Max {
122- break
123- }
124- }
125- return out
126-}
127-
128-// paragraphBreak separates paragraphs: a blank line.
129-var paragraphBreak = regexp.MustCompile(`\n\s*\n`)
130-
131-// validUTF8 drops the broken runes a byte cut leaves at either end.
132-func validUTF8(s string) string {
133- return strings.ToValidUTF8(s, "")
134-}
135-
13659 // Judged is one piece (or the whole output) and the decider's answer.
13760 type Judged struct {
13861 Piece string
@@ -161,26 +84,19 @@ func JudgeResult(judged []Judged, questions []Question, rules []ResultRule, tool
16184 var v ResultVerdict
16285 shown := -1 // the piece the notice describes
16386 for _, r := range rules {
164- best, confidence := -1, -1.0
165- for i, j := range judged {
166- if c, ok := ruleConfidence(r.When, j.Response, questions); ok && c > confidence {
167- best, confidence = i, c
168- }
169- }
87+ best, confidence := bestPiece(r, judged, questions)
17088 if best < 0 {
17189 continue
17290 }
173- if shown < 0 {
91+ if shown < 0 || (r.Action == ActionReplace && v.Replace == "") {
17492 shown = best
17593 }
17694 text := fillResultText(r.Text, tool, confidence, judged[best].Piece)
177- if r.Action == ActionReplace {
178- if v.Replace == "" {
179- v.Replace, shown = text, best
180- }
181- continue
95+ if r.Action != ActionReplace {
96+ v.Warnings = append(v.Warnings, text)
97+ } else if v.Replace == "" {
98+ v.Replace = text
18299 }
183- v.Warnings = append(v.Warnings, text)
184100 }
185101 if v.Replace != "" {
186102 v.Warnings = nil
@@ -192,6 +108,18 @@ func JudgeResult(judged []Judged, questions []Question, rules []ResultRule, tool
192108 return v
193109 }
194110
111+// bestPiece is the piece where every condition of r holds with the highest
112+// confidence, and that confidence; -1 when r holds on no piece.
113+func bestPiece(r ResultRule, judged []Judged, questions []Question) (int, float64) {
114+ best, confidence := -1, -1.0
115+ for i, j := range judged {
116+ if c, ok := ruleConfidence(r.When, j.Response, questions); ok && c > confidence {
117+ best, confidence = i, c
118+ }
119+ }
120+ return best, confidence
121+}
122+
195123 // ruleConfidence tells whether every condition holds on one answer, and
196124 // the lowest confidence among them — how sure the decider is of the rule.
197125 func ruleConfidence(when []Condition, res Response, questions []Question) (float64, bool) {
@@ -2,7 +2,6 @@ package decide
2 2
3 import (3 import (
4 "fmt"4 "fmt"
5- "regexp"
6 "slices"5 "slices"
7 "strings"6 "strings"
8 )7 )
@@ -57,82 +56,6 @@ func CheckResultRules(questions []Question, rules []ResultRule) error {
57 return CheckRules(questions, gate)56 return CheckRules(questions, gate)
58 }57 }
59 58
60-// knownResultPlaceholder is the form each placeholder of a result state
61-// must have: a call's, plus {output} and {output.tail}.
62-var knownResultPlaceholder = regexp.MustCompile(`^\{(cwd|tool|input(\.[A-Za-z0-9_-]+)?|output|output\.tail)\}$`)
63-
64-// CheckResultState reports a placeholder a result state cannot fill.
65-//
66-// decide.CheckResultState("Command: {input.command}\nOutput:\n{output.tail}") // nil
67-func CheckResultState(template string) error {
68- for _, p := range placeholder.FindAllString(template, -1) {
69- if !knownResultPlaceholder.MatchString(p) {
70- return fmt.Errorf("unknown placeholder %s ({cwd}, {tool}, {input}, {input.<field>}, {output}, {output.tail})", p)
71- }
72- }
73- return nil
74-}
75-
76-// RenderResultState fills a result state for one output (or one piece of
77-// it): {output} is its first chars characters, {output.tail} its last ones
78-// (a cut is marked with […]), "(no output)" when it is empty.
79-//
80-// decide.RenderResultState("Command: {input.command}\nOutput:\n{output.tail}", "/w", "bash", in, "…FAILED", 2000)
81-func RenderResultState(template, cwd, tool string, input any, output string, chars int) string {
82- output = strings.TrimSpace(output)
83- head, tail := output, output
84- if output == "" {
85- head, tail = noOutput, noOutput
86- }
87- if runes := []rune(output); len(runes) > chars {
88- head = string(runes[:chars]) + "\n[…]"
89- tail = "[…]\n" + string(runes[len(runes)-chars:])
90- }
91- return render(template, cwd, tool, input, map[string]string{"output": head, "output.tail": tail})
92-}
93-
94-// PieceOptions says which parts of an output are worth asking about.
95-type PieceOptions struct {
96- Keep *regexp.Regexp // a paragraph is kept when it matches
97- Long int // a kept paragraph longer than this is cut…
98- Around int // …to this many characters on each side of the match
99- Max int // at most this many pieces
100-}
101-
102-// Pieces returns the paragraphs of text that Keep matches, a long one cut
103-// around its first match — a decider judges a text as a whole, and one
104-// hidden sentence drowns in a long page (0.44 whole, 0.93 alone, ticket 132).
105-// No match, no piece: the output costs no call.
106-//
107-// decide.Pieces(page, decide.PieceOptions{Keep: regexp.MustCompile(`(?i)\bagents?\b`), Long: 500, Around: 200, Max: 10})
108-func Pieces(text string, o PieceOptions) []string {
109- var out []string
110- for _, paragraph := range paragraphBreak.Split(text, -1) {
111- loc := o.Keep.FindStringIndex(paragraph)
112- if loc == nil {
113- continue
114- }
115- piece := strings.TrimSpace(paragraph)
116- if len(piece) > o.Long {
117- start, end := max(0, loc[0]-o.Around), min(len(paragraph), loc[1]+o.Around)
118- piece = strings.TrimSpace(validUTF8(paragraph[start:end]))
119- }
120- out = append(out, piece)
121- if len(out) == o.Max {
122- break
123- }
124- }
125- return out
126-}
127-
128-// paragraphBreak separates paragraphs: a blank line.
129-var paragraphBreak = regexp.MustCompile(`\n\s*\n`)
130-
131-// validUTF8 drops the broken runes a byte cut leaves at either end.
132-func validUTF8(s string) string {
133- return strings.ToValidUTF8(s, "")
134-}
135-
136 // Judged is one piece (or the whole output) and the decider's answer.59 // Judged is one piece (or the whole output) and the decider's answer.
137 type Judged struct {60 type Judged struct {
138 Piece string61 Piece string
@@ -161,26 +84,19 @@ func JudgeResult(judged []Judged, questions []Question, rules []ResultRule, tool
161 var v ResultVerdict84 var v ResultVerdict
162 shown := -1 // the piece the notice describes85 shown := -1 // the piece the notice describes
163 for _, r := range rules {86 for _, r := range rules {
164- best, confidence := -1, -1.087+ best, confidence := bestPiece(r, judged, questions)
165- for i, j := range judged {
166- if c, ok := ruleConfidence(r.When, j.Response, questions); ok && c > confidence {
167- best, confidence = i, c
168- }
169- }
170 if best < 0 {88 if best < 0 {
171 continue89 continue
172 }90 }
173- if shown < 0 {91+ if shown < 0 || (r.Action == ActionReplace && v.Replace == "") {
174 shown = best92 shown = best
175 }93 }
176 text := fillResultText(r.Text, tool, confidence, judged[best].Piece)94 text := fillResultText(r.Text, tool, confidence, judged[best].Piece)
177- if r.Action == ActionReplace {95+ if r.Action != ActionReplace {
178- if v.Replace == "" {96+ v.Warnings = append(v.Warnings, text)
179- v.Replace, shown = text, best97+ } else if v.Replace == "" {
180- }98+ v.Replace = text
181- continue
182 }99 }
183- v.Warnings = append(v.Warnings, text)
184 }100 }
185 if v.Replace != "" {101 if v.Replace != "" {
186 v.Warnings = nil102 v.Warnings = nil
@@ -192,6 +108,18 @@ func JudgeResult(judged []Judged, questions []Question, rules []ResultRule, tool
192 return v108 return v
193 }109 }
194 110
111+// bestPiece is the piece where every condition of r holds with the highest
112+// confidence, and that confidence; -1 when r holds on no piece.
113+func bestPiece(r ResultRule, judged []Judged, questions []Question) (int, float64) {
114+ best, confidence := -1, -1.0
115+ for i, j := range judged {
116+ if c, ok := ruleConfidence(r.When, j.Response, questions); ok && c > confidence {
117+ best, confidence = i, c
118+ }
119+ }
120+ return best, confidence
121+}
122+
195 // ruleConfidence tells whether every condition holds on one answer, and123 // ruleConfidence tells whether every condition holds on one answer, and
196 // the lowest confidence among them — how sure the decider is of the rule.124 // the lowest confidence among them — how sure the decider is of the rule.
197 func ruleConfidence(when []Condition, res Response, questions []Question) (float64, bool) {125 func ruleConfidence(when []Condition, res Response, questions []Question) (float64, bool) {
added internal/decide/resultstate.go +86 -0
new file mode 100644
@@ -0,0 +1,86 @@
1+package decide
2+
3+import (
4+ "fmt"
5+ "regexp"
6+ "strings"
7+)
8+
9+// The output side of a result decision (ticket 279): the placeholders of a
10+// result state, and the pieces of an output worth asking about.
11+
12+// knownResultPlaceholder is the form each placeholder of a result state
13+// must have: a call's, plus {output} and {output.tail}.
14+var knownResultPlaceholder = regexp.MustCompile(`^\{(cwd|tool|input(\.[A-Za-z0-9_-]+)?|output|output\.tail)\}$`)
15+
16+// CheckResultState reports a placeholder a result state cannot fill.
17+//
18+// decide.CheckResultState("Command: {input.command}\nOutput:\n{output.tail}") // nil
19+func CheckResultState(template string) error {
20+ for _, p := range placeholder.FindAllString(template, -1) {
21+ if !knownResultPlaceholder.MatchString(p) {
22+ return fmt.Errorf("unknown placeholder %s ({cwd}, {tool}, {input}, {input.<field>}, {output}, {output.tail})", p)
23+ }
24+ }
25+ return nil
26+}
27+
28+// RenderResultState fills a result state for one output (or one piece of
29+// it): {output} is its first chars characters, {output.tail} its last ones
30+// (a cut is marked with […]), "(no output)" when it is empty.
31+//
32+// decide.RenderResultState("Command: {input.command}\nOutput:\n{output.tail}", "/w", "bash", in, "…FAILED", 2000)
33+func RenderResultState(template, cwd, tool string, input any, output string, chars int) string {
34+ output = strings.TrimSpace(output)
35+ head, tail := output, output
36+ if output == "" {
37+ head, tail = noOutput, noOutput
38+ }
39+ if runes := []rune(output); len(runes) > chars {
40+ head = string(runes[:chars]) + "\n[…]"
41+ tail = "[…]\n" + string(runes[len(runes)-chars:])
42+ }
43+ return render(template, cwd, tool, input, map[string]string{"output": head, "output.tail": tail})
44+}
45+
46+// PieceOptions says which parts of an output are worth asking about.
47+type PieceOptions struct {
48+ Keep *regexp.Regexp // a paragraph is kept when it matches
49+ Long int // a kept paragraph longer than this is cut…
50+ Around int // …to this many characters on each side of the match
51+ Max int // at most this many pieces
52+}
53+
54+// Pieces returns the paragraphs of text that Keep matches, a long one cut
55+// around its first match — a decider judges a text as a whole, and one
56+// hidden sentence drowns in a long page (0.44 whole, 0.93 alone, ticket 132).
57+// No match, no piece: the output costs no call.
58+//
59+// decide.Pieces(page, decide.PieceOptions{Keep: regexp.MustCompile(`(?i)\bagents?\b`), Long: 500, Around: 200, Max: 10})
60+func Pieces(text string, o PieceOptions) []string {
61+ var out []string
62+ for _, paragraph := range paragraphBreak.Split(text, -1) {
63+ loc := o.Keep.FindStringIndex(paragraph)
64+ if loc == nil {
65+ continue
66+ }
67+ piece := strings.TrimSpace(paragraph)
68+ if len(piece) > o.Long {
69+ start, end := max(0, loc[0]-o.Around), min(len(paragraph), loc[1]+o.Around)
70+ piece = strings.TrimSpace(validUTF8(paragraph[start:end]))
71+ }
72+ out = append(out, piece)
73+ if len(out) == o.Max {
74+ break
75+ }
76+ }
77+ return out
78+}
79+
80+// paragraphBreak separates paragraphs: a blank line.
81+var paragraphBreak = regexp.MustCompile(`\n\s*\n`)
82+
83+// validUTF8 drops the broken runes a byte cut leaves at either end.
84+func validUTF8(s string) string {
85+ return strings.ToValidUTF8(s, "")
86+}
new file mode 100644
@@ -0,0 +1,86 @@
1+package decide
2+
3+import (
4+ "fmt"
5+ "regexp"
6+ "strings"
7+)
8+
9+// The output side of a result decision (ticket 279): the placeholders of a
10+// result state, and the pieces of an output worth asking about.
11+
12+// knownResultPlaceholder is the form each placeholder of a result state
13+// must have: a call's, plus {output} and {output.tail}.
14+var knownResultPlaceholder = regexp.MustCompile(`^\{(cwd|tool|input(\.[A-Za-z0-9_-]+)?|output|output\.tail)\}$`)
15+
16+// CheckResultState reports a placeholder a result state cannot fill.
17+//
18+// decide.CheckResultState("Command: {input.command}\nOutput:\n{output.tail}") // nil
19+func CheckResultState(template string) error {
20+ for _, p := range placeholder.FindAllString(template, -1) {
21+ if !knownResultPlaceholder.MatchString(p) {
22+ return fmt.Errorf("unknown placeholder %s ({cwd}, {tool}, {input}, {input.<field>}, {output}, {output.tail})", p)
23+ }
24+ }
25+ return nil
26+}
27+
28+// RenderResultState fills a result state for one output (or one piece of
29+// it): {output} is its first chars characters, {output.tail} its last ones
30+// (a cut is marked with […]), "(no output)" when it is empty.
31+//
32+// decide.RenderResultState("Command: {input.command}\nOutput:\n{output.tail}", "/w", "bash", in, "…FAILED", 2000)
33+func RenderResultState(template, cwd, tool string, input any, output string, chars int) string {
34+ output = strings.TrimSpace(output)
35+ head, tail := output, output
36+ if output == "" {
37+ head, tail = noOutput, noOutput
38+ }
39+ if runes := []rune(output); len(runes) > chars {
40+ head = string(runes[:chars]) + "\n[…]"
41+ tail = "[…]\n" + string(runes[len(runes)-chars:])
42+ }
43+ return render(template, cwd, tool, input, map[string]string{"output": head, "output.tail": tail})
44+}
45+
46+// PieceOptions says which parts of an output are worth asking about.
47+type PieceOptions struct {
48+ Keep *regexp.Regexp // a paragraph is kept when it matches
49+ Long int // a kept paragraph longer than this is cut…
50+ Around int // …to this many characters on each side of the match
51+ Max int // at most this many pieces
52+}
53+
54+// Pieces returns the paragraphs of text that Keep matches, a long one cut
55+// around its first match — a decider judges a text as a whole, and one
56+// hidden sentence drowns in a long page (0.44 whole, 0.93 alone, ticket 132).
57+// No match, no piece: the output costs no call.
58+//
59+// decide.Pieces(page, decide.PieceOptions{Keep: regexp.MustCompile(`(?i)\bagents?\b`), Long: 500, Around: 200, Max: 10})
60+func Pieces(text string, o PieceOptions) []string {
61+ var out []string
62+ for _, paragraph := range paragraphBreak.Split(text, -1) {
63+ loc := o.Keep.FindStringIndex(paragraph)
64+ if loc == nil {
65+ continue
66+ }
67+ piece := strings.TrimSpace(paragraph)
68+ if len(piece) > o.Long {
69+ start, end := max(0, loc[0]-o.Around), min(len(paragraph), loc[1]+o.Around)
70+ piece = strings.TrimSpace(validUTF8(paragraph[start:end]))
71+ }
72+ out = append(out, piece)
73+ if len(out) == o.Max {
74+ break
75+ }
76+ }
77+ return out
78+}
79+
80+// paragraphBreak separates paragraphs: a blank line.
81+var paragraphBreak = regexp.MustCompile(`\n\s*\n`)
82+
83+// validUTF8 drops the broken runes a byte cut leaves at either end.
84+func validUTF8(s string) string {
85+ return strings.ToValidUTF8(s, "")
86+}
added internal/decide/state.go +116 -0
new file mode 100644
@@ -0,0 +1,116 @@
1+package decide
2+
3+import (
4+ "encoding/json"
5+ "fmt"
6+ "regexp"
7+ "strings"
8+)
9+
10+// The state templates of the tool-call and result decisions (tickets 277,
11+// 279): what a decider is sent about a call, filled in one pass.
12+
13+// DefaultToolState is the state a decisionTool block without `state` sends.
14+const DefaultToolState = "Tool call in {cwd}: {tool} {input}"
15+
16+// placeholder matches every {…} of a state template.
17+var placeholder = regexp.MustCompile(`\{[^{}]*\}`)
18+
19+// knownPlaceholder is the form each one must have.
20+var knownPlaceholder = regexp.MustCompile(`^\{(cwd|tool|input(\.[A-Za-z0-9_-]+)?)\}$`)
21+
22+// CheckState reports a placeholder a state template cannot fill.
23+//
24+// decide.CheckState("Command in {cwd}: {input.command}") // nil
25+// decide.CheckState("{user}") // unknown placeholder {user} (…)
26+func CheckState(template string) error {
27+ for _, p := range placeholder.FindAllString(template, -1) {
28+ if !knownPlaceholder.MatchString(p) {
29+ return fmt.Errorf("unknown placeholder %s ({cwd}, {tool}, {input}, {input.<field>})", p)
30+ }
31+ }
32+ return nil
33+}
34+
35+// RenderState fills a state template for one call: {cwd}, {tool}, {input}
36+// (the arguments as JSON) and {input.<field>} (one argument: a string as it
37+// is, anything else as JSON, "" when absent).
38+//
39+// decide.RenderState("Command in {cwd}: {input.command}", "/work", "bash", map[string]any{"command": "ls"})
40+// // "Command in /work: ls"
41+func RenderState(template, cwd, tool string, input any) string {
42+ return render(template, cwd, tool, input, nil)
43+}
44+
45+// render fills a template in one pass: a value put in is never read again
46+// as a template, so a "{cwd}" inside a command or an output stays as it is.
47+// extra holds more placeholders (a result's {output}); unknown ones stay.
48+func render(template, cwd, tool string, input any, extra map[string]string) string {
49+ return placeholder.ReplaceAllStringFunc(template, func(p string) string {
50+ name := p[1 : len(p)-1]
51+ if v, ok := extra[name]; ok {
52+ return v
53+ }
54+ switch {
55+ case name == "cwd":
56+ return cwd
57+ case name == "tool":
58+ return tool
59+ case name == "input":
60+ return toJSON(input)
61+ case strings.HasPrefix(name, "input."):
62+ return inputField(input, strings.TrimPrefix(name, "input."))
63+ }
64+ return p
65+ })
66+}
67+
68+func inputField(input any, field string) string {
69+ m, ok := asMap(input)
70+ if !ok {
71+ return ""
72+ }
73+ v, ok := m[field]
74+ if !ok {
75+ return ""
76+ }
77+ if s, ok := v.(string); ok {
78+ return s
79+ }
80+ return toJSON(v)
81+}
82+
83+// asMap reads the arguments as an object: a map already, or JSON text.
84+func asMap(input any) (map[string]any, bool) {
85+ switch v := input.(type) {
86+ case map[string]any:
87+ return v, true
88+ case string:
89+ var m map[string]any
90+ if json.Unmarshal([]byte(v), &m) == nil {
91+ return m, true
92+ }
93+ case json.RawMessage:
94+ var m map[string]any
95+ if json.Unmarshal(v, &m) == nil {
96+ return m, true
97+ }
98+ }
99+ var m map[string]any
100+ data, err := json.Marshal(input)
101+ if err != nil || json.Unmarshal(data, &m) != nil {
102+ return nil, false
103+ }
104+ return m, true
105+}
106+
107+func toJSON(v any) string {
108+ if s, ok := v.(string); ok {
109+ return s
110+ }
111+ data, err := json.Marshal(v)
112+ if err != nil {
113+ return fmt.Sprint(v)
114+ }
115+ return string(data)
116+}
new file mode 100644
@@ -0,0 +1,116 @@
1+package decide
2+
3+import (
4+ "encoding/json"
5+ "fmt"
6+ "regexp"
7+ "strings"
8+)
9+
10+// The state templates of the tool-call and result decisions (tickets 277,
11+// 279): what a decider is sent about a call, filled in one pass.
12+
13+// DefaultToolState is the state a decisionTool block without `state` sends.
14+const DefaultToolState = "Tool call in {cwd}: {tool} {input}"
15+
16+// placeholder matches every {…} of a state template.
17+var placeholder = regexp.MustCompile(`\{[^{}]*\}`)
18+
19+// knownPlaceholder is the form each one must have.
20+var knownPlaceholder = regexp.MustCompile(`^\{(cwd|tool|input(\.[A-Za-z0-9_-]+)?)\}$`)
21+
22+// CheckState reports a placeholder a state template cannot fill.
23+//
24+// decide.CheckState("Command in {cwd}: {input.command}") // nil
25+// decide.CheckState("{user}") // unknown placeholder {user} (…)
26+func CheckState(template string) error {
27+ for _, p := range placeholder.FindAllString(template, -1) {
28+ if !knownPlaceholder.MatchString(p) {
29+ return fmt.Errorf("unknown placeholder %s ({cwd}, {tool}, {input}, {input.<field>})", p)
30+ }
31+ }
32+ return nil
33+}
34+
35+// RenderState fills a state template for one call: {cwd}, {tool}, {input}
36+// (the arguments as JSON) and {input.<field>} (one argument: a string as it
37+// is, anything else as JSON, "" when absent).
38+//
39+// decide.RenderState("Command in {cwd}: {input.command}", "/work", "bash", map[string]any{"command": "ls"})
40+// // "Command in /work: ls"
41+func RenderState(template, cwd, tool string, input any) string {
42+ return render(template, cwd, tool, input, nil)
43+}
44+
45+// render fills a template in one pass: a value put in is never read again
46+// as a template, so a "{cwd}" inside a command or an output stays as it is.
47+// extra holds more placeholders (a result's {output}); unknown ones stay.
48+func render(template, cwd, tool string, input any, extra map[string]string) string {
49+ return placeholder.ReplaceAllStringFunc(template, func(p string) string {
50+ name := p[1 : len(p)-1]
51+ if v, ok := extra[name]; ok {
52+ return v
53+ }
54+ switch {
55+ case name == "cwd":
56+ return cwd
57+ case name == "tool":
58+ return tool
59+ case name == "input":
60+ return toJSON(input)
61+ case strings.HasPrefix(name, "input."):
62+ return inputField(input, strings.TrimPrefix(name, "input."))
63+ }
64+ return p
65+ })
66+}
67+
68+func inputField(input any, field string) string {
69+ m, ok := asMap(input)
70+ if !ok {
71+ return ""
72+ }
73+ v, ok := m[field]
74+ if !ok {
75+ return ""
76+ }
77+ if s, ok := v.(string); ok {
78+ return s
79+ }
80+ return toJSON(v)
81+}
82+
83+// asMap reads the arguments as an object: a map already, or JSON text.
84+func asMap(input any) (map[string]any, bool) {
85+ switch v := input.(type) {
86+ case map[string]any:
87+ return v, true
88+ case string:
89+ var m map[string]any
90+ if json.Unmarshal([]byte(v), &m) == nil {
91+ return m, true
92+ }
93+ case json.RawMessage:
94+ var m map[string]any
95+ if json.Unmarshal(v, &m) == nil {
96+ return m, true
97+ }
98+ }
99+ var m map[string]any
100+ data, err := json.Marshal(input)
101+ if err != nil || json.Unmarshal(data, &m) != nil {
102+ return nil, false
103+ }
104+ return m, true
105+}
106+
107+func toJSON(v any) string {
108+ if s, ok := v.(string); ok {
109+ return s
110+ }
111+ data, err := json.Marshal(v)
112+ if err != nil {
113+ return fmt.Sprint(v)
114+ }
115+ return string(data)
116+}
modified internal/decide/toolgate.go +0 -107
@@ -1,9 +1,7 @@
11 package decide
22
33 import (
4- "encoding/json"
54 "fmt"
6- "regexp"
75 "slices"
86 "strings"
97 )
@@ -173,108 +171,3 @@ func verdictNotice(tool string, v Verdict) string {
173171 }
174172 return fmt.Sprintf("🚦 %s: %s → %s", tool, strings.Join(parts, " · "), action)
175173 }
176-
177-// DefaultToolState is the state a decisionTool block without `state` sends.
178-const DefaultToolState = "Tool call in {cwd}: {tool} {input}"
179-
180-// placeholder matches every {…} of a state template.
181-var placeholder = regexp.MustCompile(`\{[^{}]*\}`)
182-
183-// knownPlaceholder is the form each one must have.
184-var knownPlaceholder = regexp.MustCompile(`^\{(cwd|tool|input(\.[A-Za-z0-9_-]+)?)\}$`)
185-
186-// CheckState reports a placeholder a state template cannot fill.
187-//
188-// decide.CheckState("Command in {cwd}: {input.command}") // nil
189-// decide.CheckState("{user}") // unknown placeholder {user} (…)
190-func CheckState(template string) error {
191- for _, p := range placeholder.FindAllString(template, -1) {
192- if !knownPlaceholder.MatchString(p) {
193- return fmt.Errorf("unknown placeholder %s ({cwd}, {tool}, {input}, {input.<field>})", p)
194- }
195- }
196- return nil
197-}
198-
199-// RenderState fills a state template for one call: {cwd}, {tool}, {input}
200-// (the arguments as JSON) and {input.<field>} (one argument: a string as it
201-// is, anything else as JSON, "" when absent).
202-//
203-// decide.RenderState("Command in {cwd}: {input.command}", "/work", "bash", map[string]any{"command": "ls"})
204-// // "Command in /work: ls"
205-func RenderState(template, cwd, tool string, input any) string {
206- return render(template, cwd, tool, input, nil)
207-}
208-
209-// render fills a template in one pass: a value put in is never read again
210-// as a template, so a "{cwd}" inside a command or an output stays as it is.
211-// extra holds more placeholders (a result's {output}); unknown ones stay.
212-func render(template, cwd, tool string, input any, extra map[string]string) string {
213- return placeholder.ReplaceAllStringFunc(template, func(p string) string {
214- name := p[1 : len(p)-1]
215- if v, ok := extra[name]; ok {
216- return v
217- }
218- switch {
219- case name == "cwd":
220- return cwd
221- case name == "tool":
222- return tool
223- case name == "input":
224- return toJSON(input)
225- case strings.HasPrefix(name, "input."):
226- return inputField(input, strings.TrimPrefix(name, "input."))
227- }
228- return p
229- })
230-}
231-
232-func inputField(input any, field string) string {
233- m, ok := asMap(input)
234- if !ok {
235- return ""
236- }
237- v, ok := m[field]
238- if !ok {
239- return ""
240- }
241- if s, ok := v.(string); ok {
242- return s
243- }
244- return toJSON(v)
245-}
246-
247-// asMap reads the arguments as an object: a map already, or JSON text.
248-func asMap(input any) (map[string]any, bool) {
249- switch v := input.(type) {
250- case map[string]any:
251- return v, true
252- case string:
253- var m map[string]any
254- if json.Unmarshal([]byte(v), &m) == nil {
255- return m, true
256- }
257- case json.RawMessage:
258- var m map[string]any
259- if json.Unmarshal(v, &m) == nil {
260- return m, true
261- }
262- }
263- var m map[string]any
264- data, err := json.Marshal(input)
265- if err != nil || json.Unmarshal(data, &m) != nil {
266- return nil, false
267- }
268- return m, true
269-}
270-
271-func toJSON(v any) string {
272- if s, ok := v.(string); ok {
273- return s
274- }
275- data, err := json.Marshal(v)
276- if err != nil {
277- return fmt.Sprint(v)
278- }
279- return string(data)
280-}
@@ -1,9 +1,7 @@
1 package decide1 package decide
2 2
3 import (3 import (
4- "encoding/json"
5 "fmt"4 "fmt"
6- "regexp"
7 "slices"5 "slices"
8 "strings"6 "strings"
9 )7 )
@@ -173,108 +171,3 @@ func verdictNotice(tool string, v Verdict) string {
173 }171 }
174 return fmt.Sprintf("🚦 %s: %s → %s", tool, strings.Join(parts, " · "), action)172 return fmt.Sprintf("🚦 %s: %s → %s", tool, strings.Join(parts, " · "), action)
175 }173 }
176-
177-// DefaultToolState is the state a decisionTool block without `state` sends.
178-const DefaultToolState = "Tool call in {cwd}: {tool} {input}"
179-
180-// placeholder matches every {…} of a state template.
181-var placeholder = regexp.MustCompile(`\{[^{}]*\}`)
182-
183-// knownPlaceholder is the form each one must have.
184-var knownPlaceholder = regexp.MustCompile(`^\{(cwd|tool|input(\.[A-Za-z0-9_-]+)?)\}$`)
185-
186-// CheckState reports a placeholder a state template cannot fill.
187-//
188-// decide.CheckState("Command in {cwd}: {input.command}") // nil
189-// decide.CheckState("{user}") // unknown placeholder {user} (…)
190-func CheckState(template string) error {
191- for _, p := range placeholder.FindAllString(template, -1) {
192- if !knownPlaceholder.MatchString(p) {
193- return fmt.Errorf("unknown placeholder %s ({cwd}, {tool}, {input}, {input.<field>})", p)
194- }
195- }
196- return nil
197-}
198-
199-// RenderState fills a state template for one call: {cwd}, {tool}, {input}
200-// (the arguments as JSON) and {input.<field>} (one argument: a string as it
201-// is, anything else as JSON, "" when absent).
202-//
203-// decide.RenderState("Command in {cwd}: {input.command}", "/work", "bash", map[string]any{"command": "ls"})
204-// // "Command in /work: ls"
205-func RenderState(template, cwd, tool string, input any) string {
206- return render(template, cwd, tool, input, nil)
207-}
208-
209-// render fills a template in one pass: a value put in is never read again
210-// as a template, so a "{cwd}" inside a command or an output stays as it is.
211-// extra holds more placeholders (a result's {output}); unknown ones stay.
212-func render(template, cwd, tool string, input any, extra map[string]string) string {
213- return placeholder.ReplaceAllStringFunc(template, func(p string) string {
214- name := p[1 : len(p)-1]
215- if v, ok := extra[name]; ok {
216- return v
217- }
218- switch {
219- case name == "cwd":
220- return cwd
221- case name == "tool":
222- return tool
223- case name == "input":
224- return toJSON(input)
225- case strings.HasPrefix(name, "input."):
226- return inputField(input, strings.TrimPrefix(name, "input."))
227- }
228- return p
229- })
230-}
231-
232-func inputField(input any, field string) string {
233- m, ok := asMap(input)
234- if !ok {
235- return ""
236- }
237- v, ok := m[field]
238- if !ok {
239- return ""
240- }
241- if s, ok := v.(string); ok {
242- return s
243- }
244- return toJSON(v)
245-}
246-
247-// asMap reads the arguments as an object: a map already, or JSON text.
248-func asMap(input any) (map[string]any, bool) {
249- switch v := input.(type) {
250- case map[string]any:
251- return v, true
252- case string:
253- var m map[string]any
254- if json.Unmarshal([]byte(v), &m) == nil {
255- return m, true
256- }
257- case json.RawMessage:
258- var m map[string]any
259- if json.Unmarshal(v, &m) == nil {
260- return m, true
261- }
262- }
263- var m map[string]any
264- data, err := json.Marshal(input)
265- if err != nil || json.Unmarshal(data, &m) != nil {
266- return nil, false
267- }
268- return m, true
269-}
270-
271-func toJSON(v any) string {
272- if s, ok := v.(string); ok {
273- return s
274- }
275- data, err := json.Marshal(v)
276- if err != nil {
277- return fmt.Sprint(v)
278- }
279- return string(data)
280-}
added internal/engine/decisionblocks.go +63 -0
new file mode 100644
@@ -0,0 +1,63 @@
1+package engine
2+
3+import (
4+ "fmt"
5+ "regexp"
6+ "time"
7+
8+ "mm/internal/config"
9+ "mm/internal/decide"
10+)
11+
12+// What the decision blocks of a chat agent (decisionContext, decisionTool,
13+// decisionResult) build alike: their decider, resolved, and their matcher.
14+
15+// blockDecider is a decision block's decider, ready to be asked.
16+type blockDecider struct {
17+ Client decide.Client
18+ Questions []decide.Question
19+ // Wait is the decider's own decision.timeout: a block's timeout when it
20+ // has none of its own.
21+ Wait time.Duration
22+}
23+
24+// timeout is the block's own timeout, else the decider's.
25+func (d blockDecider) timeout(own time.Duration) time.Duration {
26+ if own > 0 {
27+ return own
28+ }
29+ return d.Wait
30+}
31+
32+// readBlockDecider reads a block's decider file and resolves it like
33+// ResolveDecider (never AGENT_BASE_URL, which names the chat model's server);
34+// its calls go through decisionClient, named purpose in the trace. Errors
35+// read "<block>.decider: …".
36+//
37+// d, err := readBlockDecider("decisionTool", settings.Decider, "decision-tool")
38+func readBlockDecider(block, path, purpose string) (blockDecider, error) {
39+ cfg, err := config.ReadDecider(path)
40+ if err == nil && (cfg.Decision == nil || len(cfg.Decision.Questions) == 0) {
41+ err = fmt.Errorf("%s has no decision.questions to ask", path)
42+ }
43+ var b Backend
44+ if err == nil {
45+ b, err = ResolveDecider(cfg)
46+ }
47+ if err != nil {
48+ return blockDecider{}, fmt.Errorf("%s.decider: %w", block, err)
49+ }
50+ return blockDecider{Client: decisionClient(b, purpose), Questions: cfg.Decision.Questions, Wait: cfg.Decision.Wait()}, nil
51+}
52+
53+// compileMatcher compiles a block's matcher; "" (every tool) is nil.
54+func compileMatcher(block, matcher string) (*regexp.Regexp, error) {
55+ if matcher == "" {
56+ return nil, nil
57+ }
58+ re, err := regexp.Compile(matcher)
59+ if err != nil {
60+ return nil, fmt.Errorf("%s.matcher: %w", block, err)
61+ }
62+ return re, nil
63+}
new file mode 100644
@@ -0,0 +1,63 @@
1+package engine
2+
3+import (
4+ "fmt"
5+ "regexp"
6+ "time"
7+
8+ "mm/internal/config"
9+ "mm/internal/decide"
10+)
11+
12+// What the decision blocks of a chat agent (decisionContext, decisionTool,
13+// decisionResult) build alike: their decider, resolved, and their matcher.
14+
15+// blockDecider is a decision block's decider, ready to be asked.
16+type blockDecider struct {
17+ Client decide.Client
18+ Questions []decide.Question
19+ // Wait is the decider's own decision.timeout: a block's timeout when it
20+ // has none of its own.
21+ Wait time.Duration
22+}
23+
24+// timeout is the block's own timeout, else the decider's.
25+func (d blockDecider) timeout(own time.Duration) time.Duration {
26+ if own > 0 {
27+ return own
28+ }
29+ return d.Wait
30+}
31+
32+// readBlockDecider reads a block's decider file and resolves it like
33+// ResolveDecider (never AGENT_BASE_URL, which names the chat model's server);
34+// its calls go through decisionClient, named purpose in the trace. Errors
35+// read "<block>.decider: …".
36+//
37+// d, err := readBlockDecider("decisionTool", settings.Decider, "decision-tool")
38+func readBlockDecider(block, path, purpose string) (blockDecider, error) {
39+ cfg, err := config.ReadDecider(path)
40+ if err == nil && (cfg.Decision == nil || len(cfg.Decision.Questions) == 0) {
41+ err = fmt.Errorf("%s has no decision.questions to ask", path)
42+ }
43+ var b Backend
44+ if err == nil {
45+ b, err = ResolveDecider(cfg)
46+ }
47+ if err != nil {
48+ return blockDecider{}, fmt.Errorf("%s.decider: %w", block, err)
49+ }
50+ return blockDecider{Client: decisionClient(b, purpose), Questions: cfg.Decision.Questions, Wait: cfg.Decision.Wait()}, nil
51+}
52+
53+// compileMatcher compiles a block's matcher; "" (every tool) is nil.
54+func compileMatcher(block, matcher string) (*regexp.Regexp, error) {
55+ if matcher == "" {
56+ return nil, nil
57+ }
58+ re, err := regexp.Compile(matcher)
59+ if err != nil {
60+ return nil, fmt.Errorf("%s.matcher: %w", block, err)
61+ }
62+ return re, nil
63+}
modified internal/engine/decisioncontext.go +5 -16
@@ -48,25 +48,14 @@ func SetContextAsker(a *ContextAsker) { contextAsker = a }
4848 // a, err := engine.NewContextAsker(config.Cfg.DecisionContext)
4949 // engine.SetContextAsker(a)
5050 func NewContextAsker(settings config.DecisionContextConfig) (*ContextAsker, error) {
51- d, err := config.ReadDecider(settings.Decider)
51+ d, err := readBlockDecider("decisionContext", settings.Decider, "decision-context")
5252 if err != nil {
53- return nil, fmt.Errorf("decisionContext.decider: %w", err)
54- }
55- if d.Decision == nil || len(d.Decision.Questions) == 0 {
56- return nil, fmt.Errorf("decisionContext.decider: %s has no decision.questions to ask", settings.Decider)
57- }
58- b, err := ResolveDecider(d)
59- if err != nil {
60- return nil, fmt.Errorf("decisionContext.decider: %w", err)
61- }
62- timeout := settings.Timeout
63- if timeout <= 0 {
64- timeout = d.Decision.Wait()
53+ return nil, err
6554 }
6655 return &ContextAsker{
67- Client: decisionClient(b, "decision-context"),
68- Questions: d.Decision.Questions,
69- Timeout: timeout,
56+ Client: d.Client,
57+ Questions: d.Questions,
58+ Timeout: d.timeout(settings.Timeout),
7059 Options: decide.ContextOptions{MinConfidence: settings.MinConfidence, Answers: settings.Answers, Then: settings.Then},
7160 Display: settings.Display,
7261 }, nil
@@ -48,25 +48,14 @@ func SetContextAsker(a *ContextAsker) { contextAsker = a }
48 // a, err := engine.NewContextAsker(config.Cfg.DecisionContext)48 // a, err := engine.NewContextAsker(config.Cfg.DecisionContext)
49 // engine.SetContextAsker(a)49 // engine.SetContextAsker(a)
50 func NewContextAsker(settings config.DecisionContextConfig) (*ContextAsker, error) {50 func NewContextAsker(settings config.DecisionContextConfig) (*ContextAsker, error) {
51- d, err := config.ReadDecider(settings.Decider)51+ d, err := readBlockDecider("decisionContext", settings.Decider, "decision-context")
52 if err != nil {52 if err != nil {
53- return nil, fmt.Errorf("decisionContext.decider: %w", err)53+ return nil, err
54- }
55- if d.Decision == nil || len(d.Decision.Questions) == 0 {
56- return nil, fmt.Errorf("decisionContext.decider: %s has no decision.questions to ask", settings.Decider)
57- }
58- b, err := ResolveDecider(d)
59- if err != nil {
60- return nil, fmt.Errorf("decisionContext.decider: %w", err)
61- }
62- timeout := settings.Timeout
63- if timeout <= 0 {
64- timeout = d.Decision.Wait()
65 }54 }
66 return &ContextAsker{55 return &ContextAsker{
67- Client: decisionClient(b, "decision-context"),56+ Client: d.Client,
68- Questions: d.Decision.Questions,57+ Questions: d.Questions,
69- Timeout: timeout,58+ Timeout: d.timeout(settings.Timeout),
70 Options: decide.ContextOptions{MinConfidence: settings.MinConfidence, Answers: settings.Answers, Then: settings.Then},59 Options: decide.ContextOptions{MinConfidence: settings.MinConfidence, Answers: settings.Answers, Then: settings.Then},
71 Display: settings.Display,60 Display: settings.Display,
72 }, nil61 }, nil
modified internal/engine/decisionresult.go +41 -32
@@ -46,49 +46,58 @@ func SetResultJudge(j *ResultJudge) { resultJudge = j }
4646 // j, err := engine.NewResultJudge(config.Cfg.DecisionResult)
4747 // engine.SetResultJudge(j)
4848 func NewResultJudge(settings config.DecisionResultConfig) (*ResultJudge, error) {
49- d, err := config.ReadDecider(settings.Decider)
49+ d, err := readBlockDecider("decisionResult", settings.Decider, "decision-result")
5050 if err != nil {
51- return nil, fmt.Errorf("decisionResult.decider: %w", err)
51+ return nil, err
5252 }
53- if d.Decision == nil || len(d.Decision.Questions) == 0 {
54- return nil, fmt.Errorf("decisionResult.decider: %s has no decision.questions to ask", settings.Decider)
53+ matcher, err := compileMatcher("decisionResult", settings.Matcher)
54+ if err != nil {
55+ return nil, err
5556 }
56- b, err := ResolveDecider(d)
57+ pieces, err := pieceOptions(settings.Pieces)
5758 if err != nil {
58- return nil, fmt.Errorf("decisionResult.decider: %w", err)
59- }
60- j := &ResultJudge{
61- Client: decisionClient(b, "decision-result"),
62- Questions: d.Decision.Questions,
63- State: settings.State,
64- Chars: settings.OutputChars,
65- Timeout: settings.Timeout,
59+ return nil, err
60+ }
61+ return &ResultJudge{
62+ Client: d.Client,
63+ Questions: d.Questions,
64+ Matcher: matcher,
65+ State: nonEmptyOr(settings.State, decide.DefaultResultState),
66+ Chars: positiveOr(settings.OutputChars, decide.DefaultOutputChars),
67+ Pieces: pieces,
68+ Timeout: d.timeout(settings.Timeout),
6669 Rules: settings.Rules,
6770 Notice: settings.Notice,
6871 Display: settings.Display,
72+ }, nil
73+}
74+
75+// pieceOptions compiles decisionResult.pieces; nil (the whole output) stays nil.
76+func pieceOptions(p *config.DecisionPiecesConfig) (*decide.PieceOptions, error) {
77+ if p == nil {
78+ return nil, nil
6979 }
70- if j.State == "" {
71- j.State = decide.DefaultResultState
72- }
73- if j.Chars <= 0 {
74- j.Chars = decide.DefaultOutputChars
75- }
76- if j.Timeout <= 0 {
77- j.Timeout = d.Decision.Wait()
80+ keep, err := regexp.Compile(p.Keep)
81+ if err != nil {
82+ return nil, fmt.Errorf("decisionResult.pieces.keep: %w", err)
7883 }
79- if settings.Matcher != "" {
80- if j.Matcher, err = regexp.Compile(settings.Matcher); err != nil {
81- return nil, fmt.Errorf("decisionResult.matcher: %w", err)
82- }
84+ return &decide.PieceOptions{Keep: keep, Long: p.Long, Around: p.Around, Max: p.Max}, nil
85+}
86+
87+// nonEmptyOr is s, or def when s is empty.
88+func nonEmptyOr(s, def string) string {
89+ if s == "" {
90+ return def
8391 }
84- if p := settings.Pieces; p != nil {
85- keep, err := regexp.Compile(p.Keep)
86- if err != nil {
87- return nil, fmt.Errorf("decisionResult.pieces.keep: %w", err)
88- }
89- j.Pieces = &decide.PieceOptions{Keep: keep, Long: p.Long, Around: p.Around, Max: p.Max}
92+ return s
93+}
94+
95+// positiveOr is n, or def when n is not positive.
96+func positiveOr(n, def int) int {
97+ if n <= 0 {
98+ return def
9099 }
91- return j, nil
100+ return n
92101 }
93102
94103 // Matches tells whether the judge looks at the outputs of tool.
@@ -46,49 +46,58 @@ func SetResultJudge(j *ResultJudge) { resultJudge = j }
46 // j, err := engine.NewResultJudge(config.Cfg.DecisionResult)46 // j, err := engine.NewResultJudge(config.Cfg.DecisionResult)
47 // engine.SetResultJudge(j)47 // engine.SetResultJudge(j)
48 func NewResultJudge(settings config.DecisionResultConfig) (*ResultJudge, error) {48 func NewResultJudge(settings config.DecisionResultConfig) (*ResultJudge, error) {
49- d, err := config.ReadDecider(settings.Decider)49+ d, err := readBlockDecider("decisionResult", settings.Decider, "decision-result")
50 if err != nil {50 if err != nil {
51- return nil, fmt.Errorf("decisionResult.decider: %w", err)51+ return nil, err
52 }52 }
53- if d.Decision == nil || len(d.Decision.Questions) == 0 {53+ matcher, err := compileMatcher("decisionResult", settings.Matcher)
54- return nil, fmt.Errorf("decisionResult.decider: %s has no decision.questions to ask", settings.Decider)54+ if err != nil {
55+ return nil, err
55 }56 }
56- b, err := ResolveDecider(d)57+ pieces, err := pieceOptions(settings.Pieces)
57 if err != nil {58 if err != nil {
58- return nil, fmt.Errorf("decisionResult.decider: %w", err)59+ return nil, err
59- }60+ }
60- j := &ResultJudge{61+ return &ResultJudge{
61- Client: decisionClient(b, "decision-result"),62+ Client: d.Client,
62- Questions: d.Decision.Questions,63+ Questions: d.Questions,
63- State: settings.State,64+ Matcher: matcher,
64- Chars: settings.OutputChars,65+ State: nonEmptyOr(settings.State, decide.DefaultResultState),
65- Timeout: settings.Timeout,66+ Chars: positiveOr(settings.OutputChars, decide.DefaultOutputChars),
67+ Pieces: pieces,
68+ Timeout: d.timeout(settings.Timeout),
66 Rules: settings.Rules,69 Rules: settings.Rules,
67 Notice: settings.Notice,70 Notice: settings.Notice,
68 Display: settings.Display,71 Display: settings.Display,
72+ }, nil
73+}
74+
75+// pieceOptions compiles decisionResult.pieces; nil (the whole output) stays nil.
76+func pieceOptions(p *config.DecisionPiecesConfig) (*decide.PieceOptions, error) {
77+ if p == nil {
78+ return nil, nil
69 }79 }
70- if j.State == "" {80+ keep, err := regexp.Compile(p.Keep)
71- j.State = decide.DefaultResultState81+ if err != nil {
72- }82+ return nil, fmt.Errorf("decisionResult.pieces.keep: %w", err)
73- if j.Chars <= 0 {
74- j.Chars = decide.DefaultOutputChars
75- }
76- if j.Timeout <= 0 {
77- j.Timeout = d.Decision.Wait()
78 }83 }
79- if settings.Matcher != "" {84+ return &decide.PieceOptions{Keep: keep, Long: p.Long, Around: p.Around, Max: p.Max}, nil
80- if j.Matcher, err = regexp.Compile(settings.Matcher); err != nil {85+}
81- return nil, fmt.Errorf("decisionResult.matcher: %w", err)86+
82- }87+// nonEmptyOr is s, or def when s is empty.
88+func nonEmptyOr(s, def string) string {
89+ if s == "" {
90+ return def
83 }91 }
84- if p := settings.Pieces; p != nil {92+ return s
85- keep, err := regexp.Compile(p.Keep)93+}
86- if err != nil {94+
87- return nil, fmt.Errorf("decisionResult.pieces.keep: %w", err)95+// positiveOr is n, or def when n is not positive.
88- }96+func positiveOr(n, def int) int {
89- j.Pieces = &decide.PieceOptions{Keep: keep, Long: p.Long, Around: p.Around, Max: p.Max}97+ if n <= 0 {
98+ return def
90 }99 }
91- return j, nil100+ return n
92 }101 }
93 102
94 // Matches tells whether the judge looks at the outputs of tool.103 // Matches tells whether the judge looks at the outputs of tool.
modified internal/engine/decisiontool.go +11 -25
@@ -45,38 +45,24 @@ func SetToolJudge(j *ToolJudge) { toolJudge = j }
4545 // j, err := engine.NewToolJudge(config.Cfg.DecisionTool)
4646 // engine.SetToolJudge(j)
4747 func NewToolJudge(settings config.DecisionToolConfig) (*ToolJudge, error) {
48- d, err := config.ReadDecider(settings.Decider)
48+ d, err := readBlockDecider("decisionTool", settings.Decider, "decision-tool")
4949 if err != nil {
50- return nil, fmt.Errorf("decisionTool.decider: %w", err)
50+ return nil, err
5151 }
52- if d.Decision == nil || len(d.Decision.Questions) == 0 {
53- return nil, fmt.Errorf("decisionTool.decider: %s has no decision.questions to ask", settings.Decider)
54- }
55- b, err := ResolveDecider(d)
52+ matcher, err := compileMatcher("decisionTool", settings.Matcher)
5653 if err != nil {
57- return nil, fmt.Errorf("decisionTool.decider: %w", err)
54+ return nil, err
5855 }
59- j := &ToolJudge{
60- Client: decisionClient(b, "decision-tool"),
61- Questions: d.Decision.Questions,
62- State: settings.State,
63- Timeout: settings.Timeout,
56+ return &ToolJudge{
57+ Client: d.Client,
58+ Questions: d.Questions,
59+ Matcher: matcher,
60+ State: nonEmptyOr(settings.State, decide.DefaultToolState),
61+ Timeout: d.timeout(settings.Timeout),
6462 Rules: settings.Rules,
6563 Notice: settings.Notice,
6664 Display: settings.Display,
67- }
68- if j.State == "" {
69- j.State = decide.DefaultToolState
70- }
71- if j.Timeout <= 0 {
72- j.Timeout = d.Decision.Wait()
73- }
74- if settings.Matcher != "" {
75- if j.Matcher, err = regexp.Compile(settings.Matcher); err != nil {
76- return nil, fmt.Errorf("decisionTool.matcher: %w", err)
77- }
78- }
79- return j, nil
65+ }, nil
8066 }
8167
8268 // Matches tells whether the judge looks at calls of tool.
@@ -45,38 +45,24 @@ func SetToolJudge(j *ToolJudge) { toolJudge = j }
45 // j, err := engine.NewToolJudge(config.Cfg.DecisionTool)45 // j, err := engine.NewToolJudge(config.Cfg.DecisionTool)
46 // engine.SetToolJudge(j)46 // engine.SetToolJudge(j)
47 func NewToolJudge(settings config.DecisionToolConfig) (*ToolJudge, error) {47 func NewToolJudge(settings config.DecisionToolConfig) (*ToolJudge, error) {
48- d, err := config.ReadDecider(settings.Decider)48+ d, err := readBlockDecider("decisionTool", settings.Decider, "decision-tool")
49 if err != nil {49 if err != nil {
50- return nil, fmt.Errorf("decisionTool.decider: %w", err)50+ return nil, err
51 }51 }
52- if d.Decision == nil || len(d.Decision.Questions) == 0 {52+ matcher, err := compileMatcher("decisionTool", settings.Matcher)
53- return nil, fmt.Errorf("decisionTool.decider: %s has no decision.questions to ask", settings.Decider)
54- }
55- b, err := ResolveDecider(d)
56 if err != nil {53 if err != nil {
57- return nil, fmt.Errorf("decisionTool.decider: %w", err)54+ return nil, err
58 }55 }
59- j := &ToolJudge{56+ return &ToolJudge{
60- Client: decisionClient(b, "decision-tool"),57+ Client: d.Client,
61- Questions: d.Decision.Questions,58+ Questions: d.Questions,
62- State: settings.State,59+ Matcher: matcher,
63- Timeout: settings.Timeout,60+ State: nonEmptyOr(settings.State, decide.DefaultToolState),
61+ Timeout: d.timeout(settings.Timeout),
64 Rules: settings.Rules,62 Rules: settings.Rules,
65 Notice: settings.Notice,63 Notice: settings.Notice,
66 Display: settings.Display,64 Display: settings.Display,
67- }65+ }, nil
68- if j.State == "" {
69- j.State = decide.DefaultToolState
70- }
71- if j.Timeout <= 0 {
72- j.Timeout = d.Decision.Wait()
73- }
74- if settings.Matcher != "" {
75- if j.Matcher, err = regexp.Compile(settings.Matcher); err != nil {
76- return nil, fmt.Errorf("decisionTool.matcher: %w", err)
77- }
78- }
79- return j, nil
80 }66 }
81 67
82 // Matches tells whether the judge looks at calls of tool.68 // Matches tells whether the judge looks at calls of tool.
modified internal/engine/llamastart.go +11 -10
@@ -44,11 +44,8 @@ func RazorbillStartAddress(cfg config.Config) (host string, port int, ok bool) {
4444 // loopback one, AGENT_BASE_URL is not set, and no other address of the
4545 // provider (its alternates, its fallback) answers.
4646 func startAddress(cfg config.Config) (host string, port int, ok bool) {
47- if os.Getenv("AGENT_BASE_URL") != "" {
48- return "", 0, false
49- }
5047 p, _ := registry[cfg.Provider].(*openaiCompat)
51- if p == nil {
48+ if os.Getenv("AGENT_BASE_URL") != "" || p == nil {
5249 return "", 0, false
5350 }
5451 base := cfg.BaseURL
@@ -56,12 +53,16 @@ func startAddress(cfg config.Config) (host string, port int, ok bool) {
5653 base = p.baseURL
5754 }
5855 host, port, ok = loopbackHostPort(base)
59- if !ok {
60- return "", 0, false
61- }
62- if reachable(base) {
56+ if ok && (reachable(base) || !anotherAddressAnswers(cfg, p, base)) {
6357 return host, port, true
6458 }
59+ return "", 0, false
60+}
61+
62+// anotherAddressAnswers tells whether one of the provider's other addresses
63+// answers — its alternates (when base is its default), the fallback — where
64+// the user's own server would be.
65+func anotherAddressAnswers(cfg config.Config, p *openaiCompat, base string) bool {
6566 var others []string
6667 if base == p.baseURL {
6768 others = append(others, p.alternates...)
@@ -75,10 +76,10 @@ func startAddress(cfg config.Config) (host string, port int, ok bool) {
7576 }
7677 for _, o := range others {
7778 if reachable(o) {
78- return "", 0, false
79+ return true
7980 }
8081 }
81- return host, port, true
82+ return false
8283 }
8384
8485 // loopbackHostPort is the host and port of base when it is a loopback
@@ -44,11 +44,8 @@ func RazorbillStartAddress(cfg config.Config) (host string, port int, ok bool) {
44 // loopback one, AGENT_BASE_URL is not set, and no other address of the44 // loopback one, AGENT_BASE_URL is not set, and no other address of the
45 // provider (its alternates, its fallback) answers.45 // provider (its alternates, its fallback) answers.
46 func startAddress(cfg config.Config) (host string, port int, ok bool) {46 func startAddress(cfg config.Config) (host string, port int, ok bool) {
47- if os.Getenv("AGENT_BASE_URL") != "" {
48- return "", 0, false
49- }
50 p, _ := registry[cfg.Provider].(*openaiCompat)47 p, _ := registry[cfg.Provider].(*openaiCompat)
51- if p == nil {48+ if os.Getenv("AGENT_BASE_URL") != "" || p == nil {
52 return "", 0, false49 return "", 0, false
53 }50 }
54 base := cfg.BaseURL51 base := cfg.BaseURL
@@ -56,12 +53,16 @@ func startAddress(cfg config.Config) (host string, port int, ok bool) {
56 base = p.baseURL53 base = p.baseURL
57 }54 }
58 host, port, ok = loopbackHostPort(base)55 host, port, ok = loopbackHostPort(base)
59- if !ok {56+ if ok && (reachable(base) || !anotherAddressAnswers(cfg, p, base)) {
60- return "", 0, false
61- }
62- if reachable(base) {
63 return host, port, true57 return host, port, true
64 }58 }
59+ return "", 0, false
60+}
61+
62+// anotherAddressAnswers tells whether one of the provider's other addresses
63+// answers — its alternates (when base is its default), the fallback — where
64+// the user's own server would be.
65+func anotherAddressAnswers(cfg config.Config, p *openaiCompat, base string) bool {
65 var others []string66 var others []string
66 if base == p.baseURL {67 if base == p.baseURL {
67 others = append(others, p.alternates...)68 others = append(others, p.alternates...)
@@ -75,10 +76,10 @@ func startAddress(cfg config.Config) (host string, port int, ok bool) {
75 }76 }
76 for _, o := range others {77 for _, o := range others {
77 if reachable(o) {78 if reachable(o) {
78- return "", 0, false79+ return true
79 }80 }
80 }81 }
81- return host, port, true82+ return false
82 }83 }
83 84
84 // loopbackHostPort is the host and port of base when it is a loopback85 // loopbackHostPort is the host and port of base when it is a loopback
modified internal/llamastart/llamastart.go +41 -15
@@ -191,18 +191,25 @@ type routerModel struct {
191191 // loaded — downloaded first when it is not in the cache.
192192 func ensureModel(ctx context.Context, model string, so serverstart.Options, base string) error {
193193 m, found, err := findModel(ctx, base, model)
194- switch {
195- case err != nil:
194+ if err != nil || m.Status.Value == "loaded" {
196195 return err
197- case !found:
196+ }
197+ if !found {
198198 return fmt.Errorf("the llama-server mm started does not list %s (it was started for other models; quit the other mm sessions so the next start lists this one)", model)
199- case m.Status.Value == "loaded":
200- return nil
201199 }
202200 done := so.WaitFor("Loading " + model + " (downloaded first when missing)…")
203201 defer done()
204202 ctx, cancel := context.WithTimeout(ctx, so.Timeout)
205203 defer cancel()
204+ if err := requestLoad(ctx, base, model); err != nil {
205+ return err
206+ }
207+ return waitLoaded(ctx, model, so, base)
208+}
209+
210+// requestLoad asks the router to load model; it answers at once, the load
211+// goes on (waitLoaded follows it).
212+func requestLoad(ctx context.Context, base, model string) error {
206213 body := fmt.Sprintf(`{"model":%q}`, model)
207214 req, err := http.NewRequestWithContext(ctx, http.MethodPost, base+"/models/load", strings.NewReader(body))
208215 if err != nil {
@@ -217,27 +224,46 @@ func ensureModel(ctx context.Context, model string, so serverstart.Options, base
217224 if resp.StatusCode != http.StatusOK {
218225 return fmt.Errorf("llama-server refused to load %s (%d)", model, resp.StatusCode)
219226 }
227+ return nil
228+}
229+
230+// waitLoaded polls the router until model is loaded, has failed, or ctx
231+// (bounded by the start timeout) is over.
232+func waitLoaded(ctx context.Context, model string, so serverstart.Options, base string) error {
233+ log := serverstart.LogPath(so)
234+ timedOut := fmt.Errorf("%s was not loaded within %s — see %s", model, so.Timeout, log)
220235 for {
221236 m, _, err := findModel(ctx, base, model)
222- switch {
223- case err != nil && ctx.Err() != nil:
224- return fmt.Errorf("%s was not loaded within %s — see %s", model, so.Timeout, serverstart.LogPath(so))
225- case err != nil:
237+ if over, err := loadOutcome(ctx, m, err, timedOut, log); over {
238+ if err == nil {
239+ so.Say("%s loaded", model)
240+ }
226241 return err
227- case m.Status.Value == "loaded":
228- so.Say("%s loaded", model)
229- return nil
230- case m.Status.Failed:
231- return fmt.Errorf("llama-server could not load %s (exit code %d) — see %s", model, m.Status.ExitCode, serverstart.LogPath(so))
232242 }
233243 select {
234244 case <-ctx.Done():
235- return fmt.Errorf("%s was not loaded within %s — see %s", model, so.Timeout, serverstart.LogPath(so))
245+ return timedOut
236246 case <-time.After(serverstart.Poll):
237247 }
238248 }
239249 }
240250
251+// loadOutcome says whether a poll of the router ends the wait, and how:
252+// nil for a loaded model, the error otherwise (log: the server's log file).
253+func loadOutcome(ctx context.Context, m routerModel, err, timedOut error, log string) (bool, error) {
254+ switch {
255+ case err != nil && ctx.Err() != nil:
256+ return true, timedOut
257+ case err != nil:
258+ return true, err
259+ case m.Status.Value == "loaded":
260+ return true, nil
261+ case m.Status.Failed:
262+ return true, fmt.Errorf("llama-server could not load %s (exit code %d) — see %s", m.ID, m.Status.ExitCode, log)
263+ }
264+ return false, nil
265+}
266+
241267 func findModel(ctx context.Context, base, model string) (routerModel, bool, error) {
242268 req, err := http.NewRequestWithContext(ctx, http.MethodGet, base+"/models", nil)
243269 if err != nil {
@@ -191,18 +191,25 @@ type routerModel struct {
191 // loaded — downloaded first when it is not in the cache.191 // loaded — downloaded first when it is not in the cache.
192 func ensureModel(ctx context.Context, model string, so serverstart.Options, base string) error {192 func ensureModel(ctx context.Context, model string, so serverstart.Options, base string) error {
193 m, found, err := findModel(ctx, base, model)193 m, found, err := findModel(ctx, base, model)
194- switch {194+ if err != nil || m.Status.Value == "loaded" {
195- case err != nil:
196 return err195 return err
197- case !found:196+ }
197+ if !found {
198 return fmt.Errorf("the llama-server mm started does not list %s (it was started for other models; quit the other mm sessions so the next start lists this one)", model)198 return fmt.Errorf("the llama-server mm started does not list %s (it was started for other models; quit the other mm sessions so the next start lists this one)", model)
199- case m.Status.Value == "loaded":
200- return nil
201 }199 }
202 done := so.WaitFor("Loading " + model + " (downloaded first when missing)…")200 done := so.WaitFor("Loading " + model + " (downloaded first when missing)…")
203 defer done()201 defer done()
204 ctx, cancel := context.WithTimeout(ctx, so.Timeout)202 ctx, cancel := context.WithTimeout(ctx, so.Timeout)
205 defer cancel()203 defer cancel()
204+ if err := requestLoad(ctx, base, model); err != nil {
205+ return err
206+ }
207+ return waitLoaded(ctx, model, so, base)
208+}
209+
210+// requestLoad asks the router to load model; it answers at once, the load
211+// goes on (waitLoaded follows it).
212+func requestLoad(ctx context.Context, base, model string) error {
206 body := fmt.Sprintf(`{"model":%q}`, model)213 body := fmt.Sprintf(`{"model":%q}`, model)
207 req, err := http.NewRequestWithContext(ctx, http.MethodPost, base+"/models/load", strings.NewReader(body))214 req, err := http.NewRequestWithContext(ctx, http.MethodPost, base+"/models/load", strings.NewReader(body))
208 if err != nil {215 if err != nil {
@@ -217,27 +224,46 @@ func ensureModel(ctx context.Context, model string, so serverstart.Options, base
217 if resp.StatusCode != http.StatusOK {224 if resp.StatusCode != http.StatusOK {
218 return fmt.Errorf("llama-server refused to load %s (%d)", model, resp.StatusCode)225 return fmt.Errorf("llama-server refused to load %s (%d)", model, resp.StatusCode)
219 }226 }
227+ return nil
228+}
229+
230+// waitLoaded polls the router until model is loaded, has failed, or ctx
231+// (bounded by the start timeout) is over.
232+func waitLoaded(ctx context.Context, model string, so serverstart.Options, base string) error {
233+ log := serverstart.LogPath(so)
234+ timedOut := fmt.Errorf("%s was not loaded within %s — see %s", model, so.Timeout, log)
220 for {235 for {
221 m, _, err := findModel(ctx, base, model)236 m, _, err := findModel(ctx, base, model)
222- switch {237+ if over, err := loadOutcome(ctx, m, err, timedOut, log); over {
223- case err != nil && ctx.Err() != nil:238+ if err == nil {
224- return fmt.Errorf("%s was not loaded within %s — see %s", model, so.Timeout, serverstart.LogPath(so))239+ so.Say("%s loaded", model)
225- case err != nil:240+ }
226 return err241 return err
227- case m.Status.Value == "loaded":
228- so.Say("%s loaded", model)
229- return nil
230- case m.Status.Failed:
231- return fmt.Errorf("llama-server could not load %s (exit code %d) — see %s", model, m.Status.ExitCode, serverstart.LogPath(so))
232 }242 }
233 select {243 select {
234 case <-ctx.Done():244 case <-ctx.Done():
235- return fmt.Errorf("%s was not loaded within %s — see %s", model, so.Timeout, serverstart.LogPath(so))245+ return timedOut
236 case <-time.After(serverstart.Poll):246 case <-time.After(serverstart.Poll):
237 }247 }
238 }248 }
239 }249 }
240 250
251+// loadOutcome says whether a poll of the router ends the wait, and how:
252+// nil for a loaded model, the error otherwise (log: the server's log file).
253+func loadOutcome(ctx context.Context, m routerModel, err, timedOut error, log string) (bool, error) {
254+ switch {
255+ case err != nil && ctx.Err() != nil:
256+ return true, timedOut
257+ case err != nil:
258+ return true, err
259+ case m.Status.Value == "loaded":
260+ return true, nil
261+ case m.Status.Failed:
262+ return true, fmt.Errorf("llama-server could not load %s (exit code %d) — see %s", m.ID, m.Status.ExitCode, log)
263+ }
264+ return false, nil
265+}
266+
241 func findModel(ctx context.Context, base, model string) (routerModel, bool, error) {267 func findModel(ctx context.Context, base, model string) (routerModel, bool, error) {
242 req, err := http.NewRequestWithContext(ctx, http.MethodGet, base+"/models", nil)268 req, err := http.NewRequestWithContext(ctx, http.MethodGet, base+"/models", nil)
243 if err != nil {269 if err != nil {