bots-garden/mini-mepublic Fork
⑂ 5aa79d9
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: main.go and the root wiring files without smells

- main(): runSubcommand (a table) → parseCommandLine (cliOptions,
  valueFlags) → answered (--version, --about) → loadConfig → runAsk or
  runAgent (declareCommands, startEngine, agentSession: assemble,
  runPrompt, runFrontEnd)
- cli.go, tools_wiring.go and banner_wiring.go split out of main.go;
  agentsMdBanner and runA2A in small steps
- the old and new binaries answer identically on the command line; -p,
  --ask and A2A checked live

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
agent committed 2026-11-28T11:55:17+01:00 Browse files
5aa79d9 parent: fe04469
modified .tickets/issues/0283-quality-code-smells-of-the-core-zone-by-zone.yaml +11 -2
@@ -6,7 +6,7 @@ author:
66 name: k33g
77 email: ph.charriere@gmail.com
88 createdAt: 2026-11-28T10:19:47.000Z
9-updatedAt: 2026-11-28T10:51:44.000Z
9+updatedAt: 2026-11-28T10:55:16.000Z
1010 labels:
1111 - kind::chore
1212 milestone: v2.2.0
@@ -37,12 +37,14 @@ tasks:
3737 closedAt: 2026-11-28T10:51:44.000Z
3838 - id: 3
3939 title: "main.go and the root wiring files"
40- state: open
40+ state: closed
4141 priority: medium
4242 author:
4343 name: k33g
4444 email: ph.charriere@gmail.com
4545 createdAt: 2026-11-28T10:19:47.000Z
46+ updatedAt: 2026-11-28T10:55:16.000Z
47+ closedAt: 2026-11-28T10:55:16.000Z
4648 - id: 4
4749 title: "internal/agentinit"
4850 state: open
@@ -90,3 +92,10 @@ comments:
9092 createdAt: 2026-11-28T10:51:44.000Z
9193 body: |
9294 internal/config: 18 → 0 smells (total 182 → 164). The validations use checks.go (problem, firstError, and firstFailing — lazy, for checks that must not run once an earlier one failed, e.g. Command[0] on an empty command); Load → applyFile + resolvePaths; validation code moved to validate.go and toolsvalidate.go, parameter coercion to toolparams.go; hooks' slot a map. Error messages unchanged. Checked: go test ./... green, and the 152 agent files of demos/ and testing/ load to exactly the same result as before the change (old/new comparison, no difference).
95+ - id: 3
96+ author:
97+ name: k33g
98+ email: ph.charriere@gmail.com
99+ createdAt: 2026-11-28T10:55:16.000Z
100+ body: |
101+ main.go and the root files: 7 → 0 smells. main() = runSubcommand (a table) → parseCommandLine (cliOptions, valueFlags) → answered → loadConfig → runAsk / runAgent; runAgent → declareCommands, startEngine, an agentSession (assemble, runPrompt, runFrontEnd); runWindow takes the session; cli.go, tools_wiring.go, banner_wiring.go split out; agentsMdBanner and runA2A in small steps. Checked: go test ./... green; the old and new binaries answer identically to -h, help, --version, --about, usage errors, no agent file, a config error, a decider's -p, init -h, a2a-send -h (only the binary name and +dirty differ); live: -p, --ask, A2A served and answered through mm a2a-send.
@@ -6,7 +6,7 @@ author:
6 name: k33g6 name: k33g
7 email: ph.charriere@gmail.com7 email: ph.charriere@gmail.com
8 createdAt: 2026-11-28T10:19:47.000Z8 createdAt: 2026-11-28T10:19:47.000Z
9-updatedAt: 2026-11-28T10:51:44.000Z9+updatedAt: 2026-11-28T10:55:16.000Z
10 labels:10 labels:
11 - kind::chore11 - kind::chore
12 milestone: v2.2.012 milestone: v2.2.0
@@ -37,12 +37,14 @@ tasks:
37 closedAt: 2026-11-28T10:51:44.000Z37 closedAt: 2026-11-28T10:51:44.000Z
38 - id: 338 - id: 3
39 title: "main.go and the root wiring files"39 title: "main.go and the root wiring files"
40- state: open40+ state: closed
41 priority: medium41 priority: medium
42 author:42 author:
43 name: k33g43 name: k33g
44 email: ph.charriere@gmail.com44 email: ph.charriere@gmail.com
45 createdAt: 2026-11-28T10:19:47.000Z45 createdAt: 2026-11-28T10:19:47.000Z
46+ updatedAt: 2026-11-28T10:55:16.000Z
47+ closedAt: 2026-11-28T10:55:16.000Z
46 - id: 448 - id: 4
47 title: "internal/agentinit"49 title: "internal/agentinit"
48 state: open50 state: open
@@ -90,3 +92,10 @@ comments:
90 createdAt: 2026-11-28T10:51:44.000Z92 createdAt: 2026-11-28T10:51:44.000Z
91 body: |93 body: |
92 internal/config: 18 → 0 smells (total 182 → 164). The validations use checks.go (problem, firstError, and firstFailing — lazy, for checks that must not run once an earlier one failed, e.g. Command[0] on an empty command); Load → applyFile + resolvePaths; validation code moved to validate.go and toolsvalidate.go, parameter coercion to toolparams.go; hooks' slot a map. Error messages unchanged. Checked: go test ./... green, and the 152 agent files of demos/ and testing/ load to exactly the same result as before the change (old/new comparison, no difference).94 internal/config: 18 → 0 smells (total 182 → 164). The validations use checks.go (problem, firstError, and firstFailing — lazy, for checks that must not run once an earlier one failed, e.g. Command[0] on an empty command); Load → applyFile + resolvePaths; validation code moved to validate.go and toolsvalidate.go, parameter coercion to toolparams.go; hooks' slot a map. Error messages unchanged. Checked: go test ./... green, and the 152 agent files of demos/ and testing/ load to exactly the same result as before the change (old/new comparison, no difference).
95+ - id: 3
96+ author:
97+ name: k33g
98+ email: ph.charriere@gmail.com
99+ createdAt: 2026-11-28T10:55:16.000Z
100+ body: |
101+ main.go and the root files: 7 → 0 smells. main() = runSubcommand (a table) → parseCommandLine (cliOptions, valueFlags) → answered → loadConfig → runAsk / runAgent; runAgent → declareCommands, startEngine, an agentSession (assemble, runPrompt, runFrontEnd); runWindow takes the session; cli.go, tools_wiring.go, banner_wiring.go split out; agentsMdBanner and runA2A in small steps. Checked: go test ./... green; the old and new binaries answer identically to -h, help, --version, --about, usage errors, no agent file, a config error, a decider's -p, init -h, a2a-send -h (only the binary name and +dirty differ); live: -p, --ask, A2A served and answered through mm a2a-send.
modified a2a_wiring.go +42 -18
@@ -39,6 +39,27 @@ import (
3939 // consent: with yolo false, a tool that needs it is refused, as under -p.
4040 func runA2A(ctx context.Context, e *engine.Engine, system string, tools []ai.ToolRef, portFlag int) error {
4141 cfg := config.Cfg.A2A
42+ token, err := a2aToken(cfg)
43+ if err != nil {
44+ return err
45+ }
46+ addr := a2aAddress(cfg, portFlag)
47+ url := "http://" + addr
48+ srv := &http.Server{Addr: addr, Handler: a2a.NewServer(a2aCard(url), a2aHandler(e, system, tools), token), ReadHeaderTimeout: 10 * time.Second}
49+ ln, err := net.Listen("tcp", addr)
50+ if err != nil {
51+ return fmt.Errorf("a2a: cannot listen on %s: %w (another agent on this port? set a2a.port or --a2a-port)", addr, err)
52+ }
53+ fmt.Fprintf(os.Stderr, "🤝 A2A agent %q on %s — card: %s%s\n", a2aName(), url, url, a2a.CardPath)
54+ if token != "" {
55+ fmt.Fprintf(os.Stderr, " callers must send Authorization: Bearer $%s\n", cfg.TokenEnv)
56+ }
57+ return serveA2A(ctx, srv, ln)
58+}
59+
60+// a2aAddress is host:port — a2a.host, else the default; --a2a-port, else
61+// a2a.port, else the default.
62+func a2aAddress(cfg config.A2AConfig, portFlag int) string {
4263 host, port := cfg.Host, cfg.Port
4364 if host == "" {
4465 host = config.DefaultA2AHost
@@ -49,19 +70,29 @@ func runA2A(ctx context.Context, e *engine.Engine, system string, tools []ai.Too
4970 if port == 0 {
5071 port = config.DefaultA2APort
5172 }
52- token := ""
53- if cfg.TokenEnv != "" {
54- if token = os.Getenv(cfg.TokenEnv); token == "" {
55- return fmt.Errorf("a2a.tokenEnv: %s is not set — export the token callers must send, or remove the key", cfg.TokenEnv)
56- }
73+ return net.JoinHostPort(host, strconv.Itoa(port))
74+}
75+
76+// a2aToken is the token callers must send: the value of a2a.tokenEnv, ""
77+// without one; a named variable that is not set is an error.
78+func a2aToken(cfg config.A2AConfig) (string, error) {
79+ if cfg.TokenEnv == "" {
80+ return "", nil
5781 }
58- addr := net.JoinHostPort(host, strconv.Itoa(port))
59- url := "http://" + addr
82+ token := os.Getenv(cfg.TokenEnv)
83+ if token == "" {
84+ return "", fmt.Errorf("a2a.tokenEnv: %s is not set — export the token callers must send, or remove the key", cfg.TokenEnv)
85+ }
86+ return token, nil
87+}
6088
89+// a2aHandler answers one A2A message: one conversation per contextID, kept
90+// in memory, compacted like a session's, the turn run by the engine.
91+func a2aHandler(e *engine.Engine, system string, tools []ai.ToolRef) func(context.Context, string, string) (string, error) {
6192 cwd, _ := os.Getwd()
6293 var mu sync.Mutex
6394 conversations := map[string][]*ai.Message{}
64- handle := func(ctx context.Context, contextID, text string) (string, error) {
95+ return func(ctx context.Context, contextID, text string) (string, error) {
6596 mu.Lock()
6697 msgs, ok := conversations[contextID]
6798 mu.Unlock()
@@ -85,17 +116,10 @@ func runA2A(ctx context.Context, e *engine.Engine, system string, tools []ai.Too
85116 mu.Unlock()
86117 return resp.Text(), nil
87118 }
119+}
88120
89- srv := &http.Server{Addr: addr, Handler: a2a.NewServer(a2aCard(url), handle, token), ReadHeaderTimeout: 10 * time.Second}
90- ln, err := net.Listen("tcp", addr)
91- if err != nil {
92- return fmt.Errorf("a2a: cannot listen on %s: %w (another agent on this port? set a2a.port or --a2a-port)", addr, err)
93- }
94- fmt.Fprintf(os.Stderr, "🤝 A2A agent %q on %s — card: %s%s\n", a2aName(), url, url, a2a.CardPath)
95- if token != "" {
96- fmt.Fprintf(os.Stderr, " callers must send Authorization: Bearer $%s\n", cfg.TokenEnv)
97- }
98-
121+// serveA2A serves until Ctrl-C, SIGTERM or SIGHUP, then shuts down.
122+func serveA2A(ctx context.Context, srv *http.Server, ln net.Listener) error {
99123 ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
100124 defer stop()
101125 go func() {
@@ -39,6 +39,27 @@ import (
39 // consent: with yolo false, a tool that needs it is refused, as under -p.39 // consent: with yolo false, a tool that needs it is refused, as under -p.
40 func runA2A(ctx context.Context, e *engine.Engine, system string, tools []ai.ToolRef, portFlag int) error {40 func runA2A(ctx context.Context, e *engine.Engine, system string, tools []ai.ToolRef, portFlag int) error {
41 cfg := config.Cfg.A2A41 cfg := config.Cfg.A2A
42+ token, err := a2aToken(cfg)
43+ if err != nil {
44+ return err
45+ }
46+ addr := a2aAddress(cfg, portFlag)
47+ url := "http://" + addr
48+ srv := &http.Server{Addr: addr, Handler: a2a.NewServer(a2aCard(url), a2aHandler(e, system, tools), token), ReadHeaderTimeout: 10 * time.Second}
49+ ln, err := net.Listen("tcp", addr)
50+ if err != nil {
51+ return fmt.Errorf("a2a: cannot listen on %s: %w (another agent on this port? set a2a.port or --a2a-port)", addr, err)
52+ }
53+ fmt.Fprintf(os.Stderr, "🤝 A2A agent %q on %s — card: %s%s\n", a2aName(), url, url, a2a.CardPath)
54+ if token != "" {
55+ fmt.Fprintf(os.Stderr, " callers must send Authorization: Bearer $%s\n", cfg.TokenEnv)
56+ }
57+ return serveA2A(ctx, srv, ln)
58+}
59+
60+// a2aAddress is host:port — a2a.host, else the default; --a2a-port, else
61+// a2a.port, else the default.
62+func a2aAddress(cfg config.A2AConfig, portFlag int) string {
42 host, port := cfg.Host, cfg.Port63 host, port := cfg.Host, cfg.Port
43 if host == "" {64 if host == "" {
44 host = config.DefaultA2AHost65 host = config.DefaultA2AHost
@@ -49,19 +70,29 @@ func runA2A(ctx context.Context, e *engine.Engine, system string, tools []ai.Too
49 if port == 0 {70 if port == 0 {
50 port = config.DefaultA2APort71 port = config.DefaultA2APort
51 }72 }
52- token := ""73+ return net.JoinHostPort(host, strconv.Itoa(port))
53- if cfg.TokenEnv != "" {74+}
54- if token = os.Getenv(cfg.TokenEnv); token == "" {75+
55- return fmt.Errorf("a2a.tokenEnv: %s is not set — export the token callers must send, or remove the key", cfg.TokenEnv)76+// a2aToken is the token callers must send: the value of a2a.tokenEnv, ""
56- }77+// without one; a named variable that is not set is an error.
78+func a2aToken(cfg config.A2AConfig) (string, error) {
79+ if cfg.TokenEnv == "" {
80+ return "", nil
57 }81 }
58- addr := net.JoinHostPort(host, strconv.Itoa(port))82+ token := os.Getenv(cfg.TokenEnv)
59- url := "http://" + addr83+ if token == "" {
84+ return "", fmt.Errorf("a2a.tokenEnv: %s is not set — export the token callers must send, or remove the key", cfg.TokenEnv)
85+ }
86+ return token, nil
87+}
60 88
89+// a2aHandler answers one A2A message: one conversation per contextID, kept
90+// in memory, compacted like a session's, the turn run by the engine.
91+func a2aHandler(e *engine.Engine, system string, tools []ai.ToolRef) func(context.Context, string, string) (string, error) {
61 cwd, _ := os.Getwd()92 cwd, _ := os.Getwd()
62 var mu sync.Mutex93 var mu sync.Mutex
63 conversations := map[string][]*ai.Message{}94 conversations := map[string][]*ai.Message{}
64- handle := func(ctx context.Context, contextID, text string) (string, error) {95+ return func(ctx context.Context, contextID, text string) (string, error) {
65 mu.Lock()96 mu.Lock()
66 msgs, ok := conversations[contextID]97 msgs, ok := conversations[contextID]
67 mu.Unlock()98 mu.Unlock()
@@ -85,17 +116,10 @@ func runA2A(ctx context.Context, e *engine.Engine, system string, tools []ai.Too
85 mu.Unlock()116 mu.Unlock()
86 return resp.Text(), nil117 return resp.Text(), nil
87 }118 }
119+}
88 120
89- srv := &http.Server{Addr: addr, Handler: a2a.NewServer(a2aCard(url), handle, token), ReadHeaderTimeout: 10 * time.Second}121+// serveA2A serves until Ctrl-C, SIGTERM or SIGHUP, then shuts down.
90- ln, err := net.Listen("tcp", addr)122+func serveA2A(ctx context.Context, srv *http.Server, ln net.Listener) error {
91- if err != nil {
92- return fmt.Errorf("a2a: cannot listen on %s: %w (another agent on this port? set a2a.port or --a2a-port)", addr, err)
93- }
94- fmt.Fprintf(os.Stderr, "🤝 A2A agent %q on %s — card: %s%s\n", a2aName(), url, url, a2a.CardPath)
95- if token != "" {
96- fmt.Fprintf(os.Stderr, " callers must send Authorization: Bearer $%s\n", cfg.TokenEnv)
97- }
98-
99 ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)123 ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
100 defer stop()124 defer stop()
101 go func() {125 go func() {
modified agentsmd_banner.go +16 -11
@@ -22,29 +22,34 @@ const largeAgentsMdShare = 20
2222 // // " | agents.md: /home/me/project/AGENTS.md (~350 tokens)", nil
2323 func agentsMdBanner(acpMode bool, window int) (string, []string) {
2424 settings := config.Cfg.AgentsMd
25- if !settings.Enabled {
25+ switch {
26+ case !settings.Enabled:
2627 return "", nil
27- }
28- // A decider never sends the file, whatever the session's directory.
29- if acpMode && config.Cfg.Decision == nil {
28+ case acpMode && config.Cfg.Decision == nil:
29+ // A decider never sends the file, whatever the session's directory.
3030 return " | agents.md: <session cwd>/" + settings.Path, nil
3131 }
32- f := agentsmd.Load("")
32+ return agentsMdColumn(agentsmd.Load(""), settings.MaxChars, window)
33+}
34+
35+// agentsMdColumn is the banner's column for the file as it was found, and
36+// the warnings it deserves.
37+func agentsMdColumn(f agentsmd.File, maxChars, window int) (column string, warnings []string) {
3338 switch f.Status {
3439 case agentsmd.Loaded:
35- return fmt.Sprintf(" | agents.md: %s (~%d tokens)", f.Path, f.Tokens()), largeAgentsMdWarning(f, window)
40+ column, warnings = fmt.Sprintf(" | agents.md: %s (~%d tokens)", f.Path, f.Tokens()), largeAgentsMdWarning(f, window)
3641 case agentsmd.Ignored:
3742 // Neutral, not a warning: a structured agent and a decider skip it
3843 // on purpose.
39- return " | agents.md: ignored (" + ignoredBecause() + ")", nil
44+ column = " | agents.md: ignored (" + ignoredBecause() + ")"
4045 case agentsmd.Skipped:
41- return " | agents.md: skipped (too long)", []string{fmt.Sprintf(
46+ column, warnings = " | agents.md: skipped (too long)", []string{fmt.Sprintf(
4247 "%s skipped: %d characters > agentsMd.maxChars %d — it is not read at all (shorten it, or raise the limit)",
43- f.Path, f.Chars(), settings.MaxChars)}
48+ f.Path, f.Chars(), maxChars)}
4449 case agentsmd.Unreadable:
45- return "", []string{fmt.Sprintf("%s cannot be read: %v — no project instructions", f.Path, f.Err)}
50+ warnings = []string{fmt.Sprintf("%s cannot be read: %v — no project instructions", f.Path, f.Err)}
4651 }
47- return "", nil
52+ return column, warnings
4853 }
4954
5055 // largeAgentsMdWarning says when the file takes a large share of a known
@@ -22,29 +22,34 @@ const largeAgentsMdShare = 20
22 // // " | agents.md: /home/me/project/AGENTS.md (~350 tokens)", nil22 // // " | agents.md: /home/me/project/AGENTS.md (~350 tokens)", nil
23 func agentsMdBanner(acpMode bool, window int) (string, []string) {23 func agentsMdBanner(acpMode bool, window int) (string, []string) {
24 settings := config.Cfg.AgentsMd24 settings := config.Cfg.AgentsMd
25- if !settings.Enabled {25+ switch {
26+ case !settings.Enabled:
26 return "", nil27 return "", nil
27- }28+ case acpMode && config.Cfg.Decision == nil:
28- // A decider never sends the file, whatever the session's directory.29+ // A decider never sends the file, whatever the session's directory.
29- if acpMode && config.Cfg.Decision == nil {
30 return " | agents.md: <session cwd>/" + settings.Path, nil30 return " | agents.md: <session cwd>/" + settings.Path, nil
31 }31 }
32- f := agentsmd.Load("")32+ return agentsMdColumn(agentsmd.Load(""), settings.MaxChars, window)
33+}
34+
35+// agentsMdColumn is the banner's column for the file as it was found, and
36+// the warnings it deserves.
37+func agentsMdColumn(f agentsmd.File, maxChars, window int) (column string, warnings []string) {
33 switch f.Status {38 switch f.Status {
34 case agentsmd.Loaded:39 case agentsmd.Loaded:
35- return fmt.Sprintf(" | agents.md: %s (~%d tokens)", f.Path, f.Tokens()), largeAgentsMdWarning(f, window)40+ column, warnings = fmt.Sprintf(" | agents.md: %s (~%d tokens)", f.Path, f.Tokens()), largeAgentsMdWarning(f, window)
36 case agentsmd.Ignored:41 case agentsmd.Ignored:
37 // Neutral, not a warning: a structured agent and a decider skip it42 // Neutral, not a warning: a structured agent and a decider skip it
38 // on purpose.43 // on purpose.
39- return " | agents.md: ignored (" + ignoredBecause() + ")", nil44+ column = " | agents.md: ignored (" + ignoredBecause() + ")"
40 case agentsmd.Skipped:45 case agentsmd.Skipped:
41- return " | agents.md: skipped (too long)", []string{fmt.Sprintf(46+ column, warnings = " | agents.md: skipped (too long)", []string{fmt.Sprintf(
42 "%s skipped: %d characters > agentsMd.maxChars %d — it is not read at all (shorten it, or raise the limit)",47 "%s skipped: %d characters > agentsMd.maxChars %d — it is not read at all (shorten it, or raise the limit)",
43- f.Path, f.Chars(), settings.MaxChars)}48+ f.Path, f.Chars(), maxChars)}
44 case agentsmd.Unreadable:49 case agentsmd.Unreadable:
45- return "", []string{fmt.Sprintf("%s cannot be read: %v — no project instructions", f.Path, f.Err)}50+ warnings = []string{fmt.Sprintf("%s cannot be read: %v — no project instructions", f.Path, f.Err)}
46 }51 }
47- return "", nil52+ return column, warnings
48 }53 }
49 54
50 // largeAgentsMdWarning says when the file takes a large share of a known55 // largeAgentsMdWarning says when the file takes a large share of a known
added banner_wiring.go +191 -0
new file mode 100644
@@ -0,0 +1,191 @@
1+package main
2+
3+import (
4+ "bytes"
5+ "context"
6+ "fmt"
7+ "mm/internal/command"
8+ "mm/internal/config"
9+ "mm/internal/engine"
10+ "mm/internal/skills"
11+ "mm/internal/spinner"
12+ "mm/internal/tui"
13+ "mm/internal/ui"
14+ "mm/internal/version"
15+ "os"
16+ "path/filepath"
17+ "strings"
18+)
19+
20+// printBanner probes the server and prints the warnings and the one-line
21+// banner. The probe runs before the banner so its warnings sit right under
22+// the prompt they explain; it never stops the agent — on a demo machine the
23+// server is often started AFTER the agent.
24+func printBanner(ctx context.Context, e *engine.Engine, path string, set toolSet, acpMode bool) {
25+ toolNames, skillCount := set.names, set.skillCount
26+ info := e.Probe(ctx)
27+ info.Warnings = append(info.Warnings, set.warnings...)
28+ ctxCol := "unknown"
29+ if info.ContextWindow > 0 {
30+ ctxCol = fmt.Sprintf("%d (%s)", info.ContextWindow, info.ContextSource)
31+ }
32+ // Dimmed on a terminal, plain in a pipe: the agent's output is meant to be
33+ // consumed by another program as much as it is meant to be read.
34+ dim, off := "", ""
35+ if spinner.Styled() {
36+ dim, off = "\033[2m", "\033[0m"
37+ }
38+ // The compression's own warning belongs with the provider's: it is the
39+ // same kind of advice, and it depends on what the probe just learned.
40+ if c := config.Cfg.Context; c.Enabled && e.ContextWindow == 0 && c.MaxMessages == 0 {
41+ info.Warnings = append(info.Warnings,
42+ "context compression is on, but the context window is unknown and context.maxMessages is 0 — it will never trigger (set contextWindow, or maxMessages)")
43+ }
44+ // "skills: 0" alone sends people hunting; the resolved path says at once
45+ // whether mm looked in the wrong place or found the right one empty.
46+ // An agent with a structuredOutput has neither tools nor skills on
47+ // purpose (config.StructuredOutputConflict): nothing to warn about.
48+ // A decider has neither on purpose either (assembleTools, ticket 141).
49+ structuredAgent := config.Cfg.OutputSchema != nil || config.Cfg.Decision != nil
50+ agentsMdCol, agentsMdWarnings := agentsMdBanner(acpMode, info.ContextWindow)
51+ info.Warnings = append(info.Warnings, agentsMdWarnings...)
52+ if skillCount == 0 && !structuredAgent {
53+ info.Warnings = append(info.Warnings,
54+ fmt.Sprintf("no skills found in %s (expected <name>.md or <name>/SKILL.md there)", config.Cfg.SkillsDir))
55+ }
56+ // A skill with no description reaches the catalogue as a bare name, which
57+ // is the worst entry there is: the model has nothing to match a request
58+ // against, and the failure is silent — the count is not zero, so the
59+ // warning above never fires.
60+ if bare := skills.Undescribed(set.skills); len(bare) > 0 {
61+ info.Warnings = append(info.Warnings,
62+ fmt.Sprintf("%d skill(s) with no description (%s) — the model sees only the name and will pick blindly",
63+ len(bare), strings.Join(bare, ", ")))
64+ }
65+ // A skill whose name a slash command owns is unreachable from an editor's
66+ // command menu, and nothing else would say so.
67+ if shadowed := skills.Shadowed(set.skills, commandNames()); len(shadowed) > 0 {
68+ info.Warnings = append(info.Warnings,
69+ fmt.Sprintf("skill(s) named like a slash command (%s) — reachable as $%s in a question, but not from an editor's / menu",
70+ strings.Join(shadowed, ", "), shadowed[0]))
71+ }
72+ // Only the first maxKeywords of a list reach the catalogue, so the order
73+ // of a keyword line decides what the model gets to match against. An
74+ // author cannot see that from their own file.
75+ if cut := skills.Truncated(set.skills); len(cut) > 0 {
76+ info.Warnings = append(info.Warnings,
77+ fmt.Sprintf("keywords truncated for %s — only the first ones reach the model, so put the most distinctive first",
78+ strings.Join(cut, ", ")))
79+ }
80+ // Two skills under one name: the catalogue shows it twice and the second
81+ // is unreachable, since a lookup always returns the first.
82+ if dup := skills.Duplicates(set.skills); len(dup) > 0 {
83+ info.Warnings = append(info.Warnings,
84+ fmt.Sprintf("two skills share a name (%s) — only the first is reachable", strings.Join(dup, ", ")))
85+ }
86+ // No tool at all is a legal set-up — a chat with the model — but rarely the
87+ // intended one; say so where the "tools:" column would otherwise be empty.
88+ if len(toolNames) == 0 && !structuredAgent {
89+ info.Warnings = append(info.Warnings,
90+ "no tool is declared (bashTool and editTools are both off, and there are no skills): the model can only answer, not act")
91+ }
92+ info.Warnings = append(info.Warnings, config.Deprecations()...)
93+ for _, w := range info.Warnings {
94+ say("%s[warning: %s]%s", dim, w, off)
95+ }
96+ toolCol := strings.Join(toolNames, ", ")
97+ switch {
98+ case config.Cfg.Decision != nil:
99+ toolCol = decisionToolColumn()
100+ case structuredAgent:
101+ toolCol = "none (structured output: JSON answers)"
102+ case toolCol == "":
103+ toolCol = "none"
104+ }
105+ // The version leads the line: it is the first thing anyone is asked for
106+ // when something behaves oddly, and the banner is the one output every
107+ // front end shows — the window keeps it as the conversation's first line.
108+ say("%smm %s | config: %s | provider: %s | model: %s | ctx: %s | tools: %s | %s | %s%s%s%s%s%s",
109+ dim, version.Short(), path, e.Backend.Provider, config.Cfg.Model, ctxCol, toolCol, skillsColumn(skillCount), yoloColumn(), agentsMdCol, traceColumn(acpMode), hooksColumn(), routing, off)
110+}
111+
112+// hooksColumn says in the banner which hooks run, per event: a command that
113+// can rewrite prompts or deny tool calls must not act unseen.
114+func hooksColumn() string {
115+ if summary := config.Cfg.Hooks.Summary(); summary != "" {
116+ return " | hooks: " + summary
117+ }
118+ return ""
119+}
120+
121+// yoloColumn says in the banner whether the tools run unasked — the one
122+// setting nobody should discover by surprise, in either direction.
123+func yoloColumn() string {
124+ if config.Cfg.Yolo {
125+ return "yolo: on"
126+ }
127+ return "yolo: off (tools ask)"
128+}
129+
130+// traceColumn says in the banner that every request and response is being
131+// written to disk — prompts included — and where. In ACP mode a relative
132+// dir is in each session's cwd, which no session has given yet.
133+func traceColumn(acpMode bool) string {
134+ if !config.Cfg.Trace.Enabled {
135+ return ""
136+ }
137+ dir := config.Cfg.Trace.Dir
138+ if filepath.IsAbs(dir) {
139+ return " | trace: " + dir
140+ }
141+ if acpMode {
142+ return " | trace: <session cwd>/" + dir
143+ }
144+ if abs, err := filepath.Abs(dir); err == nil {
145+ dir = abs
146+ }
147+ return " | trace: " + dir
148+}
149+
150+// commandNames is the slash commands' names, for the shadowing check.
151+func commandNames() []string {
152+ var out []string
153+ for _, c := range command.All() {
154+ out = append(out, c.Name)
155+ }
156+ return out
157+}
158+
159+// windowMode decides whether the window front end runs, and where the banner
160+// goes. The window owns the screen: the spinner must not draw on it, and
161+// the banner is kept in the returned buffer to be shown INSIDE the window as
162+// its first line. Without a terminal (`mm -tui | tee`) the line mode runs
163+// instead, banner on stdout as usual, after one line saying so.
164+func windowMode(wanted bool) (bool, *bytes.Buffer) {
165+ banner := &bytes.Buffer{}
166+ if !wanted {
167+ return false, banner
168+ }
169+ if !tui.Terminal() {
170+ say("[tui: stdin or stdout is not a terminal — running the line mode]")
171+ return false, banner
172+ }
173+ ui.Out = banner
174+ spinner.Disable()
175+ return true, banner
176+}
177+
178+// skillsColumn is the banner's skills count, and where they come from when
179+// that is not under the current directory (the ticket 231 fallback): a user
180+// who sees skills they did not put in this project should know why.
181+func skillsColumn(count int) string {
182+ col := fmt.Sprintf("skills: %d", count)
183+ cwd, err := os.Getwd()
184+ if count == 0 || err != nil {
185+ return col
186+ }
187+ if rel, err := filepath.Rel(cwd, config.Cfg.SkillsDir); err == nil && !strings.HasPrefix(rel, "..") {
188+ return col
189+ }
190+ return col + " (from " + config.Cfg.SkillsDir + ")"
191+}
new file mode 100644
@@ -0,0 +1,191 @@
1+package main
2+
3+import (
4+ "bytes"
5+ "context"
6+ "fmt"
7+ "mm/internal/command"
8+ "mm/internal/config"
9+ "mm/internal/engine"
10+ "mm/internal/skills"
11+ "mm/internal/spinner"
12+ "mm/internal/tui"
13+ "mm/internal/ui"
14+ "mm/internal/version"
15+ "os"
16+ "path/filepath"
17+ "strings"
18+)
19+
20+// printBanner probes the server and prints the warnings and the one-line
21+// banner. The probe runs before the banner so its warnings sit right under
22+// the prompt they explain; it never stops the agent — on a demo machine the
23+// server is often started AFTER the agent.
24+func printBanner(ctx context.Context, e *engine.Engine, path string, set toolSet, acpMode bool) {
25+ toolNames, skillCount := set.names, set.skillCount
26+ info := e.Probe(ctx)
27+ info.Warnings = append(info.Warnings, set.warnings...)
28+ ctxCol := "unknown"
29+ if info.ContextWindow > 0 {
30+ ctxCol = fmt.Sprintf("%d (%s)", info.ContextWindow, info.ContextSource)
31+ }
32+ // Dimmed on a terminal, plain in a pipe: the agent's output is meant to be
33+ // consumed by another program as much as it is meant to be read.
34+ dim, off := "", ""
35+ if spinner.Styled() {
36+ dim, off = "\033[2m", "\033[0m"
37+ }
38+ // The compression's own warning belongs with the provider's: it is the
39+ // same kind of advice, and it depends on what the probe just learned.
40+ if c := config.Cfg.Context; c.Enabled && e.ContextWindow == 0 && c.MaxMessages == 0 {
41+ info.Warnings = append(info.Warnings,
42+ "context compression is on, but the context window is unknown and context.maxMessages is 0 — it will never trigger (set contextWindow, or maxMessages)")
43+ }
44+ // "skills: 0" alone sends people hunting; the resolved path says at once
45+ // whether mm looked in the wrong place or found the right one empty.
46+ // An agent with a structuredOutput has neither tools nor skills on
47+ // purpose (config.StructuredOutputConflict): nothing to warn about.
48+ // A decider has neither on purpose either (assembleTools, ticket 141).
49+ structuredAgent := config.Cfg.OutputSchema != nil || config.Cfg.Decision != nil
50+ agentsMdCol, agentsMdWarnings := agentsMdBanner(acpMode, info.ContextWindow)
51+ info.Warnings = append(info.Warnings, agentsMdWarnings...)
52+ if skillCount == 0 && !structuredAgent {
53+ info.Warnings = append(info.Warnings,
54+ fmt.Sprintf("no skills found in %s (expected <name>.md or <name>/SKILL.md there)", config.Cfg.SkillsDir))
55+ }
56+ // A skill with no description reaches the catalogue as a bare name, which
57+ // is the worst entry there is: the model has nothing to match a request
58+ // against, and the failure is silent — the count is not zero, so the
59+ // warning above never fires.
60+ if bare := skills.Undescribed(set.skills); len(bare) > 0 {
61+ info.Warnings = append(info.Warnings,
62+ fmt.Sprintf("%d skill(s) with no description (%s) — the model sees only the name and will pick blindly",
63+ len(bare), strings.Join(bare, ", ")))
64+ }
65+ // A skill whose name a slash command owns is unreachable from an editor's
66+ // command menu, and nothing else would say so.
67+ if shadowed := skills.Shadowed(set.skills, commandNames()); len(shadowed) > 0 {
68+ info.Warnings = append(info.Warnings,
69+ fmt.Sprintf("skill(s) named like a slash command (%s) — reachable as $%s in a question, but not from an editor's / menu",
70+ strings.Join(shadowed, ", "), shadowed[0]))
71+ }
72+ // Only the first maxKeywords of a list reach the catalogue, so the order
73+ // of a keyword line decides what the model gets to match against. An
74+ // author cannot see that from their own file.
75+ if cut := skills.Truncated(set.skills); len(cut) > 0 {
76+ info.Warnings = append(info.Warnings,
77+ fmt.Sprintf("keywords truncated for %s — only the first ones reach the model, so put the most distinctive first",
78+ strings.Join(cut, ", ")))
79+ }
80+ // Two skills under one name: the catalogue shows it twice and the second
81+ // is unreachable, since a lookup always returns the first.
82+ if dup := skills.Duplicates(set.skills); len(dup) > 0 {
83+ info.Warnings = append(info.Warnings,
84+ fmt.Sprintf("two skills share a name (%s) — only the first is reachable", strings.Join(dup, ", ")))
85+ }
86+ // No tool at all is a legal set-up — a chat with the model — but rarely the
87+ // intended one; say so where the "tools:" column would otherwise be empty.
88+ if len(toolNames) == 0 && !structuredAgent {
89+ info.Warnings = append(info.Warnings,
90+ "no tool is declared (bashTool and editTools are both off, and there are no skills): the model can only answer, not act")
91+ }
92+ info.Warnings = append(info.Warnings, config.Deprecations()...)
93+ for _, w := range info.Warnings {
94+ say("%s[warning: %s]%s", dim, w, off)
95+ }
96+ toolCol := strings.Join(toolNames, ", ")
97+ switch {
98+ case config.Cfg.Decision != nil:
99+ toolCol = decisionToolColumn()
100+ case structuredAgent:
101+ toolCol = "none (structured output: JSON answers)"
102+ case toolCol == "":
103+ toolCol = "none"
104+ }
105+ // The version leads the line: it is the first thing anyone is asked for
106+ // when something behaves oddly, and the banner is the one output every
107+ // front end shows — the window keeps it as the conversation's first line.
108+ say("%smm %s | config: %s | provider: %s | model: %s | ctx: %s | tools: %s | %s | %s%s%s%s%s%s",
109+ dim, version.Short(), path, e.Backend.Provider, config.Cfg.Model, ctxCol, toolCol, skillsColumn(skillCount), yoloColumn(), agentsMdCol, traceColumn(acpMode), hooksColumn(), routing, off)
110+}
111+
112+// hooksColumn says in the banner which hooks run, per event: a command that
113+// can rewrite prompts or deny tool calls must not act unseen.
114+func hooksColumn() string {
115+ if summary := config.Cfg.Hooks.Summary(); summary != "" {
116+ return " | hooks: " + summary
117+ }
118+ return ""
119+}
120+
121+// yoloColumn says in the banner whether the tools run unasked — the one
122+// setting nobody should discover by surprise, in either direction.
123+func yoloColumn() string {
124+ if config.Cfg.Yolo {
125+ return "yolo: on"
126+ }
127+ return "yolo: off (tools ask)"
128+}
129+
130+// traceColumn says in the banner that every request and response is being
131+// written to disk — prompts included — and where. In ACP mode a relative
132+// dir is in each session's cwd, which no session has given yet.
133+func traceColumn(acpMode bool) string {
134+ if !config.Cfg.Trace.Enabled {
135+ return ""
136+ }
137+ dir := config.Cfg.Trace.Dir
138+ if filepath.IsAbs(dir) {
139+ return " | trace: " + dir
140+ }
141+ if acpMode {
142+ return " | trace: <session cwd>/" + dir
143+ }
144+ if abs, err := filepath.Abs(dir); err == nil {
145+ dir = abs
146+ }
147+ return " | trace: " + dir
148+}
149+
150+// commandNames is the slash commands' names, for the shadowing check.
151+func commandNames() []string {
152+ var out []string
153+ for _, c := range command.All() {
154+ out = append(out, c.Name)
155+ }
156+ return out
157+}
158+
159+// windowMode decides whether the window front end runs, and where the banner
160+// goes. The window owns the screen: the spinner must not draw on it, and
161+// the banner is kept in the returned buffer to be shown INSIDE the window as
162+// its first line. Without a terminal (`mm -tui | tee`) the line mode runs
163+// instead, banner on stdout as usual, after one line saying so.
164+func windowMode(wanted bool) (bool, *bytes.Buffer) {
165+ banner := &bytes.Buffer{}
166+ if !wanted {
167+ return false, banner
168+ }
169+ if !tui.Terminal() {
170+ say("[tui: stdin or stdout is not a terminal — running the line mode]")
171+ return false, banner
172+ }
173+ ui.Out = banner
174+ spinner.Disable()
175+ return true, banner
176+}
177+
178+// skillsColumn is the banner's skills count, and where they come from when
179+// that is not under the current directory (the ticket 231 fallback): a user
180+// who sees skills they did not put in this project should know why.
181+func skillsColumn(count int) string {
182+ col := fmt.Sprintf("skills: %d", count)
183+ cwd, err := os.Getwd()
184+ if count == 0 || err != nil {
185+ return col
186+ }
187+ if rel, err := filepath.Rel(cwd, config.Cfg.SkillsDir); err == nil && !strings.HasPrefix(rel, "..") {
188+ return col
189+ }
190+ return col + " (from " + config.Cfg.SkillsDir + ")"
191+}
added cli.go +270 -0
new file mode 100644
@@ -0,0 +1,270 @@
1+package main
2+
3+import (
4+ "flag"
5+ "fmt"
6+ "os"
7+
8+ "mm/internal/acpcreate"
9+ "mm/internal/agentinit"
10+ "mm/internal/config"
11+ "mm/internal/dockerinit"
12+ "mm/internal/sbxinit"
13+ "mm/internal/skillcreate"
14+ "mm/internal/spinner"
15+ "mm/internal/tui"
16+ "mm/internal/ui"
17+ "mm/internal/version"
18+)
19+
20+// The command line: the subcommands answered before any configuration, the
21+// flags, and the configuration they name.
22+
23+// subcommand is a word, first on the command line, that runs its own main.
24+type subcommand struct {
25+ is func(arg string) bool
26+ run func(args []string) int
27+}
28+
29+// subcommands are answered before anything reads a configuration — there is
30+// none yet, or the subcommand reads it itself:
31+//
32+// - `mm init` (ticket 97): the agent.yaml wizard, with its own flags;
33+// - `mm acp-create` (ticket 210): the same wizard served over ACP, for an
34+// editor; stdout is the protocol's, so its help and errors go to stderr;
35+// - `mm dockerinit` (ticket 189) and `mm sbxinit` (ticket 191): files for
36+// a container, a Docker Sandbox;
37+// - `mm a2a-send` (ticket 243): one message to an A2A agent, from a script;
38+// - `mm skillcreate` (ticket 206): a wizard that writes a new skill where
39+// the agent's config reads its skills.
40+var subcommands = []subcommand{
41+ {isInit, func(args []string) int {
42+ return agentinit.Main(args, os.Stdin, os.Stdout, agentinit.Options{Window: tui.RunInit, Terminal: tui.Terminal})
43+ }},
44+ {acpcreate.Is, func(args []string) int { return acpcreate.Main(args, os.Stdin, os.Stdout, os.Stderr) }},
45+ {isDockerInit, func(args []string) int { return dockerinit.Main(args, os.Stdin, os.Stdout) }},
46+ {isSbxInit, func(args []string) int { return sbxinit.Main(args, os.Stdin, os.Stdout) }},
47+ {isA2ASend, func(args []string) int { return a2aSendMain(args, os.Stdin, os.Stdout, os.Stderr) }},
48+ {isSkillCreate, func(args []string) int {
49+ return skillcreate.Main(args, os.Stdin, os.Stdout, skillcreate.Options{Window: tui.RunSkillCreate, Terminal: tui.Terminal})
50+ }},
51+}
52+
53+// runSubcommand runs the subcommand args[1] names, if any, and returns its
54+// exit code; ok is false when args[1] is no subcommand.
55+func runSubcommand(args []string) (code int, ok bool) {
56+ if len(args) < 2 {
57+ return 0, false
58+ }
59+ for _, s := range subcommands {
60+ if s.is(args[1]) {
61+ return s.run(args[2:]), true
62+ }
63+ }
64+ return 0, false
65+}
66+
67+// cliOptions is what the command line asks for.
68+type cliOptions struct {
69+ configPath string
70+ configExplicit bool // -config was given
71+ args []string
72+ a2a, acp, tui bool
73+ a2aPort int
74+ prompt string
75+ version, about bool
76+ askName string
77+ askContext bool // --ask-with-context
78+}
79+
80+// parseCommandLine reads the flags. The config file has three ways in, from
81+// the most local to the most ambient:
82+//
83+// go run . -config ./fast.yaml (the flag)
84+// go run . ./fast.yaml (a lone argument, handy in a demo)
85+// AGENT_CONFIG=./fast.yaml go run .
86+//
87+// The flag package gives "-h" for free; a second argument is a typo, and
88+// loadConfig says so rather than ignoring it.
89+func parseCommandLine() cliOptions {
90+ var valued valueFlags
91+ os.Args = valued.extract(os.Args)
92+
93+ configPath := flag.String("config", "", "path to the YAML config file (default: $AGENT_CONFIG, then ./agent.yaml, then ./.mm/agent.yaml)")
94+ a2aMode := flag.Bool("a2a", false, "serve this agent over the Agent2Agent protocol (A2A, JSON-RPC over HTTP) on a2a.host:a2a.port, 127.0.0.1:9100 by default (same as: mm a2a)")
95+ a2aPort := flag.Int("a2a-port", 0, "with -a2a: the port to listen on, instead of a2a.port")
96+ flag.Bool("a2a-send", false, "send one message to an A2A agent and print its answer (same as mm a2a-send; mm a2a-send -h for its flags)")
97+ acpMode := flag.Bool("acp", false, "serve the Agent Client Protocol on stdio (for Zed, JetBrains, Neovim…) instead of the terminal REPL (same as: mm acp)")
98+ tuiMode := flag.Bool("tui", false, "open the single-window mode (conversation above, input box below); falls back to the line mode when stdout is not a terminal (same as: mm tui)")
99+ promptMode := flag.String("prompt", "", "run a single prompt and exit")
100+ flag.StringVar(promptMode, "p", "", "shorthand for --prompt")
101+ showVersion := flag.Bool("version", false, "print the version and exit")
102+ showAbout := flag.Bool("about", false, "print what mm is, and exit")
103+ // Listed for -h only: the subcommands are answered before flag.Parse.
104+ flag.Bool("init", false, "write a new agent.yaml with a wizard (same as `mm init`; `mm init -h` for its flags)")
105+ flag.Bool("acp-create", false, "serve mm init's wizard over the Agent Client Protocol, to create an agent.yaml from an editor (same as mm acp-create; mm acp-create -h for its flags)")
106+ flag.Bool("dockerinit", false, "write a Dockerfile and a compose.yaml to run mm in a container (same as mm dockerinit; mm dockerinit -h for its flags)")
107+ flag.Bool("skillcreate", false, "write a new skill with a wizard, where the agent reads its skills (same as mm skillcreate; mm skillcreate -h for its flags)")
108+ flag.Bool("sbxinit", false, "write a sbxenv.yaml to run mm in a Docker Sandbox (same as mm sbxinit; mm sbxinit -h for its flags)")
109+ askAgent := flag.String("ask", "", "ask the agent `name` (a key of mmConfigs) the -p prompt, or stdin; print only its answer on stdout, and exit")
110+ askWithContext := flag.String("ask-with-context", "", "same as --ask, with the conversation read from stdin (question with -p, or after a \"---\" line)")
111+ flag.Parse()
112+
113+ cli := cliOptions{
114+ configPath: *configPath, args: flag.Args(),
115+ a2a: *a2aMode, a2aPort: *a2aPort, acp: *acpMode, tui: *tuiMode,
116+ prompt: firstSet(valued.prompt, *promptMode), version: *showVersion, about: *showAbout,
117+ askName: firstSet(valued.ask, *askAgent),
118+ }
119+ if ctxName := firstSet(valued.askContext, *askWithContext); ctxName != "" {
120+ cli.askName, cli.askContext = ctxName, true
121+ }
122+ flag.Visit(func(f *flag.Flag) {
123+ if f.Name == "config" {
124+ cli.configExplicit = true
125+ }
126+ })
127+ return cli
128+}
129+
130+// valueFlags are the flags whose value may follow the config file:
131+// `mm agent.yaml --prompt "hello"` like `mm --prompt "hello" agent.yaml`, and
132+// `mm agent.yaml --ask lucy -p "…"` — flag.Parse stops at the first
133+// positional argument, so they are taken out before it.
134+type valueFlags struct {
135+ prompt, ask, askContext string
136+}
137+
138+// extract takes the value flags out of args and returns the rest.
139+func (v *valueFlags) extract(args []string) []string {
140+ rest := []string{args[0]}
141+ for i := 1; i < len(args); i++ {
142+ target := v.target(args[i])
143+ if target == nil {
144+ rest = append(rest, args[i])
145+ continue
146+ }
147+ if i+1 < len(args) {
148+ *target = args[i+1]
149+ i++ // skip the value
150+ }
151+ }
152+ return rest
153+}
154+
155+// target is where a value flag's value goes; nil for any other argument.
156+func (v *valueFlags) target(arg string) *string {
157+ switch arg {
158+ case "--prompt", "-prompt", "-p":
159+ return &v.prompt
160+ case "--ask", "-ask":
161+ return &v.ask
162+ case "--ask-with-context", "-ask-with-context":
163+ return &v.askContext
164+ }
165+ return nil
166+}
167+
168+// firstSet is the first non-empty value.
169+func firstSet(values ...string) string {
170+ for _, v := range values {
171+ if v != "" {
172+ return v
173+ }
174+ }
175+ return ""
176+}
177+
178+// answered prints what --version and --about ask for, and reports whether
179+// it did. Answered before anything can go wrong: asking which mm this is
180+// must work without a config file, without a model server, and in a
181+// directory mm knows nothing about. Straight to stdout, not ui.Out — this is
182+// the answer to a question, not part of a session's output.
183+func (cli cliOptions) answered() bool {
184+ switch {
185+ case cli.version:
186+ fmt.Println(version.Long())
187+ case cli.about:
188+ fmt.Println(version.About())
189+ default:
190+ return false
191+ }
192+ return true
193+}
194+
195+// loadConfig checks the arguments, sends everything human to stderr when
196+// stdout is a protocol or an answer, loads the agent file and returns its
197+// path. A usage error, a config error or no agent file ends mm.
198+func (cli *cliOptions) loadConfig() string {
199+ cli.checkArgs()
200+ cli.redirectOutput()
201+ path, err := config.Load(cli.configPath)
202+ if err != nil {
203+ fail("[config error: %v ]", err)
204+ os.Exit(1)
205+ }
206+ // No agent file found: stop rather than run a built-in model on a
207+ // built-in server the user never chose (ticket 220). Every mode that
208+ // reaches this point talks to a model; the commands that write the files
209+ // and --version / --about were answered before.
210+ if path == "" {
211+ fail("%s", noAgentFile())
212+ os.Exit(1)
213+ }
214+ // Where a relative skillsDir points depends on who started mm. From a
215+ // terminal, it is the directory mm was started from — an installed mm
216+ // (/usr/local/bin) run inside a project loads THAT project's skills. The
217+ // editor launches mm with ITS working directory, so in ACP mode with a
218+ // config file the anchor is that file — the one path the user actually
219+ // named (env AGENT_CONFIG in the editor's settings). Either way the path
220+ // is made absolute here, so the banner can say exactly where it looked.
221+ config.Cfg.SkillsDir = resolveSkillsDir(config.Cfg.SkillsDir, path, cli.acp)
222+ exportSelf(path)
223+ return path
224+}
225+
226+// checkArgs takes the config file from a lone argument, and refuses more.
227+func (cli *cliOptions) checkArgs() {
228+ if cli.configPath == "" && len(cli.args) > 0 {
229+ cli.configPath = cli.args[0]
230+ }
231+ switch {
232+ case cli.configExplicit && len(cli.args) > 0:
233+ fail("[usage: --config already specified, got %d extra arguments]", len(cli.args))
234+ os.Exit(1)
235+ case len(cli.args) > 1:
236+ fail("[usage: at most one config file, got %d arguments]", len(cli.args))
237+ os.Exit(1)
238+ }
239+}
240+
241+// redirectOutput sends everything human to stderr when stdout is not the
242+// user's. --ask: stdout carries the answer and nothing else; with no config
243+// named, the config of the mm whose bash tool runs this command (MM_CONFIG,
244+// exported by exportSelf) is the one whose mmConfigs a skill means. ACP:
245+// stdout belongs to JSON-RPC — the spec forbids anything else on it; the
246+// banner, warnings and errors go through ui.Out, so ONE move sends them to
247+// stderr, where the editor's agent logs pick them up. The spinner is
248+// silenced outright: it cannot tell "a terminal" from "a terminal used as a
249+// protocol pipe".
250+func (cli *cliOptions) redirectOutput() {
251+ if cli.askName != "" {
252+ ui.Out = os.Stderr
253+ spinner.Disable()
254+ if cli.configPath == "" {
255+ cli.configPath = os.Getenv(configEnv)
256+ }
257+ }
258+ if cli.acp {
259+ ui.Out = os.Stderr
260+ spinner.Disable()
261+ }
262+}
263+
264+// isA2ASend reports whether the first argument is `mm a2a-send`.
265+func isA2ASend(arg string) bool {
266+ return arg == "a2a-send" || arg == "--a2a-send" || arg == "-a2a-send"
267+}
268+
269+// modeWords are the first arguments that name a mode, as their flag.
270+var modeWords = []string{"tui", "acp", "a2a", "help"}
new file mode 100644
@@ -0,0 +1,270 @@
1+package main
2+
3+import (
4+ "flag"
5+ "fmt"
6+ "os"
7+
8+ "mm/internal/acpcreate"
9+ "mm/internal/agentinit"
10+ "mm/internal/config"
11+ "mm/internal/dockerinit"
12+ "mm/internal/sbxinit"
13+ "mm/internal/skillcreate"
14+ "mm/internal/spinner"
15+ "mm/internal/tui"
16+ "mm/internal/ui"
17+ "mm/internal/version"
18+)
19+
20+// The command line: the subcommands answered before any configuration, the
21+// flags, and the configuration they name.
22+
23+// subcommand is a word, first on the command line, that runs its own main.
24+type subcommand struct {
25+ is func(arg string) bool
26+ run func(args []string) int
27+}
28+
29+// subcommands are answered before anything reads a configuration — there is
30+// none yet, or the subcommand reads it itself:
31+//
32+// - `mm init` (ticket 97): the agent.yaml wizard, with its own flags;
33+// - `mm acp-create` (ticket 210): the same wizard served over ACP, for an
34+// editor; stdout is the protocol's, so its help and errors go to stderr;
35+// - `mm dockerinit` (ticket 189) and `mm sbxinit` (ticket 191): files for
36+// a container, a Docker Sandbox;
37+// - `mm a2a-send` (ticket 243): one message to an A2A agent, from a script;
38+// - `mm skillcreate` (ticket 206): a wizard that writes a new skill where
39+// the agent's config reads its skills.
40+var subcommands = []subcommand{
41+ {isInit, func(args []string) int {
42+ return agentinit.Main(args, os.Stdin, os.Stdout, agentinit.Options{Window: tui.RunInit, Terminal: tui.Terminal})
43+ }},
44+ {acpcreate.Is, func(args []string) int { return acpcreate.Main(args, os.Stdin, os.Stdout, os.Stderr) }},
45+ {isDockerInit, func(args []string) int { return dockerinit.Main(args, os.Stdin, os.Stdout) }},
46+ {isSbxInit, func(args []string) int { return sbxinit.Main(args, os.Stdin, os.Stdout) }},
47+ {isA2ASend, func(args []string) int { return a2aSendMain(args, os.Stdin, os.Stdout, os.Stderr) }},
48+ {isSkillCreate, func(args []string) int {
49+ return skillcreate.Main(args, os.Stdin, os.Stdout, skillcreate.Options{Window: tui.RunSkillCreate, Terminal: tui.Terminal})
50+ }},
51+}
52+
53+// runSubcommand runs the subcommand args[1] names, if any, and returns its
54+// exit code; ok is false when args[1] is no subcommand.
55+func runSubcommand(args []string) (code int, ok bool) {
56+ if len(args) < 2 {
57+ return 0, false
58+ }
59+ for _, s := range subcommands {
60+ if s.is(args[1]) {
61+ return s.run(args[2:]), true
62+ }
63+ }
64+ return 0, false
65+}
66+
67+// cliOptions is what the command line asks for.
68+type cliOptions struct {
69+ configPath string
70+ configExplicit bool // -config was given
71+ args []string
72+ a2a, acp, tui bool
73+ a2aPort int
74+ prompt string
75+ version, about bool
76+ askName string
77+ askContext bool // --ask-with-context
78+}
79+
80+// parseCommandLine reads the flags. The config file has three ways in, from
81+// the most local to the most ambient:
82+//
83+// go run . -config ./fast.yaml (the flag)
84+// go run . ./fast.yaml (a lone argument, handy in a demo)
85+// AGENT_CONFIG=./fast.yaml go run .
86+//
87+// The flag package gives "-h" for free; a second argument is a typo, and
88+// loadConfig says so rather than ignoring it.
89+func parseCommandLine() cliOptions {
90+ var valued valueFlags
91+ os.Args = valued.extract(os.Args)
92+
93+ configPath := flag.String("config", "", "path to the YAML config file (default: $AGENT_CONFIG, then ./agent.yaml, then ./.mm/agent.yaml)")
94+ a2aMode := flag.Bool("a2a", false, "serve this agent over the Agent2Agent protocol (A2A, JSON-RPC over HTTP) on a2a.host:a2a.port, 127.0.0.1:9100 by default (same as: mm a2a)")
95+ a2aPort := flag.Int("a2a-port", 0, "with -a2a: the port to listen on, instead of a2a.port")
96+ flag.Bool("a2a-send", false, "send one message to an A2A agent and print its answer (same as mm a2a-send; mm a2a-send -h for its flags)")
97+ acpMode := flag.Bool("acp", false, "serve the Agent Client Protocol on stdio (for Zed, JetBrains, Neovim…) instead of the terminal REPL (same as: mm acp)")
98+ tuiMode := flag.Bool("tui", false, "open the single-window mode (conversation above, input box below); falls back to the line mode when stdout is not a terminal (same as: mm tui)")
99+ promptMode := flag.String("prompt", "", "run a single prompt and exit")
100+ flag.StringVar(promptMode, "p", "", "shorthand for --prompt")
101+ showVersion := flag.Bool("version", false, "print the version and exit")
102+ showAbout := flag.Bool("about", false, "print what mm is, and exit")
103+ // Listed for -h only: the subcommands are answered before flag.Parse.
104+ flag.Bool("init", false, "write a new agent.yaml with a wizard (same as `mm init`; `mm init -h` for its flags)")
105+ flag.Bool("acp-create", false, "serve mm init's wizard over the Agent Client Protocol, to create an agent.yaml from an editor (same as mm acp-create; mm acp-create -h for its flags)")
106+ flag.Bool("dockerinit", false, "write a Dockerfile and a compose.yaml to run mm in a container (same as mm dockerinit; mm dockerinit -h for its flags)")
107+ flag.Bool("skillcreate", false, "write a new skill with a wizard, where the agent reads its skills (same as mm skillcreate; mm skillcreate -h for its flags)")
108+ flag.Bool("sbxinit", false, "write a sbxenv.yaml to run mm in a Docker Sandbox (same as mm sbxinit; mm sbxinit -h for its flags)")
109+ askAgent := flag.String("ask", "", "ask the agent `name` (a key of mmConfigs) the -p prompt, or stdin; print only its answer on stdout, and exit")
110+ askWithContext := flag.String("ask-with-context", "", "same as --ask, with the conversation read from stdin (question with -p, or after a \"---\" line)")
111+ flag.Parse()
112+
113+ cli := cliOptions{
114+ configPath: *configPath, args: flag.Args(),
115+ a2a: *a2aMode, a2aPort: *a2aPort, acp: *acpMode, tui: *tuiMode,
116+ prompt: firstSet(valued.prompt, *promptMode), version: *showVersion, about: *showAbout,
117+ askName: firstSet(valued.ask, *askAgent),
118+ }
119+ if ctxName := firstSet(valued.askContext, *askWithContext); ctxName != "" {
120+ cli.askName, cli.askContext = ctxName, true
121+ }
122+ flag.Visit(func(f *flag.Flag) {
123+ if f.Name == "config" {
124+ cli.configExplicit = true
125+ }
126+ })
127+ return cli
128+}
129+
130+// valueFlags are the flags whose value may follow the config file:
131+// `mm agent.yaml --prompt "hello"` like `mm --prompt "hello" agent.yaml`, and
132+// `mm agent.yaml --ask lucy -p "…"` — flag.Parse stops at the first
133+// positional argument, so they are taken out before it.
134+type valueFlags struct {
135+ prompt, ask, askContext string
136+}
137+
138+// extract takes the value flags out of args and returns the rest.
139+func (v *valueFlags) extract(args []string) []string {
140+ rest := []string{args[0]}
141+ for i := 1; i < len(args); i++ {
142+ target := v.target(args[i])
143+ if target == nil {
144+ rest = append(rest, args[i])
145+ continue
146+ }
147+ if i+1 < len(args) {
148+ *target = args[i+1]
149+ i++ // skip the value
150+ }
151+ }
152+ return rest
153+}
154+
155+// target is where a value flag's value goes; nil for any other argument.
156+func (v *valueFlags) target(arg string) *string {
157+ switch arg {
158+ case "--prompt", "-prompt", "-p":
159+ return &v.prompt
160+ case "--ask", "-ask":
161+ return &v.ask
162+ case "--ask-with-context", "-ask-with-context":
163+ return &v.askContext
164+ }
165+ return nil
166+}
167+
168+// firstSet is the first non-empty value.
169+func firstSet(values ...string) string {
170+ for _, v := range values {
171+ if v != "" {
172+ return v
173+ }
174+ }
175+ return ""
176+}
177+
178+// answered prints what --version and --about ask for, and reports whether
179+// it did. Answered before anything can go wrong: asking which mm this is
180+// must work without a config file, without a model server, and in a
181+// directory mm knows nothing about. Straight to stdout, not ui.Out — this is
182+// the answer to a question, not part of a session's output.
183+func (cli cliOptions) answered() bool {
184+ switch {
185+ case cli.version:
186+ fmt.Println(version.Long())
187+ case cli.about:
188+ fmt.Println(version.About())
189+ default:
190+ return false
191+ }
192+ return true
193+}
194+
195+// loadConfig checks the arguments, sends everything human to stderr when
196+// stdout is a protocol or an answer, loads the agent file and returns its
197+// path. A usage error, a config error or no agent file ends mm.
198+func (cli *cliOptions) loadConfig() string {
199+ cli.checkArgs()
200+ cli.redirectOutput()
201+ path, err := config.Load(cli.configPath)
202+ if err != nil {
203+ fail("[config error: %v ]", err)
204+ os.Exit(1)
205+ }
206+ // No agent file found: stop rather than run a built-in model on a
207+ // built-in server the user never chose (ticket 220). Every mode that
208+ // reaches this point talks to a model; the commands that write the files
209+ // and --version / --about were answered before.
210+ if path == "" {
211+ fail("%s", noAgentFile())
212+ os.Exit(1)
213+ }
214+ // Where a relative skillsDir points depends on who started mm. From a
215+ // terminal, it is the directory mm was started from — an installed mm
216+ // (/usr/local/bin) run inside a project loads THAT project's skills. The
217+ // editor launches mm with ITS working directory, so in ACP mode with a
218+ // config file the anchor is that file — the one path the user actually
219+ // named (env AGENT_CONFIG in the editor's settings). Either way the path
220+ // is made absolute here, so the banner can say exactly where it looked.
221+ config.Cfg.SkillsDir = resolveSkillsDir(config.Cfg.SkillsDir, path, cli.acp)
222+ exportSelf(path)
223+ return path
224+}
225+
226+// checkArgs takes the config file from a lone argument, and refuses more.
227+func (cli *cliOptions) checkArgs() {
228+ if cli.configPath == "" && len(cli.args) > 0 {
229+ cli.configPath = cli.args[0]
230+ }
231+ switch {
232+ case cli.configExplicit && len(cli.args) > 0:
233+ fail("[usage: --config already specified, got %d extra arguments]", len(cli.args))
234+ os.Exit(1)
235+ case len(cli.args) > 1:
236+ fail("[usage: at most one config file, got %d arguments]", len(cli.args))
237+ os.Exit(1)
238+ }
239+}
240+
241+// redirectOutput sends everything human to stderr when stdout is not the
242+// user's. --ask: stdout carries the answer and nothing else; with no config
243+// named, the config of the mm whose bash tool runs this command (MM_CONFIG,
244+// exported by exportSelf) is the one whose mmConfigs a skill means. ACP:
245+// stdout belongs to JSON-RPC — the spec forbids anything else on it; the
246+// banner, warnings and errors go through ui.Out, so ONE move sends them to
247+// stderr, where the editor's agent logs pick them up. The spinner is
248+// silenced outright: it cannot tell "a terminal" from "a terminal used as a
249+// protocol pipe".
250+func (cli *cliOptions) redirectOutput() {
251+ if cli.askName != "" {
252+ ui.Out = os.Stderr
253+ spinner.Disable()
254+ if cli.configPath == "" {
255+ cli.configPath = os.Getenv(configEnv)
256+ }
257+ }
258+ if cli.acp {
259+ ui.Out = os.Stderr
260+ spinner.Disable()
261+ }
262+}
263+
264+// isA2ASend reports whether the first argument is `mm a2a-send`.
265+func isA2ASend(arg string) bool {
266+ return arg == "a2a-send" || arg == "--a2a-send" || arg == "-a2a-send"
267+}
268+
269+// modeWords are the first arguments that name a mode, as their flag.
270+var modeWords = []string{"tui", "acp", "a2a", "help"}
modified main.go +124 -705
@@ -30,7 +30,6 @@ import (
3030 "bytes"
3131 "context"
3232 "errors"
33- "flag"
3433 "fmt"
3534 "io"
3635 "os"
@@ -41,353 +40,199 @@ import (
4140 "time"
4241
4342 "mm/internal/acp"
44- "mm/internal/acpcreate"
4543 "mm/internal/agent"
46- "mm/internal/agentinit"
4744 "mm/internal/ask"
4845 "mm/internal/command"
4946 "mm/internal/config"
5047 "mm/internal/detector"
51- "mm/internal/dockerinit"
5248 "mm/internal/engine"
5349 "mm/internal/hooks"
54- "mm/internal/lsp"
55- "mm/internal/mcp"
5650 "mm/internal/metaprompt"
57- "mm/internal/sbxinit"
58- "mm/internal/skillcreate"
5951 "mm/internal/skills"
60- "mm/internal/spinner"
6152 "mm/internal/tools"
6253 "mm/internal/tui"
6354 "mm/internal/ui"
6455 "mm/internal/version"
65- "mm/internal/webmd"
6656
6757 "github.com/firebase/genkit/go/ai"
6858 )
6959
7060 func main() {
71- ctx := context.Background()
72-
73- // Where the config file is. Same value, three ways to give it, from the most
74- // local to the most ambient:
75- //
76- // go run . -config ./fast.yaml (the flag)
77- // go run . ./fast.yaml (a lone argument, handy in a demo)
78- // AGENT_CONFIG=./fast.yaml go run .
79- //
80- // The flag package gives us "-h" for free; a second argument is a typo, and
81- // saying so is better than ignoring it.
82-
83- // `mm init` and `mm --init` (ticket 97): the agent.yaml wizard, with its
84- // own flags, before anything reads a configuration — there is none yet.
85- if len(os.Args) > 1 && isInit(os.Args[1]) {
86- os.Exit(agentinit.Main(os.Args[2:], os.Stdin, os.Stdout, agentinit.Options{Window: tui.RunInit, Terminal: tui.Terminal}))
87- }
88- // `mm acp-create` and `mm --acp-create` (ticket 210): the same wizard
89- // served over ACP, for an editor; no configuration either. stdout is
90- // the protocol's, so its help and errors go to stderr.
91- if len(os.Args) > 1 && acpcreate.Is(os.Args[1]) {
92- os.Exit(acpcreate.Main(os.Args[2:], os.Stdin, os.Stdout, os.Stderr))
93- }
94- // `mm dockerinit` (ticket 189): writes files, before any configuration too.
95- if len(os.Args) > 1 && isDockerInit(os.Args[1]) {
96- os.Exit(dockerinit.Main(os.Args[2:], os.Stdin, os.Stdout))
97- }
98- // `mm sbxinit` (ticket 191): the same, for a Docker Sandbox.
99- if len(os.Args) > 1 && isSbxInit(os.Args[1]) {
100- os.Exit(sbxinit.Main(os.Args[2:], os.Stdin, os.Stdout))
101- }
102- // `mm a2a-send` (ticket 243): one message to an A2A agent, from a script.
103- // No configuration, no model: answered before anything is read.
104- if len(os.Args) > 1 && (os.Args[1] == "a2a-send" || os.Args[1] == "--a2a-send" || os.Args[1] == "-a2a-send") {
105- os.Exit(a2aSendMain(os.Args[2:], os.Stdin, os.Stdout, os.Stderr))
106- }
107- // `mm skillcreate` (ticket 206): a wizard that writes a new skill where
108- // the agent's config reads its skills; it reads the config itself.
109- if len(os.Args) > 1 && isSkillCreate(os.Args[1]) {
110- os.Exit(skillcreate.Main(os.Args[2:], os.Stdin, os.Stdout, skillcreate.Options{Window: tui.RunSkillCreate, Terminal: tui.Terminal}))
61+ // `mm init`, `mm acp-create`, `mm dockerinit`, `mm sbxinit`, `mm a2a-send`
62+ // and `mm skillcreate`: answered before anything reads a configuration.
63+ if code, ok := runSubcommand(os.Args); ok {
64+ os.Exit(code)
11165 }
11266 // `mm tui` and `mm acp` (ticket 117): the modes as words too, like
11367 // `mm init` — `mm tui agent.yaml` is `mm -tui agent.yaml`. `mm help`
11468 // (ticket 273) is `mm -help` the same way.
11569 os.Args = modeWordAsFlag(os.Args)
116-
117- // Handle --prompt/-p flag which can appear after the config file argument
118- // We manually extract it before flag.Parse() so both orders work:
119- // mm --prompt "hello" agent.yaml AND mm agent.yaml --prompt "hello"
120- // The same goes for --ask and --ask-with-context, whose agent name follows
121- // them: `mm agent.yaml --ask lucy -p "…"` must work like the flags-first
122- // order, and flag.Parse stops at the first positional argument.
123- promptArg, askArg, askContextArg := "", "", ""
124- remainingArgs := []string{}
125- for i := 1; i < len(os.Args); i++ {
126- arg := os.Args[i]
127- var target *string
128- switch arg {
129- case "--prompt", "-prompt", "-p":
130- target = &promptArg
131- case "--ask", "-ask":
132- target = &askArg
133- case "--ask-with-context", "-ask-with-context":
134- target = &askContextArg
135- default:
136- remainingArgs = append(remainingArgs, arg)
137- continue
138- }
139- if i+1 < len(os.Args) {
140- *target = os.Args[i+1]
141- i++ // skip the value
142- }
143- }
144- // Replace os.Args for flag.Parse()
145- os.Args = append([]string{os.Args[0]}, remainingArgs...)
146-
147- configPath := flag.String("config", "", "path to the YAML config file (default: $AGENT_CONFIG, then ./agent.yaml, then ./.mm/agent.yaml)")
148- a2aMode := flag.Bool("a2a", false, "serve this agent over the Agent2Agent protocol (A2A, JSON-RPC over HTTP) on a2a.host:a2a.port, 127.0.0.1:9100 by default (same as: mm a2a)")
149- a2aPort := flag.Int("a2a-port", 0, "with -a2a: the port to listen on, instead of a2a.port")
150- flag.Bool("a2a-send", false, "send one message to an A2A agent and print its answer (same as mm a2a-send; mm a2a-send -h for its flags)")
151- acpMode := flag.Bool("acp", false, "serve the Agent Client Protocol on stdio (for Zed, JetBrains, Neovim…) instead of the terminal REPL (same as: mm acp)")
152- tuiMode := flag.Bool("tui", false, "open the single-window mode (conversation above, input box below); falls back to the line mode when stdout is not a terminal (same as: mm tui)")
153- promptMode := flag.String("prompt", "", "run a single prompt and exit")
154- flag.StringVar(promptMode, "p", "", "shorthand for --prompt")
155- showVersion := flag.Bool("version", false, "print the version and exit")
156- showAbout := flag.Bool("about", false, "print what mm is, and exit")
157- // Listed for -h only: `mm --init` is answered before flag.Parse.
158- flag.Bool("init", false, "write a new agent.yaml with a wizard (same as `mm init`; `mm init -h` for its flags)")
159- flag.Bool("acp-create", false, "serve mm init's wizard over the Agent Client Protocol, to create an agent.yaml from an editor (same as mm acp-create; mm acp-create -h for its flags)")
160- flag.Bool("dockerinit", false, "write a Dockerfile and a compose.yaml to run mm in a container (same as mm dockerinit; mm dockerinit -h for its flags)")
161- flag.Bool("skillcreate", false, "write a new skill with a wizard, where the agent reads its skills (same as mm skillcreate; mm skillcreate -h for its flags)")
162- flag.Bool("sbxinit", false, "write a sbxenv.yaml to run mm in a Docker Sandbox (same as mm sbxinit; mm sbxinit -h for its flags)")
163- askAgent := flag.String("ask", "", "ask the agent `name` (a key of mmConfigs) the -p prompt, or stdin; print only its answer on stdout, and exit")
164- askWithContext := flag.String("ask-with-context", "", "same as --ask, with the conversation read from stdin (question with -p, or after a \"---\" line)")
165- flag.Parse()
166-
167- // If prompt was extracted manually, use it (overrides flag value)
168- if promptArg != "" {
169- *promptMode = promptArg
170- }
171- if askArg != "" {
172- *askAgent = askArg
173- }
174- if askContextArg != "" {
175- *askWithContext = askContextArg
176- }
177-
178- // Track if --config was explicitly set via the flag
179- configExplicit := false
180- flag.Visit(func(f *flag.Flag) {
181- if f.Name == "config" {
182- configExplicit = true
183- }
184- })
185- // Answered before anything can go wrong: asking which mm this is must
186- // work without a config file, without a model server, and in a directory
187- // mm knows nothing about. Straight to stdout, not ui.Out — this is the
188- // answer to a question, not part of a session's output.
189- if *showVersion {
190- fmt.Println(version.Long())
191- return
192- }
193- // Same rule as --version: answered before the configuration is looked
194- // for, so it works in any directory with no model server running.
195- if *showAbout {
196- fmt.Println(version.About())
70+ cli := parseCommandLine()
71+ if cli.answered() {
19772 return
19873 }
199- if *configPath == "" && flag.NArg() > 0 {
200- *configPath = flag.Arg(0)
201- }
202- if configExplicit && flag.NArg() > 0 {
203- fail("[usage: --config already specified, got %d extra arguments]", flag.NArg())
204- os.Exit(1)
205- }
206- if flag.NArg() > 1 {
207- fail("[usage: at most one config file, got %d arguments]", flag.NArg())
208- os.Exit(1)
74+ path := cli.loadConfig()
75+ ctx := context.Background()
76+ if cli.askName != "" {
77+ os.Exit(runAsk(ctx, cli.askName, cli.askContext, cli.prompt))
20978 }
79+ runAgent(ctx, cli, path)
80+}
21081
211- // --ask: stdout carries the answer and nothing else, so everything human
212- // goes to stderr, like in ACP mode. With no config named, the config of
213- // the mm whose bash tool runs this command (MM_CONFIG, exported below) is
214- // the one whose mmConfigs a skill means.
215- askName, askContext := *askAgent, false
216- if *askWithContext != "" {
217- askName, askContext = *askWithContext, true
218- }
219- if askName != "" {
220- ui.Out = os.Stderr
221- spinner.Disable()
222- if *configPath == "" {
223- *configPath = os.Getenv(configEnv)
224- }
225- }
82+// runAgent runs the agent of the file at path: the engine, the tools, then
83+// -p or one of the front ends. Every way out from here on — returning,
84+// exit(), a signal — runs onExit.
85+func runAgent(ctx context.Context, cli cliOptions, path string) {
86+ showHooks(cli.acp)
87+ declareCommands()
88+ asker := ask.NewPool()
89+ defer asker.Close()
22690
227- // In ACP mode, stdout belongs to JSON-RPC — the spec forbids anything else
228- // on it. Everything below that prints (banner, warnings, errors) goes
229- // through ui.Out, so ONE move sends it all to stderr, where the editor's
230- // agent logs pick it up. The spinner is silenced outright: supported()
231- // cannot tell "a terminal" from "a terminal used as a protocol pipe".
232- if *acpMode {
233- ui.Out = os.Stderr
234- spinner.Disable()
235- }
91+ window, banner := windowMode((cli.tui || config.Cfg.TUI) && !cli.acp && !cli.a2a)
23692
237- // Settings: built-in defaults, overridden by the agent file.
238- path, err := config.Load(*configPath)
239- if err != nil {
240- fail("[config error: %v ]", err)
241- os.Exit(1)
242- }
243- // No agent file found: stop rather than run a built-in model on a
244- // built-in server the user never chose (ticket 220). Every mode that
245- // reaches this point talks to a model; the commands that write the
246- // files (init, acp-create, skillcreate, dockerinit, sbxinit) and
247- // --version / --about were answered before.
248- if path == "" {
249- fail("%s", noAgentFile())
250- os.Exit(1)
251- }
252-
253- // Where a relative skillsDir points depends on who started mm. From a
254- // terminal, it is the directory mm was started from — an installed mm
255- // (/usr/local/bin) run inside a project loads THAT project's skills. The
256- // editor launches mm with ITS working directory, so in ACP mode with a
257- // config file the anchor is that file — the one path the user actually
258- // named (env AGENT_CONFIG in the editor's settings). Either way the path
259- // is made absolute here, so the banner can say exactly where it looked.
260- config.Cfg.SkillsDir = resolveSkillsDir(config.Cfg.SkillsDir, path, *acpMode)
261- exportSelf(path)
93+ // onExit: the model's unload (unloadOnExit, ticket 255), then the lease on
94+ // the server mm started (llamacpp.autoStart, ticket 223;
95+ // razorbill.autoStart, ticket 264).
96+ defer onExit.run()
97+ // autoStart: nothing answers at the agent's address, mm starts
98+ // llama-server or rzb and waits for the model — before the engine picks
99+ // its address, so it finds the server it started. It handles a signal
100+ // during the start itself; the watch starts after.
101+ onExit.release = startLocalServer(ctx, cli.acp).Release
102+ defer watchExitSignals(onExit, cli.prompt != "")()
103+
104+ e := startEngine(ctx, cli.acp, asker)
105+ s := agentSession{e: e, detector: newLoopDetector(), asker: asker}
106+ set := s.assemble()
107+ defer set.close()
108+ s.tools = set.tools
262109
263- if askName != "" {
264- os.Exit(runAsk(ctx, askName, askContext, *promptMode))
110+ if s.runPrompt(ctx, cli.prompt, set) {
111+ return
265112 }
266- showHooks(*acpMode)
113+ printBanner(ctx, e, path, set, cli.acp)
114+ s.runFrontEnd(ctx, cli, window, banner)
115+}
267116
268- // The other agents this one can ask (`mmConfigs`): their /ask-<name>
269- // commands join the shared table before any front end reads it, and their
270- // processes start on the first ask and stop when this one exits.
117+// declareCommands puts in the shared command table what the file enables:
118+// the other agents this one can ask (`mmConfigs`: /ask-<name>, their
119+// processes start on the first ask and stop when this one exits), the A2A
120+// agents, /unload, /memory, /docs.
121+func declareCommands() {
271122 command.SetAgents(config.AgentNames())
272123 command.SetA2AAgents(config.A2AAgentNames())
273124 command.SetUnload(config.Cfg.UnloadModels)
274125 command.SetMemory(config.Cfg.Sessions.MemoryCommand())
275126 command.SetDocs(config.Cfg.DocSearch.DocsCommand())
276- asker := ask.NewPool()
277- defer asker.Close()
278-
279- window, banner := windowMode((*tuiMode || config.Cfg.TUI) && !*acpMode && !*a2aMode)
280-
281- // Every way out from here on — main returning, exit(), a signal — runs
282- // onExit: the model's unload (unloadOnExit, ticket 255), then the
283- // lease on the server mm started (llamacpp.autoStart, ticket 223;
284- // razorbill.autoStart, ticket 264).
285- defer onExit.run()
286- // autoStart: nothing answers at the agent's address, mm starts
287- // llama-server or rzb and waits for the model — before the engine
288- // picks its address, so it finds the server it started. It handles a
289- // signal during the start itself; the watch starts after.
290- onExit.release = startLocalServer(ctx, *acpMode).Release
291- defer watchExitSignals(onExit, *promptMode != "")()
127+}
292128
129+// startEngine builds the engine, downloads the missing models (autoPull,
130+// ticket 61, the progress on stderr), arms the unload on exit, and gives the
131+// pool its unloads (mmConfigs.<name>.unloadModels, ticket 161: this agent's
132+// model before the hand-off, the asked agent's after it). A failure ends mm.
133+func startEngine(ctx context.Context, acpMode bool, asker *ask.Pool) *engine.Engine {
293134 e, err := engine.New(ctx)
294- if err != nil {
295- fail("[engine error: %v ]", err)
296- exit(1)
135+ if err == nil {
136+ err = autoPull(ctx, e, os.Stderr, stderrIsTerminal())
297137 }
298- // autoPull (ticket 61): the missing models are downloaded before the
299- // agent is ready, the progress on stderr.
300- if err := autoPull(ctx, e, os.Stderr, stderrIsTerminal()); err != nil {
138+ if err != nil {
301139 fail("[engine error: %v ]", err)
302140 exit(1)
303141 }
304- onExit.arm(e, *acpMode)
305-
306- // mmConfigs.<name>.unloadModels (ticket 161): the pool frees this
307- // agent's model before the hand-off, the asked agent's after it.
142+ onExit.arm(e, acpMode)
308143 asker.SetUnloads(ask.Unloads{
309144 Asker: func(ctx context.Context) string { return e.Unload(ctx, "") },
310145 Asked: engine.UnloadAgent,
311146 })
312-
313147 // bashBackground: stop (ticket 228) — the process groups a turn's commands
314148 // left running are stopped once the turn is over, in every front end.
315149 engine.OnTurnEnd(func() { tools.StopBackground() })
150+ return e
151+}
152+
153+// newLoopDetector: the same call with the same result three times in a row
154+// is flagged (the model is told to change approach); three flagged repeats
155+// more — six identical calls — and the turn is stopped, since a model that
156+// ignored the advice three times will not read it a fourth time (seen on
157+// 2026-09-18: 30 identical refused edits before the user pressed Escape).
158+// Every flagged repeat is also shown to the user (ticket 153), and so is a
159+// run of three failed calls or more with different inputs (ticket 160).
160+func newLoopDetector() *detector.LoopDetector {
161+ return detector.NewLoopDetector(10, 3).WithStop(3).WithFailures(3).WithReport(reportLoop)
162+}
316163
317- // The loop detector: the same call with the same result three times in a
318- // row is flagged (the model is told to change approach); three flagged
319- // repeats more — six identical calls — and the turn is stopped, since a
320- // model that ignored the advice three times will not read it a fourth
321- // time (seen on 2026-09-18: 30 identical refused edits before the user
322- // pressed Escape).
323- // Every flagged repeat is also shown to the user (ticket 153), and so is
324- // a run of three failed calls or more with different inputs (ticket 160).
325- loopDetector := detector.NewLoopDetector(10, 3).WithStop(3).WithFailures(3).WithReport(reportLoop)
164+// agentSession is what every front end runs on: the engine, the tools, the loop
165+// detector and the pool of other agents.
166+type agentSession struct {
167+ e *engine.Engine
168+ tools []ai.ToolRef
169+ detector *detector.LoopDetector
170+ asker *ask.Pool
171+}
326172
327- // A decider answers with its decision model: no tool is ever called.
328- // Checked before the tools are assembled, so no MCP or language server
329- // is started for a file that is about to be refused.
173+// assemble builds the tool set and the routers. A decider declares no tool
174+// source (checked before the tools are assembled, so no MCP or language
175+// server is started for a file about to be refused); a structuredOutput
176+// leaves no room for a tool call. A refusal ends mm.
177+func (s agentSession) assemble() toolSet {
330178 if err := config.DecisionConflict(); err != nil {
331179 fail("[config error: %v ]", err)
332180 exit(1)
333181 }
334- set := assembleTools(e, loopDetector, asker)
335- defer set.close()
336- // A structuredOutput constrains every answer: no room for a tool call.
337- if err := config.StructuredOutputConflict(set.names); err != nil {
338- fail("[config error: %v ]", err)
339- set.close()
340- exit(1)
182+ set := assembleTools(s.e, s.detector, s.asker)
183+ err := config.StructuredOutputConflict(set.names)
184+ if err == nil {
185+ err = installRouter()
341186 }
342- if err := installRouter(); err != nil {
187+ if err != nil {
343188 fail("[config error: %v ]", err)
344189 set.close()
345190 exit(1)
346191 }
347- agentTools := set.tools
348192 set.warnings = append(set.warnings, ask.Missing()...)
349193 set.warnings = append(set.warnings, config.Cfg.PromptWarnings()...)
194+ return set
195+}
350196
351- // Handle prompt mode: run a single prompt and exit
352- if *promptMode != "" && e.IsDecider() {
197+// runPrompt runs -p — a decider's JSON, a structured answer, or a plain
198+// turn — and reports whether it did. No banner, no session persistence. A
199+// failed generation exits 1 (ticket 224); os.Exit skips the deferred
200+// cleanups, so they run first.
201+func (s agentSession) runPrompt(ctx context.Context, prompt string, set toolSet) bool {
202+ switch {
203+ case prompt == "":
204+ return false
205+ case s.e.IsDecider():
353206 ui.Out = os.Stderr
354- exit(runDecisionPrompt(ctx, e, *promptMode, os.Stdout))
355- }
356- if *promptMode != "" && config.Cfg.OutputSchema != nil {
357- exit(runStructuredPrompt(ctx, e, *promptMode))
207+ exit(runDecisionPrompt(ctx, s.e, prompt, os.Stdout))
208+ case config.Cfg.OutputSchema != nil:
209+ exit(runStructuredPrompt(ctx, s.e, prompt))
358210 }
359- if *promptMode != "" {
360- // In prompt mode, no banner, no session persistence. A failed
361- // generation exits 1 (ticket 224); os.Exit skips the deferred
362- // cleanups, so they run first.
363- if code := agent.RunPrompt(ctx, e, config.Cfg.System, agentTools, loopDetector, *promptMode); code != 0 {
364- set.close()
365- asker.Close()
366- exit(code)
367- }
368- return
211+ if code := agent.RunPrompt(ctx, s.e, config.Cfg.System, s.tools, s.detector, prompt); code != 0 {
212+ set.close()
213+ s.asker.Close()
214+ exit(code)
369215 }
216+ return true
217+}
370218
371- printBanner(ctx, e, path, set, *acpMode)
372-
373- // Three front ends, one wiring: everything above — config, engine, tools,
374- // detector — is strictly identical whichever loop runs below.
375- if *acpMode {
376- acp.Run(ctx, e, config.Cfg.System, agentTools, loopDetector, asker)
377- return
378- }
379- if *a2aMode {
380- if err := runA2A(ctx, e, config.Cfg.System, agentTools, *a2aPort); err != nil {
219+// runFrontEnd runs the front end the command line asks for. Three front
220+// ends, one wiring: config, engine, tools, detector are strictly identical
221+// whichever loop runs.
222+func (s agentSession) runFrontEnd(ctx context.Context, cli cliOptions, window bool, banner *bytes.Buffer) {
223+ switch {
224+ case cli.acp:
225+ acp.Run(ctx, s.e, config.Cfg.System, s.tools, s.detector, s.asker)
226+ case cli.a2a:
227+ if err := runA2A(ctx, s.e, config.Cfg.System, s.tools, cli.a2aPort); err != nil {
381228 fail("[a2a: %v ]", err)
382229 exit(1)
383230 }
384- return
385- }
386- if window {
387- runWindow(ctx, e, agentTools, loopDetector, strings.TrimSpace(banner.String()), asker)
388- return
231+ case window:
232+ runWindow(ctx, s, strings.TrimSpace(banner.String()))
233+ default:
234+ agent.Run(ctx, s.e, config.Cfg.System, s.tools, s.detector, s.asker)
389235 }
390- agent.Run(ctx, e, config.Cfg.System, agentTools, loopDetector, asker)
391236 }
392237
393238 // showHooks installs, when displayHooks is on, what every hook run goes to:
@@ -417,7 +262,8 @@ func runStructuredPrompt(ctx context.Context, e *engine.Engine, prompt string) i
417262
418263 // runWindow starts the single-window front end, falling back to the line
419264 // mode — banner first — if the terminal cannot be opened after all.
420-func runWindow(ctx context.Context, e *engine.Engine, agentTools []ai.ToolRef, d *detector.LoopDetector, banner string, asker ask.Runner) {
265+func runWindow(ctx context.Context, s agentSession, banner string) {
266+ e, agentTools, d, asker := s.e, s.tools, s.detector, s.asker
421267 cwd, _ := os.Getwd()
422268 err := tui.Run(ctx, tui.Options{
423269 Model: e,
@@ -448,418 +294,6 @@ func runWindow(ctx context.Context, e *engine.Engine, agentTools []ai.ToolRef, d
448294 agent.Run(ctx, e, config.Cfg.System, agentTools, d, asker)
449295 }
450296
451-// toolSet is what assembleTools hands main: the tools, their names for the
452-// banner, the skill count, the warnings the banner must show, and what to
453-// stop at exit (the language servers).
454-type toolSet struct {
455- tools []ai.ToolRef
456- names []string
457- skillCount int
458- // skills is the catalogue itself, kept so the banner can say what is
459- // wrong with it and not only how many there are.
460- skills []skills.Skill
461- warnings []string
462- close func()
463-}
464-
465-// assembleTools declares the tools every front end gets: `bash` unless
466-// `bashTool: false` turned it off; `read_skill` only when the skills
467-// directory holds something to read (its
468-// description carries the catalogue, so declaring it empty would advertise a
469-// tool that can do nothing); the file tools behind `editTools` — the same
470-// binary must run as part 09 did (bash + the `edit` CLI) and as this part
471-// (built-in tools), so the two can be compared on the same prompts;
472-// `fetch_content` behind `fetchContentTool`, off by default because it is the
473-// one built-in tool that reaches the network; and `lsp` when `lsp.servers` names at least one server whose command is on
474-// the PATH — a missing server is a warning, never a refusal to start; and
475-// `ask_agent` when mmConfigs names at least one agent, over the same pool as
476-// /ask; `ask_user` behind `askUserTool` (on by default), never with a
477-// structuredOutput; `save_answer` behind `saveAnswerTool` (off by default);
478-// `search_memory` behind `sessions.autoSearchMemory` (off by default, sessions on);
479-// `search_docs` behind `docSearch.autoSearchDocs` (off by default);
480-// and the agent file's declared `tools:`.
481-//
482-// A decider gets none of them, whatever bashTool, editTools, skillsDir… say
483-// (ticket 141): its model never calls a tool, so a decider file needs no
484-// `…: false` lines. What only a deliberate entry declares (mcp, lsp,
485-// mmConfigs, tools:) is refused earlier by config.DecisionConflict.
486-func assembleTools(e *engine.Engine, d *detector.LoopDetector, asker tools.AgentAsker) toolSet {
487- set := toolSet{close: func() {}}
488- if config.Cfg.Decision != nil {
489- engine.DeclareSkills(false)
490- skills.Declare(nil)
491- return set
492- }
493- if config.Cfg.BashTool {
494- set.tools = append(set.tools, tools.Bash(e.G, d))
495- set.names = append(set.names, "bash")
496- }
497- set.skills = skills.List(config.Cfg.SkillsDir)
498- set.skillCount = len(set.skills)
499- // The turn recap shows `📖 0 skill(s)` only where a skill could have been
500- // used — see engine.SkillsAvailable.
501- engine.DeclareSkills(set.skillCount > 0)
502- // The catalogue every front end resolves `$skill` against.
503- skills.Declare(set.skills)
504- if skillTool := tools.ReadSkill(e.G, config.Cfg.SkillsDir, d); skillTool != nil {
505- set.tools = append(set.tools, skillTool)
506- set.names = append(set.names, "read_skill")
507- }
508- if config.Cfg.EditTools {
509- set.tools = append(set.tools,
510- tools.ReadFile(e.G, d),
511- tools.WriteFile(e.G, d),
512- tools.EditFile(e.G, d))
513- set.names = append(set.names, "read_file", "write_file", "edit_file")
514- }
515- if config.Cfg.PlanTool {
516- set.tools = append(set.tools, tools.PlanTool(e.G, d))
517- set.names = append(set.names, "plan")
518- }
519- // Not for an agent with a structuredOutput: it answers once, in JSON, and
520- // declaring a tool would stop it from starting (StructuredOutputConflict)
521- // — the existing structured agents would all break on a default.
522- if config.Cfg.AskUserTool && config.Cfg.OutputSchema == nil {
523- set.tools = append(set.tools, tools.AskUser(e.G, d))
524- set.names = append(set.names, "ask_user")
525- }
526- if config.Cfg.SaveAnswerTool {
527- set.tools = append(set.tools, tools.SaveAnswer(e.G, d))
528- set.names = append(set.names, "save_answer")
529- }
530- if config.Cfg.UnloadModels && config.Cfg.OutputSchema == nil {
531- set.tools = append(set.tools, tools.UnloadModel(e.G, d, e.Unload))
532- set.names = append(set.names, "unload_model")
533- }
534- if config.Cfg.FetchContentTool {
535- // The product token "mm" is what the sites' robots.txt are read for.
536- fetcher := webmd.NewFetcher("mm/" + version.Short())
537- set.tools = append(set.tools, tools.FetchContent(e.G, d, fetcher))
538- set.names = append(set.names, "fetch_content")
539- }
540- if config.Cfg.DocSearch.DocsTool() {
541- set.tools = append(set.tools, tools.SearchDocs(e.G, d))
542- set.names = append(set.names, "search_docs")
543- }
544- if config.Cfg.Sessions.MemoryTool() {
545- set.tools = append(set.tools, tools.SearchMemory(e.G, d))
546- set.names = append(set.names, "search_memory")
547- }
548- if w := config.Cfg.Sessions.MemoryWarning(); w != "" {
549- set.warnings = append(set.warnings, w)
550- }
551- if len(config.Cfg.MMConfigs) > 0 {
552- set.tools = append(set.tools, tools.AskAgent(e.G, d, asker))
553- set.names = append(set.names, "ask_agent")
554- }
555- // a2a.agents (ticket 243): the remote A2A agents the model can talk to.
556- if len(config.Cfg.A2A.Agents) > 0 {
557- set.tools = append(set.tools, tools.AskA2AAgent(e.G, d))
558- set.names = append(set.names, "ask_a2a_agent")
559- }
560- assembleLSP(e, d, &set)
561- assembleMCP(e, d, &set)
562- assembleDeclared(e, d, &set)
563- return set
564-}
565-
566-// assembleDeclared adds the agent file's `tools:` entries (ticket 88). They
567-// come last because an MCP tool's name is only known once its server
568-// answered: a declared tool that would take an MCP tool's name is skipped
569-// with a warning, never an error — the agent still starts. A built-in name
570-// cannot clash: the config refuses it at load.
571-func assembleDeclared(e *engine.Engine, d *detector.LoopDetector, set *toolSet) {
572- for _, t := range config.Cfg.Tools {
573- if slices.Contains(set.names, t.Name) {
574- set.warnings = append(set.warnings, fmt.Sprintf("tools: %s skipped — an MCP tool already has that name", t.Name))
575- continue
576- }
577- set.tools = append(set.tools, tools.DeclaredTool(e.G, d, t))
578- set.names = append(set.names, t.Name)
579- }
580-}
581-
582-// assembleLSP adds the `lsp` tool over the configured servers that exist.
583-// The servers are not started here — each starts on its first use — but
584-// the client is created now so main can stop them at exit. The project root
585-// the servers get is the directory mm runs in; an editor launches mm in the
586-// project it opened.
587-func assembleLSP(e *engine.Engine, d *detector.LoopDetector, set *toolSet) {
588- servers := config.Cfg.LSP.Servers
589- if len(servers) == 0 {
590- return
591- }
592- ok, missing := lsp.Available(servers)
593- for _, m := range missing {
594- set.warnings = append(set.warnings, fmt.Sprintf("lsp server %s not found on the PATH — skipped", m))
595- }
596- if len(ok) == 0 {
597- set.warnings = append(set.warnings, "lsp: none of the configured servers is on the PATH — the lsp tool is not declared")
598- return
599- }
600- cwd, _ := os.Getwd()
601- client := lsp.New(cwd, ok)
602- set.tools = append(set.tools, tools.LSP(e.G, d, client, ok))
603- // lsp.diagnosticsAfterEdit / diagnosticsAfterRead (tickets 227, 245):
604- // the file tools ask the same servers after a change or a read.
605- tools.SetEditDiagnostics(client, ok)
606- set.names = append(set.names, "lsp")
607- set.close = client.Close
608-}
609-
610-// assembleMCP adds MCP tools from configured servers.
611-// MCP discovery runs at startup (not lazy) and creates a static tool list.
612-// All MCP tools are wrapped to respect mini-me's safety contracts.
613-func assembleMCP(e *engine.Engine, d *detector.LoopDetector, set *toolSet) {
614- // Skip if MCP is disabled
615- if !config.Cfg.MCP.Enabled {
616- return
617- }
618-
619- // Check for sbx MCP gateway - if present, add it as a server
620- // sbx injects MCP_GATEWAY_URL and handles OAuth tokens via its gateway
621- // The gateway substitutes sentinel tokens with real OAuth tokens
622- gatewayURL := os.Getenv("MCP_GATEWAY_URL")
623-
624- servers := config.Cfg.MCP.Servers
625-
626- // If gateway URL is set and no servers configured, use gateway only
627- // If gateway URL is set and servers configured, add gateway as additional server
628- if gatewayURL != "" {
629- gatewayServer := config.MCPServer{
630- Name: "sbx-gateway",
631- Transport: "http",
632- URL: gatewayURL,
633- Timeout: config.Cfg.MCP.DiscoveryTimeout,
634- Auth: config.MCPAuthConfig{
635- Type: "bearer",
636- TokenEnv: "MCP_SENTINEL_TOKEN_NAME", // sbx injects this, not MCP_GATEWAY_TOKEN
637- },
638- Headers: map[string]string{
639- "Accept": "application/json, text/event-stream",
640- },
641- }
642-
643- // If no servers configured, use gateway only
644- if len(servers) == 0 {
645- servers = []config.MCPServer{gatewayServer}
646- } else {
647- // Add gateway as first server (prefer gateway tools)
648- servers = append([]config.MCPServer{gatewayServer}, servers...)
649- }
650- } else if len(servers) == 0 {
651- set.warnings = append(set.warnings, "mcp: enabled but no servers configured")
652- return
653- }
654-
655- // Create a context with discovery timeout
656- ctx, cancel := context.WithTimeout(context.Background(), config.Cfg.MCP.DiscoveryTimeout)
657- defer cancel()
658-
659- // Connect to all servers and discover tools
660- clients, warnings, err := mcp.ConnectAll(ctx, servers)
661- if err != nil {
662- set.warnings = append(set.warnings, fmt.Sprintf("mcp: connection/discovery failed: %v", err))
663- return
664- }
665-
666- // Add any discovery warnings
667- set.warnings = append(set.warnings, warnings...)
668-
669- // Check for name collisions
670- if len(clients) > 0 {
671- collisions := mcp.CheckCollisions(clients)
672- if len(collisions) > 0 {
673- set.warnings = append(set.warnings, collisions...)
674- // Close clients and return - collisions are fatal
675- mcp.CloseAll(clients)
676- return
677- }
678- }
679-
680- // Wrap all MCP tools
681- mcpToolRefs, mcpNames, mcpWarnings, err := tools.MCP(e.G, d, clients)
682- if err != nil {
683- set.warnings = append(set.warnings, fmt.Sprintf("mcp: tool wrapping failed: %v", err))
684- mcp.CloseAll(clients)
685- return
686- }
687-
688- // Add any MCP-specific warnings
689- if len(mcpWarnings) > 0 {
690- set.warnings = append(set.warnings, mcpWarnings...)
691- }
692-
693- // Add MCP tools to the set
694- set.tools = append(set.tools, mcpToolRefs...)
695- set.names = append(set.names, mcpNames...)
696-
697- // Chain close functions
698- oldClose := set.close
699- set.close = func() {
700- mcp.CloseAll(clients)
701- oldClose()
702- }
703-}
704-
705-// printBanner probes the server and prints the warnings and the one-line
706-// banner. The probe runs before the banner so its warnings sit right under
707-// the prompt they explain; it never stops the agent — on a demo machine the
708-// server is often started AFTER the agent.
709-func printBanner(ctx context.Context, e *engine.Engine, path string, set toolSet, acpMode bool) {
710- toolNames, skillCount := set.names, set.skillCount
711- info := e.Probe(ctx)
712- info.Warnings = append(info.Warnings, set.warnings...)
713- ctxCol := "unknown"
714- if info.ContextWindow > 0 {
715- ctxCol = fmt.Sprintf("%d (%s)", info.ContextWindow, info.ContextSource)
716- }
717- // Dimmed on a terminal, plain in a pipe: the agent's output is meant to be
718- // consumed by another program as much as it is meant to be read.
719- dim, off := "", ""
720- if spinner.Styled() {
721- dim, off = "\033[2m", "\033[0m"
722- }
723- // The compression's own warning belongs with the provider's: it is the
724- // same kind of advice, and it depends on what the probe just learned.
725- if c := config.Cfg.Context; c.Enabled && e.ContextWindow == 0 && c.MaxMessages == 0 {
726- info.Warnings = append(info.Warnings,
727- "context compression is on, but the context window is unknown and context.maxMessages is 0 — it will never trigger (set contextWindow, or maxMessages)")
728- }
729- // "skills: 0" alone sends people hunting; the resolved path says at once
730- // whether mm looked in the wrong place or found the right one empty.
731- // An agent with a structuredOutput has neither tools nor skills on
732- // purpose (config.StructuredOutputConflict): nothing to warn about.
733- // A decider has neither on purpose either (assembleTools, ticket 141).
734- structuredAgent := config.Cfg.OutputSchema != nil || config.Cfg.Decision != nil
735- agentsMdCol, agentsMdWarnings := agentsMdBanner(acpMode, info.ContextWindow)
736- info.Warnings = append(info.Warnings, agentsMdWarnings...)
737- if skillCount == 0 && !structuredAgent {
738- info.Warnings = append(info.Warnings,
739- fmt.Sprintf("no skills found in %s (expected <name>.md or <name>/SKILL.md there)", config.Cfg.SkillsDir))
740- }
741- // A skill with no description reaches the catalogue as a bare name, which
742- // is the worst entry there is: the model has nothing to match a request
743- // against, and the failure is silent — the count is not zero, so the
744- // warning above never fires.
745- if bare := skills.Undescribed(set.skills); len(bare) > 0 {
746- info.Warnings = append(info.Warnings,
747- fmt.Sprintf("%d skill(s) with no description (%s) — the model sees only the name and will pick blindly",
748- len(bare), strings.Join(bare, ", ")))
749- }
750- // A skill whose name a slash command owns is unreachable from an editor's
751- // command menu, and nothing else would say so.
752- if shadowed := skills.Shadowed(set.skills, commandNames()); len(shadowed) > 0 {
753- info.Warnings = append(info.Warnings,
754- fmt.Sprintf("skill(s) named like a slash command (%s) — reachable as $%s in a question, but not from an editor's / menu",
755- strings.Join(shadowed, ", "), shadowed[0]))
756- }
757- // Only the first maxKeywords of a list reach the catalogue, so the order
758- // of a keyword line decides what the model gets to match against. An
759- // author cannot see that from their own file.
760- if cut := skills.Truncated(set.skills); len(cut) > 0 {
761- info.Warnings = append(info.Warnings,
762- fmt.Sprintf("keywords truncated for %s — only the first ones reach the model, so put the most distinctive first",
763- strings.Join(cut, ", ")))
764- }
765- // Two skills under one name: the catalogue shows it twice and the second
766- // is unreachable, since a lookup always returns the first.
767- if dup := skills.Duplicates(set.skills); len(dup) > 0 {
768- info.Warnings = append(info.Warnings,
769- fmt.Sprintf("two skills share a name (%s) — only the first is reachable", strings.Join(dup, ", ")))
770- }
771- // No tool at all is a legal set-up — a chat with the model — but rarely the
772- // intended one; say so where the "tools:" column would otherwise be empty.
773- if len(toolNames) == 0 && !structuredAgent {
774- info.Warnings = append(info.Warnings,
775- "no tool is declared (bashTool and editTools are both off, and there are no skills): the model can only answer, not act")
776- }
777- info.Warnings = append(info.Warnings, config.Deprecations()...)
778- for _, w := range info.Warnings {
779- say("%s[warning: %s]%s", dim, w, off)
780- }
781- toolCol := strings.Join(toolNames, ", ")
782- switch {
783- case config.Cfg.Decision != nil:
784- toolCol = decisionToolColumn()
785- case structuredAgent:
786- toolCol = "none (structured output: JSON answers)"
787- case toolCol == "":
788- toolCol = "none"
789- }
790- // The version leads the line: it is the first thing anyone is asked for
791- // when something behaves oddly, and the banner is the one output every
792- // front end shows — the window keeps it as the conversation's first line.
793- say("%smm %s | config: %s | provider: %s | model: %s | ctx: %s | tools: %s | %s | %s%s%s%s%s%s",
794- dim, version.Short(), path, e.Backend.Provider, config.Cfg.Model, ctxCol, toolCol, skillsColumn(skillCount), yoloColumn(), agentsMdCol, traceColumn(acpMode), hooksColumn(), routing, off)
795-}
796-
797-// hooksColumn says in the banner which hooks run, per event: a command that
798-// can rewrite prompts or deny tool calls must not act unseen.
799-func hooksColumn() string {
800- if summary := config.Cfg.Hooks.Summary(); summary != "" {
801- return " | hooks: " + summary
802- }
803- return ""
804-}
805-
806-// yoloColumn says in the banner whether the tools run unasked — the one
807-// setting nobody should discover by surprise, in either direction.
808-func yoloColumn() string {
809- if config.Cfg.Yolo {
810- return "yolo: on"
811- }
812- return "yolo: off (tools ask)"
813-}
814-
815-// traceColumn says in the banner that every request and response is being
816-// written to disk — prompts included — and where. In ACP mode a relative
817-// dir is in each session's cwd, which no session has given yet.
818-func traceColumn(acpMode bool) string {
819- if !config.Cfg.Trace.Enabled {
820- return ""
821- }
822- dir := config.Cfg.Trace.Dir
823- if filepath.IsAbs(dir) {
824- return " | trace: " + dir
825- }
826- if acpMode {
827- return " | trace: <session cwd>/" + dir
828- }
829- if abs, err := filepath.Abs(dir); err == nil {
830- dir = abs
831- }
832- return " | trace: " + dir
833-}
834-
835-// commandNames is the slash commands' names, for the shadowing check.
836-func commandNames() []string {
837- var out []string
838- for _, c := range command.All() {
839- out = append(out, c.Name)
840- }
841- return out
842-}
843-
844-// windowMode decides whether the window front end runs, and where the banner
845-// goes. The window owns the screen: the spinner must not draw on it, and
846-// the banner is kept in the returned buffer to be shown INSIDE the window as
847-// its first line. Without a terminal (`mm -tui | tee`) the line mode runs
848-// instead, banner on stdout as usual, after one line saying so.
849-func windowMode(wanted bool) (bool, *bytes.Buffer) {
850- banner := &bytes.Buffer{}
851- if !wanted {
852- return false, banner
853- }
854- if !tui.Terminal() {
855- say("[tui: stdin or stdout is not a terminal — running the line mode]")
856- return false, banner
857- }
858- ui.Out = banner
859- spinner.Disable()
860- return true, banner
861-}
862-
863297 // say prints one line of human-facing text where it belongs (ui.Out). A
864298 // write error to a terminal or a log is nothing the agent can act on.
865299 func say(format string, args ...any) {
@@ -937,21 +371,6 @@ func absJoin(anchor, dir string) string {
937371 return abs
938372 }
939373
940-// skillsColumn is the banner's skills count, and where they come from when
941-// that is not under the current directory (the ticket 231 fallback): a user
942-// who sees skills they did not put in this project should know why.
943-func skillsColumn(count int) string {
944- col := fmt.Sprintf("skills: %d", count)
945- cwd, err := os.Getwd()
946- if count == 0 || err != nil {
947- return col
948- }
949- if rel, err := filepath.Rel(cwd, config.Cfg.SkillsDir); err == nil && !strings.HasPrefix(rel, "..") {
950- return col
951- }
952- return col + " (from " + config.Cfg.SkillsDir + ")"
953-}
954-
955374 // The two variables an mm exports to the commands its bash tool runs, so a
956375 // skill can call this same mm back — `"$MM_BIN" --ask lucy -p …` — with this
957376 // same configuration, without knowing where either lives.
@@ -1049,7 +468,7 @@ func isSbxInit(arg string) bool {
1049468 // Only the first argument is a mode word: `mm agent.yaml tui` still names two
1050469 // config files, and a config file called tui is reached as ./tui.
1051470 func modeWordAsFlag(args []string) []string {
1052- if len(args) < 2 || (args[1] != "tui" && args[1] != "acp" && args[1] != "a2a" && args[1] != "help") {
471+ if len(args) < 2 || !slices.Contains(modeWords, args[1]) {
1053472 return args
1054473 }
1055474 return append([]string{args[0], "-" + args[1]}, args[2:]...)
@@ -30,7 +30,6 @@ import (
30 "bytes"30 "bytes"
31 "context"31 "context"
32 "errors"32 "errors"
33- "flag"
34 "fmt"33 "fmt"
35 "io"34 "io"
36 "os"35 "os"
@@ -41,353 +40,199 @@ import (
41 "time"40 "time"
42 41
43 "mm/internal/acp"42 "mm/internal/acp"
44- "mm/internal/acpcreate"
45 "mm/internal/agent"43 "mm/internal/agent"
46- "mm/internal/agentinit"
47 "mm/internal/ask"44 "mm/internal/ask"
48 "mm/internal/command"45 "mm/internal/command"
49 "mm/internal/config"46 "mm/internal/config"
50 "mm/internal/detector"47 "mm/internal/detector"
51- "mm/internal/dockerinit"
52 "mm/internal/engine"48 "mm/internal/engine"
53 "mm/internal/hooks"49 "mm/internal/hooks"
54- "mm/internal/lsp"
55- "mm/internal/mcp"
56 "mm/internal/metaprompt"50 "mm/internal/metaprompt"
57- "mm/internal/sbxinit"
58- "mm/internal/skillcreate"
59 "mm/internal/skills"51 "mm/internal/skills"
60- "mm/internal/spinner"
61 "mm/internal/tools"52 "mm/internal/tools"
62 "mm/internal/tui"53 "mm/internal/tui"
63 "mm/internal/ui"54 "mm/internal/ui"
64 "mm/internal/version"55 "mm/internal/version"
65- "mm/internal/webmd"
66 56
67 "github.com/firebase/genkit/go/ai"57 "github.com/firebase/genkit/go/ai"
68 )58 )
69 59
70 func main() {60 func main() {
71- ctx := context.Background()61+ // `mm init`, `mm acp-create`, `mm dockerinit`, `mm sbxinit`, `mm a2a-send`
72-62+ // and `mm skillcreate`: answered before anything reads a configuration.
73- // Where the config file is. Same value, three ways to give it, from the most63+ if code, ok := runSubcommand(os.Args); ok {
74- // local to the most ambient:64+ os.Exit(code)
75- //
76- // go run . -config ./fast.yaml (the flag)
77- // go run . ./fast.yaml (a lone argument, handy in a demo)
78- // AGENT_CONFIG=./fast.yaml go run .
79- //
80- // The flag package gives us "-h" for free; a second argument is a typo, and
81- // saying so is better than ignoring it.
82-
83- // `mm init` and `mm --init` (ticket 97): the agent.yaml wizard, with its
84- // own flags, before anything reads a configuration — there is none yet.
85- if len(os.Args) > 1 && isInit(os.Args[1]) {
86- os.Exit(agentinit.Main(os.Args[2:], os.Stdin, os.Stdout, agentinit.Options{Window: tui.RunInit, Terminal: tui.Terminal}))
87- }
88- // `mm acp-create` and `mm --acp-create` (ticket 210): the same wizard
89- // served over ACP, for an editor; no configuration either. stdout is
90- // the protocol's, so its help and errors go to stderr.
91- if len(os.Args) > 1 && acpcreate.Is(os.Args[1]) {
92- os.Exit(acpcreate.Main(os.Args[2:], os.Stdin, os.Stdout, os.Stderr))
93- }
94- // `mm dockerinit` (ticket 189): writes files, before any configuration too.
95- if len(os.Args) > 1 && isDockerInit(os.Args[1]) {
96- os.Exit(dockerinit.Main(os.Args[2:], os.Stdin, os.Stdout))
97- }
98- // `mm sbxinit` (ticket 191): the same, for a Docker Sandbox.
99- if len(os.Args) > 1 && isSbxInit(os.Args[1]) {
100- os.Exit(sbxinit.Main(os.Args[2:], os.Stdin, os.Stdout))
101- }
102- // `mm a2a-send` (ticket 243): one message to an A2A agent, from a script.
103- // No configuration, no model: answered before anything is read.
104- if len(os.Args) > 1 && (os.Args[1] == "a2a-send" || os.Args[1] == "--a2a-send" || os.Args[1] == "-a2a-send") {
105- os.Exit(a2aSendMain(os.Args[2:], os.Stdin, os.Stdout, os.Stderr))
106- }
107- // `mm skillcreate` (ticket 206): a wizard that writes a new skill where
108- // the agent's config reads its skills; it reads the config itself.
109- if len(os.Args) > 1 && isSkillCreate(os.Args[1]) {
110- os.Exit(skillcreate.Main(os.Args[2:], os.Stdin, os.Stdout, skillcreate.Options{Window: tui.RunSkillCreate, Terminal: tui.Terminal}))
111 }65 }
112 // `mm tui` and `mm acp` (ticket 117): the modes as words too, like66 // `mm tui` and `mm acp` (ticket 117): the modes as words too, like
113 // `mm init` — `mm tui agent.yaml` is `mm -tui agent.yaml`. `mm help`67 // `mm init` — `mm tui agent.yaml` is `mm -tui agent.yaml`. `mm help`
114 // (ticket 273) is `mm -help` the same way.68 // (ticket 273) is `mm -help` the same way.
115 os.Args = modeWordAsFlag(os.Args)69 os.Args = modeWordAsFlag(os.Args)
116-70+ cli := parseCommandLine()
117- // Handle --prompt/-p flag which can appear after the config file argument71+ if cli.answered() {
118- // We manually extract it before flag.Parse() so both orders work:
119- // mm --prompt "hello" agent.yaml AND mm agent.yaml --prompt "hello"
120- // The same goes for --ask and --ask-with-context, whose agent name follows
121- // them: `mm agent.yaml --ask lucy -p "…"` must work like the flags-first
122- // order, and flag.Parse stops at the first positional argument.
123- promptArg, askArg, askContextArg := "", "", ""
124- remainingArgs := []string{}
125- for i := 1; i < len(os.Args); i++ {
126- arg := os.Args[i]
127- var target *string
128- switch arg {
129- case "--prompt", "-prompt", "-p":
130- target = &promptArg
131- case "--ask", "-ask":
132- target = &askArg
133- case "--ask-with-context", "-ask-with-context":
134- target = &askContextArg
135- default:
136- remainingArgs = append(remainingArgs, arg)
137- continue
138- }
139- if i+1 < len(os.Args) {
140- *target = os.Args[i+1]
141- i++ // skip the value
142- }
143- }
144- // Replace os.Args for flag.Parse()
145- os.Args = append([]string{os.Args[0]}, remainingArgs...)
146-
147- configPath := flag.String("config", "", "path to the YAML config file (default: $AGENT_CONFIG, then ./agent.yaml, then ./.mm/agent.yaml)")
148- a2aMode := flag.Bool("a2a", false, "serve this agent over the Agent2Agent protocol (A2A, JSON-RPC over HTTP) on a2a.host:a2a.port, 127.0.0.1:9100 by default (same as: mm a2a)")
149- a2aPort := flag.Int("a2a-port", 0, "with -a2a: the port to listen on, instead of a2a.port")
150- flag.Bool("a2a-send", false, "send one message to an A2A agent and print its answer (same as mm a2a-send; mm a2a-send -h for its flags)")
151- acpMode := flag.Bool("acp", false, "serve the Agent Client Protocol on stdio (for Zed, JetBrains, Neovim…) instead of the terminal REPL (same as: mm acp)")
152- tuiMode := flag.Bool("tui", false, "open the single-window mode (conversation above, input box below); falls back to the line mode when stdout is not a terminal (same as: mm tui)")
153- promptMode := flag.String("prompt", "", "run a single prompt and exit")
154- flag.StringVar(promptMode, "p", "", "shorthand for --prompt")
155- showVersion := flag.Bool("version", false, "print the version and exit")
156- showAbout := flag.Bool("about", false, "print what mm is, and exit")
157- // Listed for -h only: `mm --init` is answered before flag.Parse.
158- flag.Bool("init", false, "write a new agent.yaml with a wizard (same as `mm init`; `mm init -h` for its flags)")
159- flag.Bool("acp-create", false, "serve mm init's wizard over the Agent Client Protocol, to create an agent.yaml from an editor (same as mm acp-create; mm acp-create -h for its flags)")
160- flag.Bool("dockerinit", false, "write a Dockerfile and a compose.yaml to run mm in a container (same as mm dockerinit; mm dockerinit -h for its flags)")
161- flag.Bool("skillcreate", false, "write a new skill with a wizard, where the agent reads its skills (same as mm skillcreate; mm skillcreate -h for its flags)")
162- flag.Bool("sbxinit", false, "write a sbxenv.yaml to run mm in a Docker Sandbox (same as mm sbxinit; mm sbxinit -h for its flags)")
163- askAgent := flag.String("ask", "", "ask the agent `name` (a key of mmConfigs) the -p prompt, or stdin; print only its answer on stdout, and exit")
164- askWithContext := flag.String("ask-with-context", "", "same as --ask, with the conversation read from stdin (question with -p, or after a \"---\" line)")
165- flag.Parse()
166-
167- // If prompt was extracted manually, use it (overrides flag value)
168- if promptArg != "" {
169- *promptMode = promptArg
170- }
171- if askArg != "" {
172- *askAgent = askArg
173- }
174- if askContextArg != "" {
175- *askWithContext = askContextArg
176- }
177-
178- // Track if --config was explicitly set via the flag
179- configExplicit := false
180- flag.Visit(func(f *flag.Flag) {
181- if f.Name == "config" {
182- configExplicit = true
183- }
184- })
185- // Answered before anything can go wrong: asking which mm this is must
186- // work without a config file, without a model server, and in a directory
187- // mm knows nothing about. Straight to stdout, not ui.Out — this is the
188- // answer to a question, not part of a session's output.
189- if *showVersion {
190- fmt.Println(version.Long())
191- return
192- }
193- // Same rule as --version: answered before the configuration is looked
194- // for, so it works in any directory with no model server running.
195- if *showAbout {
196- fmt.Println(version.About())
197 return72 return
198 }73 }
199- if *configPath == "" && flag.NArg() > 0 {74+ path := cli.loadConfig()
200- *configPath = flag.Arg(0)75+ ctx := context.Background()
201- }76+ if cli.askName != "" {
202- if configExplicit && flag.NArg() > 0 {77+ os.Exit(runAsk(ctx, cli.askName, cli.askContext, cli.prompt))
203- fail("[usage: --config already specified, got %d extra arguments]", flag.NArg())
204- os.Exit(1)
205- }
206- if flag.NArg() > 1 {
207- fail("[usage: at most one config file, got %d arguments]", flag.NArg())
208- os.Exit(1)
209 }78 }
79+ runAgent(ctx, cli, path)
80+}
210 81
211- // --ask: stdout carries the answer and nothing else, so everything human82+// runAgent runs the agent of the file at path: the engine, the tools, then
212- // goes to stderr, like in ACP mode. With no config named, the config of83+// -p or one of the front ends. Every way out from here on — returning,
213- // the mm whose bash tool runs this command (MM_CONFIG, exported below) is84+// exit(), a signal — runs onExit.
214- // the one whose mmConfigs a skill means.85+func runAgent(ctx context.Context, cli cliOptions, path string) {
215- askName, askContext := *askAgent, false86+ showHooks(cli.acp)
216- if *askWithContext != "" {87+ declareCommands()
217- askName, askContext = *askWithContext, true88+ asker := ask.NewPool()
218- }89+ defer asker.Close()
219- if askName != "" {
220- ui.Out = os.Stderr
221- spinner.Disable()
222- if *configPath == "" {
223- *configPath = os.Getenv(configEnv)
224- }
225- }
226 90
227- // In ACP mode, stdout belongs to JSON-RPC — the spec forbids anything else91+ window, banner := windowMode((cli.tui || config.Cfg.TUI) && !cli.acp && !cli.a2a)
228- // on it. Everything below that prints (banner, warnings, errors) goes
229- // through ui.Out, so ONE move sends it all to stderr, where the editor's
230- // agent logs pick it up. The spinner is silenced outright: supported()
231- // cannot tell "a terminal" from "a terminal used as a protocol pipe".
232- if *acpMode {
233- ui.Out = os.Stderr
234- spinner.Disable()
235- }
236 92
237- // Settings: built-in defaults, overridden by the agent file.93+ // onExit: the model's unload (unloadOnExit, ticket 255), then the lease on
238- path, err := config.Load(*configPath)94+ // the server mm started (llamacpp.autoStart, ticket 223;
239- if err != nil {95+ // razorbill.autoStart, ticket 264).
240- fail("[config error: %v ]", err)96+ defer onExit.run()
241- os.Exit(1)97+ // autoStart: nothing answers at the agent's address, mm starts
242- }98+ // llama-server or rzb and waits for the model — before the engine picks
243- // No agent file found: stop rather than run a built-in model on a99+ // its address, so it finds the server it started. It handles a signal
244- // built-in server the user never chose (ticket 220). Every mode that100+ // during the start itself; the watch starts after.
245- // reaches this point talks to a model; the commands that write the101+ onExit.release = startLocalServer(ctx, cli.acp).Release
246- // files (init, acp-create, skillcreate, dockerinit, sbxinit) and102+ defer watchExitSignals(onExit, cli.prompt != "")()
247- // --version / --about were answered before.103+
248- if path == "" {104+ e := startEngine(ctx, cli.acp, asker)
249- fail("%s", noAgentFile())105+ s := agentSession{e: e, detector: newLoopDetector(), asker: asker}
250- os.Exit(1)106+ set := s.assemble()
251- }107+ defer set.close()
252-108+ s.tools = set.tools
253- // Where a relative skillsDir points depends on who started mm. From a
254- // terminal, it is the directory mm was started from — an installed mm
255- // (/usr/local/bin) run inside a project loads THAT project's skills. The
256- // editor launches mm with ITS working directory, so in ACP mode with a
257- // config file the anchor is that file — the one path the user actually
258- // named (env AGENT_CONFIG in the editor's settings). Either way the path
259- // is made absolute here, so the banner can say exactly where it looked.
260- config.Cfg.SkillsDir = resolveSkillsDir(config.Cfg.SkillsDir, path, *acpMode)
261- exportSelf(path)
262 109
263- if askName != "" {110+ if s.runPrompt(ctx, cli.prompt, set) {
264- os.Exit(runAsk(ctx, askName, askContext, *promptMode))111+ return
265 }112 }
266- showHooks(*acpMode)113+ printBanner(ctx, e, path, set, cli.acp)
114+ s.runFrontEnd(ctx, cli, window, banner)
115+}
267 116
268- // The other agents this one can ask (`mmConfigs`): their /ask-<name>117+// declareCommands puts in the shared command table what the file enables:
269- // commands join the shared table before any front end reads it, and their118+// the other agents this one can ask (`mmConfigs`: /ask-<name>, their
270- // processes start on the first ask and stop when this one exits.119+// processes start on the first ask and stop when this one exits), the A2A
120+// agents, /unload, /memory, /docs.
121+func declareCommands() {
271 command.SetAgents(config.AgentNames())122 command.SetAgents(config.AgentNames())
272 command.SetA2AAgents(config.A2AAgentNames())123 command.SetA2AAgents(config.A2AAgentNames())
273 command.SetUnload(config.Cfg.UnloadModels)124 command.SetUnload(config.Cfg.UnloadModels)
274 command.SetMemory(config.Cfg.Sessions.MemoryCommand())125 command.SetMemory(config.Cfg.Sessions.MemoryCommand())
275 command.SetDocs(config.Cfg.DocSearch.DocsCommand())126 command.SetDocs(config.Cfg.DocSearch.DocsCommand())
276- asker := ask.NewPool()127+}
277- defer asker.Close()
278-
279- window, banner := windowMode((*tuiMode || config.Cfg.TUI) && !*acpMode && !*a2aMode)
280-
281- // Every way out from here on — main returning, exit(), a signal — runs
282- // onExit: the model's unload (unloadOnExit, ticket 255), then the
283- // lease on the server mm started (llamacpp.autoStart, ticket 223;
284- // razorbill.autoStart, ticket 264).
285- defer onExit.run()
286- // autoStart: nothing answers at the agent's address, mm starts
287- // llama-server or rzb and waits for the model — before the engine
288- // picks its address, so it finds the server it started. It handles a
289- // signal during the start itself; the watch starts after.
290- onExit.release = startLocalServer(ctx, *acpMode).Release
291- defer watchExitSignals(onExit, *promptMode != "")()
292 128
129+// startEngine builds the engine, downloads the missing models (autoPull,
130+// ticket 61, the progress on stderr), arms the unload on exit, and gives the
131+// pool its unloads (mmConfigs.<name>.unloadModels, ticket 161: this agent's
132+// model before the hand-off, the asked agent's after it). A failure ends mm.
133+func startEngine(ctx context.Context, acpMode bool, asker *ask.Pool) *engine.Engine {
293 e, err := engine.New(ctx)134 e, err := engine.New(ctx)
294- if err != nil {135+ if err == nil {
295- fail("[engine error: %v ]", err)136+ err = autoPull(ctx, e, os.Stderr, stderrIsTerminal())
296- exit(1)
297 }137 }
298- // autoPull (ticket 61): the missing models are downloaded before the138+ if err != nil {
299- // agent is ready, the progress on stderr.
300- if err := autoPull(ctx, e, os.Stderr, stderrIsTerminal()); err != nil {
301 fail("[engine error: %v ]", err)139 fail("[engine error: %v ]", err)
302 exit(1)140 exit(1)
303 }141 }
304- onExit.arm(e, *acpMode)142+ onExit.arm(e, acpMode)
305-
306- // mmConfigs.<name>.unloadModels (ticket 161): the pool frees this
307- // agent's model before the hand-off, the asked agent's after it.
308 asker.SetUnloads(ask.Unloads{143 asker.SetUnloads(ask.Unloads{
309 Asker: func(ctx context.Context) string { return e.Unload(ctx, "") },144 Asker: func(ctx context.Context) string { return e.Unload(ctx, "") },
310 Asked: engine.UnloadAgent,145 Asked: engine.UnloadAgent,
311 })146 })
312-
313 // bashBackground: stop (ticket 228) — the process groups a turn's commands147 // bashBackground: stop (ticket 228) — the process groups a turn's commands
314 // left running are stopped once the turn is over, in every front end.148 // left running are stopped once the turn is over, in every front end.
315 engine.OnTurnEnd(func() { tools.StopBackground() })149 engine.OnTurnEnd(func() { tools.StopBackground() })
150+ return e
151+}
152+
153+// newLoopDetector: the same call with the same result three times in a row
154+// is flagged (the model is told to change approach); three flagged repeats
155+// more — six identical calls — and the turn is stopped, since a model that
156+// ignored the advice three times will not read it a fourth time (seen on
157+// 2026-09-18: 30 identical refused edits before the user pressed Escape).
158+// Every flagged repeat is also shown to the user (ticket 153), and so is a
159+// run of three failed calls or more with different inputs (ticket 160).
160+func newLoopDetector() *detector.LoopDetector {
161+ return detector.NewLoopDetector(10, 3).WithStop(3).WithFailures(3).WithReport(reportLoop)
162+}
316 163
317- // The loop detector: the same call with the same result three times in a164+// agentSession is what every front end runs on: the engine, the tools, the loop
318- // row is flagged (the model is told to change approach); three flagged165+// detector and the pool of other agents.
319- // repeats more — six identical calls — and the turn is stopped, since a166+type agentSession struct {
320- // model that ignored the advice three times will not read it a fourth167+ e *engine.Engine
321- // time (seen on 2026-09-18: 30 identical refused edits before the user168+ tools []ai.ToolRef
322- // pressed Escape).169+ detector *detector.LoopDetector
323- // Every flagged repeat is also shown to the user (ticket 153), and so is170+ asker *ask.Pool
324- // a run of three failed calls or more with different inputs (ticket 160).171+}
325- loopDetector := detector.NewLoopDetector(10, 3).WithStop(3).WithFailures(3).WithReport(reportLoop)
326 172
327- // A decider answers with its decision model: no tool is ever called.173+// assemble builds the tool set and the routers. A decider declares no tool
328- // Checked before the tools are assembled, so no MCP or language server174+// source (checked before the tools are assembled, so no MCP or language
329- // is started for a file that is about to be refused.175+// server is started for a file about to be refused); a structuredOutput
176+// leaves no room for a tool call. A refusal ends mm.
177+func (s agentSession) assemble() toolSet {
330 if err := config.DecisionConflict(); err != nil {178 if err := config.DecisionConflict(); err != nil {
331 fail("[config error: %v ]", err)179 fail("[config error: %v ]", err)
332 exit(1)180 exit(1)
333 }181 }
334- set := assembleTools(e, loopDetector, asker)182+ set := assembleTools(s.e, s.detector, s.asker)
335- defer set.close()183+ err := config.StructuredOutputConflict(set.names)
336- // A structuredOutput constrains every answer: no room for a tool call.184+ if err == nil {
337- if err := config.StructuredOutputConflict(set.names); err != nil {185+ err = installRouter()
338- fail("[config error: %v ]", err)
339- set.close()
340- exit(1)
341 }186 }
342- if err := installRouter(); err != nil {187+ if err != nil {
343 fail("[config error: %v ]", err)188 fail("[config error: %v ]", err)
344 set.close()189 set.close()
345 exit(1)190 exit(1)
346 }191 }
347- agentTools := set.tools
348 set.warnings = append(set.warnings, ask.Missing()...)192 set.warnings = append(set.warnings, ask.Missing()...)
349 set.warnings = append(set.warnings, config.Cfg.PromptWarnings()...)193 set.warnings = append(set.warnings, config.Cfg.PromptWarnings()...)
194+ return set
195+}
350 196
351- // Handle prompt mode: run a single prompt and exit197+// runPrompt runs -p — a decider's JSON, a structured answer, or a plain
352- if *promptMode != "" && e.IsDecider() {198+// turn — and reports whether it did. No banner, no session persistence. A
199+// failed generation exits 1 (ticket 224); os.Exit skips the deferred
200+// cleanups, so they run first.
201+func (s agentSession) runPrompt(ctx context.Context, prompt string, set toolSet) bool {
202+ switch {
203+ case prompt == "":
204+ return false
205+ case s.e.IsDecider():
353 ui.Out = os.Stderr206 ui.Out = os.Stderr
354- exit(runDecisionPrompt(ctx, e, *promptMode, os.Stdout))207+ exit(runDecisionPrompt(ctx, s.e, prompt, os.Stdout))
355- }208+ case config.Cfg.OutputSchema != nil:
356- if *promptMode != "" && config.Cfg.OutputSchema != nil {209+ exit(runStructuredPrompt(ctx, s.e, prompt))
357- exit(runStructuredPrompt(ctx, e, *promptMode))
358 }210 }
359- if *promptMode != "" {211+ if code := agent.RunPrompt(ctx, s.e, config.Cfg.System, s.tools, s.detector, prompt); code != 0 {
360- // In prompt mode, no banner, no session persistence. A failed212+ set.close()
361- // generation exits 1 (ticket 224); os.Exit skips the deferred213+ s.asker.Close()
362- // cleanups, so they run first.214+ exit(code)
363- if code := agent.RunPrompt(ctx, e, config.Cfg.System, agentTools, loopDetector, *promptMode); code != 0 {
364- set.close()
365- asker.Close()
366- exit(code)
367- }
368- return
369 }215 }
216+ return true
217+}
370 218
371- printBanner(ctx, e, path, set, *acpMode)219+// runFrontEnd runs the front end the command line asks for. Three front
372-220+// ends, one wiring: config, engine, tools, detector are strictly identical
373- // Three front ends, one wiring: everything above — config, engine, tools,221+// whichever loop runs.
374- // detector — is strictly identical whichever loop runs below.222+func (s agentSession) runFrontEnd(ctx context.Context, cli cliOptions, window bool, banner *bytes.Buffer) {
375- if *acpMode {223+ switch {
376- acp.Run(ctx, e, config.Cfg.System, agentTools, loopDetector, asker)224+ case cli.acp:
377- return225+ acp.Run(ctx, s.e, config.Cfg.System, s.tools, s.detector, s.asker)
378- }226+ case cli.a2a:
379- if *a2aMode {227+ if err := runA2A(ctx, s.e, config.Cfg.System, s.tools, cli.a2aPort); err != nil {
380- if err := runA2A(ctx, e, config.Cfg.System, agentTools, *a2aPort); err != nil {
381 fail("[a2a: %v ]", err)228 fail("[a2a: %v ]", err)
382 exit(1)229 exit(1)
383 }230 }
384- return231+ case window:
385- }232+ runWindow(ctx, s, strings.TrimSpace(banner.String()))
386- if window {233+ default:
387- runWindow(ctx, e, agentTools, loopDetector, strings.TrimSpace(banner.String()), asker)234+ agent.Run(ctx, s.e, config.Cfg.System, s.tools, s.detector, s.asker)
388- return
389 }235 }
390- agent.Run(ctx, e, config.Cfg.System, agentTools, loopDetector, asker)
391 }236 }
392 237
393 // showHooks installs, when displayHooks is on, what every hook run goes to:238 // showHooks installs, when displayHooks is on, what every hook run goes to:
@@ -417,7 +262,8 @@ func runStructuredPrompt(ctx context.Context, e *engine.Engine, prompt string) i
417 262
418 // runWindow starts the single-window front end, falling back to the line263 // runWindow starts the single-window front end, falling back to the line
419 // mode — banner first — if the terminal cannot be opened after all.264 // mode — banner first — if the terminal cannot be opened after all.
420-func runWindow(ctx context.Context, e *engine.Engine, agentTools []ai.ToolRef, d *detector.LoopDetector, banner string, asker ask.Runner) {265+func runWindow(ctx context.Context, s agentSession, banner string) {
266+ e, agentTools, d, asker := s.e, s.tools, s.detector, s.asker
421 cwd, _ := os.Getwd()267 cwd, _ := os.Getwd()
422 err := tui.Run(ctx, tui.Options{268 err := tui.Run(ctx, tui.Options{
423 Model: e,269 Model: e,
@@ -448,418 +294,6 @@ func runWindow(ctx context.Context, e *engine.Engine, agentTools []ai.ToolRef, d
448 agent.Run(ctx, e, config.Cfg.System, agentTools, d, asker)294 agent.Run(ctx, e, config.Cfg.System, agentTools, d, asker)
449 }295 }
450 296
451-// toolSet is what assembleTools hands main: the tools, their names for the
452-// banner, the skill count, the warnings the banner must show, and what to
453-// stop at exit (the language servers).
454-type toolSet struct {
455- tools []ai.ToolRef
456- names []string
457- skillCount int
458- // skills is the catalogue itself, kept so the banner can say what is
459- // wrong with it and not only how many there are.
460- skills []skills.Skill
461- warnings []string
462- close func()
463-}
464-
465-// assembleTools declares the tools every front end gets: `bash` unless
466-// `bashTool: false` turned it off; `read_skill` only when the skills
467-// directory holds something to read (its
468-// description carries the catalogue, so declaring it empty would advertise a
469-// tool that can do nothing); the file tools behind `editTools` — the same
470-// binary must run as part 09 did (bash + the `edit` CLI) and as this part
471-// (built-in tools), so the two can be compared on the same prompts;
472-// `fetch_content` behind `fetchContentTool`, off by default because it is the
473-// one built-in tool that reaches the network; and `lsp` when `lsp.servers` names at least one server whose command is on
474-// the PATH — a missing server is a warning, never a refusal to start; and
475-// `ask_agent` when mmConfigs names at least one agent, over the same pool as
476-// /ask; `ask_user` behind `askUserTool` (on by default), never with a
477-// structuredOutput; `save_answer` behind `saveAnswerTool` (off by default);
478-// `search_memory` behind `sessions.autoSearchMemory` (off by default, sessions on);
479-// `search_docs` behind `docSearch.autoSearchDocs` (off by default);
480-// and the agent file's declared `tools:`.
481-//
482-// A decider gets none of them, whatever bashTool, editTools, skillsDir… say
483-// (ticket 141): its model never calls a tool, so a decider file needs no
484-// `…: false` lines. What only a deliberate entry declares (mcp, lsp,
485-// mmConfigs, tools:) is refused earlier by config.DecisionConflict.
486-func assembleTools(e *engine.Engine, d *detector.LoopDetector, asker tools.AgentAsker) toolSet {
487- set := toolSet{close: func() {}}
488- if config.Cfg.Decision != nil {
489- engine.DeclareSkills(false)
490- skills.Declare(nil)
491- return set
492- }
493- if config.Cfg.BashTool {
494- set.tools = append(set.tools, tools.Bash(e.G, d))
495- set.names = append(set.names, "bash")
496- }
497- set.skills = skills.List(config.Cfg.SkillsDir)
498- set.skillCount = len(set.skills)
499- // The turn recap shows `📖 0 skill(s)` only where a skill could have been
500- // used — see engine.SkillsAvailable.
501- engine.DeclareSkills(set.skillCount > 0)
502- // The catalogue every front end resolves `$skill` against.
503- skills.Declare(set.skills)
504- if skillTool := tools.ReadSkill(e.G, config.Cfg.SkillsDir, d); skillTool != nil {
505- set.tools = append(set.tools, skillTool)
506- set.names = append(set.names, "read_skill")
507- }
508- if config.Cfg.EditTools {
509- set.tools = append(set.tools,
510- tools.ReadFile(e.G, d),
511- tools.WriteFile(e.G, d),
512- tools.EditFile(e.G, d))
513- set.names = append(set.names, "read_file", "write_file", "edit_file")
514- }
515- if config.Cfg.PlanTool {
516- set.tools = append(set.tools, tools.PlanTool(e.G, d))
517- set.names = append(set.names, "plan")
518- }
519- // Not for an agent with a structuredOutput: it answers once, in JSON, and
520- // declaring a tool would stop it from starting (StructuredOutputConflict)
521- // — the existing structured agents would all break on a default.
522- if config.Cfg.AskUserTool && config.Cfg.OutputSchema == nil {
523- set.tools = append(set.tools, tools.AskUser(e.G, d))
524- set.names = append(set.names, "ask_user")
525- }
526- if config.Cfg.SaveAnswerTool {
527- set.tools = append(set.tools, tools.SaveAnswer(e.G, d))
528- set.names = append(set.names, "save_answer")
529- }
530- if config.Cfg.UnloadModels && config.Cfg.OutputSchema == nil {
531- set.tools = append(set.tools, tools.UnloadModel(e.G, d, e.Unload))
532- set.names = append(set.names, "unload_model")
533- }
534- if config.Cfg.FetchContentTool {
535- // The product token "mm" is what the sites' robots.txt are read for.
536- fetcher := webmd.NewFetcher("mm/" + version.Short())
537- set.tools = append(set.tools, tools.FetchContent(e.G, d, fetcher))
538- set.names = append(set.names, "fetch_content")
539- }
540- if config.Cfg.DocSearch.DocsTool() {
541- set.tools = append(set.tools, tools.SearchDocs(e.G, d))
542- set.names = append(set.names, "search_docs")
543- }
544- if config.Cfg.Sessions.MemoryTool() {
545- set.tools = append(set.tools, tools.SearchMemory(e.G, d))
546- set.names = append(set.names, "search_memory")
547- }
548- if w := config.Cfg.Sessions.MemoryWarning(); w != "" {
549- set.warnings = append(set.warnings, w)
550- }
551- if len(config.Cfg.MMConfigs) > 0 {
552- set.tools = append(set.tools, tools.AskAgent(e.G, d, asker))
553- set.names = append(set.names, "ask_agent")
554- }
555- // a2a.agents (ticket 243): the remote A2A agents the model can talk to.
556- if len(config.Cfg.A2A.Agents) > 0 {
557- set.tools = append(set.tools, tools.AskA2AAgent(e.G, d))
558- set.names = append(set.names, "ask_a2a_agent")
559- }
560- assembleLSP(e, d, &set)
561- assembleMCP(e, d, &set)
562- assembleDeclared(e, d, &set)
563- return set
564-}
565-
566-// assembleDeclared adds the agent file's `tools:` entries (ticket 88). They
567-// come last because an MCP tool's name is only known once its server
568-// answered: a declared tool that would take an MCP tool's name is skipped
569-// with a warning, never an error — the agent still starts. A built-in name
570-// cannot clash: the config refuses it at load.
571-func assembleDeclared(e *engine.Engine, d *detector.LoopDetector, set *toolSet) {
572- for _, t := range config.Cfg.Tools {
573- if slices.Contains(set.names, t.Name) {
574- set.warnings = append(set.warnings, fmt.Sprintf("tools: %s skipped — an MCP tool already has that name", t.Name))
575- continue
576- }
577- set.tools = append(set.tools, tools.DeclaredTool(e.G, d, t))
578- set.names = append(set.names, t.Name)
579- }
580-}
581-
582-// assembleLSP adds the `lsp` tool over the configured servers that exist.
583-// The servers are not started here — each starts on its first use — but
584-// the client is created now so main can stop them at exit. The project root
585-// the servers get is the directory mm runs in; an editor launches mm in the
586-// project it opened.
587-func assembleLSP(e *engine.Engine, d *detector.LoopDetector, set *toolSet) {
588- servers := config.Cfg.LSP.Servers
589- if len(servers) == 0 {
590- return
591- }
592- ok, missing := lsp.Available(servers)
593- for _, m := range missing {
594- set.warnings = append(set.warnings, fmt.Sprintf("lsp server %s not found on the PATH — skipped", m))
595- }
596- if len(ok) == 0 {
597- set.warnings = append(set.warnings, "lsp: none of the configured servers is on the PATH — the lsp tool is not declared")
598- return
599- }
600- cwd, _ := os.Getwd()
601- client := lsp.New(cwd, ok)
602- set.tools = append(set.tools, tools.LSP(e.G, d, client, ok))
603- // lsp.diagnosticsAfterEdit / diagnosticsAfterRead (tickets 227, 245):
604- // the file tools ask the same servers after a change or a read.
605- tools.SetEditDiagnostics(client, ok)
606- set.names = append(set.names, "lsp")
607- set.close = client.Close
608-}
609-
610-// assembleMCP adds MCP tools from configured servers.
611-// MCP discovery runs at startup (not lazy) and creates a static tool list.
612-// All MCP tools are wrapped to respect mini-me's safety contracts.
613-func assembleMCP(e *engine.Engine, d *detector.LoopDetector, set *toolSet) {
614- // Skip if MCP is disabled
615- if !config.Cfg.MCP.Enabled {
616- return
617- }
618-
619- // Check for sbx MCP gateway - if present, add it as a server
620- // sbx injects MCP_GATEWAY_URL and handles OAuth tokens via its gateway
621- // The gateway substitutes sentinel tokens with real OAuth tokens
622- gatewayURL := os.Getenv("MCP_GATEWAY_URL")
623-
624- servers := config.Cfg.MCP.Servers
625-
626- // If gateway URL is set and no servers configured, use gateway only
627- // If gateway URL is set and servers configured, add gateway as additional server
628- if gatewayURL != "" {
629- gatewayServer := config.MCPServer{
630- Name: "sbx-gateway",
631- Transport: "http",
632- URL: gatewayURL,
633- Timeout: config.Cfg.MCP.DiscoveryTimeout,
634- Auth: config.MCPAuthConfig{
635- Type: "bearer",
636- TokenEnv: "MCP_SENTINEL_TOKEN_NAME", // sbx injects this, not MCP_GATEWAY_TOKEN
637- },
638- Headers: map[string]string{
639- "Accept": "application/json, text/event-stream",
640- },
641- }
642-
643- // If no servers configured, use gateway only
644- if len(servers) == 0 {
645- servers = []config.MCPServer{gatewayServer}
646- } else {
647- // Add gateway as first server (prefer gateway tools)
648- servers = append([]config.MCPServer{gatewayServer}, servers...)
649- }
650- } else if len(servers) == 0 {
651- set.warnings = append(set.warnings, "mcp: enabled but no servers configured")
652- return
653- }
654-
655- // Create a context with discovery timeout
656- ctx, cancel := context.WithTimeout(context.Background(), config.Cfg.MCP.DiscoveryTimeout)
657- defer cancel()
658-
659- // Connect to all servers and discover tools
660- clients, warnings, err := mcp.ConnectAll(ctx, servers)
661- if err != nil {
662- set.warnings = append(set.warnings, fmt.Sprintf("mcp: connection/discovery failed: %v", err))
663- return
664- }
665-
666- // Add any discovery warnings
667- set.warnings = append(set.warnings, warnings...)
668-
669- // Check for name collisions
670- if len(clients) > 0 {
671- collisions := mcp.CheckCollisions(clients)
672- if len(collisions) > 0 {
673- set.warnings = append(set.warnings, collisions...)
674- // Close clients and return - collisions are fatal
675- mcp.CloseAll(clients)
676- return
677- }
678- }
679-
680- // Wrap all MCP tools
681- mcpToolRefs, mcpNames, mcpWarnings, err := tools.MCP(e.G, d, clients)
682- if err != nil {
683- set.warnings = append(set.warnings, fmt.Sprintf("mcp: tool wrapping failed: %v", err))
684- mcp.CloseAll(clients)
685- return
686- }
687-
688- // Add any MCP-specific warnings
689- if len(mcpWarnings) > 0 {
690- set.warnings = append(set.warnings, mcpWarnings...)
691- }
692-
693- // Add MCP tools to the set
694- set.tools = append(set.tools, mcpToolRefs...)
695- set.names = append(set.names, mcpNames...)
696-
697- // Chain close functions
698- oldClose := set.close
699- set.close = func() {
700- mcp.CloseAll(clients)
701- oldClose()
702- }
703-}
704-
705-// printBanner probes the server and prints the warnings and the one-line
706-// banner. The probe runs before the banner so its warnings sit right under
707-// the prompt they explain; it never stops the agent — on a demo machine the
708-// server is often started AFTER the agent.
709-func printBanner(ctx context.Context, e *engine.Engine, path string, set toolSet, acpMode bool) {
710- toolNames, skillCount := set.names, set.skillCount
711- info := e.Probe(ctx)
712- info.Warnings = append(info.Warnings, set.warnings...)
713- ctxCol := "unknown"
714- if info.ContextWindow > 0 {
715- ctxCol = fmt.Sprintf("%d (%s)", info.ContextWindow, info.ContextSource)
716- }
717- // Dimmed on a terminal, plain in a pipe: the agent's output is meant to be
718- // consumed by another program as much as it is meant to be read.
719- dim, off := "", ""
720- if spinner.Styled() {
721- dim, off = "\033[2m", "\033[0m"
722- }
723- // The compression's own warning belongs with the provider's: it is the
724- // same kind of advice, and it depends on what the probe just learned.
725- if c := config.Cfg.Context; c.Enabled && e.ContextWindow == 0 && c.MaxMessages == 0 {
726- info.Warnings = append(info.Warnings,
727- "context compression is on, but the context window is unknown and context.maxMessages is 0 — it will never trigger (set contextWindow, or maxMessages)")
728- }
729- // "skills: 0" alone sends people hunting; the resolved path says at once
730- // whether mm looked in the wrong place or found the right one empty.
731- // An agent with a structuredOutput has neither tools nor skills on
732- // purpose (config.StructuredOutputConflict): nothing to warn about.
733- // A decider has neither on purpose either (assembleTools, ticket 141).
734- structuredAgent := config.Cfg.OutputSchema != nil || config.Cfg.Decision != nil
735- agentsMdCol, agentsMdWarnings := agentsMdBanner(acpMode, info.ContextWindow)
736- info.Warnings = append(info.Warnings, agentsMdWarnings...)
737- if skillCount == 0 && !structuredAgent {
738- info.Warnings = append(info.Warnings,
739- fmt.Sprintf("no skills found in %s (expected <name>.md or <name>/SKILL.md there)", config.Cfg.SkillsDir))
740- }
741- // A skill with no description reaches the catalogue as a bare name, which
742- // is the worst entry there is: the model has nothing to match a request
743- // against, and the failure is silent — the count is not zero, so the
744- // warning above never fires.
745- if bare := skills.Undescribed(set.skills); len(bare) > 0 {
746- info.Warnings = append(info.Warnings,
747- fmt.Sprintf("%d skill(s) with no description (%s) — the model sees only the name and will pick blindly",
748- len(bare), strings.Join(bare, ", ")))
749- }
750- // A skill whose name a slash command owns is unreachable from an editor's
751- // command menu, and nothing else would say so.
752- if shadowed := skills.Shadowed(set.skills, commandNames()); len(shadowed) > 0 {
753- info.Warnings = append(info.Warnings,
754- fmt.Sprintf("skill(s) named like a slash command (%s) — reachable as $%s in a question, but not from an editor's / menu",
755- strings.Join(shadowed, ", "), shadowed[0]))
756- }
757- // Only the first maxKeywords of a list reach the catalogue, so the order
758- // of a keyword line decides what the model gets to match against. An
759- // author cannot see that from their own file.
760- if cut := skills.Truncated(set.skills); len(cut) > 0 {
761- info.Warnings = append(info.Warnings,
762- fmt.Sprintf("keywords truncated for %s — only the first ones reach the model, so put the most distinctive first",
763- strings.Join(cut, ", ")))
764- }
765- // Two skills under one name: the catalogue shows it twice and the second
766- // is unreachable, since a lookup always returns the first.
767- if dup := skills.Duplicates(set.skills); len(dup) > 0 {
768- info.Warnings = append(info.Warnings,
769- fmt.Sprintf("two skills share a name (%s) — only the first is reachable", strings.Join(dup, ", ")))
770- }
771- // No tool at all is a legal set-up — a chat with the model — but rarely the
772- // intended one; say so where the "tools:" column would otherwise be empty.
773- if len(toolNames) == 0 && !structuredAgent {
774- info.Warnings = append(info.Warnings,
775- "no tool is declared (bashTool and editTools are both off, and there are no skills): the model can only answer, not act")
776- }
777- info.Warnings = append(info.Warnings, config.Deprecations()...)
778- for _, w := range info.Warnings {
779- say("%s[warning: %s]%s", dim, w, off)
780- }
781- toolCol := strings.Join(toolNames, ", ")
782- switch {
783- case config.Cfg.Decision != nil:
784- toolCol = decisionToolColumn()
785- case structuredAgent:
786- toolCol = "none (structured output: JSON answers)"
787- case toolCol == "":
788- toolCol = "none"
789- }
790- // The version leads the line: it is the first thing anyone is asked for
791- // when something behaves oddly, and the banner is the one output every
792- // front end shows — the window keeps it as the conversation's first line.
793- say("%smm %s | config: %s | provider: %s | model: %s | ctx: %s | tools: %s | %s | %s%s%s%s%s%s",
794- dim, version.Short(), path, e.Backend.Provider, config.Cfg.Model, ctxCol, toolCol, skillsColumn(skillCount), yoloColumn(), agentsMdCol, traceColumn(acpMode), hooksColumn(), routing, off)
795-}
796-
797-// hooksColumn says in the banner which hooks run, per event: a command that
798-// can rewrite prompts or deny tool calls must not act unseen.
799-func hooksColumn() string {
800- if summary := config.Cfg.Hooks.Summary(); summary != "" {
801- return " | hooks: " + summary
802- }
803- return ""
804-}
805-
806-// yoloColumn says in the banner whether the tools run unasked — the one
807-// setting nobody should discover by surprise, in either direction.
808-func yoloColumn() string {
809- if config.Cfg.Yolo {
810- return "yolo: on"
811- }
812- return "yolo: off (tools ask)"
813-}
814-
815-// traceColumn says in the banner that every request and response is being
816-// written to disk — prompts included — and where. In ACP mode a relative
817-// dir is in each session's cwd, which no session has given yet.
818-func traceColumn(acpMode bool) string {
819- if !config.Cfg.Trace.Enabled {
820- return ""
821- }
822- dir := config.Cfg.Trace.Dir
823- if filepath.IsAbs(dir) {
824- return " | trace: " + dir
825- }
826- if acpMode {
827- return " | trace: <session cwd>/" + dir
828- }
829- if abs, err := filepath.Abs(dir); err == nil {
830- dir = abs
831- }
832- return " | trace: " + dir
833-}
834-
835-// commandNames is the slash commands' names, for the shadowing check.
836-func commandNames() []string {
837- var out []string
838- for _, c := range command.All() {
839- out = append(out, c.Name)
840- }
841- return out
842-}
843-
844-// windowMode decides whether the window front end runs, and where the banner
845-// goes. The window owns the screen: the spinner must not draw on it, and
846-// the banner is kept in the returned buffer to be shown INSIDE the window as
847-// its first line. Without a terminal (`mm -tui | tee`) the line mode runs
848-// instead, banner on stdout as usual, after one line saying so.
849-func windowMode(wanted bool) (bool, *bytes.Buffer) {
850- banner := &bytes.Buffer{}
851- if !wanted {
852- return false, banner
853- }
854- if !tui.Terminal() {
855- say("[tui: stdin or stdout is not a terminal — running the line mode]")
856- return false, banner
857- }
858- ui.Out = banner
859- spinner.Disable()
860- return true, banner
861-}
862-
863 // say prints one line of human-facing text where it belongs (ui.Out). A297 // say prints one line of human-facing text where it belongs (ui.Out). A
864 // write error to a terminal or a log is nothing the agent can act on.298 // write error to a terminal or a log is nothing the agent can act on.
865 func say(format string, args ...any) {299 func say(format string, args ...any) {
@@ -937,21 +371,6 @@ func absJoin(anchor, dir string) string {
937 return abs371 return abs
938 }372 }
939 373
940-// skillsColumn is the banner's skills count, and where they come from when
941-// that is not under the current directory (the ticket 231 fallback): a user
942-// who sees skills they did not put in this project should know why.
943-func skillsColumn(count int) string {
944- col := fmt.Sprintf("skills: %d", count)
945- cwd, err := os.Getwd()
946- if count == 0 || err != nil {
947- return col
948- }
949- if rel, err := filepath.Rel(cwd, config.Cfg.SkillsDir); err == nil && !strings.HasPrefix(rel, "..") {
950- return col
951- }
952- return col + " (from " + config.Cfg.SkillsDir + ")"
953-}
954-
955 // The two variables an mm exports to the commands its bash tool runs, so a374 // The two variables an mm exports to the commands its bash tool runs, so a
956 // skill can call this same mm back — `"$MM_BIN" --ask lucy -p …` — with this375 // skill can call this same mm back — `"$MM_BIN" --ask lucy -p …` — with this
957 // same configuration, without knowing where either lives.376 // same configuration, without knowing where either lives.
@@ -1049,7 +468,7 @@ func isSbxInit(arg string) bool {
1049 // Only the first argument is a mode word: `mm agent.yaml tui` still names two468 // Only the first argument is a mode word: `mm agent.yaml tui` still names two
1050 // config files, and a config file called tui is reached as ./tui.469 // config files, and a config file called tui is reached as ./tui.
1051 func modeWordAsFlag(args []string) []string {470 func modeWordAsFlag(args []string) []string {
1052- if len(args) < 2 || (args[1] != "tui" && args[1] != "acp" && args[1] != "a2a" && args[1] != "help") {471+ if len(args) < 2 || !slices.Contains(modeWords, args[1]) {
1053 return args472 return args
1054 }473 }
1055 return append([]string{args[0], "-" + args[1]}, args[2:]...)474 return append([]string{args[0], "-" + args[1]}, args[2:]...)
added tools_wiring.go +273 -0
new file mode 100644
@@ -0,0 +1,273 @@
1+package main
2+
3+import (
4+ "context"
5+ "fmt"
6+ "mm/internal/config"
7+ "mm/internal/detector"
8+ "mm/internal/engine"
9+ "mm/internal/lsp"
10+ "mm/internal/mcp"
11+ "mm/internal/skills"
12+ "mm/internal/tools"
13+ "mm/internal/version"
14+ "mm/internal/webmd"
15+ "os"
16+ "slices"
17+
18+ "github.com/firebase/genkit/go/ai"
19+)
20+
21+// toolSet is what assembleTools hands main: the tools, their names for the
22+// banner, the skill count, the warnings the banner must show, and what to
23+// stop at exit (the language servers).
24+type toolSet struct {
25+ tools []ai.ToolRef
26+ names []string
27+ skillCount int
28+ // skills is the catalogue itself, kept so the banner can say what is
29+ // wrong with it and not only how many there are.
30+ skills []skills.Skill
31+ warnings []string
32+ close func()
33+}
34+
35+// assembleTools declares the tools every front end gets: `bash` unless
36+// `bashTool: false` turned it off; `read_skill` only when the skills
37+// directory holds something to read (its
38+// description carries the catalogue, so declaring it empty would advertise a
39+// tool that can do nothing); the file tools behind `editTools` — the same
40+// binary must run as part 09 did (bash + the `edit` CLI) and as this part
41+// (built-in tools), so the two can be compared on the same prompts;
42+// `fetch_content` behind `fetchContentTool`, off by default because it is the
43+// one built-in tool that reaches the network; and `lsp` when `lsp.servers` names at least one server whose command is on
44+// the PATH — a missing server is a warning, never a refusal to start; and
45+// `ask_agent` when mmConfigs names at least one agent, over the same pool as
46+// /ask; `ask_user` behind `askUserTool` (on by default), never with a
47+// structuredOutput; `save_answer` behind `saveAnswerTool` (off by default);
48+// `search_memory` behind `sessions.autoSearchMemory` (off by default, sessions on);
49+// `search_docs` behind `docSearch.autoSearchDocs` (off by default);
50+// and the agent file's declared `tools:`.
51+//
52+// A decider gets none of them, whatever bashTool, editTools, skillsDir… say
53+// (ticket 141): its model never calls a tool, so a decider file needs no
54+// `…: false` lines. What only a deliberate entry declares (mcp, lsp,
55+// mmConfigs, tools:) is refused earlier by config.DecisionConflict.
56+func assembleTools(e *engine.Engine, d *detector.LoopDetector, asker tools.AgentAsker) toolSet {
57+ set := toolSet{close: func() {}}
58+ if config.Cfg.Decision != nil {
59+ engine.DeclareSkills(false)
60+ skills.Declare(nil)
61+ return set
62+ }
63+ if config.Cfg.BashTool {
64+ set.tools = append(set.tools, tools.Bash(e.G, d))
65+ set.names = append(set.names, "bash")
66+ }
67+ set.skills = skills.List(config.Cfg.SkillsDir)
68+ set.skillCount = len(set.skills)
69+ // The turn recap shows `📖 0 skill(s)` only where a skill could have been
70+ // used — see engine.SkillsAvailable.
71+ engine.DeclareSkills(set.skillCount > 0)
72+ // The catalogue every front end resolves `$skill` against.
73+ skills.Declare(set.skills)
74+ if skillTool := tools.ReadSkill(e.G, config.Cfg.SkillsDir, d); skillTool != nil {
75+ set.tools = append(set.tools, skillTool)
76+ set.names = append(set.names, "read_skill")
77+ }
78+ if config.Cfg.EditTools {
79+ set.tools = append(set.tools,
80+ tools.ReadFile(e.G, d),
81+ tools.WriteFile(e.G, d),
82+ tools.EditFile(e.G, d))
83+ set.names = append(set.names, "read_file", "write_file", "edit_file")
84+ }
85+ if config.Cfg.PlanTool {
86+ set.tools = append(set.tools, tools.PlanTool(e.G, d))
87+ set.names = append(set.names, "plan")
88+ }
89+ // Not for an agent with a structuredOutput: it answers once, in JSON, and
90+ // declaring a tool would stop it from starting (StructuredOutputConflict)
91+ // — the existing structured agents would all break on a default.
92+ if config.Cfg.AskUserTool && config.Cfg.OutputSchema == nil {
93+ set.tools = append(set.tools, tools.AskUser(e.G, d))
94+ set.names = append(set.names, "ask_user")
95+ }
96+ if config.Cfg.SaveAnswerTool {
97+ set.tools = append(set.tools, tools.SaveAnswer(e.G, d))
98+ set.names = append(set.names, "save_answer")
99+ }
100+ if config.Cfg.UnloadModels && config.Cfg.OutputSchema == nil {
101+ set.tools = append(set.tools, tools.UnloadModel(e.G, d, e.Unload))
102+ set.names = append(set.names, "unload_model")
103+ }
104+ if config.Cfg.FetchContentTool {
105+ // The product token "mm" is what the sites' robots.txt are read for.
106+ fetcher := webmd.NewFetcher("mm/" + version.Short())
107+ set.tools = append(set.tools, tools.FetchContent(e.G, d, fetcher))
108+ set.names = append(set.names, "fetch_content")
109+ }
110+ if config.Cfg.DocSearch.DocsTool() {
111+ set.tools = append(set.tools, tools.SearchDocs(e.G, d))
112+ set.names = append(set.names, "search_docs")
113+ }
114+ if config.Cfg.Sessions.MemoryTool() {
115+ set.tools = append(set.tools, tools.SearchMemory(e.G, d))
116+ set.names = append(set.names, "search_memory")
117+ }
118+ if w := config.Cfg.Sessions.MemoryWarning(); w != "" {
119+ set.warnings = append(set.warnings, w)
120+ }
121+ if len(config.Cfg.MMConfigs) > 0 {
122+ set.tools = append(set.tools, tools.AskAgent(e.G, d, asker))
123+ set.names = append(set.names, "ask_agent")
124+ }
125+ // a2a.agents (ticket 243): the remote A2A agents the model can talk to.
126+ if len(config.Cfg.A2A.Agents) > 0 {
127+ set.tools = append(set.tools, tools.AskA2AAgent(e.G, d))
128+ set.names = append(set.names, "ask_a2a_agent")
129+ }
130+ assembleLSP(e, d, &set)
131+ assembleMCP(e, d, &set)
132+ assembleDeclared(e, d, &set)
133+ return set
134+}
135+
136+// assembleDeclared adds the agent file's `tools:` entries (ticket 88). They
137+// come last because an MCP tool's name is only known once its server
138+// answered: a declared tool that would take an MCP tool's name is skipped
139+// with a warning, never an error — the agent still starts. A built-in name
140+// cannot clash: the config refuses it at load.
141+func assembleDeclared(e *engine.Engine, d *detector.LoopDetector, set *toolSet) {
142+ for _, t := range config.Cfg.Tools {
143+ if slices.Contains(set.names, t.Name) {
144+ set.warnings = append(set.warnings, fmt.Sprintf("tools: %s skipped — an MCP tool already has that name", t.Name))
145+ continue
146+ }
147+ set.tools = append(set.tools, tools.DeclaredTool(e.G, d, t))
148+ set.names = append(set.names, t.Name)
149+ }
150+}
151+
152+// assembleLSP adds the `lsp` tool over the configured servers that exist.
153+// The servers are not started here — each starts on its first use — but
154+// the client is created now so main can stop them at exit. The project root
155+// the servers get is the directory mm runs in; an editor launches mm in the
156+// project it opened.
157+func assembleLSP(e *engine.Engine, d *detector.LoopDetector, set *toolSet) {
158+ servers := config.Cfg.LSP.Servers
159+ if len(servers) == 0 {
160+ return
161+ }
162+ ok, missing := lsp.Available(servers)
163+ for _, m := range missing {
164+ set.warnings = append(set.warnings, fmt.Sprintf("lsp server %s not found on the PATH — skipped", m))
165+ }
166+ if len(ok) == 0 {
167+ set.warnings = append(set.warnings, "lsp: none of the configured servers is on the PATH — the lsp tool is not declared")
168+ return
169+ }
170+ cwd, _ := os.Getwd()
171+ client := lsp.New(cwd, ok)
172+ set.tools = append(set.tools, tools.LSP(e.G, d, client, ok))
173+ // lsp.diagnosticsAfterEdit / diagnosticsAfterRead (tickets 227, 245):
174+ // the file tools ask the same servers after a change or a read.
175+ tools.SetEditDiagnostics(client, ok)
176+ set.names = append(set.names, "lsp")
177+ set.close = client.Close
178+}
179+
180+// assembleMCP adds MCP tools from configured servers.
181+// MCP discovery runs at startup (not lazy) and creates a static tool list.
182+// All MCP tools are wrapped to respect mini-me's safety contracts.
183+func assembleMCP(e *engine.Engine, d *detector.LoopDetector, set *toolSet) {
184+ // Skip if MCP is disabled
185+ if !config.Cfg.MCP.Enabled {
186+ return
187+ }
188+
189+ // Check for sbx MCP gateway - if present, add it as a server
190+ // sbx injects MCP_GATEWAY_URL and handles OAuth tokens via its gateway
191+ // The gateway substitutes sentinel tokens with real OAuth tokens
192+ gatewayURL := os.Getenv("MCP_GATEWAY_URL")
193+
194+ servers := config.Cfg.MCP.Servers
195+
196+ // If gateway URL is set and no servers configured, use gateway only
197+ // If gateway URL is set and servers configured, add gateway as additional server
198+ if gatewayURL != "" {
199+ gatewayServer := config.MCPServer{
200+ Name: "sbx-gateway",
201+ Transport: "http",
202+ URL: gatewayURL,
203+ Timeout: config.Cfg.MCP.DiscoveryTimeout,
204+ Auth: config.MCPAuthConfig{
205+ Type: "bearer",
206+ TokenEnv: "MCP_SENTINEL_TOKEN_NAME", // sbx injects this, not MCP_GATEWAY_TOKEN
207+ },
208+ Headers: map[string]string{
209+ "Accept": "application/json, text/event-stream",
210+ },
211+ }
212+
213+ // If no servers configured, use gateway only
214+ if len(servers) == 0 {
215+ servers = []config.MCPServer{gatewayServer}
216+ } else {
217+ // Add gateway as first server (prefer gateway tools)
218+ servers = append([]config.MCPServer{gatewayServer}, servers...)
219+ }
220+ } else if len(servers) == 0 {
221+ set.warnings = append(set.warnings, "mcp: enabled but no servers configured")
222+ return
223+ }
224+
225+ // Create a context with discovery timeout
226+ ctx, cancel := context.WithTimeout(context.Background(), config.Cfg.MCP.DiscoveryTimeout)
227+ defer cancel()
228+
229+ // Connect to all servers and discover tools
230+ clients, warnings, err := mcp.ConnectAll(ctx, servers)
231+ if err != nil {
232+ set.warnings = append(set.warnings, fmt.Sprintf("mcp: connection/discovery failed: %v", err))
233+ return
234+ }
235+
236+ // Add any discovery warnings
237+ set.warnings = append(set.warnings, warnings...)
238+
239+ // Check for name collisions
240+ if len(clients) > 0 {
241+ collisions := mcp.CheckCollisions(clients)
242+ if len(collisions) > 0 {
243+ set.warnings = append(set.warnings, collisions...)
244+ // Close clients and return - collisions are fatal
245+ mcp.CloseAll(clients)
246+ return
247+ }
248+ }
249+
250+ // Wrap all MCP tools
251+ mcpToolRefs, mcpNames, mcpWarnings, err := tools.MCP(e.G, d, clients)
252+ if err != nil {
253+ set.warnings = append(set.warnings, fmt.Sprintf("mcp: tool wrapping failed: %v", err))
254+ mcp.CloseAll(clients)
255+ return
256+ }
257+
258+ // Add any MCP-specific warnings
259+ if len(mcpWarnings) > 0 {
260+ set.warnings = append(set.warnings, mcpWarnings...)
261+ }
262+
263+ // Add MCP tools to the set
264+ set.tools = append(set.tools, mcpToolRefs...)
265+ set.names = append(set.names, mcpNames...)
266+
267+ // Chain close functions
268+ oldClose := set.close
269+ set.close = func() {
270+ mcp.CloseAll(clients)
271+ oldClose()
272+ }
273+}
new file mode 100644
@@ -0,0 +1,273 @@
1+package main
2+
3+import (
4+ "context"
5+ "fmt"
6+ "mm/internal/config"
7+ "mm/internal/detector"
8+ "mm/internal/engine"
9+ "mm/internal/lsp"
10+ "mm/internal/mcp"
11+ "mm/internal/skills"
12+ "mm/internal/tools"
13+ "mm/internal/version"
14+ "mm/internal/webmd"
15+ "os"
16+ "slices"
17+
18+ "github.com/firebase/genkit/go/ai"
19+)
20+
21+// toolSet is what assembleTools hands main: the tools, their names for the
22+// banner, the skill count, the warnings the banner must show, and what to
23+// stop at exit (the language servers).
24+type toolSet struct {
25+ tools []ai.ToolRef
26+ names []string
27+ skillCount int
28+ // skills is the catalogue itself, kept so the banner can say what is
29+ // wrong with it and not only how many there are.
30+ skills []skills.Skill
31+ warnings []string
32+ close func()
33+}
34+
35+// assembleTools declares the tools every front end gets: `bash` unless
36+// `bashTool: false` turned it off; `read_skill` only when the skills
37+// directory holds something to read (its
38+// description carries the catalogue, so declaring it empty would advertise a
39+// tool that can do nothing); the file tools behind `editTools` — the same
40+// binary must run as part 09 did (bash + the `edit` CLI) and as this part
41+// (built-in tools), so the two can be compared on the same prompts;
42+// `fetch_content` behind `fetchContentTool`, off by default because it is the
43+// one built-in tool that reaches the network; and `lsp` when `lsp.servers` names at least one server whose command is on
44+// the PATH — a missing server is a warning, never a refusal to start; and
45+// `ask_agent` when mmConfigs names at least one agent, over the same pool as
46+// /ask; `ask_user` behind `askUserTool` (on by default), never with a
47+// structuredOutput; `save_answer` behind `saveAnswerTool` (off by default);
48+// `search_memory` behind `sessions.autoSearchMemory` (off by default, sessions on);
49+// `search_docs` behind `docSearch.autoSearchDocs` (off by default);
50+// and the agent file's declared `tools:`.
51+//
52+// A decider gets none of them, whatever bashTool, editTools, skillsDir… say
53+// (ticket 141): its model never calls a tool, so a decider file needs no
54+// `…: false` lines. What only a deliberate entry declares (mcp, lsp,
55+// mmConfigs, tools:) is refused earlier by config.DecisionConflict.
56+func assembleTools(e *engine.Engine, d *detector.LoopDetector, asker tools.AgentAsker) toolSet {
57+ set := toolSet{close: func() {}}
58+ if config.Cfg.Decision != nil {
59+ engine.DeclareSkills(false)
60+ skills.Declare(nil)
61+ return set
62+ }
63+ if config.Cfg.BashTool {
64+ set.tools = append(set.tools, tools.Bash(e.G, d))
65+ set.names = append(set.names, "bash")
66+ }
67+ set.skills = skills.List(config.Cfg.SkillsDir)
68+ set.skillCount = len(set.skills)
69+ // The turn recap shows `📖 0 skill(s)` only where a skill could have been
70+ // used — see engine.SkillsAvailable.
71+ engine.DeclareSkills(set.skillCount > 0)
72+ // The catalogue every front end resolves `$skill` against.
73+ skills.Declare(set.skills)
74+ if skillTool := tools.ReadSkill(e.G, config.Cfg.SkillsDir, d); skillTool != nil {
75+ set.tools = append(set.tools, skillTool)
76+ set.names = append(set.names, "read_skill")
77+ }
78+ if config.Cfg.EditTools {
79+ set.tools = append(set.tools,
80+ tools.ReadFile(e.G, d),
81+ tools.WriteFile(e.G, d),
82+ tools.EditFile(e.G, d))
83+ set.names = append(set.names, "read_file", "write_file", "edit_file")
84+ }
85+ if config.Cfg.PlanTool {
86+ set.tools = append(set.tools, tools.PlanTool(e.G, d))
87+ set.names = append(set.names, "plan")
88+ }
89+ // Not for an agent with a structuredOutput: it answers once, in JSON, and
90+ // declaring a tool would stop it from starting (StructuredOutputConflict)
91+ // — the existing structured agents would all break on a default.
92+ if config.Cfg.AskUserTool && config.Cfg.OutputSchema == nil {
93+ set.tools = append(set.tools, tools.AskUser(e.G, d))
94+ set.names = append(set.names, "ask_user")
95+ }
96+ if config.Cfg.SaveAnswerTool {
97+ set.tools = append(set.tools, tools.SaveAnswer(e.G, d))
98+ set.names = append(set.names, "save_answer")
99+ }
100+ if config.Cfg.UnloadModels && config.Cfg.OutputSchema == nil {
101+ set.tools = append(set.tools, tools.UnloadModel(e.G, d, e.Unload))
102+ set.names = append(set.names, "unload_model")
103+ }
104+ if config.Cfg.FetchContentTool {
105+ // The product token "mm" is what the sites' robots.txt are read for.
106+ fetcher := webmd.NewFetcher("mm/" + version.Short())
107+ set.tools = append(set.tools, tools.FetchContent(e.G, d, fetcher))
108+ set.names = append(set.names, "fetch_content")
109+ }
110+ if config.Cfg.DocSearch.DocsTool() {
111+ set.tools = append(set.tools, tools.SearchDocs(e.G, d))
112+ set.names = append(set.names, "search_docs")
113+ }
114+ if config.Cfg.Sessions.MemoryTool() {
115+ set.tools = append(set.tools, tools.SearchMemory(e.G, d))
116+ set.names = append(set.names, "search_memory")
117+ }
118+ if w := config.Cfg.Sessions.MemoryWarning(); w != "" {
119+ set.warnings = append(set.warnings, w)
120+ }
121+ if len(config.Cfg.MMConfigs) > 0 {
122+ set.tools = append(set.tools, tools.AskAgent(e.G, d, asker))
123+ set.names = append(set.names, "ask_agent")
124+ }
125+ // a2a.agents (ticket 243): the remote A2A agents the model can talk to.
126+ if len(config.Cfg.A2A.Agents) > 0 {
127+ set.tools = append(set.tools, tools.AskA2AAgent(e.G, d))
128+ set.names = append(set.names, "ask_a2a_agent")
129+ }
130+ assembleLSP(e, d, &set)
131+ assembleMCP(e, d, &set)
132+ assembleDeclared(e, d, &set)
133+ return set
134+}
135+
136+// assembleDeclared adds the agent file's `tools:` entries (ticket 88). They
137+// come last because an MCP tool's name is only known once its server
138+// answered: a declared tool that would take an MCP tool's name is skipped
139+// with a warning, never an error — the agent still starts. A built-in name
140+// cannot clash: the config refuses it at load.
141+func assembleDeclared(e *engine.Engine, d *detector.LoopDetector, set *toolSet) {
142+ for _, t := range config.Cfg.Tools {
143+ if slices.Contains(set.names, t.Name) {
144+ set.warnings = append(set.warnings, fmt.Sprintf("tools: %s skipped — an MCP tool already has that name", t.Name))
145+ continue
146+ }
147+ set.tools = append(set.tools, tools.DeclaredTool(e.G, d, t))
148+ set.names = append(set.names, t.Name)
149+ }
150+}
151+
152+// assembleLSP adds the `lsp` tool over the configured servers that exist.
153+// The servers are not started here — each starts on its first use — but
154+// the client is created now so main can stop them at exit. The project root
155+// the servers get is the directory mm runs in; an editor launches mm in the
156+// project it opened.
157+func assembleLSP(e *engine.Engine, d *detector.LoopDetector, set *toolSet) {
158+ servers := config.Cfg.LSP.Servers
159+ if len(servers) == 0 {
160+ return
161+ }
162+ ok, missing := lsp.Available(servers)
163+ for _, m := range missing {
164+ set.warnings = append(set.warnings, fmt.Sprintf("lsp server %s not found on the PATH — skipped", m))
165+ }
166+ if len(ok) == 0 {
167+ set.warnings = append(set.warnings, "lsp: none of the configured servers is on the PATH — the lsp tool is not declared")
168+ return
169+ }
170+ cwd, _ := os.Getwd()
171+ client := lsp.New(cwd, ok)
172+ set.tools = append(set.tools, tools.LSP(e.G, d, client, ok))
173+ // lsp.diagnosticsAfterEdit / diagnosticsAfterRead (tickets 227, 245):
174+ // the file tools ask the same servers after a change or a read.
175+ tools.SetEditDiagnostics(client, ok)
176+ set.names = append(set.names, "lsp")
177+ set.close = client.Close
178+}
179+
180+// assembleMCP adds MCP tools from configured servers.
181+// MCP discovery runs at startup (not lazy) and creates a static tool list.
182+// All MCP tools are wrapped to respect mini-me's safety contracts.
183+func assembleMCP(e *engine.Engine, d *detector.LoopDetector, set *toolSet) {
184+ // Skip if MCP is disabled
185+ if !config.Cfg.MCP.Enabled {
186+ return
187+ }
188+
189+ // Check for sbx MCP gateway - if present, add it as a server
190+ // sbx injects MCP_GATEWAY_URL and handles OAuth tokens via its gateway
191+ // The gateway substitutes sentinel tokens with real OAuth tokens
192+ gatewayURL := os.Getenv("MCP_GATEWAY_URL")
193+
194+ servers := config.Cfg.MCP.Servers
195+
196+ // If gateway URL is set and no servers configured, use gateway only
197+ // If gateway URL is set and servers configured, add gateway as additional server
198+ if gatewayURL != "" {
199+ gatewayServer := config.MCPServer{
200+ Name: "sbx-gateway",
201+ Transport: "http",
202+ URL: gatewayURL,
203+ Timeout: config.Cfg.MCP.DiscoveryTimeout,
204+ Auth: config.MCPAuthConfig{
205+ Type: "bearer",
206+ TokenEnv: "MCP_SENTINEL_TOKEN_NAME", // sbx injects this, not MCP_GATEWAY_TOKEN
207+ },
208+ Headers: map[string]string{
209+ "Accept": "application/json, text/event-stream",
210+ },
211+ }
212+
213+ // If no servers configured, use gateway only
214+ if len(servers) == 0 {
215+ servers = []config.MCPServer{gatewayServer}
216+ } else {
217+ // Add gateway as first server (prefer gateway tools)
218+ servers = append([]config.MCPServer{gatewayServer}, servers...)
219+ }
220+ } else if len(servers) == 0 {
221+ set.warnings = append(set.warnings, "mcp: enabled but no servers configured")
222+ return
223+ }
224+
225+ // Create a context with discovery timeout
226+ ctx, cancel := context.WithTimeout(context.Background(), config.Cfg.MCP.DiscoveryTimeout)
227+ defer cancel()
228+
229+ // Connect to all servers and discover tools
230+ clients, warnings, err := mcp.ConnectAll(ctx, servers)
231+ if err != nil {
232+ set.warnings = append(set.warnings, fmt.Sprintf("mcp: connection/discovery failed: %v", err))
233+ return
234+ }
235+
236+ // Add any discovery warnings
237+ set.warnings = append(set.warnings, warnings...)
238+
239+ // Check for name collisions
240+ if len(clients) > 0 {
241+ collisions := mcp.CheckCollisions(clients)
242+ if len(collisions) > 0 {
243+ set.warnings = append(set.warnings, collisions...)
244+ // Close clients and return - collisions are fatal
245+ mcp.CloseAll(clients)
246+ return
247+ }
248+ }
249+
250+ // Wrap all MCP tools
251+ mcpToolRefs, mcpNames, mcpWarnings, err := tools.MCP(e.G, d, clients)
252+ if err != nil {
253+ set.warnings = append(set.warnings, fmt.Sprintf("mcp: tool wrapping failed: %v", err))
254+ mcp.CloseAll(clients)
255+ return
256+ }
257+
258+ // Add any MCP-specific warnings
259+ if len(mcpWarnings) > 0 {
260+ set.warnings = append(set.warnings, mcpWarnings...)
261+ }
262+
263+ // Add MCP tools to the set
264+ set.tools = append(set.tools, mcpToolRefs...)
265+ set.names = append(set.names, mcpNames...)
266+
267+ // Chain close functions
268+ oldClose := set.close
269+ set.close = func() {
270+ mcp.CloseAll(clients)
271+ oldClose()
272+ }
273+}