bots-garden/mini-mepublic Fork
⑂ ff391e0
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: internal/agentinit without smells (15 → 0)

- Flow.Set and Flow.Step as tables, one method per question
- decideSampling with samplingValues; Render as one writer per section
- Main → prepareFlow, answerFlow, reportFailure; WriteFile →
  saveAgentFile, checkWritten; the line wizard's ask in two steps
- flow, wizard, facts, render and decide split by theme
- mm init writes byte-identical files (13 combinations against the
  host's llama-server, and on disk)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
agent committed 2026-11-28T12:01:25+01:00 Browse files
ff391e0 parent: 5aa79d9
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:55:16.000Z
9+updatedAt: 2026-11-28T11:01:25.000Z
1010 labels:
1111 - kind::chore
1212 milestone: v2.2.0
@@ -47,12 +47,14 @@ tasks:
4747 closedAt: 2026-11-28T10:55:16.000Z
4848 - id: 4
4949 title: "internal/agentinit"
50- state: open
50+ state: closed
5151 priority: medium
5252 author:
5353 name: k33g
5454 email: ph.charriere@gmail.com
5555 createdAt: 2026-11-28T10:19:47.000Z
56+ updatedAt: 2026-11-28T11:01:25.000Z
57+ closedAt: 2026-11-28T11:01:25.000Z
5658 - id: 5
5759 title: "internal/tui"
5860 state: open
@@ -99,3 +101,10 @@ comments:
99101 createdAt: 2026-11-28T10:55:16.000Z
100102 body: |
101103 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.
104+ - id: 4
105+ author:
106+ name: k33g
107+ email: ph.charriere@gmail.com
108+ createdAt: 2026-11-28T11:01:25.000Z
109+ body: |
110+ internal/agentinit (mm init): 15 → 0 smells (total 157 → 142). Flow.Set / Flow.Step as tables (setters, stepBuilders, one method per question); decideSampling with samplingValues; Render as one writer per section; Main → prepareFlow, answerFlow, reportFailure; WriteFile → saveAgentFile, checkWritten; the line wizard's ask → showDetails, readAnswer; flow, wizard, facts, render and decide split by theme (flow_steps, flow_answers, flow_server, args, linewizard, write, base, models, kronkfacts, render_server, render_header, sampling). Checked: go test ./... green; the old and new binaries write byte-identical files on 13 mm init --yes combinations (11 providers / usages / machines / layouts, 2 errors) against the host's llama-server, and the same files, messages, exit codes and .mm/skills tree on disk (a gpt-oss case first differed by timing — the model was loading on the server — and was identical when run again, twice).
@@ -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:55:16.000Z9+updatedAt: 2026-11-28T11:01:25.000Z
10 labels:10 labels:
11 - kind::chore11 - kind::chore
12 milestone: v2.2.012 milestone: v2.2.0
@@ -47,12 +47,14 @@ tasks:
47 closedAt: 2026-11-28T10:55:16.000Z47 closedAt: 2026-11-28T10:55:16.000Z
48 - id: 448 - id: 4
49 title: "internal/agentinit"49 title: "internal/agentinit"
50- state: open50+ state: closed
51 priority: medium51 priority: medium
52 author:52 author:
53 name: k33g53 name: k33g
54 email: ph.charriere@gmail.com54 email: ph.charriere@gmail.com
55 createdAt: 2026-11-28T10:19:47.000Z55 createdAt: 2026-11-28T10:19:47.000Z
56+ updatedAt: 2026-11-28T11:01:25.000Z
57+ closedAt: 2026-11-28T11:01:25.000Z
56 - id: 558 - id: 5
57 title: "internal/tui"59 title: "internal/tui"
58 state: open60 state: open
@@ -99,3 +101,10 @@ comments:
99 createdAt: 2026-11-28T10:55:16.000Z101 createdAt: 2026-11-28T10:55:16.000Z
100 body: |102 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.103 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.
104+ - id: 4
105+ author:
106+ name: k33g
107+ email: ph.charriere@gmail.com
108+ createdAt: 2026-11-28T11:01:25.000Z
109+ body: |
110+ internal/agentinit (mm init): 15 → 0 smells (total 157 → 142). Flow.Set / Flow.Step as tables (setters, stepBuilders, one method per question); decideSampling with samplingValues; Render as one writer per section; Main → prepareFlow, answerFlow, reportFailure; WriteFile → saveAgentFile, checkWritten; the line wizard's ask → showDetails, readAnswer; flow, wizard, facts, render and decide split by theme (flow_steps, flow_answers, flow_server, args, linewizard, write, base, models, kronkfacts, render_server, render_header, sampling). Checked: go test ./... green; the old and new binaries write byte-identical files on 13 mm init --yes combinations (11 providers / usages / machines / layouts, 2 errors) against the host's llama-server, and the same files, messages, exit codes and .mm/skills tree on disk (a gpt-oss case first differed by timing — the model was loading on the server — and was identical when run again, twice).
added internal/agentinit/args.go +89 -0
new file mode 100644
@@ -0,0 +1,89 @@
1+package agentinit
2+
3+import (
4+ "context"
5+ "errors"
6+ "flag"
7+ "fmt"
8+ "io"
9+ "strings"
10+)
11+
12+// Args are mm init's flags, read: the answers they give, the file, and the
13+// line mode's own switches (Check, Yes, Line — not offered by mm
14+// acp-create, which has no use for them).
15+type Args struct {
16+ Choices Choices
17+ Output string
18+ Check, Yes, Line bool
19+ presets Presets
20+}
21+
22+// ParseArgs reads mm init's flags (name is the command shown by -h). With
23+// lineSwitches false, --check, --yes and --line are not offered. ok is
24+// false when the command must stop: -h (code 0), a bad flag (2) or presets
25+// that do not load (1); the reason is already written to out.
26+func ParseArgs(name string, args []string, out io.Writer, lineSwitches bool) (a Args, code int, ok bool) {
27+ fs := flag.NewFlagSet(name, flag.ContinueOnError)
28+ fs.SetOutput(out)
29+ c := &a.Choices
30+ var yolo, project, sessions, skills, autostart, launch string
31+ fs.StringVar(&c.Provider, "provider", "", "model server: "+strings.Join(providers, ", "))
32+ fs.StringVar(&c.BaseURL, "base-url", "", "the server's OpenAI-compatible address (default: the provider's); for openai, the endpoint question")
33+ fs.StringVar(&c.APIKeyEnv, "api-key-env", "", "openai: the environment variable that holds the API key (default OPENAI_API_KEY)")
34+ fs.StringVar(&c.Model, "model", "", "the model, as the server names it")
35+ fs.StringVar(&c.Family, "family", "", "the model family (default: detected from the name)")
36+ fs.StringVar(&c.Usage, "usage", "", "what the agent is for (developer, translator, docs, json…)")
37+ fs.StringVar(&c.Machine, "machine", "", "small, medium or large")
38+ fs.StringVar(&c.Name, "name", "", "the agent's name")
39+ fs.StringVar(&yolo, "yolo", "", "yes: tools run without asking; no: every change waits for your answer (default: the usage's)")
40+ fs.StringVar(&project, "project", "", "yes: create .mm/ and write .mm/agent.yaml, paths from the project root; no: one agent.yaml (default: no)")
41+ fs.StringVar(&sessions, "sessions", "", "yes: write a sessions section that saves every conversation; no: none (default: no)")
42+ fs.StringVar(&skills, "skills", "", "yes: write skillsDir and create the folder (skills/, or .mm/skills/ with --project yes); no: skillsDir: no-skills (default: no)")
43+ fs.StringVar(&autostart, "autostart", "", "llamacpp or razorbill on this machine — yes: mm starts llama-server (rzb) when it is not running and stops it with the last session; no: you start it (default: yes)")
44+ fs.StringVar(&launch, "launch-settings", "", "llamacpp with --autostart yes — yes: write llama-server's launch settings (the Llama app's values); no: llama-server's defaults (default: no)")
45+ fs.StringVar(&a.Output, "o", "", "the file to write (default agent.yaml, .mm/agent.yaml with --project yes; - for stdout, which creates nothing); an existing file is replaced only if you agree, never with --yes")
46+ fs.StringVar(&a.Output, "output", "", "same as -o")
47+ if lineSwitches {
48+ fs.BoolVar(&a.Check, "check", false, "after writing, ask the model one question to prove it answers")
49+ fs.BoolVar(&a.Yes, "yes", false, "ask nothing: every unanswered question takes its default")
50+ fs.BoolVar(&a.Line, "line", false, "ask line by line even in a terminal (no window)")
51+ }
52+ if err := fs.Parse(args); err != nil {
53+ if errors.Is(err, flag.ErrHelp) {
54+ return a, 0, false
55+ }
56+ return a, 2, false
57+ }
58+ presets, err := LoadPresets()
59+ if err != nil {
60+ fmt.Fprintln(out, "⚠️ "+err.Error())
61+ return a, 1, false
62+ }
63+ a.presets = presets
64+ if yolo != "" {
65+ on := yolo == "yes" || yolo == "true"
66+ c.Yolo = &on
67+ }
68+ for flagName, value := range map[string]struct {
69+ text string
70+ target **bool
71+ }{"project": {project, &c.Project}, "sessions": {sessions, &c.Sessions}, "skills": {skills, &c.Skills}, "autostart": {autostart, &c.AutoStart}, "launch-settings": {launch, &c.Launch}} {
72+ if value.text == "" {
73+ continue
74+ }
75+ if err := setYesNo("--"+flagName, value.text, value.target); err != nil {
76+ fmt.Fprintln(out, "⚠️ "+err.Error())
77+ return a, 2, false
78+ }
79+ }
80+ return a, 0, true
81+}
82+
83+// Flow starts a flow from the flags: what they gave is answered, and
84+// checked as if typed. Each call is a new flow (mm acp-create: one per
85+// session).
86+func (a Args) Flow(ctx context.Context) (*Flow, error) {
87+ flow := NewFlow(ctx, a.presets, a.Choices, a.Output)
88+ return flow, flow.validateGiven()
89+}
new file mode 100644
@@ -0,0 +1,89 @@
1+package agentinit
2+
3+import (
4+ "context"
5+ "errors"
6+ "flag"
7+ "fmt"
8+ "io"
9+ "strings"
10+)
11+
12+// Args are mm init's flags, read: the answers they give, the file, and the
13+// line mode's own switches (Check, Yes, Line — not offered by mm
14+// acp-create, which has no use for them).
15+type Args struct {
16+ Choices Choices
17+ Output string
18+ Check, Yes, Line bool
19+ presets Presets
20+}
21+
22+// ParseArgs reads mm init's flags (name is the command shown by -h). With
23+// lineSwitches false, --check, --yes and --line are not offered. ok is
24+// false when the command must stop: -h (code 0), a bad flag (2) or presets
25+// that do not load (1); the reason is already written to out.
26+func ParseArgs(name string, args []string, out io.Writer, lineSwitches bool) (a Args, code int, ok bool) {
27+ fs := flag.NewFlagSet(name, flag.ContinueOnError)
28+ fs.SetOutput(out)
29+ c := &a.Choices
30+ var yolo, project, sessions, skills, autostart, launch string
31+ fs.StringVar(&c.Provider, "provider", "", "model server: "+strings.Join(providers, ", "))
32+ fs.StringVar(&c.BaseURL, "base-url", "", "the server's OpenAI-compatible address (default: the provider's); for openai, the endpoint question")
33+ fs.StringVar(&c.APIKeyEnv, "api-key-env", "", "openai: the environment variable that holds the API key (default OPENAI_API_KEY)")
34+ fs.StringVar(&c.Model, "model", "", "the model, as the server names it")
35+ fs.StringVar(&c.Family, "family", "", "the model family (default: detected from the name)")
36+ fs.StringVar(&c.Usage, "usage", "", "what the agent is for (developer, translator, docs, json…)")
37+ fs.StringVar(&c.Machine, "machine", "", "small, medium or large")
38+ fs.StringVar(&c.Name, "name", "", "the agent's name")
39+ fs.StringVar(&yolo, "yolo", "", "yes: tools run without asking; no: every change waits for your answer (default: the usage's)")
40+ fs.StringVar(&project, "project", "", "yes: create .mm/ and write .mm/agent.yaml, paths from the project root; no: one agent.yaml (default: no)")
41+ fs.StringVar(&sessions, "sessions", "", "yes: write a sessions section that saves every conversation; no: none (default: no)")
42+ fs.StringVar(&skills, "skills", "", "yes: write skillsDir and create the folder (skills/, or .mm/skills/ with --project yes); no: skillsDir: no-skills (default: no)")
43+ fs.StringVar(&autostart, "autostart", "", "llamacpp or razorbill on this machine — yes: mm starts llama-server (rzb) when it is not running and stops it with the last session; no: you start it (default: yes)")
44+ fs.StringVar(&launch, "launch-settings", "", "llamacpp with --autostart yes — yes: write llama-server's launch settings (the Llama app's values); no: llama-server's defaults (default: no)")
45+ fs.StringVar(&a.Output, "o", "", "the file to write (default agent.yaml, .mm/agent.yaml with --project yes; - for stdout, which creates nothing); an existing file is replaced only if you agree, never with --yes")
46+ fs.StringVar(&a.Output, "output", "", "same as -o")
47+ if lineSwitches {
48+ fs.BoolVar(&a.Check, "check", false, "after writing, ask the model one question to prove it answers")
49+ fs.BoolVar(&a.Yes, "yes", false, "ask nothing: every unanswered question takes its default")
50+ fs.BoolVar(&a.Line, "line", false, "ask line by line even in a terminal (no window)")
51+ }
52+ if err := fs.Parse(args); err != nil {
53+ if errors.Is(err, flag.ErrHelp) {
54+ return a, 0, false
55+ }
56+ return a, 2, false
57+ }
58+ presets, err := LoadPresets()
59+ if err != nil {
60+ fmt.Fprintln(out, "⚠️ "+err.Error())
61+ return a, 1, false
62+ }
63+ a.presets = presets
64+ if yolo != "" {
65+ on := yolo == "yes" || yolo == "true"
66+ c.Yolo = &on
67+ }
68+ for flagName, value := range map[string]struct {
69+ text string
70+ target **bool
71+ }{"project": {project, &c.Project}, "sessions": {sessions, &c.Sessions}, "skills": {skills, &c.Skills}, "autostart": {autostart, &c.AutoStart}, "launch-settings": {launch, &c.Launch}} {
72+ if value.text == "" {
73+ continue
74+ }
75+ if err := setYesNo("--"+flagName, value.text, value.target); err != nil {
76+ fmt.Fprintln(out, "⚠️ "+err.Error())
77+ return a, 2, false
78+ }
79+ }
80+ return a, 0, true
81+}
82+
83+// Flow starts a flow from the flags: what they gave is answered, and
84+// checked as if typed. Each call is a new flow (mm acp-create: one per
85+// session).
86+func (a Args) Flow(ctx context.Context) (*Flow, error) {
87+ flow := NewFlow(ctx, a.presets, a.Choices, a.Output)
88+ return flow, flow.validateGiven()
89+}
added internal/agentinit/base.go +89 -0
new file mode 100644
@@ -0,0 +1,89 @@
1+package agentinit
2+
3+import (
4+ "context"
5+ "mm/internal/config"
6+ "mm/internal/engine"
7+ "strings"
8+)
9+
10+// resolveBase is the server's address the wizard lists models from: the
11+// flag's, else the one the environment imposes (AGENT_BASE_URL…), else the
12+// first that answers of the provider's local addresses, then its fallback
13+// (chooseBase).
14+//
15+// Ticket 214: it used to take the engine's own resolution, whose probe gives
16+// the default address 2 s on /models and switches to the container fallback
17+// (host.docker.internal) without a word. mm on a Mac with Docker Desktop —
18+// where that name resolves on the host too — then listed Ollama's models
19+// from the container address. The written file is not concerned: it carries
20+// no baseUrl for the default address.
21+func resolveBase(ctx context.Context, c Choices) string {
22+ if c.BaseURL != "" {
23+ return c.BaseURL
24+ }
25+ if env := engine.EnvBaseURL(c.Provider); env != "" {
26+ return env
27+ }
28+ if _, fallback, ok := engine.DefaultURLs(c.Provider); ok {
29+ return chooseBase(engine.LocalURLs(c.Provider), fallback, func(url string) bool {
30+ _, err := Models(ctx, c.Provider, url)
31+ return err == nil
32+ })
33+ }
34+ return engineBase(c)
35+}
36+
37+// chooseBase picks the address to list models from: the first that lists
38+// them among the local ones — locals is the provider's default, then its
39+// alternates (engine.LocalURLs), each with its localAddresses — else the
40+// fallback when it does, else the default, whose error the model question
41+// then shows. A provider with one address and no fallback (openai) is not
42+// probed at all: there is nothing to choose, and openai's default is a
43+// remote service nobody asked mm to call yet.
44+//
45+// chooseBase([]string{"http://127.0.0.1:9931/v1", "http://127.0.0.1:8080/v1"}, "http://host.docker.internal:9931/v1", lists)
46+func chooseBase(locals []string, fallback string, lists func(string) bool) string {
47+ base := locals[0]
48+ if fallback == "" && len(locals) == 1 {
49+ return base
50+ }
51+ for _, local := range locals {
52+ for _, url := range localAddresses(local) {
53+ if lists(url) {
54+ return url
55+ }
56+ }
57+ }
58+ if fallback != "" && lists(fallback) {
59+ return fallback
60+ }
61+ return base
62+}
63+
64+// localAddresses is the default address, then — when it names localhost —
65+// the same with 127.0.0.1: a server listening on IPv4 only does not answer
66+// a localhost that resolves to ::1 first.
67+//
68+// localAddresses("http://localhost:11434/v1") // [http://localhost:11434/v1 http://127.0.0.1:11434/v1]
69+func localAddresses(base string) []string {
70+ out := []string{base}
71+ if strings.Contains(base, "://localhost:") || strings.HasSuffix(base, "://localhost") {
72+ out = append(out, strings.Replace(base, "://localhost", "://127.0.0.1", 1))
73+ }
74+ return out
75+}
76+
77+// engineBase is the engine's own resolution, for a provider the wizard has
78+// no addresses for.
79+func engineBase(c Choices) string {
80+ p, err := engine.Lookup(c.Provider)
81+ if err != nil {
82+ return ""
83+ }
84+ b, err := p.Resolve(config.Config{Provider: c.Provider, Model: "probe"})
85+ if err != nil {
86+ return ""
87+ }
88+ return b.BaseURL
89+}
new file mode 100644
@@ -0,0 +1,89 @@
1+package agentinit
2+
3+import (
4+ "context"
5+ "mm/internal/config"
6+ "mm/internal/engine"
7+ "strings"
8+)
9+
10+// resolveBase is the server's address the wizard lists models from: the
11+// flag's, else the one the environment imposes (AGENT_BASE_URL…), else the
12+// first that answers of the provider's local addresses, then its fallback
13+// (chooseBase).
14+//
15+// Ticket 214: it used to take the engine's own resolution, whose probe gives
16+// the default address 2 s on /models and switches to the container fallback
17+// (host.docker.internal) without a word. mm on a Mac with Docker Desktop —
18+// where that name resolves on the host too — then listed Ollama's models
19+// from the container address. The written file is not concerned: it carries
20+// no baseUrl for the default address.
21+func resolveBase(ctx context.Context, c Choices) string {
22+ if c.BaseURL != "" {
23+ return c.BaseURL
24+ }
25+ if env := engine.EnvBaseURL(c.Provider); env != "" {
26+ return env
27+ }
28+ if _, fallback, ok := engine.DefaultURLs(c.Provider); ok {
29+ return chooseBase(engine.LocalURLs(c.Provider), fallback, func(url string) bool {
30+ _, err := Models(ctx, c.Provider, url)
31+ return err == nil
32+ })
33+ }
34+ return engineBase(c)
35+}
36+
37+// chooseBase picks the address to list models from: the first that lists
38+// them among the local ones — locals is the provider's default, then its
39+// alternates (engine.LocalURLs), each with its localAddresses — else the
40+// fallback when it does, else the default, whose error the model question
41+// then shows. A provider with one address and no fallback (openai) is not
42+// probed at all: there is nothing to choose, and openai's default is a
43+// remote service nobody asked mm to call yet.
44+//
45+// chooseBase([]string{"http://127.0.0.1:9931/v1", "http://127.0.0.1:8080/v1"}, "http://host.docker.internal:9931/v1", lists)
46+func chooseBase(locals []string, fallback string, lists func(string) bool) string {
47+ base := locals[0]
48+ if fallback == "" && len(locals) == 1 {
49+ return base
50+ }
51+ for _, local := range locals {
52+ for _, url := range localAddresses(local) {
53+ if lists(url) {
54+ return url
55+ }
56+ }
57+ }
58+ if fallback != "" && lists(fallback) {
59+ return fallback
60+ }
61+ return base
62+}
63+
64+// localAddresses is the default address, then — when it names localhost —
65+// the same with 127.0.0.1: a server listening on IPv4 only does not answer
66+// a localhost that resolves to ::1 first.
67+//
68+// localAddresses("http://localhost:11434/v1") // [http://localhost:11434/v1 http://127.0.0.1:11434/v1]
69+func localAddresses(base string) []string {
70+ out := []string{base}
71+ if strings.Contains(base, "://localhost:") || strings.HasSuffix(base, "://localhost") {
72+ out = append(out, strings.Replace(base, "://localhost", "://127.0.0.1", 1))
73+ }
74+ return out
75+}
76+
77+// engineBase is the engine's own resolution, for a provider the wizard has
78+// no addresses for.
79+func engineBase(c Choices) string {
80+ p, err := engine.Lookup(c.Provider)
81+ if err != nil {
82+ return ""
83+ }
84+ b, err := p.Resolve(config.Config{Provider: c.Provider, Model: "probe"})
85+ if err != nil {
86+ return ""
87+ }
88+ return b.BaseURL
89+}
modified internal/agentinit/decide.go +0 -100
@@ -178,106 +178,6 @@ func (s *Settings) decideTop() {
178178 }
179179 }
180180
181-func (s *Settings) decideSampling() {
182- fam, f := s.Family, s.Facts
183- base, source, origin := fam.General, "family "+fam.Name+": "+fam.Source, fam.Origin["general"]
184- if s.Thinking && fam.Thinking.Temperature != nil {
185- base, origin = fam.Thinking, fam.Origin["thinking"]
186- }
187- values := map[string]float64{}
188- put := func(key string, v *float64) {
189- if v != nil {
190- values[key] = *v
191- }
192- }
193- put("temperature", base.Temperature)
194- put("top_p", base.TopP)
195- put("min_p", base.MinP)
196- if base.TopK != nil {
197- values["top_k"] = float64(*base.TopK)
198- }
199- reasons, origins := map[string]string{}, map[string]string{}
200- for k := range values {
201- reasons[k], origins[k] = source, origin
202- }
203- if len(f.Sampling) > 0 {
204- for k, v := range f.Sampling {
205- values[k], reasons[k], origins[k] = v, "the GGUF's own sampling, read from the server", OriginServer
206- }
207- }
208- if !s.Thinking && s.Usage.Precise && fam.Precise != nil {
209- values["temperature"] = *fam.Precise
210- reasons["temperature"] = fmt.Sprintf("precise temperature for a %s agent without reasoning (family %s)", s.Usage.Name, fam.Name)
211- origins["temperature"] = fam.Origin["precise"]
212- }
213- if s.Thinking && values["temperature"] < 0.5 {
214- values["temperature"], reasons["temperature"], origins["temperature"] = 0.6, "reasoning is on: a thinking model loops at a low temperature", OriginRule
215- }
216- profileReason := "Kronk profile " + f.Profile + " (model_config.yaml), read from the server: mm's values replace a profile's, so they are copied here"
217- for k, v := range f.ProfileSampling {
218- if k != "max_tokens" {
219- values[k], reasons[k], origins[k] = v, profileReason, OriginServer
220- }
221- }
222- for _, k := range []string{"temperature", "top_p", "top_k", "min_p"} {
223- if v, ok := values[k]; ok {
224- s.Sampling = append(s.Sampling, Setting{Key: k, Value: number(k, v), Reason: reasons[k], Origin: origins[k]})
225- }
226- }
227- tokens, tokensReason := "4096", "room for an answer or a whole file in one tool call"
228- if s.Thinking {
229- tokens, tokensReason = "16384", "reasoning on: room for the thoughts plus a whole tool call"
230- }
231- tokensOrigin := OriginRule
232- if n, ok := f.ProfileSampling["max_tokens"]; ok {
233- tokens, tokensReason, tokensOrigin = fmt.Sprint(int(n)), profileReason, OriginServer
234- }
235- maxKey := "max_tokens"
236- if s.Family.MaxTokensKey != "" {
237- maxKey, tokensReason = s.Family.MaxTokensKey, tokensReason+" (family "+s.Family.Name+" names it "+s.Family.MaxTokensKey+")"
238- }
239- s.Sampling = append(s.Sampling, Setting{Key: maxKey, Value: tokens, Reason: tokensReason, Origin: tokensOrigin})
240- if s.anyTool() {
241- s.Sampling = append(s.Sampling, Setting{Key: "parallel_tool_calls", Value: "false", Reason: "one tool call per reply: small models run a check before the change it checks has landed otherwise"})
242- }
243- s.decideKwargs()
244-}
245-
246-func (s *Settings) decideKwargs() {
247- sw := s.Facts.Thinking.Switch
248- source := "read from the chat template"
249- if sw == "" {
250- sw, source = s.Family.Reasoning, "family "+s.Family.Name
251- }
252- switch sw {
253- case "enable_thinking":
254- why := "reasoning off: short, direct answers"
255- if s.Family.ThinkingOff {
256- why = "reasoning off: family " + s.Family.Name + " is kept off — see the note at the end of the file"
257- }
258- if s.Thinking {
259- why = "reasoning on: code and multi-step work"
260- }
261- if d := s.Facts.Thinking.Default; d != "" {
262- why += "; the template's default is " + d
263- }
264- s.Kwargs = append(s.Kwargs, Setting{Key: "enable_thinking", Value: boolYAML(s.Thinking), Reason: why + " (" + source + ")"})
265- case "reasoning_effort":
266- values := s.Facts.Thinking.EffortValues
267- if len(values) == 0 {
268- values = s.Family.EffortValues
269- }
270- effort := "low"
271- if s.Thinking {
272- effort = "medium"
273- }
274- if len(values) > 0 && !contains(values, effort) {
275- effort = values[0]
276- }
277- s.Kwargs = append(s.Kwargs, Setting{Key: "reasoning_effort", Value: effort, Reason: fmt.Sprintf("one of %s (%s); a value the template does not know may make every request fail", strings.Join(values, ", "), source)})
278- }
279-}
280-
281181 func (s *Settings) decideContext() {
282182 s.Context = append(s.Context, Setting{Key: "enabled", Value: "true", Reason: "compress the history before the window is full (settings guide, every row)"})
283183 // The percentage applies to the window the server SERVES, which mm
@@ -178,106 +178,6 @@ func (s *Settings) decideTop() {
178 }178 }
179 }179 }
180 180
181-func (s *Settings) decideSampling() {
182- fam, f := s.Family, s.Facts
183- base, source, origin := fam.General, "family "+fam.Name+": "+fam.Source, fam.Origin["general"]
184- if s.Thinking && fam.Thinking.Temperature != nil {
185- base, origin = fam.Thinking, fam.Origin["thinking"]
186- }
187- values := map[string]float64{}
188- put := func(key string, v *float64) {
189- if v != nil {
190- values[key] = *v
191- }
192- }
193- put("temperature", base.Temperature)
194- put("top_p", base.TopP)
195- put("min_p", base.MinP)
196- if base.TopK != nil {
197- values["top_k"] = float64(*base.TopK)
198- }
199- reasons, origins := map[string]string{}, map[string]string{}
200- for k := range values {
201- reasons[k], origins[k] = source, origin
202- }
203- if len(f.Sampling) > 0 {
204- for k, v := range f.Sampling {
205- values[k], reasons[k], origins[k] = v, "the GGUF's own sampling, read from the server", OriginServer
206- }
207- }
208- if !s.Thinking && s.Usage.Precise && fam.Precise != nil {
209- values["temperature"] = *fam.Precise
210- reasons["temperature"] = fmt.Sprintf("precise temperature for a %s agent without reasoning (family %s)", s.Usage.Name, fam.Name)
211- origins["temperature"] = fam.Origin["precise"]
212- }
213- if s.Thinking && values["temperature"] < 0.5 {
214- values["temperature"], reasons["temperature"], origins["temperature"] = 0.6, "reasoning is on: a thinking model loops at a low temperature", OriginRule
215- }
216- profileReason := "Kronk profile " + f.Profile + " (model_config.yaml), read from the server: mm's values replace a profile's, so they are copied here"
217- for k, v := range f.ProfileSampling {
218- if k != "max_tokens" {
219- values[k], reasons[k], origins[k] = v, profileReason, OriginServer
220- }
221- }
222- for _, k := range []string{"temperature", "top_p", "top_k", "min_p"} {
223- if v, ok := values[k]; ok {
224- s.Sampling = append(s.Sampling, Setting{Key: k, Value: number(k, v), Reason: reasons[k], Origin: origins[k]})
225- }
226- }
227- tokens, tokensReason := "4096", "room for an answer or a whole file in one tool call"
228- if s.Thinking {
229- tokens, tokensReason = "16384", "reasoning on: room for the thoughts plus a whole tool call"
230- }
231- tokensOrigin := OriginRule
232- if n, ok := f.ProfileSampling["max_tokens"]; ok {
233- tokens, tokensReason, tokensOrigin = fmt.Sprint(int(n)), profileReason, OriginServer
234- }
235- maxKey := "max_tokens"
236- if s.Family.MaxTokensKey != "" {
237- maxKey, tokensReason = s.Family.MaxTokensKey, tokensReason+" (family "+s.Family.Name+" names it "+s.Family.MaxTokensKey+")"
238- }
239- s.Sampling = append(s.Sampling, Setting{Key: maxKey, Value: tokens, Reason: tokensReason, Origin: tokensOrigin})
240- if s.anyTool() {
241- s.Sampling = append(s.Sampling, Setting{Key: "parallel_tool_calls", Value: "false", Reason: "one tool call per reply: small models run a check before the change it checks has landed otherwise"})
242- }
243- s.decideKwargs()
244-}
245-
246-func (s *Settings) decideKwargs() {
247- sw := s.Facts.Thinking.Switch
248- source := "read from the chat template"
249- if sw == "" {
250- sw, source = s.Family.Reasoning, "family "+s.Family.Name
251- }
252- switch sw {
253- case "enable_thinking":
254- why := "reasoning off: short, direct answers"
255- if s.Family.ThinkingOff {
256- why = "reasoning off: family " + s.Family.Name + " is kept off — see the note at the end of the file"
257- }
258- if s.Thinking {
259- why = "reasoning on: code and multi-step work"
260- }
261- if d := s.Facts.Thinking.Default; d != "" {
262- why += "; the template's default is " + d
263- }
264- s.Kwargs = append(s.Kwargs, Setting{Key: "enable_thinking", Value: boolYAML(s.Thinking), Reason: why + " (" + source + ")"})
265- case "reasoning_effort":
266- values := s.Facts.Thinking.EffortValues
267- if len(values) == 0 {
268- values = s.Family.EffortValues
269- }
270- effort := "low"
271- if s.Thinking {
272- effort = "medium"
273- }
274- if len(values) > 0 && !contains(values, effort) {
275- effort = values[0]
276- }
277- s.Kwargs = append(s.Kwargs, Setting{Key: "reasoning_effort", Value: effort, Reason: fmt.Sprintf("one of %s (%s); a value the template does not know may make every request fail", strings.Join(values, ", "), source)})
278- }
279-}
280-
281 func (s *Settings) decideContext() {181 func (s *Settings) decideContext() {
282 s.Context = append(s.Context, Setting{Key: "enabled", Value: "true", Reason: "compress the history before the window is full (settings guide, every row)"})182 s.Context = append(s.Context, Setting{Key: "enabled", Value: "true", Reason: "compress the history before the window is full (settings guide, every row)"})
283 // The percentage applies to the window the server SERVES, which mm183 // The percentage applies to the window the server SERVES, which mm
modified internal/agentinit/facts.go +0 -194
@@ -1,13 +1,9 @@
11 package agentinit
22
33 import (
4- "bytes"
54 "context"
6- "encoding/json"
7- "fmt"
85 "net/http"
96 neturl "net/url"
10- "os"
117 "regexp"
128 "sort"
139 "strconv"
@@ -42,75 +38,6 @@ type Thinking struct {
4238 EffortValues []string // the reasoning_effort values the template names
4339 }
4440
45-// root is a server's address without its OpenAI prefix: llmman's and
46-// Ollama's /api/*, llama.cpp's /props live there.
47-func root(base string) string {
48- base = strings.TrimRight(base, "/")
49- for _, suffix := range []string{"/engines/v1", "/v1"} {
50- if strings.HasSuffix(base, suffix) {
51- return strings.TrimSuffix(base, suffix)
52- }
53- }
54- return base
55-}
56-
57-var client = &http.Client{}
58-
59-// keyContext carries the key a provider needs to list its models (the
60-// generic `openai` one: a remote API answers 401 to an anonymous request).
61-type keyContext struct{}
62-
63-func withKey(ctx context.Context, key string) context.Context {
64- return context.WithValue(ctx, keyContext{}, key)
65-}
66-
67-func apiKey(ctx context.Context) string {
68- key, _ := ctx.Value(keyContext{}).(string)
69- return key
70-}
71-
72-func call(ctx context.Context, method, url string, body any, timeout time.Duration, out any) error {
73- ctx, cancel := context.WithTimeout(ctx, timeout)
74- defer cancel()
75- var reader *bytes.Reader
76- if body != nil {
77- data, _ := json.Marshal(body)
78- reader = bytes.NewReader(data)
79- } else {
80- reader = bytes.NewReader(nil)
81- }
82- req, err := http.NewRequestWithContext(ctx, method, url, reader)
83- if err != nil {
84- return err
85- }
86- req.Header.Set("Content-Type", "application/json")
87- if key := apiKey(ctx); key != "" {
88- req.Header.Set("Authorization", "Bearer "+key)
89- }
90- resp, err := client.Do(req)
91- if err != nil {
92- return err
93- }
94- defer resp.Body.Close()
95- if resp.StatusCode != http.StatusOK {
96- return fmt.Errorf("%s %s: %s", method, url, resp.Status)
97- }
98- return json.NewDecoder(resp.Body).Decode(out)
99-}
100-
101-// Models lists the models a server serves: llmman's and Ollama's /api/tags,
102-// the OpenAI /models of the others. Sorted. For `openai` the key is read
103-// from OPENAI_API_KEY; ListModels takes it from elsewhere.
104-//
105-// names, err := agentinit.Models(ctx, "llmman", "http://127.0.0.1:17434/v1")
106-func Models(ctx context.Context, provider, base string) ([]string, error) {
107- key := ""
108- if isOpenAI(provider) {
109- key = os.Getenv("OPENAI_API_KEY")
110- }
111- return ListModels(ctx, provider, base, key)
112-}
113-
11441 // Timeouts of a model list: a local server answers at once or is not
11542 // there — the first question probes four of them, so it must stay short; a
11643 // remote service (provider openai) may take seconds on a first, cold
@@ -121,48 +48,6 @@ const (
12148 remoteListTimeout = 20 * time.Second
12249 )
12350
124-// ListModels is Models with the API key given (sent as a Bearer token when
125-// not empty) — the key of an OpenAI-compatible service, read from the
126-// variable the user named.
127-//
128-// names, err := agentinit.ListModels(ctx, "openai", "https://api.cerebras.ai/v1", os.Getenv("CEREBRAS_API_KEY"))
129-func ListModels(ctx context.Context, provider, base, key string) ([]string, error) {
130- ctx = withKey(ctx, key)
131- timeout := localListTimeout
132- if isOpenAI(provider) {
133- timeout = remoteListTimeout
134- }
135- var names []string
136- switch provider {
137- case "llmman", "ollama":
138- var tags struct {
139- Models []struct {
140- Name string `json:"name"`
141- } `json:"models"`
142- }
143- if err := call(ctx, http.MethodGet, root(base)+"/api/tags", nil, timeout, &tags); err != nil {
144- return nil, err
145- }
146- for _, m := range tags.Models {
147- names = append(names, m.Name)
148- }
149- default:
150- var list struct {
151- Data []struct {
152- ID string `json:"id"`
153- } `json:"data"`
154- }
155- if err := call(ctx, http.MethodGet, strings.TrimRight(base, "/")+"/models", nil, timeout, &list); err != nil {
156- return nil, err
157- }
158- for _, m := range list.Data {
159- names = append(names, m.ID)
160- }
161- }
162- sort.Strings(names)
163- return names, nil
164-}
165-
16651 // ModelFacts asks the server about one model. llmman and Ollama answer
16752 // /api/show (GGUF metadata, chat template); llama-server answers /props
16853 // (window, chat template); Kronk answers /v1/kronk/models/<id> (GGUF
@@ -221,85 +106,6 @@ func mlxFacts(ctx context.Context, base, model string) Facts {
221106 return f
222107 }
223108
224-// modelDetail is the line shown beside a model in the wizard's list, "" for
225-// most. Kronk lists configuration profiles beside the models
226-// (`provider/modelID/PROFILE`, e.g. `…/Qwopus3.5-4B-Coder.Q8_0/AGENT`): the
227-// same weights, served with the settings of that key in Kronk's
228-// model_config.yaml (its own window, max_tokens…). A valid choice, but one
229-// that looks like a stray file without a word of explanation.
230-//
231-// modelDetail("kronk", "mradermacher/Qwopus3.5-4B-Coder.Q8_0/AGENT")
232-// // "Kronk profile of mradermacher/Qwopus3.5-4B-Coder.Q8_0: same model, its own settings in model_config.yaml"
233-func modelDetail(provider, model string) string {
234- profile, ok := kronkProfile(provider, model)
235- if !ok {
236- return ""
237- }
238- base := strings.TrimSuffix(model, "/"+profile)
239- return "Kronk profile of " + base + ": same model, its own settings in model_config.yaml"
240-}
241-
242-// kronkProfile returns the profile a Kronk model id names: the third
243-// segment of `provider/modelID/PROFILE`.
244-//
245-// kronkProfile("kronk", "mradermacher/Qwopus3.5-4B-Coder.Q8_0/AGENT") // "AGENT", true
246-func kronkProfile(provider, model string) (string, bool) {
247- if provider != "kronk" || strings.Count(model, "/") != 2 {
248- return "", false
249- }
250- return model[strings.LastIndex(model, "/")+1:], true
251-}
252-
253-// kronkFacts reads Kronk's model details (measured on Kronk 1.33.2): the
254-// GGUF metadata as strings — `general.architecture`, `<arch>.context_length`,
255-// `general.sampling.*`, `tokenizer.chat_template` — and the configuration
256-// it serves the model with, whose `context-window` is the window actually
257-// served (131072 for a model trained on 262144). The id holds a "/", so it
258-// goes in the path escaped.
259-func kronkFacts(ctx context.Context, base, model string) Facts {
260- var details struct {
261- Metadata map[string]string `json:"metadata"`
262- Config struct {
263- ContextWindow int `json:"context-window"`
264- Sampling map[string]any `json:"sampling-parameters"`
265- } `json:"model_config"`
266- }
267- url := root(base) + "/v1/kronk/models/" + neturl.PathEscape(model)
268- if err := call(ctx, http.MethodGet, url, nil, 30*time.Second, &details); err != nil {
269- return Facts{}
270- }
271- arch := details.Metadata["general.architecture"]
272- f := Facts{Known: true, ServerFamily: arch, Sampling: map[string]float64{}, Thinking: templateThinking(details.Metadata["tokenizer.chat_template"])}
273- f.ContextLength = details.Config.ContextWindow
274- if f.ContextLength == 0 {
275- f.ContextLength, _ = strconv.Atoi(details.Metadata[arch+".context_length"])
276- }
277- for key, value := range details.Metadata {
278- if name, ok := strings.CutPrefix(key, "general.sampling."); ok {
279- if n, err := strconv.ParseFloat(value, 64); err == nil {
280- f.Sampling[samplingKey(name)] = n
281- }
282- }
283- }
284- if profile, ok := kronkProfile("kronk", model); ok {
285- f.Profile, f.ProfileSampling = profile, profileSampling(details.Config.Sampling)
286- }
287- return f
288-}
289-
290-// profileSampling keeps, from a Kronk profile's `sampling-parameters`, the
291-// keys mm's file sets: the four sampling numbers, and max_tokens when the
292-// profile caps it (0 means no cap).
293-func profileSampling(params map[string]any) map[string]float64 {
294- out := map[string]float64{}
295- for _, k := range []string{"temperature", "top_p", "top_k", "min_p", "max_tokens"} {
296- if n, ok := params[k].(float64); ok && (k != "max_tokens" || n > 0) {
297- out[k] = n
298- }
299- }
300- return out
301-}
302-
303109 func showFacts(ctx context.Context, base, model string) Facts {
304110 var show struct {
305111 ModelInfo map[string]any `json:"model_info"`
@@ -1,13 +1,9 @@
1 package agentinit1 package agentinit
2 2
3 import (3 import (
4- "bytes"
5 "context"4 "context"
6- "encoding/json"
7- "fmt"
8 "net/http"5 "net/http"
9 neturl "net/url"6 neturl "net/url"
10- "os"
11 "regexp"7 "regexp"
12 "sort"8 "sort"
13 "strconv"9 "strconv"
@@ -42,75 +38,6 @@ type Thinking struct {
42 EffortValues []string // the reasoning_effort values the template names38 EffortValues []string // the reasoning_effort values the template names
43 }39 }
44 40
45-// root is a server's address without its OpenAI prefix: llmman's and
46-// Ollama's /api/*, llama.cpp's /props live there.
47-func root(base string) string {
48- base = strings.TrimRight(base, "/")
49- for _, suffix := range []string{"/engines/v1", "/v1"} {
50- if strings.HasSuffix(base, suffix) {
51- return strings.TrimSuffix(base, suffix)
52- }
53- }
54- return base
55-}
56-
57-var client = &http.Client{}
58-
59-// keyContext carries the key a provider needs to list its models (the
60-// generic `openai` one: a remote API answers 401 to an anonymous request).
61-type keyContext struct{}
62-
63-func withKey(ctx context.Context, key string) context.Context {
64- return context.WithValue(ctx, keyContext{}, key)
65-}
66-
67-func apiKey(ctx context.Context) string {
68- key, _ := ctx.Value(keyContext{}).(string)
69- return key
70-}
71-
72-func call(ctx context.Context, method, url string, body any, timeout time.Duration, out any) error {
73- ctx, cancel := context.WithTimeout(ctx, timeout)
74- defer cancel()
75- var reader *bytes.Reader
76- if body != nil {
77- data, _ := json.Marshal(body)
78- reader = bytes.NewReader(data)
79- } else {
80- reader = bytes.NewReader(nil)
81- }
82- req, err := http.NewRequestWithContext(ctx, method, url, reader)
83- if err != nil {
84- return err
85- }
86- req.Header.Set("Content-Type", "application/json")
87- if key := apiKey(ctx); key != "" {
88- req.Header.Set("Authorization", "Bearer "+key)
89- }
90- resp, err := client.Do(req)
91- if err != nil {
92- return err
93- }
94- defer resp.Body.Close()
95- if resp.StatusCode != http.StatusOK {
96- return fmt.Errorf("%s %s: %s", method, url, resp.Status)
97- }
98- return json.NewDecoder(resp.Body).Decode(out)
99-}
100-
101-// Models lists the models a server serves: llmman's and Ollama's /api/tags,
102-// the OpenAI /models of the others. Sorted. For `openai` the key is read
103-// from OPENAI_API_KEY; ListModels takes it from elsewhere.
104-//
105-// names, err := agentinit.Models(ctx, "llmman", "http://127.0.0.1:17434/v1")
106-func Models(ctx context.Context, provider, base string) ([]string, error) {
107- key := ""
108- if isOpenAI(provider) {
109- key = os.Getenv("OPENAI_API_KEY")
110- }
111- return ListModels(ctx, provider, base, key)
112-}
113-
114 // Timeouts of a model list: a local server answers at once or is not41 // Timeouts of a model list: a local server answers at once or is not
115 // there — the first question probes four of them, so it must stay short; a42 // there — the first question probes four of them, so it must stay short; a
116 // remote service (provider openai) may take seconds on a first, cold43 // remote service (provider openai) may take seconds on a first, cold
@@ -121,48 +48,6 @@ const (
121 remoteListTimeout = 20 * time.Second48 remoteListTimeout = 20 * time.Second
122 )49 )
123 50
124-// ListModels is Models with the API key given (sent as a Bearer token when
125-// not empty) — the key of an OpenAI-compatible service, read from the
126-// variable the user named.
127-//
128-// names, err := agentinit.ListModels(ctx, "openai", "https://api.cerebras.ai/v1", os.Getenv("CEREBRAS_API_KEY"))
129-func ListModels(ctx context.Context, provider, base, key string) ([]string, error) {
130- ctx = withKey(ctx, key)
131- timeout := localListTimeout
132- if isOpenAI(provider) {
133- timeout = remoteListTimeout
134- }
135- var names []string
136- switch provider {
137- case "llmman", "ollama":
138- var tags struct {
139- Models []struct {
140- Name string `json:"name"`
141- } `json:"models"`
142- }
143- if err := call(ctx, http.MethodGet, root(base)+"/api/tags", nil, timeout, &tags); err != nil {
144- return nil, err
145- }
146- for _, m := range tags.Models {
147- names = append(names, m.Name)
148- }
149- default:
150- var list struct {
151- Data []struct {
152- ID string `json:"id"`
153- } `json:"data"`
154- }
155- if err := call(ctx, http.MethodGet, strings.TrimRight(base, "/")+"/models", nil, timeout, &list); err != nil {
156- return nil, err
157- }
158- for _, m := range list.Data {
159- names = append(names, m.ID)
160- }
161- }
162- sort.Strings(names)
163- return names, nil
164-}
165-
166 // ModelFacts asks the server about one model. llmman and Ollama answer51 // ModelFacts asks the server about one model. llmman and Ollama answer
167 // /api/show (GGUF metadata, chat template); llama-server answers /props52 // /api/show (GGUF metadata, chat template); llama-server answers /props
168 // (window, chat template); Kronk answers /v1/kronk/models/<id> (GGUF53 // (window, chat template); Kronk answers /v1/kronk/models/<id> (GGUF
@@ -221,85 +106,6 @@ func mlxFacts(ctx context.Context, base, model string) Facts {
221 return f106 return f
222 }107 }
223 108
224-// modelDetail is the line shown beside a model in the wizard's list, "" for
225-// most. Kronk lists configuration profiles beside the models
226-// (`provider/modelID/PROFILE`, e.g. `…/Qwopus3.5-4B-Coder.Q8_0/AGENT`): the
227-// same weights, served with the settings of that key in Kronk's
228-// model_config.yaml (its own window, max_tokens…). A valid choice, but one
229-// that looks like a stray file without a word of explanation.
230-//
231-// modelDetail("kronk", "mradermacher/Qwopus3.5-4B-Coder.Q8_0/AGENT")
232-// // "Kronk profile of mradermacher/Qwopus3.5-4B-Coder.Q8_0: same model, its own settings in model_config.yaml"
233-func modelDetail(provider, model string) string {
234- profile, ok := kronkProfile(provider, model)
235- if !ok {
236- return ""
237- }
238- base := strings.TrimSuffix(model, "/"+profile)
239- return "Kronk profile of " + base + ": same model, its own settings in model_config.yaml"
240-}
241-
242-// kronkProfile returns the profile a Kronk model id names: the third
243-// segment of `provider/modelID/PROFILE`.
244-//
245-// kronkProfile("kronk", "mradermacher/Qwopus3.5-4B-Coder.Q8_0/AGENT") // "AGENT", true
246-func kronkProfile(provider, model string) (string, bool) {
247- if provider != "kronk" || strings.Count(model, "/") != 2 {
248- return "", false
249- }
250- return model[strings.LastIndex(model, "/")+1:], true
251-}
252-
253-// kronkFacts reads Kronk's model details (measured on Kronk 1.33.2): the
254-// GGUF metadata as strings — `general.architecture`, `<arch>.context_length`,
255-// `general.sampling.*`, `tokenizer.chat_template` — and the configuration
256-// it serves the model with, whose `context-window` is the window actually
257-// served (131072 for a model trained on 262144). The id holds a "/", so it
258-// goes in the path escaped.
259-func kronkFacts(ctx context.Context, base, model string) Facts {
260- var details struct {
261- Metadata map[string]string `json:"metadata"`
262- Config struct {
263- ContextWindow int `json:"context-window"`
264- Sampling map[string]any `json:"sampling-parameters"`
265- } `json:"model_config"`
266- }
267- url := root(base) + "/v1/kronk/models/" + neturl.PathEscape(model)
268- if err := call(ctx, http.MethodGet, url, nil, 30*time.Second, &details); err != nil {
269- return Facts{}
270- }
271- arch := details.Metadata["general.architecture"]
272- f := Facts{Known: true, ServerFamily: arch, Sampling: map[string]float64{}, Thinking: templateThinking(details.Metadata["tokenizer.chat_template"])}
273- f.ContextLength = details.Config.ContextWindow
274- if f.ContextLength == 0 {
275- f.ContextLength, _ = strconv.Atoi(details.Metadata[arch+".context_length"])
276- }
277- for key, value := range details.Metadata {
278- if name, ok := strings.CutPrefix(key, "general.sampling."); ok {
279- if n, err := strconv.ParseFloat(value, 64); err == nil {
280- f.Sampling[samplingKey(name)] = n
281- }
282- }
283- }
284- if profile, ok := kronkProfile("kronk", model); ok {
285- f.Profile, f.ProfileSampling = profile, profileSampling(details.Config.Sampling)
286- }
287- return f
288-}
289-
290-// profileSampling keeps, from a Kronk profile's `sampling-parameters`, the
291-// keys mm's file sets: the four sampling numbers, and max_tokens when the
292-// profile caps it (0 means no cap).
293-func profileSampling(params map[string]any) map[string]float64 {
294- out := map[string]float64{}
295- for _, k := range []string{"temperature", "top_p", "top_k", "min_p", "max_tokens"} {
296- if n, ok := params[k].(float64); ok && (k != "max_tokens" || n > 0) {
297- out[k] = n
298- }
299- }
300- return out
301-}
302-
303 func showFacts(ctx context.Context, base, model string) Facts {109 func showFacts(ctx context.Context, base, model string) Facts {
304 var show struct {110 var show struct {
305 ModelInfo map[string]any `json:"model_info"`111 ModelInfo map[string]any `json:"model_info"`
modified internal/agentinit/flow.go +0 -445
@@ -2,11 +2,8 @@ package agentinit
22
33 import (
44 "context"
5- "fmt"
6- "os"
75 "path/filepath"
86 "regexp"
9- "strings"
107
118 "mm/internal/config"
129 "mm/internal/elicit"
@@ -212,123 +209,6 @@ func (f *Flow) usageOrDefault() string {
212209 return "developer"
213210 }
214211
215-// Step builds one question as it stands now: its options may depend on the
216-// answers before it (the model list on the server, the family's default on
217-// the model).
218-func (f *Flow) Step(key string) Step {
219- st := Step{Key: key, Title: stepTitles[key], Value: f.answer[key], Given: f.given[key], Kind: elicit.Choice}
220- if st.Value != "" {
221- // Answered: the list of steps needs its title and value only — the
222- // options (a probe of every server, the model list) are built when
223- // the question is asked again.
224- return st
225- }
226- switch key {
227- case "provider":
228- st.Prompt = "Model server?"
229- for _, name := range providers {
230- detail := "not probed: its default address is the OpenAI API"
231- if contains(local, name) {
232- detail = "does not answer"
233- if f.answers(name) {
234- detail = "answers"
235- }
236- }
237- st.Options = append(st.Options, Option{Value: name, Label: name, Detail: detail})
238- }
239- st.Default = f.firstAnswering()
240- case "endpoint":
241- st.Prompt, st.Kind, st.Default = "Endpoint (the service's OpenAI-compatible address)?", elicit.Text, openAIDefaultBase()
242- case "keyenv":
243- st.Prompt, st.Kind, st.Default = "Environment variable that holds the API key?", elicit.Text, defaultKeyEnv
244- case "model":
245- st.Prompt = "Model?"
246- models := f.modelList()
247- if len(models) == 0 {
248- st.Kind, st.Prompt = elicit.Text, f.typeModelPrompt()
249- break
250- }
251- // Where the list comes from (ticket 214): a wrong address — the
252- // container one on the host — shows at once.
253- st.Prompt = fmt.Sprintf("Model? (listed from %s)", f.Base())
254- for _, m := range models {
255- st.Options = append(st.Options, Option{Value: m, Label: m, Detail: modelDetail(f.c.Provider, m)})
256- }
257- st.Default = models[0]
258- case "family":
259- st.Prompt = "Model family?"
260- for _, fam := range f.presets.Families {
261- st.Options = append(st.Options, Option{Value: fam.Name, Label: fam.Name, Detail: fam.Source})
262- }
263- st.Default = f.presets.FamilyOf(f.c.Model, f.modelFacts().ServerFamily).Name
264- case "usage":
265- st.Prompt = "What is the agent for?"
266- for _, u := range f.presets.Usages {
267- st.Options = append(st.Options, Option{Value: u.Name, Label: u.Name, Detail: u.Description})
268- }
269- st.Default = "developer"
270- case "machine":
271- st.Prompt = "Which machine runs the model?"
272- for _, m := range f.presets.Machines {
273- st.Options = append(st.Options, Option{Value: m.Name, Label: m.Name, Detail: m.Description})
274- }
275- st.Default = "small"
276- case "yolo":
277- st.Prompt, st.Kind = "Ask before each command or file change?", elicit.Confirm
278- u, _ := f.presets.Usage(f.usageOrDefault())
279- st.Default = yesNo(!u.Yolo)
280- st.Options = []Option{
281- {Value: "yes", Label: "yes", Detail: "every command and file change waits for your answer (yolo: false)"},
282- {Value: "no", Label: "no", Detail: "tools run without asking (yolo: true)"},
283- }
284- case "name":
285- st.Prompt, st.Kind, st.Default = "Agent name?", elicit.Text, f.usageOrDefault()
286- case "project":
287- st = yesNoStep(st, "Keep everything in a .mm folder?",
288- "creates .mm/ and writes .mm/agent.yaml; its paths start at the project root, and mm finds it on its own",
289- "one agent.yaml, in the file you choose")
290- case "sessions":
291- st = yesNoStep(st, "Save the conversations?",
292- "writes a sessions section: every conversation is saved in .mm/sessions, /resume reopens one",
293- "no sessions section: nothing is saved (mm's default)")
294- case "skills":
295- st = yesNoStep(st, "Use skills?",
296- "writes skillsDir: "+f.c.SkillsDir()+" and creates that folder",
297- "skillsDir: no-skills")
298- case "autostart":
299- if f.c.Provider == "razorbill" {
300- st = yesNoStep(st, "Let mm start rzb when it is not running?",
301- "razorbill.autoStart: true — mm starts rzb serve (macOS, mm on the Mac itself: not in a container or a sandbox), downloads this model when missing, and stops it with the last mm session",
302- "razorbill.autoStart: false — you start rzb serve yourself")
303- } else {
304- st = yesNoStep(st, "Let mm start llama-server when it is not running?",
305- "llamacpp.autoStart: true — mm starts it with this model (downloaded on first use) and stops it with the last mm session",
306- "llamacpp.autoStart: false — you start llama-server yourself")
307- }
308- st.Default = "yes"
309- case "launch":
310- st = yesNoStep(st, "Write llama-server's launch settings?",
311- "the Llama app's values (modelsMax, modelsMemoryMargin, fitTarget, sleepIdleSeconds, specDefault), each one editable or removable",
312- "none: llama-server's own defaults")
313- case "file":
314- st.Prompt, st.Kind, st.Default = "File to write?", elicit.Text, f.defaultFile()
315- case "overwrite":
316- st.Prompt, st.Kind, st.Default = "Overwrite "+filepath.Base(f.output)+"?", elicit.Confirm, "no"
317- st.Options = []Option{
318- {Value: "yes", Label: "yes", Detail: "replace the existing file"},
319- {Value: "no", Label: "no", Detail: "keep it and choose another file"},
320- }
321- }
322- return st
323-}
324-
325-// yesNoStep is a yes/no question whose default is no.
326-func yesNoStep(st Step, prompt, yes, no string) Step {
327- st.Prompt, st.Kind, st.Default = prompt, elicit.Confirm, "no"
328- st.Options = []Option{{Value: "yes", Label: "yes", Detail: yes}, {Value: "no", Label: "no", Detail: no}}
329- return st
330-}
331-
332212 // defaultFile is the file offered: .mm/agent.yaml for the Project layout,
333213 // where mm looks for it after ./agent.yaml.
334214 func (f *Flow) defaultFile() string {
@@ -338,262 +218,6 @@ func (f *Flow) defaultFile() string {
338218 return config.DefaultPath
339219 }
340220
341-// checkLayout refuses a Project layout whose file is not in .mm/: its paths
342-// are written from the project root, which holds only for a file directly
343-// in a .mm folder. "-" (stdout) is always fine: nothing is created.
344-func checkLayout(project bool, output string) error {
345- if !project || output == "" || output == "-" {
346- return nil
347- }
348- if filepath.Base(filepath.Dir(filepath.Clean(output))) != config.ProjectDir {
349- return fmt.Errorf("file: %q is not in a %s folder — the Project layout writes .mm/agent.yaml (or answer no to the Project question)", output, config.ProjectDir)
350- }
351- return nil
352-}
353-
354-// setYesNo reads a yes/no answer into one of the optional switches.
355-func setYesNo(key, value string, target **bool) error {
356- if value != "yes" && value != "no" {
357- return fmt.Errorf("%s: answer yes or no, not %q", key, value)
358- }
359- answer := value == "yes"
360- *target = &answer
361- return nil
362-}
363-
364-// Set answers one question. A new server forgets the model (and the
365-// family, unless a flag gave it); a new model forgets the facts.
366-func (f *Flow) Set(key, value string) error {
367- value = strings.TrimSpace(value)
368- if value == "" {
369- return fmt.Errorf("%s: an answer is needed", key)
370- }
371- switch key {
372- case "provider":
373- if !contains(providers, value) {
374- return fmt.Errorf("unknown provider %q (known: %s)", value, strings.Join(providers, ", "))
375- }
376- if value != f.c.Provider {
377- f.c.Provider = value
378- f.base = ""
379- f.forget("model")
380- f.c.Model = ""
381- // The endpoint and the key's variable belong to openai: a
382- // change of server forgets those answered here.
383- f.forgetService()
384- }
385- case "endpoint":
386- if !strings.HasPrefix(value, "http://") && !strings.HasPrefix(value, "https://") {
387- return fmt.Errorf("endpoint: %q is not an http:// or https:// address", value)
388- }
389- value = strings.TrimRight(value, "/")
390- // The OpenAI API's own address is openai's default: no baseUrl
391- // line then, the file records it as a comment instead.
392- f.c.BaseURL = value
393- if isOpenAI(f.c.Provider) && value == openAIDefaultBase() {
394- f.c.BaseURL = ""
395- }
396- f.base = ""
397- f.forget("model")
398- case "keyenv":
399- if !envName.MatchString(value) {
400- return fmt.Errorf("API key: %q is not a variable name (letters, digits, _)", value)
401- }
402- f.c.APIKeyEnv = ""
403- if value != defaultKeyEnv {
404- f.c.APIKeyEnv = value
405- }
406- f.forget("model")
407- case "model":
408- if value != f.c.Model {
409- f.c.Model = value
410- f.forget("family")
411- }
412- case "family":
413- if f.presets.Family(value).Name == "" {
414- return fmt.Errorf("unknown family %q", value)
415- }
416- f.c.Family = value
417- case "usage":
418- if _, ok := f.presets.Usage(value); !ok {
419- return fmt.Errorf("unknown usage %q (known: %s)", value, strings.Join(f.presets.UsageNames(), ", "))
420- }
421- f.c.Usage = value
422- case "machine":
423- if _, ok := f.presets.Machine(value); !ok {
424- return fmt.Errorf("unknown machine %q (known: %s)", value, strings.Join(f.presets.MachineNames(), ", "))
425- }
426- f.c.Machine = value
427- case "yolo":
428- ask := value == "yes"
429- yolo := !ask
430- f.c.Yolo = &yolo
431- case "project":
432- if err := f.setProject(value); err != nil {
433- return err
434- }
435- case "sessions":
436- if err := setYesNo(key, value, &f.c.Sessions); err != nil {
437- return err
438- }
439- case "skills":
440- if err := setYesNo(key, value, &f.c.Skills); err != nil {
441- return err
442- }
443- case "autostart":
444- if err := setYesNo(key, value, &f.c.AutoStart); err != nil {
445- return err
446- }
447- if !on(f.c.AutoStart) && !f.given["launch"] {
448- // No start, no launch settings: the question is gone.
449- f.c.Launch = nil
450- delete(f.answer, "launch")
451- }
452- case "launch":
453- if err := setYesNo(key, value, &f.c.Launch); err != nil {
454- return err
455- }
456- case "name":
457- f.c.Name = value
458- case "file":
459- if err := checkLayout(on(f.c.Project), value); err != nil {
460- return err
461- }
462- f.output = value
463- f.forgetOverwrite()
464- case "overwrite":
465- if value != "yes" && value != "no" {
466- return fmt.Errorf("overwrite: answer yes or no, not %q", value)
467- }
468- if value == "no" {
469- // Back to the file question, even for a file named by -o.
470- f.output = ""
471- delete(f.given, "file")
472- delete(f.answer, "file")
473- return nil
474- }
475- f.overwrite = true
476- default:
477- return fmt.Errorf("no question %q", key)
478- }
479- f.answer[key] = value
480- return nil
481-}
482-
483-// setProject answers the layout question. A file named by -o must suit the
484-// layout; a file answered here for the other layout is asked again, with
485-// the other default.
486-func (f *Flow) setProject(value string) error {
487- if f.given["file"] {
488- if err := checkLayout(value == "yes", f.output); err != nil {
489- return err
490- }
491- }
492- before := on(f.c.Project)
493- if err := setYesNo("project", value, &f.c.Project); err != nil {
494- return err
495- }
496- if on(f.c.Project) != before && !f.given["file"] {
497- delete(f.answer, "file")
498- f.output = ""
499- f.forgetOverwrite()
500- }
501- return nil
502-}
503-
504-// Unset takes an answer back (the window's Esc), unless a flag gave it.
505-func (f *Flow) Unset(key string) {
506- if f.given[key] {
507- return
508- }
509- delete(f.answer, key)
510- switch key {
511- case "endpoint":
512- f.c.BaseURL, f.base = "", ""
513- case "keyenv":
514- f.c.APIKeyEnv = ""
515- case "family":
516- f.c.Family = ""
517- case "usage":
518- f.c.Usage = ""
519- case "machine":
520- f.c.Machine = ""
521- case "yolo":
522- f.c.Yolo = nil
523- case "project":
524- f.c.Project = nil
525- // The file offered depended on the layout.
526- if !f.given["file"] {
527- delete(f.answer, "file")
528- f.output = ""
529- f.forgetOverwrite()
530- }
531- case "sessions":
532- f.c.Sessions = nil
533- case "skills":
534- f.c.Skills = nil
535- case "autostart":
536- f.c.AutoStart = nil
537- case "launch":
538- f.c.Launch = nil
539- case "name":
540- f.c.Name = ""
541- case "file":
542- f.output = ""
543- f.forgetOverwrite()
544- case "overwrite":
545- f.forgetOverwrite()
546- }
547-}
548-
549-// forgetOverwrite drops the agreement: it was about one file.
550-func (f *Flow) forgetOverwrite() {
551- f.overwrite = false
552- delete(f.answer, "overwrite")
553-}
554-
555-func (f *Flow) forget(key string) {
556- if !f.given[key] {
557- delete(f.answer, key)
558- if key == "family" {
559- f.c.Family = ""
560- }
561- }
562-}
563-
564-// forgetService drops the endpoint and key variable answered for openai
565-// (not those given by flags), when another server is chosen.
566-func (f *Flow) forgetService() {
567- if !f.given["endpoint"] {
568- delete(f.answer, "endpoint")
569- f.c.BaseURL = ""
570- }
571- if !f.given["keyenv"] {
572- delete(f.answer, "keyenv")
573- f.c.APIKeyEnv = ""
574- }
575-}
576-
577-// keyEnv is the variable the openai provider reads its key from.
578-func (f *Flow) keyEnv() string {
579- if f.c.APIKeyEnv != "" {
580- return f.c.APIKeyEnv
581- }
582- return defaultKeyEnv
583-}
584-
585-// typeModelPrompt asks for the model's ID when there is no list, and says
586-// why — in the window as in the line mode, both show the prompt.
587-func (f *Flow) typeModelPrompt() string {
588- if isOpenAI(f.c.Provider) && os.Getenv(f.keyEnv()) == "" {
589- return fmt.Sprintf("Model ID? (%s is not set: no list — type it)", f.keyEnv())
590- }
591- if f.modelsErr != nil {
592- return fmt.Sprintf("Model ID? (no list from %s: %v)", f.Base(), f.modelsErr)
593- }
594- return "Model (as the server names it)?"
595-}
596-
597221 // isOpenAI: the provider is an OpenAI-compatible service mm asks for an
598222 // endpoint and a key variable — `openai` (Chat Completions) and
599223 // `openai-responses` (the Responses API, ticket 178), which share their
@@ -648,72 +272,3 @@ func (f *Flow) Choices() Choices { return f.c }
648272 func (f *Flow) Result() (Choices, Facts, string) {
649273 return f.c, f.modelFacts(), f.output
650274 }
651-
652-// Base is the resolved server address ("" before a provider is chosen).
653-func (f *Flow) Base() string {
654- if f.base == "" && f.c.Provider != "" {
655- f.base = resolveBase(f.ctx, f.c)
656- }
657- return f.base
658-}
659-
660-func (f *Flow) modelList() []string {
661- if f.c.Provider == "" {
662- return nil
663- }
664- key := f.c.Provider + " " + f.Base()
665- if isOpenAI(f.c.Provider) {
666- key += " " + f.keyEnv()
667- }
668- if f.listed != key {
669- f.models, f.modelsErr = f.listModels()
670- f.listed = key
671- }
672- return f.models
673-}
674-
675-// listModels asks the server for its models. An OpenAI-compatible service
676-// is asked with the key read from the variable the user named — and not at
677-// all when that variable is empty: the request would only be refused.
678-func (f *Flow) listModels() ([]string, error) {
679- if !isOpenAI(f.c.Provider) {
680- return Models(f.ctx, f.c.Provider, f.Base())
681- }
682- key := os.Getenv(f.keyEnv())
683- if key == "" {
684- return nil, fmt.Errorf("%s is not set", f.keyEnv())
685- }
686- return ListModels(f.ctx, f.c.Provider, f.Base(), key)
687-}
688-
689-func (f *Flow) modelFacts() Facts {
690- if f.c.Model == "" || f.c.Provider == "" {
691- return Facts{}
692- }
693- if f.factsFor != f.c.Provider+" "+f.c.Model {
694- f.facts = ModelFacts(f.ctx, f.c.Provider, f.Base(), f.c.Model)
695- f.factsFor = f.c.Provider + " " + f.c.Model
696- }
697- return f.facts
698-}
699-
700-// answers reports, once per provider, whether its server answers.
701-func (f *Flow) answers(name string) bool {
702- if f.reachable == nil {
703- f.reachable = map[string]bool{}
704- for _, p := range local {
705- _, err := Models(f.ctx, p, resolveBase(f.ctx, Choices{Provider: p}))
706- f.reachable[p] = err == nil
707- }
708- }
709- return f.reachable[name]
710-}
711-
712-func (f *Flow) firstAnswering() string {
713- for _, name := range local {
714- if f.answers(name) {
715- return name
716- }
717- }
718- return providers[0]
719-}
@@ -2,11 +2,8 @@ package agentinit
2 2
3 import (3 import (
4 "context"4 "context"
5- "fmt"
6- "os"
7 "path/filepath"5 "path/filepath"
8 "regexp"6 "regexp"
9- "strings"
10 7
11 "mm/internal/config"8 "mm/internal/config"
12 "mm/internal/elicit"9 "mm/internal/elicit"
@@ -212,123 +209,6 @@ func (f *Flow) usageOrDefault() string {
212 return "developer"209 return "developer"
213 }210 }
214 211
215-// Step builds one question as it stands now: its options may depend on the
216-// answers before it (the model list on the server, the family's default on
217-// the model).
218-func (f *Flow) Step(key string) Step {
219- st := Step{Key: key, Title: stepTitles[key], Value: f.answer[key], Given: f.given[key], Kind: elicit.Choice}
220- if st.Value != "" {
221- // Answered: the list of steps needs its title and value only — the
222- // options (a probe of every server, the model list) are built when
223- // the question is asked again.
224- return st
225- }
226- switch key {
227- case "provider":
228- st.Prompt = "Model server?"
229- for _, name := range providers {
230- detail := "not probed: its default address is the OpenAI API"
231- if contains(local, name) {
232- detail = "does not answer"
233- if f.answers(name) {
234- detail = "answers"
235- }
236- }
237- st.Options = append(st.Options, Option{Value: name, Label: name, Detail: detail})
238- }
239- st.Default = f.firstAnswering()
240- case "endpoint":
241- st.Prompt, st.Kind, st.Default = "Endpoint (the service's OpenAI-compatible address)?", elicit.Text, openAIDefaultBase()
242- case "keyenv":
243- st.Prompt, st.Kind, st.Default = "Environment variable that holds the API key?", elicit.Text, defaultKeyEnv
244- case "model":
245- st.Prompt = "Model?"
246- models := f.modelList()
247- if len(models) == 0 {
248- st.Kind, st.Prompt = elicit.Text, f.typeModelPrompt()
249- break
250- }
251- // Where the list comes from (ticket 214): a wrong address — the
252- // container one on the host — shows at once.
253- st.Prompt = fmt.Sprintf("Model? (listed from %s)", f.Base())
254- for _, m := range models {
255- st.Options = append(st.Options, Option{Value: m, Label: m, Detail: modelDetail(f.c.Provider, m)})
256- }
257- st.Default = models[0]
258- case "family":
259- st.Prompt = "Model family?"
260- for _, fam := range f.presets.Families {
261- st.Options = append(st.Options, Option{Value: fam.Name, Label: fam.Name, Detail: fam.Source})
262- }
263- st.Default = f.presets.FamilyOf(f.c.Model, f.modelFacts().ServerFamily).Name
264- case "usage":
265- st.Prompt = "What is the agent for?"
266- for _, u := range f.presets.Usages {
267- st.Options = append(st.Options, Option{Value: u.Name, Label: u.Name, Detail: u.Description})
268- }
269- st.Default = "developer"
270- case "machine":
271- st.Prompt = "Which machine runs the model?"
272- for _, m := range f.presets.Machines {
273- st.Options = append(st.Options, Option{Value: m.Name, Label: m.Name, Detail: m.Description})
274- }
275- st.Default = "small"
276- case "yolo":
277- st.Prompt, st.Kind = "Ask before each command or file change?", elicit.Confirm
278- u, _ := f.presets.Usage(f.usageOrDefault())
279- st.Default = yesNo(!u.Yolo)
280- st.Options = []Option{
281- {Value: "yes", Label: "yes", Detail: "every command and file change waits for your answer (yolo: false)"},
282- {Value: "no", Label: "no", Detail: "tools run without asking (yolo: true)"},
283- }
284- case "name":
285- st.Prompt, st.Kind, st.Default = "Agent name?", elicit.Text, f.usageOrDefault()
286- case "project":
287- st = yesNoStep(st, "Keep everything in a .mm folder?",
288- "creates .mm/ and writes .mm/agent.yaml; its paths start at the project root, and mm finds it on its own",
289- "one agent.yaml, in the file you choose")
290- case "sessions":
291- st = yesNoStep(st, "Save the conversations?",
292- "writes a sessions section: every conversation is saved in .mm/sessions, /resume reopens one",
293- "no sessions section: nothing is saved (mm's default)")
294- case "skills":
295- st = yesNoStep(st, "Use skills?",
296- "writes skillsDir: "+f.c.SkillsDir()+" and creates that folder",
297- "skillsDir: no-skills")
298- case "autostart":
299- if f.c.Provider == "razorbill" {
300- st = yesNoStep(st, "Let mm start rzb when it is not running?",
301- "razorbill.autoStart: true — mm starts rzb serve (macOS, mm on the Mac itself: not in a container or a sandbox), downloads this model when missing, and stops it with the last mm session",
302- "razorbill.autoStart: false — you start rzb serve yourself")
303- } else {
304- st = yesNoStep(st, "Let mm start llama-server when it is not running?",
305- "llamacpp.autoStart: true — mm starts it with this model (downloaded on first use) and stops it with the last mm session",
306- "llamacpp.autoStart: false — you start llama-server yourself")
307- }
308- st.Default = "yes"
309- case "launch":
310- st = yesNoStep(st, "Write llama-server's launch settings?",
311- "the Llama app's values (modelsMax, modelsMemoryMargin, fitTarget, sleepIdleSeconds, specDefault), each one editable or removable",
312- "none: llama-server's own defaults")
313- case "file":
314- st.Prompt, st.Kind, st.Default = "File to write?", elicit.Text, f.defaultFile()
315- case "overwrite":
316- st.Prompt, st.Kind, st.Default = "Overwrite "+filepath.Base(f.output)+"?", elicit.Confirm, "no"
317- st.Options = []Option{
318- {Value: "yes", Label: "yes", Detail: "replace the existing file"},
319- {Value: "no", Label: "no", Detail: "keep it and choose another file"},
320- }
321- }
322- return st
323-}
324-
325-// yesNoStep is a yes/no question whose default is no.
326-func yesNoStep(st Step, prompt, yes, no string) Step {
327- st.Prompt, st.Kind, st.Default = prompt, elicit.Confirm, "no"
328- st.Options = []Option{{Value: "yes", Label: "yes", Detail: yes}, {Value: "no", Label: "no", Detail: no}}
329- return st
330-}
331-
332 // defaultFile is the file offered: .mm/agent.yaml for the Project layout,212 // defaultFile is the file offered: .mm/agent.yaml for the Project layout,
333 // where mm looks for it after ./agent.yaml.213 // where mm looks for it after ./agent.yaml.
334 func (f *Flow) defaultFile() string {214 func (f *Flow) defaultFile() string {
@@ -338,262 +218,6 @@ func (f *Flow) defaultFile() string {
338 return config.DefaultPath218 return config.DefaultPath
339 }219 }
340 220
341-// checkLayout refuses a Project layout whose file is not in .mm/: its paths
342-// are written from the project root, which holds only for a file directly
343-// in a .mm folder. "-" (stdout) is always fine: nothing is created.
344-func checkLayout(project bool, output string) error {
345- if !project || output == "" || output == "-" {
346- return nil
347- }
348- if filepath.Base(filepath.Dir(filepath.Clean(output))) != config.ProjectDir {
349- return fmt.Errorf("file: %q is not in a %s folder — the Project layout writes .mm/agent.yaml (or answer no to the Project question)", output, config.ProjectDir)
350- }
351- return nil
352-}
353-
354-// setYesNo reads a yes/no answer into one of the optional switches.
355-func setYesNo(key, value string, target **bool) error {
356- if value != "yes" && value != "no" {
357- return fmt.Errorf("%s: answer yes or no, not %q", key, value)
358- }
359- answer := value == "yes"
360- *target = &answer
361- return nil
362-}
363-
364-// Set answers one question. A new server forgets the model (and the
365-// family, unless a flag gave it); a new model forgets the facts.
366-func (f *Flow) Set(key, value string) error {
367- value = strings.TrimSpace(value)
368- if value == "" {
369- return fmt.Errorf("%s: an answer is needed", key)
370- }
371- switch key {
372- case "provider":
373- if !contains(providers, value) {
374- return fmt.Errorf("unknown provider %q (known: %s)", value, strings.Join(providers, ", "))
375- }
376- if value != f.c.Provider {
377- f.c.Provider = value
378- f.base = ""
379- f.forget("model")
380- f.c.Model = ""
381- // The endpoint and the key's variable belong to openai: a
382- // change of server forgets those answered here.
383- f.forgetService()
384- }
385- case "endpoint":
386- if !strings.HasPrefix(value, "http://") && !strings.HasPrefix(value, "https://") {
387- return fmt.Errorf("endpoint: %q is not an http:// or https:// address", value)
388- }
389- value = strings.TrimRight(value, "/")
390- // The OpenAI API's own address is openai's default: no baseUrl
391- // line then, the file records it as a comment instead.
392- f.c.BaseURL = value
393- if isOpenAI(f.c.Provider) && value == openAIDefaultBase() {
394- f.c.BaseURL = ""
395- }
396- f.base = ""
397- f.forget("model")
398- case "keyenv":
399- if !envName.MatchString(value) {
400- return fmt.Errorf("API key: %q is not a variable name (letters, digits, _)", value)
401- }
402- f.c.APIKeyEnv = ""
403- if value != defaultKeyEnv {
404- f.c.APIKeyEnv = value
405- }
406- f.forget("model")
407- case "model":
408- if value != f.c.Model {
409- f.c.Model = value
410- f.forget("family")
411- }
412- case "family":
413- if f.presets.Family(value).Name == "" {
414- return fmt.Errorf("unknown family %q", value)
415- }
416- f.c.Family = value
417- case "usage":
418- if _, ok := f.presets.Usage(value); !ok {
419- return fmt.Errorf("unknown usage %q (known: %s)", value, strings.Join(f.presets.UsageNames(), ", "))
420- }
421- f.c.Usage = value
422- case "machine":
423- if _, ok := f.presets.Machine(value); !ok {
424- return fmt.Errorf("unknown machine %q (known: %s)", value, strings.Join(f.presets.MachineNames(), ", "))
425- }
426- f.c.Machine = value
427- case "yolo":
428- ask := value == "yes"
429- yolo := !ask
430- f.c.Yolo = &yolo
431- case "project":
432- if err := f.setProject(value); err != nil {
433- return err
434- }
435- case "sessions":
436- if err := setYesNo(key, value, &f.c.Sessions); err != nil {
437- return err
438- }
439- case "skills":
440- if err := setYesNo(key, value, &f.c.Skills); err != nil {
441- return err
442- }
443- case "autostart":
444- if err := setYesNo(key, value, &f.c.AutoStart); err != nil {
445- return err
446- }
447- if !on(f.c.AutoStart) && !f.given["launch"] {
448- // No start, no launch settings: the question is gone.
449- f.c.Launch = nil
450- delete(f.answer, "launch")
451- }
452- case "launch":
453- if err := setYesNo(key, value, &f.c.Launch); err != nil {
454- return err
455- }
456- case "name":
457- f.c.Name = value
458- case "file":
459- if err := checkLayout(on(f.c.Project), value); err != nil {
460- return err
461- }
462- f.output = value
463- f.forgetOverwrite()
464- case "overwrite":
465- if value != "yes" && value != "no" {
466- return fmt.Errorf("overwrite: answer yes or no, not %q", value)
467- }
468- if value == "no" {
469- // Back to the file question, even for a file named by -o.
470- f.output = ""
471- delete(f.given, "file")
472- delete(f.answer, "file")
473- return nil
474- }
475- f.overwrite = true
476- default:
477- return fmt.Errorf("no question %q", key)
478- }
479- f.answer[key] = value
480- return nil
481-}
482-
483-// setProject answers the layout question. A file named by -o must suit the
484-// layout; a file answered here for the other layout is asked again, with
485-// the other default.
486-func (f *Flow) setProject(value string) error {
487- if f.given["file"] {
488- if err := checkLayout(value == "yes", f.output); err != nil {
489- return err
490- }
491- }
492- before := on(f.c.Project)
493- if err := setYesNo("project", value, &f.c.Project); err != nil {
494- return err
495- }
496- if on(f.c.Project) != before && !f.given["file"] {
497- delete(f.answer, "file")
498- f.output = ""
499- f.forgetOverwrite()
500- }
501- return nil
502-}
503-
504-// Unset takes an answer back (the window's Esc), unless a flag gave it.
505-func (f *Flow) Unset(key string) {
506- if f.given[key] {
507- return
508- }
509- delete(f.answer, key)
510- switch key {
511- case "endpoint":
512- f.c.BaseURL, f.base = "", ""
513- case "keyenv":
514- f.c.APIKeyEnv = ""
515- case "family":
516- f.c.Family = ""
517- case "usage":
518- f.c.Usage = ""
519- case "machine":
520- f.c.Machine = ""
521- case "yolo":
522- f.c.Yolo = nil
523- case "project":
524- f.c.Project = nil
525- // The file offered depended on the layout.
526- if !f.given["file"] {
527- delete(f.answer, "file")
528- f.output = ""
529- f.forgetOverwrite()
530- }
531- case "sessions":
532- f.c.Sessions = nil
533- case "skills":
534- f.c.Skills = nil
535- case "autostart":
536- f.c.AutoStart = nil
537- case "launch":
538- f.c.Launch = nil
539- case "name":
540- f.c.Name = ""
541- case "file":
542- f.output = ""
543- f.forgetOverwrite()
544- case "overwrite":
545- f.forgetOverwrite()
546- }
547-}
548-
549-// forgetOverwrite drops the agreement: it was about one file.
550-func (f *Flow) forgetOverwrite() {
551- f.overwrite = false
552- delete(f.answer, "overwrite")
553-}
554-
555-func (f *Flow) forget(key string) {
556- if !f.given[key] {
557- delete(f.answer, key)
558- if key == "family" {
559- f.c.Family = ""
560- }
561- }
562-}
563-
564-// forgetService drops the endpoint and key variable answered for openai
565-// (not those given by flags), when another server is chosen.
566-func (f *Flow) forgetService() {
567- if !f.given["endpoint"] {
568- delete(f.answer, "endpoint")
569- f.c.BaseURL = ""
570- }
571- if !f.given["keyenv"] {
572- delete(f.answer, "keyenv")
573- f.c.APIKeyEnv = ""
574- }
575-}
576-
577-// keyEnv is the variable the openai provider reads its key from.
578-func (f *Flow) keyEnv() string {
579- if f.c.APIKeyEnv != "" {
580- return f.c.APIKeyEnv
581- }
582- return defaultKeyEnv
583-}
584-
585-// typeModelPrompt asks for the model's ID when there is no list, and says
586-// why — in the window as in the line mode, both show the prompt.
587-func (f *Flow) typeModelPrompt() string {
588- if isOpenAI(f.c.Provider) && os.Getenv(f.keyEnv()) == "" {
589- return fmt.Sprintf("Model ID? (%s is not set: no list — type it)", f.keyEnv())
590- }
591- if f.modelsErr != nil {
592- return fmt.Sprintf("Model ID? (no list from %s: %v)", f.Base(), f.modelsErr)
593- }
594- return "Model (as the server names it)?"
595-}
596-
597 // isOpenAI: the provider is an OpenAI-compatible service mm asks for an221 // isOpenAI: the provider is an OpenAI-compatible service mm asks for an
598 // endpoint and a key variable — `openai` (Chat Completions) and222 // endpoint and a key variable — `openai` (Chat Completions) and
599 // `openai-responses` (the Responses API, ticket 178), which share their223 // `openai-responses` (the Responses API, ticket 178), which share their
@@ -648,72 +272,3 @@ func (f *Flow) Choices() Choices { return f.c }
648 func (f *Flow) Result() (Choices, Facts, string) {272 func (f *Flow) Result() (Choices, Facts, string) {
649 return f.c, f.modelFacts(), f.output273 return f.c, f.modelFacts(), f.output
650 }274 }
651-
652-// Base is the resolved server address ("" before a provider is chosen).
653-func (f *Flow) Base() string {
654- if f.base == "" && f.c.Provider != "" {
655- f.base = resolveBase(f.ctx, f.c)
656- }
657- return f.base
658-}
659-
660-func (f *Flow) modelList() []string {
661- if f.c.Provider == "" {
662- return nil
663- }
664- key := f.c.Provider + " " + f.Base()
665- if isOpenAI(f.c.Provider) {
666- key += " " + f.keyEnv()
667- }
668- if f.listed != key {
669- f.models, f.modelsErr = f.listModels()
670- f.listed = key
671- }
672- return f.models
673-}
674-
675-// listModels asks the server for its models. An OpenAI-compatible service
676-// is asked with the key read from the variable the user named — and not at
677-// all when that variable is empty: the request would only be refused.
678-func (f *Flow) listModels() ([]string, error) {
679- if !isOpenAI(f.c.Provider) {
680- return Models(f.ctx, f.c.Provider, f.Base())
681- }
682- key := os.Getenv(f.keyEnv())
683- if key == "" {
684- return nil, fmt.Errorf("%s is not set", f.keyEnv())
685- }
686- return ListModels(f.ctx, f.c.Provider, f.Base(), key)
687-}
688-
689-func (f *Flow) modelFacts() Facts {
690- if f.c.Model == "" || f.c.Provider == "" {
691- return Facts{}
692- }
693- if f.factsFor != f.c.Provider+" "+f.c.Model {
694- f.facts = ModelFacts(f.ctx, f.c.Provider, f.Base(), f.c.Model)
695- f.factsFor = f.c.Provider + " " + f.c.Model
696- }
697- return f.facts
698-}
699-
700-// answers reports, once per provider, whether its server answers.
701-func (f *Flow) answers(name string) bool {
702- if f.reachable == nil {
703- f.reachable = map[string]bool{}
704- for _, p := range local {
705- _, err := Models(f.ctx, p, resolveBase(f.ctx, Choices{Provider: p}))
706- f.reachable[p] = err == nil
707- }
708- }
709- return f.reachable[name]
710-}
711-
712-func (f *Flow) firstAnswering() string {
713- for _, name := range local {
714- if f.answers(name) {
715- return name
716- }
717- }
718- return providers[0]
719-}
added internal/agentinit/flow_answers.go +288 -0
new file mode 100644
@@ -0,0 +1,288 @@
1+package agentinit
2+
3+import (
4+ "fmt"
5+ "mm/internal/config"
6+ "path/filepath"
7+ "strings"
8+)
9+
10+// checkLayout refuses a Project layout whose file is not in .mm/: its paths
11+// are written from the project root, which holds only for a file directly
12+// in a .mm folder. "-" (stdout) is always fine: nothing is created.
13+func checkLayout(project bool, output string) error {
14+ if !project || output == "" || output == "-" {
15+ return nil
16+ }
17+ if filepath.Base(filepath.Dir(filepath.Clean(output))) != config.ProjectDir {
18+ return fmt.Errorf("file: %q is not in a %s folder — the Project layout writes .mm/agent.yaml (or answer no to the Project question)", output, config.ProjectDir)
19+ }
20+ return nil
21+}
22+
23+// setYesNo reads a yes/no answer into one of the optional switches.
24+func setYesNo(key, value string, target **bool) error {
25+ if value != "yes" && value != "no" {
26+ return fmt.Errorf("%s: answer yes or no, not %q", key, value)
27+ }
28+ answer := value == "yes"
29+ *target = &answer
30+ return nil
31+}
32+
33+// Set answers one question. A new server forgets the model (and the
34+// family, unless a flag gave it); a new model forgets the facts.
35+func (f *Flow) Set(key, value string) error {
36+ value = strings.TrimSpace(value)
37+ if value == "" {
38+ return fmt.Errorf("%s: an answer is needed", key)
39+ }
40+ set, ok := setters[key]
41+ if !ok {
42+ return fmt.Errorf("no question %q", key)
43+ }
44+ if err := set(f, value); err != nil {
45+ return err
46+ }
47+ // overwrite: no goes back to the file question: nothing to record.
48+ if key != "overwrite" || value != "no" {
49+ f.answer[key] = value
50+ }
51+ return nil
52+}
53+
54+// setters answer each question.
55+var setters = map[string]func(*Flow, string) error{
56+ "provider": (*Flow).setProvider,
57+ "endpoint": (*Flow).setEndpoint,
58+ "keyenv": (*Flow).setKeyEnv,
59+ "model": (*Flow).setModel,
60+ "family": (*Flow).setFamily,
61+ "usage": (*Flow).setUsage,
62+ "machine": (*Flow).setMachine,
63+ "yolo": (*Flow).setYolo,
64+ "project": (*Flow).setProject,
65+ "sessions": func(f *Flow, v string) error { return setYesNo("sessions", v, &f.c.Sessions) },
66+ "skills": func(f *Flow, v string) error { return setYesNo("skills", v, &f.c.Skills) },
67+ "autostart": (*Flow).setAutoStart,
68+ "launch": func(f *Flow, v string) error { return setYesNo("launch", v, &f.c.Launch) },
69+ "name": func(f *Flow, v string) error { f.c.Name = v; return nil },
70+ "file": (*Flow).setFile,
71+ "overwrite": (*Flow).setOverwrite,
72+}
73+
74+// setProvider: a new server forgets the model, and the endpoint and the
75+// key's variable answered here — they belong to openai.
76+func (f *Flow) setProvider(value string) error {
77+ if !contains(providers, value) {
78+ return fmt.Errorf("unknown provider %q (known: %s)", value, strings.Join(providers, ", "))
79+ }
80+ if value != f.c.Provider {
81+ f.c.Provider = value
82+ f.base = ""
83+ f.forget("model")
84+ f.c.Model = ""
85+ f.forgetService()
86+ }
87+ return nil
88+}
89+
90+// setEndpoint: the OpenAI API's own address is openai's default — no
91+// baseUrl line then, the file records it as a comment instead.
92+func (f *Flow) setEndpoint(value string) error {
93+ if !strings.HasPrefix(value, "http://") && !strings.HasPrefix(value, "https://") {
94+ return fmt.Errorf("endpoint: %q is not an http:// or https:// address", value)
95+ }
96+ value = strings.TrimRight(value, "/")
97+ f.c.BaseURL = value
98+ if isOpenAI(f.c.Provider) && value == openAIDefaultBase() {
99+ f.c.BaseURL = ""
100+ }
101+ f.base = ""
102+ f.forget("model")
103+ return nil
104+}
105+
106+func (f *Flow) setKeyEnv(value string) error {
107+ if !envName.MatchString(value) {
108+ return fmt.Errorf("API key: %q is not a variable name (letters, digits, _)", value)
109+ }
110+ f.c.APIKeyEnv = ""
111+ if value != defaultKeyEnv {
112+ f.c.APIKeyEnv = value
113+ }
114+ f.forget("model")
115+ return nil
116+}
117+
118+// setModel: a new model forgets the family.
119+func (f *Flow) setModel(value string) error {
120+ if value != f.c.Model {
121+ f.c.Model = value
122+ f.forget("family")
123+ }
124+ return nil
125+}
126+
127+func (f *Flow) setFamily(value string) error {
128+ if f.presets.Family(value).Name == "" {
129+ return fmt.Errorf("unknown family %q", value)
130+ }
131+ f.c.Family = value
132+ return nil
133+}
134+
135+func (f *Flow) setUsage(value string) error {
136+ if _, ok := f.presets.Usage(value); !ok {
137+ return fmt.Errorf("unknown usage %q (known: %s)", value, strings.Join(f.presets.UsageNames(), ", "))
138+ }
139+ f.c.Usage = value
140+ return nil
141+}
142+
143+func (f *Flow) setMachine(value string) error {
144+ if _, ok := f.presets.Machine(value); !ok {
145+ return fmt.Errorf("unknown machine %q (known: %s)", value, strings.Join(f.presets.MachineNames(), ", "))
146+ }
147+ f.c.Machine = value
148+ return nil
149+}
150+
151+// setYolo: the question is "ask before each change?" — yes is yolo: false.
152+func (f *Flow) setYolo(value string) error {
153+ yolo := value != "yes"
154+ f.c.Yolo = &yolo
155+ return nil
156+}
157+
158+// setAutoStart: no start, no launch settings — that question is gone,
159+// unless a flag answered it.
160+func (f *Flow) setAutoStart(value string) error {
161+ if err := setYesNo("autostart", value, &f.c.AutoStart); err != nil {
162+ return err
163+ }
164+ if !on(f.c.AutoStart) && !f.given["launch"] {
165+ f.c.Launch = nil
166+ delete(f.answer, "launch")
167+ }
168+ return nil
169+}
170+
171+func (f *Flow) setFile(value string) error {
172+ if err := checkLayout(on(f.c.Project), value); err != nil {
173+ return err
174+ }
175+ f.output = value
176+ f.forgetOverwrite()
177+ return nil
178+}
179+
180+// setOverwrite: no goes back to the file question, even for a file named
181+// by -o.
182+func (f *Flow) setOverwrite(value string) error {
183+ if value != "yes" && value != "no" {
184+ return fmt.Errorf("overwrite: answer yes or no, not %q", value)
185+ }
186+ if value == "no" {
187+ f.output = ""
188+ delete(f.given, "file")
189+ delete(f.answer, "file")
190+ return nil
191+ }
192+ f.overwrite = true
193+ return nil
194+}
195+
196+// setProject answers the layout question. A file named by -o must suit the
197+// layout; a file answered here for the other layout is asked again, with
198+// the other default.
199+func (f *Flow) setProject(value string) error {
200+ if f.given["file"] {
201+ if err := checkLayout(value == "yes", f.output); err != nil {
202+ return err
203+ }
204+ }
205+ before := on(f.c.Project)
206+ if err := setYesNo("project", value, &f.c.Project); err != nil {
207+ return err
208+ }
209+ if on(f.c.Project) != before && !f.given["file"] {
210+ delete(f.answer, "file")
211+ f.output = ""
212+ f.forgetOverwrite()
213+ }
214+ return nil
215+}
216+
217+// Unset takes an answer back (the window's Esc), unless a flag gave it.
218+func (f *Flow) Unset(key string) {
219+ if f.given[key] {
220+ return
221+ }
222+ delete(f.answer, key)
223+ switch key {
224+ case "endpoint":
225+ f.c.BaseURL, f.base = "", ""
226+ case "keyenv":
227+ f.c.APIKeyEnv = ""
228+ case "family":
229+ f.c.Family = ""
230+ case "usage":
231+ f.c.Usage = ""
232+ case "machine":
233+ f.c.Machine = ""
234+ case "yolo":
235+ f.c.Yolo = nil
236+ case "project":
237+ f.c.Project = nil
238+ // The file offered depended on the layout.
239+ if !f.given["file"] {
240+ delete(f.answer, "file")
241+ f.output = ""
242+ f.forgetOverwrite()
243+ }
244+ case "sessions":
245+ f.c.Sessions = nil
246+ case "skills":
247+ f.c.Skills = nil
248+ case "autostart":
249+ f.c.AutoStart = nil
250+ case "launch":
251+ f.c.Launch = nil
252+ case "name":
253+ f.c.Name = ""
254+ case "file":
255+ f.output = ""
256+ f.forgetOverwrite()
257+ case "overwrite":
258+ f.forgetOverwrite()
259+ }
260+}
261+
262+// forgetOverwrite drops the agreement: it was about one file.
263+func (f *Flow) forgetOverwrite() {
264+ f.overwrite = false
265+ delete(f.answer, "overwrite")
266+}
267+
268+func (f *Flow) forget(key string) {
269+ if !f.given[key] {
270+ delete(f.answer, key)
271+ if key == "family" {
272+ f.c.Family = ""
273+ }
274+ }
275+}
276+
277+// forgetService drops the endpoint and key variable answered for openai
278+// (not those given by flags), when another server is chosen.
279+func (f *Flow) forgetService() {
280+ if !f.given["endpoint"] {
281+ delete(f.answer, "endpoint")
282+ f.c.BaseURL = ""
283+ }
284+ if !f.given["keyenv"] {
285+ delete(f.answer, "keyenv")
286+ f.c.APIKeyEnv = ""
287+ }
288+}
new file mode 100644
@@ -0,0 +1,288 @@
1+package agentinit
2+
3+import (
4+ "fmt"
5+ "mm/internal/config"
6+ "path/filepath"
7+ "strings"
8+)
9+
10+// checkLayout refuses a Project layout whose file is not in .mm/: its paths
11+// are written from the project root, which holds only for a file directly
12+// in a .mm folder. "-" (stdout) is always fine: nothing is created.
13+func checkLayout(project bool, output string) error {
14+ if !project || output == "" || output == "-" {
15+ return nil
16+ }
17+ if filepath.Base(filepath.Dir(filepath.Clean(output))) != config.ProjectDir {
18+ return fmt.Errorf("file: %q is not in a %s folder — the Project layout writes .mm/agent.yaml (or answer no to the Project question)", output, config.ProjectDir)
19+ }
20+ return nil
21+}
22+
23+// setYesNo reads a yes/no answer into one of the optional switches.
24+func setYesNo(key, value string, target **bool) error {
25+ if value != "yes" && value != "no" {
26+ return fmt.Errorf("%s: answer yes or no, not %q", key, value)
27+ }
28+ answer := value == "yes"
29+ *target = &answer
30+ return nil
31+}
32+
33+// Set answers one question. A new server forgets the model (and the
34+// family, unless a flag gave it); a new model forgets the facts.
35+func (f *Flow) Set(key, value string) error {
36+ value = strings.TrimSpace(value)
37+ if value == "" {
38+ return fmt.Errorf("%s: an answer is needed", key)
39+ }
40+ set, ok := setters[key]
41+ if !ok {
42+ return fmt.Errorf("no question %q", key)
43+ }
44+ if err := set(f, value); err != nil {
45+ return err
46+ }
47+ // overwrite: no goes back to the file question: nothing to record.
48+ if key != "overwrite" || value != "no" {
49+ f.answer[key] = value
50+ }
51+ return nil
52+}
53+
54+// setters answer each question.
55+var setters = map[string]func(*Flow, string) error{
56+ "provider": (*Flow).setProvider,
57+ "endpoint": (*Flow).setEndpoint,
58+ "keyenv": (*Flow).setKeyEnv,
59+ "model": (*Flow).setModel,
60+ "family": (*Flow).setFamily,
61+ "usage": (*Flow).setUsage,
62+ "machine": (*Flow).setMachine,
63+ "yolo": (*Flow).setYolo,
64+ "project": (*Flow).setProject,
65+ "sessions": func(f *Flow, v string) error { return setYesNo("sessions", v, &f.c.Sessions) },
66+ "skills": func(f *Flow, v string) error { return setYesNo("skills", v, &f.c.Skills) },
67+ "autostart": (*Flow).setAutoStart,
68+ "launch": func(f *Flow, v string) error { return setYesNo("launch", v, &f.c.Launch) },
69+ "name": func(f *Flow, v string) error { f.c.Name = v; return nil },
70+ "file": (*Flow).setFile,
71+ "overwrite": (*Flow).setOverwrite,
72+}
73+
74+// setProvider: a new server forgets the model, and the endpoint and the
75+// key's variable answered here — they belong to openai.
76+func (f *Flow) setProvider(value string) error {
77+ if !contains(providers, value) {
78+ return fmt.Errorf("unknown provider %q (known: %s)", value, strings.Join(providers, ", "))
79+ }
80+ if value != f.c.Provider {
81+ f.c.Provider = value
82+ f.base = ""
83+ f.forget("model")
84+ f.c.Model = ""
85+ f.forgetService()
86+ }
87+ return nil
88+}
89+
90+// setEndpoint: the OpenAI API's own address is openai's default — no
91+// baseUrl line then, the file records it as a comment instead.
92+func (f *Flow) setEndpoint(value string) error {
93+ if !strings.HasPrefix(value, "http://") && !strings.HasPrefix(value, "https://") {
94+ return fmt.Errorf("endpoint: %q is not an http:// or https:// address", value)
95+ }
96+ value = strings.TrimRight(value, "/")
97+ f.c.BaseURL = value
98+ if isOpenAI(f.c.Provider) && value == openAIDefaultBase() {
99+ f.c.BaseURL = ""
100+ }
101+ f.base = ""
102+ f.forget("model")
103+ return nil
104+}
105+
106+func (f *Flow) setKeyEnv(value string) error {
107+ if !envName.MatchString(value) {
108+ return fmt.Errorf("API key: %q is not a variable name (letters, digits, _)", value)
109+ }
110+ f.c.APIKeyEnv = ""
111+ if value != defaultKeyEnv {
112+ f.c.APIKeyEnv = value
113+ }
114+ f.forget("model")
115+ return nil
116+}
117+
118+// setModel: a new model forgets the family.
119+func (f *Flow) setModel(value string) error {
120+ if value != f.c.Model {
121+ f.c.Model = value
122+ f.forget("family")
123+ }
124+ return nil
125+}
126+
127+func (f *Flow) setFamily(value string) error {
128+ if f.presets.Family(value).Name == "" {
129+ return fmt.Errorf("unknown family %q", value)
130+ }
131+ f.c.Family = value
132+ return nil
133+}
134+
135+func (f *Flow) setUsage(value string) error {
136+ if _, ok := f.presets.Usage(value); !ok {
137+ return fmt.Errorf("unknown usage %q (known: %s)", value, strings.Join(f.presets.UsageNames(), ", "))
138+ }
139+ f.c.Usage = value
140+ return nil
141+}
142+
143+func (f *Flow) setMachine(value string) error {
144+ if _, ok := f.presets.Machine(value); !ok {
145+ return fmt.Errorf("unknown machine %q (known: %s)", value, strings.Join(f.presets.MachineNames(), ", "))
146+ }
147+ f.c.Machine = value
148+ return nil
149+}
150+
151+// setYolo: the question is "ask before each change?" — yes is yolo: false.
152+func (f *Flow) setYolo(value string) error {
153+ yolo := value != "yes"
154+ f.c.Yolo = &yolo
155+ return nil
156+}
157+
158+// setAutoStart: no start, no launch settings — that question is gone,
159+// unless a flag answered it.
160+func (f *Flow) setAutoStart(value string) error {
161+ if err := setYesNo("autostart", value, &f.c.AutoStart); err != nil {
162+ return err
163+ }
164+ if !on(f.c.AutoStart) && !f.given["launch"] {
165+ f.c.Launch = nil
166+ delete(f.answer, "launch")
167+ }
168+ return nil
169+}
170+
171+func (f *Flow) setFile(value string) error {
172+ if err := checkLayout(on(f.c.Project), value); err != nil {
173+ return err
174+ }
175+ f.output = value
176+ f.forgetOverwrite()
177+ return nil
178+}
179+
180+// setOverwrite: no goes back to the file question, even for a file named
181+// by -o.
182+func (f *Flow) setOverwrite(value string) error {
183+ if value != "yes" && value != "no" {
184+ return fmt.Errorf("overwrite: answer yes or no, not %q", value)
185+ }
186+ if value == "no" {
187+ f.output = ""
188+ delete(f.given, "file")
189+ delete(f.answer, "file")
190+ return nil
191+ }
192+ f.overwrite = true
193+ return nil
194+}
195+
196+// setProject answers the layout question. A file named by -o must suit the
197+// layout; a file answered here for the other layout is asked again, with
198+// the other default.
199+func (f *Flow) setProject(value string) error {
200+ if f.given["file"] {
201+ if err := checkLayout(value == "yes", f.output); err != nil {
202+ return err
203+ }
204+ }
205+ before := on(f.c.Project)
206+ if err := setYesNo("project", value, &f.c.Project); err != nil {
207+ return err
208+ }
209+ if on(f.c.Project) != before && !f.given["file"] {
210+ delete(f.answer, "file")
211+ f.output = ""
212+ f.forgetOverwrite()
213+ }
214+ return nil
215+}
216+
217+// Unset takes an answer back (the window's Esc), unless a flag gave it.
218+func (f *Flow) Unset(key string) {
219+ if f.given[key] {
220+ return
221+ }
222+ delete(f.answer, key)
223+ switch key {
224+ case "endpoint":
225+ f.c.BaseURL, f.base = "", ""
226+ case "keyenv":
227+ f.c.APIKeyEnv = ""
228+ case "family":
229+ f.c.Family = ""
230+ case "usage":
231+ f.c.Usage = ""
232+ case "machine":
233+ f.c.Machine = ""
234+ case "yolo":
235+ f.c.Yolo = nil
236+ case "project":
237+ f.c.Project = nil
238+ // The file offered depended on the layout.
239+ if !f.given["file"] {
240+ delete(f.answer, "file")
241+ f.output = ""
242+ f.forgetOverwrite()
243+ }
244+ case "sessions":
245+ f.c.Sessions = nil
246+ case "skills":
247+ f.c.Skills = nil
248+ case "autostart":
249+ f.c.AutoStart = nil
250+ case "launch":
251+ f.c.Launch = nil
252+ case "name":
253+ f.c.Name = ""
254+ case "file":
255+ f.output = ""
256+ f.forgetOverwrite()
257+ case "overwrite":
258+ f.forgetOverwrite()
259+ }
260+}
261+
262+// forgetOverwrite drops the agreement: it was about one file.
263+func (f *Flow) forgetOverwrite() {
264+ f.overwrite = false
265+ delete(f.answer, "overwrite")
266+}
267+
268+func (f *Flow) forget(key string) {
269+ if !f.given[key] {
270+ delete(f.answer, key)
271+ if key == "family" {
272+ f.c.Family = ""
273+ }
274+ }
275+}
276+
277+// forgetService drops the endpoint and key variable answered for openai
278+// (not those given by flags), when another server is chosen.
279+func (f *Flow) forgetService() {
280+ if !f.given["endpoint"] {
281+ delete(f.answer, "endpoint")
282+ f.c.BaseURL = ""
283+ }
284+ if !f.given["keyenv"] {
285+ delete(f.answer, "keyenv")
286+ f.c.APIKeyEnv = ""
287+ }
288+}
added internal/agentinit/flow_server.go +95 -0
new file mode 100644
@@ -0,0 +1,95 @@
1+package agentinit
2+
3+import (
4+ "fmt"
5+ "os"
6+)
7+
8+// keyEnv is the variable the openai provider reads its key from.
9+func (f *Flow) keyEnv() string {
10+ if f.c.APIKeyEnv != "" {
11+ return f.c.APIKeyEnv
12+ }
13+ return defaultKeyEnv
14+}
15+
16+// typeModelPrompt asks for the model's ID when there is no list, and says
17+// why — in the window as in the line mode, both show the prompt.
18+func (f *Flow) typeModelPrompt() string {
19+ if isOpenAI(f.c.Provider) && os.Getenv(f.keyEnv()) == "" {
20+ return fmt.Sprintf("Model ID? (%s is not set: no list — type it)", f.keyEnv())
21+ }
22+ if f.modelsErr != nil {
23+ return fmt.Sprintf("Model ID? (no list from %s: %v)", f.Base(), f.modelsErr)
24+ }
25+ return "Model (as the server names it)?"
26+}
27+
28+// Base is the resolved server address ("" before a provider is chosen).
29+func (f *Flow) Base() string {
30+ if f.base == "" && f.c.Provider != "" {
31+ f.base = resolveBase(f.ctx, f.c)
32+ }
33+ return f.base
34+}
35+
36+func (f *Flow) modelList() []string {
37+ if f.c.Provider == "" {
38+ return nil
39+ }
40+ key := f.c.Provider + " " + f.Base()
41+ if isOpenAI(f.c.Provider) {
42+ key += " " + f.keyEnv()
43+ }
44+ if f.listed != key {
45+ f.models, f.modelsErr = f.listModels()
46+ f.listed = key
47+ }
48+ return f.models
49+}
50+
51+// listModels asks the server for its models. An OpenAI-compatible service
52+// is asked with the key read from the variable the user named — and not at
53+// all when that variable is empty: the request would only be refused.
54+func (f *Flow) listModels() ([]string, error) {
55+ if !isOpenAI(f.c.Provider) {
56+ return Models(f.ctx, f.c.Provider, f.Base())
57+ }
58+ key := os.Getenv(f.keyEnv())
59+ if key == "" {
60+ return nil, fmt.Errorf("%s is not set", f.keyEnv())
61+ }
62+ return ListModels(f.ctx, f.c.Provider, f.Base(), key)
63+}
64+
65+func (f *Flow) modelFacts() Facts {
66+ if f.c.Model == "" || f.c.Provider == "" {
67+ return Facts{}
68+ }
69+ if f.factsFor != f.c.Provider+" "+f.c.Model {
70+ f.facts = ModelFacts(f.ctx, f.c.Provider, f.Base(), f.c.Model)
71+ f.factsFor = f.c.Provider + " " + f.c.Model
72+ }
73+ return f.facts
74+}
75+
76+// answers reports, once per provider, whether its server answers.
77+func (f *Flow) answers(name string) bool {
78+ if f.reachable == nil {
79+ f.reachable = map[string]bool{}
80+ for _, p := range local {
81+ _, err := Models(f.ctx, p, resolveBase(f.ctx, Choices{Provider: p}))
82+ f.reachable[p] = err == nil
83+ }
84+ }
85+ return f.reachable[name]
86+}
87+
88+func (f *Flow) firstAnswering() string {
89+ for _, name := range local {
90+ if f.answers(name) {
91+ return name
92+ }
93+ }
94+ return providers[0]
95+}
new file mode 100644
@@ -0,0 +1,95 @@
1+package agentinit
2+
3+import (
4+ "fmt"
5+ "os"
6+)
7+
8+// keyEnv is the variable the openai provider reads its key from.
9+func (f *Flow) keyEnv() string {
10+ if f.c.APIKeyEnv != "" {
11+ return f.c.APIKeyEnv
12+ }
13+ return defaultKeyEnv
14+}
15+
16+// typeModelPrompt asks for the model's ID when there is no list, and says
17+// why — in the window as in the line mode, both show the prompt.
18+func (f *Flow) typeModelPrompt() string {
19+ if isOpenAI(f.c.Provider) && os.Getenv(f.keyEnv()) == "" {
20+ return fmt.Sprintf("Model ID? (%s is not set: no list — type it)", f.keyEnv())
21+ }
22+ if f.modelsErr != nil {
23+ return fmt.Sprintf("Model ID? (no list from %s: %v)", f.Base(), f.modelsErr)
24+ }
25+ return "Model (as the server names it)?"
26+}
27+
28+// Base is the resolved server address ("" before a provider is chosen).
29+func (f *Flow) Base() string {
30+ if f.base == "" && f.c.Provider != "" {
31+ f.base = resolveBase(f.ctx, f.c)
32+ }
33+ return f.base
34+}
35+
36+func (f *Flow) modelList() []string {
37+ if f.c.Provider == "" {
38+ return nil
39+ }
40+ key := f.c.Provider + " " + f.Base()
41+ if isOpenAI(f.c.Provider) {
42+ key += " " + f.keyEnv()
43+ }
44+ if f.listed != key {
45+ f.models, f.modelsErr = f.listModels()
46+ f.listed = key
47+ }
48+ return f.models
49+}
50+
51+// listModels asks the server for its models. An OpenAI-compatible service
52+// is asked with the key read from the variable the user named — and not at
53+// all when that variable is empty: the request would only be refused.
54+func (f *Flow) listModels() ([]string, error) {
55+ if !isOpenAI(f.c.Provider) {
56+ return Models(f.ctx, f.c.Provider, f.Base())
57+ }
58+ key := os.Getenv(f.keyEnv())
59+ if key == "" {
60+ return nil, fmt.Errorf("%s is not set", f.keyEnv())
61+ }
62+ return ListModels(f.ctx, f.c.Provider, f.Base(), key)
63+}
64+
65+func (f *Flow) modelFacts() Facts {
66+ if f.c.Model == "" || f.c.Provider == "" {
67+ return Facts{}
68+ }
69+ if f.factsFor != f.c.Provider+" "+f.c.Model {
70+ f.facts = ModelFacts(f.ctx, f.c.Provider, f.Base(), f.c.Model)
71+ f.factsFor = f.c.Provider + " " + f.c.Model
72+ }
73+ return f.facts
74+}
75+
76+// answers reports, once per provider, whether its server answers.
77+func (f *Flow) answers(name string) bool {
78+ if f.reachable == nil {
79+ f.reachable = map[string]bool{}
80+ for _, p := range local {
81+ _, err := Models(f.ctx, p, resolveBase(f.ctx, Choices{Provider: p}))
82+ f.reachable[p] = err == nil
83+ }
84+ }
85+ return f.reachable[name]
86+}
87+
88+func (f *Flow) firstAnswering() string {
89+ for _, name := range local {
90+ if f.answers(name) {
91+ return name
92+ }
93+ }
94+ return providers[0]
95+}
added internal/agentinit/flow_steps.go +168 -0
new file mode 100644
@@ -0,0 +1,168 @@
1+package agentinit
2+
3+import (
4+ "fmt"
5+ "mm/internal/elicit"
6+ "path/filepath"
7+)
8+
9+// Step builds one question as it stands now: its options may depend on the
10+// answers before it (the model list on the server, the family's default on
11+// the model).
12+func (f *Flow) Step(key string) Step {
13+ st := Step{Key: key, Title: stepTitles[key], Value: f.answer[key], Given: f.given[key], Kind: elicit.Choice}
14+ if st.Value != "" {
15+ // Answered: the list of steps needs its title and value only — the
16+ // options (a probe of every server, the model list) are built when
17+ // the question is asked again.
18+ return st
19+ }
20+ if build, ok := stepBuilders[key]; ok {
21+ return build(f, st)
22+ }
23+ return st
24+}
25+
26+// stepBuilders build each question as it stands now.
27+var stepBuilders = map[string]func(*Flow, Step) Step{
28+ "provider": (*Flow).providerStep,
29+ "endpoint": func(_ *Flow, st Step) Step {
30+ st.Prompt, st.Kind, st.Default = "Endpoint (the service's OpenAI-compatible address)?", elicit.Text, openAIDefaultBase()
31+ return st
32+ },
33+ "keyenv": func(_ *Flow, st Step) Step {
34+ st.Prompt, st.Kind, st.Default = "Environment variable that holds the API key?", elicit.Text, defaultKeyEnv
35+ return st
36+ },
37+ "model": (*Flow).modelStep,
38+ "family": (*Flow).familyStep,
39+ "usage": (*Flow).usageStep,
40+ "machine": func(f *Flow, st Step) Step {
41+ st.Prompt = "Which machine runs the model?"
42+ for _, m := range f.presets.Machines {
43+ st.Options = append(st.Options, Option{Value: m.Name, Label: m.Name, Detail: m.Description})
44+ }
45+ st.Default = "small"
46+ return st
47+ },
48+ "yolo": (*Flow).yoloStep,
49+ "name": func(f *Flow, st Step) Step {
50+ st.Prompt, st.Kind, st.Default = "Agent name?", elicit.Text, f.usageOrDefault()
51+ return st
52+ },
53+ "project": func(_ *Flow, st Step) Step {
54+ return yesNoStep(st, "Keep everything in a .mm folder?",
55+ "creates .mm/ and writes .mm/agent.yaml; its paths start at the project root, and mm finds it on its own",
56+ "one agent.yaml, in the file you choose")
57+ },
58+ "sessions": func(_ *Flow, st Step) Step {
59+ return yesNoStep(st, "Save the conversations?",
60+ "writes a sessions section: every conversation is saved in .mm/sessions, /resume reopens one",
61+ "no sessions section: nothing is saved (mm's default)")
62+ },
63+ "skills": func(f *Flow, st Step) Step {
64+ return yesNoStep(st, "Use skills?", "writes skillsDir: "+f.c.SkillsDir()+" and creates that folder", "skillsDir: no-skills")
65+ },
66+ "autostart": (*Flow).autoStartStep,
67+ "launch": func(_ *Flow, st Step) Step {
68+ return yesNoStep(st, "Write llama-server's launch settings?",
69+ "the Llama app's values (modelsMax, modelsMemoryMargin, fitTarget, sleepIdleSeconds, specDefault), each one editable or removable",
70+ "none: llama-server's own defaults")
71+ },
72+ "file": func(f *Flow, st Step) Step {
73+ st.Prompt, st.Kind, st.Default = "File to write?", elicit.Text, f.defaultFile()
74+ return st
75+ },
76+ "overwrite": func(f *Flow, st Step) Step {
77+ st.Prompt, st.Kind, st.Default = "Overwrite "+filepath.Base(f.output)+"?", elicit.Confirm, "no"
78+ st.Options = []Option{
79+ {Value: "yes", Label: "yes", Detail: "replace the existing file"},
80+ {Value: "no", Label: "no", Detail: "keep it and choose another file"},
81+ }
82+ return st
83+ },
84+}
85+
86+// providerStep lists the servers, each probed when it is a local one.
87+func (f *Flow) providerStep(st Step) Step {
88+ st.Prompt = "Model server?"
89+ for _, name := range providers {
90+ detail := "not probed: its default address is the OpenAI API"
91+ if contains(local, name) {
92+ detail = "does not answer"
93+ if f.answers(name) {
94+ detail = "answers"
95+ }
96+ }
97+ st.Options = append(st.Options, Option{Value: name, Label: name, Detail: detail})
98+ }
99+ st.Default = f.firstAnswering()
100+ return st
101+}
102+
103+// modelStep lists the server's models, or asks for a name when it lists
104+// none. Where the list comes from (ticket 214): a wrong address — the
105+// container one on the host — shows at once.
106+func (f *Flow) modelStep(st Step) Step {
107+ models := f.modelList()
108+ if len(models) == 0 {
109+ st.Kind, st.Prompt = elicit.Text, f.typeModelPrompt()
110+ return st
111+ }
112+ st.Prompt = fmt.Sprintf("Model? (listed from %s)", f.Base())
113+ for _, m := range models {
114+ st.Options = append(st.Options, Option{Value: m, Label: m, Detail: modelDetail(f.c.Provider, m)})
115+ }
116+ st.Default = models[0]
117+ return st
118+}
119+
120+func (f *Flow) familyStep(st Step) Step {
121+ st.Prompt = "Model family?"
122+ for _, fam := range f.presets.Families {
123+ st.Options = append(st.Options, Option{Value: fam.Name, Label: fam.Name, Detail: fam.Source})
124+ }
125+ st.Default = f.presets.FamilyOf(f.c.Model, f.modelFacts().ServerFamily).Name
126+ return st
127+}
128+
129+func (f *Flow) usageStep(st Step) Step {
130+ st.Prompt = "What is the agent for?"
131+ for _, u := range f.presets.Usages {
132+ st.Options = append(st.Options, Option{Value: u.Name, Label: u.Name, Detail: u.Description})
133+ }
134+ st.Default = "developer"
135+ return st
136+}
137+
138+func (f *Flow) yoloStep(st Step) Step {
139+ st.Prompt, st.Kind = "Ask before each command or file change?", elicit.Confirm
140+ u, _ := f.presets.Usage(f.usageOrDefault())
141+ st.Default = yesNo(!u.Yolo)
142+ st.Options = []Option{
143+ {Value: "yes", Label: "yes", Detail: "every command and file change waits for your answer (yolo: false)"},
144+ {Value: "no", Label: "no", Detail: "tools run without asking (yolo: true)"},
145+ }
146+ return st
147+}
148+
149+func (f *Flow) autoStartStep(st Step) Step {
150+ if f.c.Provider == "razorbill" {
151+ st = yesNoStep(st, "Let mm start rzb when it is not running?",
152+ "razorbill.autoStart: true — mm starts rzb serve (macOS, mm on the Mac itself: not in a container or a sandbox), downloads this model when missing, and stops it with the last mm session",
153+ "razorbill.autoStart: false — you start rzb serve yourself")
154+ } else {
155+ st = yesNoStep(st, "Let mm start llama-server when it is not running?",
156+ "llamacpp.autoStart: true — mm starts it with this model (downloaded on first use) and stops it with the last mm session",
157+ "llamacpp.autoStart: false — you start llama-server yourself")
158+ }
159+ st.Default = "yes"
160+ return st
161+}
162+
163+// yesNoStep is a yes/no question whose default is no.
164+func yesNoStep(st Step, prompt, yes, no string) Step {
165+ st.Prompt, st.Kind, st.Default = prompt, elicit.Confirm, "no"
166+ st.Options = []Option{{Value: "yes", Label: "yes", Detail: yes}, {Value: "no", Label: "no", Detail: no}}
167+ return st
168+}
new file mode 100644
@@ -0,0 +1,168 @@
1+package agentinit
2+
3+import (
4+ "fmt"
5+ "mm/internal/elicit"
6+ "path/filepath"
7+)
8+
9+// Step builds one question as it stands now: its options may depend on the
10+// answers before it (the model list on the server, the family's default on
11+// the model).
12+func (f *Flow) Step(key string) Step {
13+ st := Step{Key: key, Title: stepTitles[key], Value: f.answer[key], Given: f.given[key], Kind: elicit.Choice}
14+ if st.Value != "" {
15+ // Answered: the list of steps needs its title and value only — the
16+ // options (a probe of every server, the model list) are built when
17+ // the question is asked again.
18+ return st
19+ }
20+ if build, ok := stepBuilders[key]; ok {
21+ return build(f, st)
22+ }
23+ return st
24+}
25+
26+// stepBuilders build each question as it stands now.
27+var stepBuilders = map[string]func(*Flow, Step) Step{
28+ "provider": (*Flow).providerStep,
29+ "endpoint": func(_ *Flow, st Step) Step {
30+ st.Prompt, st.Kind, st.Default = "Endpoint (the service's OpenAI-compatible address)?", elicit.Text, openAIDefaultBase()
31+ return st
32+ },
33+ "keyenv": func(_ *Flow, st Step) Step {
34+ st.Prompt, st.Kind, st.Default = "Environment variable that holds the API key?", elicit.Text, defaultKeyEnv
35+ return st
36+ },
37+ "model": (*Flow).modelStep,
38+ "family": (*Flow).familyStep,
39+ "usage": (*Flow).usageStep,
40+ "machine": func(f *Flow, st Step) Step {
41+ st.Prompt = "Which machine runs the model?"
42+ for _, m := range f.presets.Machines {
43+ st.Options = append(st.Options, Option{Value: m.Name, Label: m.Name, Detail: m.Description})
44+ }
45+ st.Default = "small"
46+ return st
47+ },
48+ "yolo": (*Flow).yoloStep,
49+ "name": func(f *Flow, st Step) Step {
50+ st.Prompt, st.Kind, st.Default = "Agent name?", elicit.Text, f.usageOrDefault()
51+ return st
52+ },
53+ "project": func(_ *Flow, st Step) Step {
54+ return yesNoStep(st, "Keep everything in a .mm folder?",
55+ "creates .mm/ and writes .mm/agent.yaml; its paths start at the project root, and mm finds it on its own",
56+ "one agent.yaml, in the file you choose")
57+ },
58+ "sessions": func(_ *Flow, st Step) Step {
59+ return yesNoStep(st, "Save the conversations?",
60+ "writes a sessions section: every conversation is saved in .mm/sessions, /resume reopens one",
61+ "no sessions section: nothing is saved (mm's default)")
62+ },
63+ "skills": func(f *Flow, st Step) Step {
64+ return yesNoStep(st, "Use skills?", "writes skillsDir: "+f.c.SkillsDir()+" and creates that folder", "skillsDir: no-skills")
65+ },
66+ "autostart": (*Flow).autoStartStep,
67+ "launch": func(_ *Flow, st Step) Step {
68+ return yesNoStep(st, "Write llama-server's launch settings?",
69+ "the Llama app's values (modelsMax, modelsMemoryMargin, fitTarget, sleepIdleSeconds, specDefault), each one editable or removable",
70+ "none: llama-server's own defaults")
71+ },
72+ "file": func(f *Flow, st Step) Step {
73+ st.Prompt, st.Kind, st.Default = "File to write?", elicit.Text, f.defaultFile()
74+ return st
75+ },
76+ "overwrite": func(f *Flow, st Step) Step {
77+ st.Prompt, st.Kind, st.Default = "Overwrite "+filepath.Base(f.output)+"?", elicit.Confirm, "no"
78+ st.Options = []Option{
79+ {Value: "yes", Label: "yes", Detail: "replace the existing file"},
80+ {Value: "no", Label: "no", Detail: "keep it and choose another file"},
81+ }
82+ return st
83+ },
84+}
85+
86+// providerStep lists the servers, each probed when it is a local one.
87+func (f *Flow) providerStep(st Step) Step {
88+ st.Prompt = "Model server?"
89+ for _, name := range providers {
90+ detail := "not probed: its default address is the OpenAI API"
91+ if contains(local, name) {
92+ detail = "does not answer"
93+ if f.answers(name) {
94+ detail = "answers"
95+ }
96+ }
97+ st.Options = append(st.Options, Option{Value: name, Label: name, Detail: detail})
98+ }
99+ st.Default = f.firstAnswering()
100+ return st
101+}
102+
103+// modelStep lists the server's models, or asks for a name when it lists
104+// none. Where the list comes from (ticket 214): a wrong address — the
105+// container one on the host — shows at once.
106+func (f *Flow) modelStep(st Step) Step {
107+ models := f.modelList()
108+ if len(models) == 0 {
109+ st.Kind, st.Prompt = elicit.Text, f.typeModelPrompt()
110+ return st
111+ }
112+ st.Prompt = fmt.Sprintf("Model? (listed from %s)", f.Base())
113+ for _, m := range models {
114+ st.Options = append(st.Options, Option{Value: m, Label: m, Detail: modelDetail(f.c.Provider, m)})
115+ }
116+ st.Default = models[0]
117+ return st
118+}
119+
120+func (f *Flow) familyStep(st Step) Step {
121+ st.Prompt = "Model family?"
122+ for _, fam := range f.presets.Families {
123+ st.Options = append(st.Options, Option{Value: fam.Name, Label: fam.Name, Detail: fam.Source})
124+ }
125+ st.Default = f.presets.FamilyOf(f.c.Model, f.modelFacts().ServerFamily).Name
126+ return st
127+}
128+
129+func (f *Flow) usageStep(st Step) Step {
130+ st.Prompt = "What is the agent for?"
131+ for _, u := range f.presets.Usages {
132+ st.Options = append(st.Options, Option{Value: u.Name, Label: u.Name, Detail: u.Description})
133+ }
134+ st.Default = "developer"
135+ return st
136+}
137+
138+func (f *Flow) yoloStep(st Step) Step {
139+ st.Prompt, st.Kind = "Ask before each command or file change?", elicit.Confirm
140+ u, _ := f.presets.Usage(f.usageOrDefault())
141+ st.Default = yesNo(!u.Yolo)
142+ st.Options = []Option{
143+ {Value: "yes", Label: "yes", Detail: "every command and file change waits for your answer (yolo: false)"},
144+ {Value: "no", Label: "no", Detail: "tools run without asking (yolo: true)"},
145+ }
146+ return st
147+}
148+
149+func (f *Flow) autoStartStep(st Step) Step {
150+ if f.c.Provider == "razorbill" {
151+ st = yesNoStep(st, "Let mm start rzb when it is not running?",
152+ "razorbill.autoStart: true — mm starts rzb serve (macOS, mm on the Mac itself: not in a container or a sandbox), downloads this model when missing, and stops it with the last mm session",
153+ "razorbill.autoStart: false — you start rzb serve yourself")
154+ } else {
155+ st = yesNoStep(st, "Let mm start llama-server when it is not running?",
156+ "llamacpp.autoStart: true — mm starts it with this model (downloaded on first use) and stops it with the last mm session",
157+ "llamacpp.autoStart: false — you start llama-server yourself")
158+ }
159+ st.Default = "yes"
160+ return st
161+}
162+
163+// yesNoStep is a yes/no question whose default is no.
164+func yesNoStep(st Step, prompt, yes, no string) Step {
165+ st.Prompt, st.Kind, st.Default = prompt, elicit.Confirm, "no"
166+ st.Options = []Option{{Value: "yes", Label: "yes", Detail: yes}, {Value: "no", Label: "no", Detail: no}}
167+ return st
168+}
added internal/agentinit/kronkfacts.go +89 -0
new file mode 100644
@@ -0,0 +1,89 @@
1+package agentinit
2+
3+import (
4+ "context"
5+ "net/http"
6+ neturl "net/url"
7+ "strconv"
8+ "strings"
9+ "time"
10+)
11+
12+// modelDetail is the line shown beside a model in the wizard's list, "" for
13+// most. Kronk lists configuration profiles beside the models
14+// (`provider/modelID/PROFILE`, e.g. `…/Qwopus3.5-4B-Coder.Q8_0/AGENT`): the
15+// same weights, served with the settings of that key in Kronk's
16+// model_config.yaml (its own window, max_tokens…). A valid choice, but one
17+// that looks like a stray file without a word of explanation.
18+//
19+// modelDetail("kronk", "mradermacher/Qwopus3.5-4B-Coder.Q8_0/AGENT")
20+// // "Kronk profile of mradermacher/Qwopus3.5-4B-Coder.Q8_0: same model, its own settings in model_config.yaml"
21+func modelDetail(provider, model string) string {
22+ profile, ok := kronkProfile(provider, model)
23+ if !ok {
24+ return ""
25+ }
26+ base := strings.TrimSuffix(model, "/"+profile)
27+ return "Kronk profile of " + base + ": same model, its own settings in model_config.yaml"
28+}
29+
30+// kronkProfile returns the profile a Kronk model id names: the third
31+// segment of `provider/modelID/PROFILE`.
32+//
33+// kronkProfile("kronk", "mradermacher/Qwopus3.5-4B-Coder.Q8_0/AGENT") // "AGENT", true
34+func kronkProfile(provider, model string) (string, bool) {
35+ if provider != "kronk" || strings.Count(model, "/") != 2 {
36+ return "", false
37+ }
38+ return model[strings.LastIndex(model, "/")+1:], true
39+}
40+
41+// kronkFacts reads Kronk's model details (measured on Kronk 1.33.2): the
42+// GGUF metadata as strings — `general.architecture`, `<arch>.context_length`,
43+// `general.sampling.*`, `tokenizer.chat_template` — and the configuration
44+// it serves the model with, whose `context-window` is the window actually
45+// served (131072 for a model trained on 262144). The id holds a "/", so it
46+// goes in the path escaped.
47+func kronkFacts(ctx context.Context, base, model string) Facts {
48+ var details struct {
49+ Metadata map[string]string `json:"metadata"`
50+ Config struct {
51+ ContextWindow int `json:"context-window"`
52+ Sampling map[string]any `json:"sampling-parameters"`
53+ } `json:"model_config"`
54+ }
55+ url := root(base) + "/v1/kronk/models/" + neturl.PathEscape(model)
56+ if err := call(ctx, http.MethodGet, url, nil, 30*time.Second, &details); err != nil {
57+ return Facts{}
58+ }
59+ arch := details.Metadata["general.architecture"]
60+ f := Facts{Known: true, ServerFamily: arch, Sampling: map[string]float64{}, Thinking: templateThinking(details.Metadata["tokenizer.chat_template"])}
61+ f.ContextLength = details.Config.ContextWindow
62+ if f.ContextLength == 0 {
63+ f.ContextLength, _ = strconv.Atoi(details.Metadata[arch+".context_length"])
64+ }
65+ for key, value := range details.Metadata {
66+ if name, ok := strings.CutPrefix(key, "general.sampling."); ok {
67+ if n, err := strconv.ParseFloat(value, 64); err == nil {
68+ f.Sampling[samplingKey(name)] = n
69+ }
70+ }
71+ }
72+ if profile, ok := kronkProfile("kronk", model); ok {
73+ f.Profile, f.ProfileSampling = profile, profileSampling(details.Config.Sampling)
74+ }
75+ return f
76+}
77+
78+// profileSampling keeps, from a Kronk profile's `sampling-parameters`, the
79+// keys mm's file sets: the four sampling numbers, and max_tokens when the
80+// profile caps it (0 means no cap).
81+func profileSampling(params map[string]any) map[string]float64 {
82+ out := map[string]float64{}
83+ for _, k := range []string{"temperature", "top_p", "top_k", "min_p", "max_tokens"} {
84+ if n, ok := params[k].(float64); ok && (k != "max_tokens" || n > 0) {
85+ out[k] = n
86+ }
87+ }
88+ return out
89+}
new file mode 100644
@@ -0,0 +1,89 @@
1+package agentinit
2+
3+import (
4+ "context"
5+ "net/http"
6+ neturl "net/url"
7+ "strconv"
8+ "strings"
9+ "time"
10+)
11+
12+// modelDetail is the line shown beside a model in the wizard's list, "" for
13+// most. Kronk lists configuration profiles beside the models
14+// (`provider/modelID/PROFILE`, e.g. `…/Qwopus3.5-4B-Coder.Q8_0/AGENT`): the
15+// same weights, served with the settings of that key in Kronk's
16+// model_config.yaml (its own window, max_tokens…). A valid choice, but one
17+// that looks like a stray file without a word of explanation.
18+//
19+// modelDetail("kronk", "mradermacher/Qwopus3.5-4B-Coder.Q8_0/AGENT")
20+// // "Kronk profile of mradermacher/Qwopus3.5-4B-Coder.Q8_0: same model, its own settings in model_config.yaml"
21+func modelDetail(provider, model string) string {
22+ profile, ok := kronkProfile(provider, model)
23+ if !ok {
24+ return ""
25+ }
26+ base := strings.TrimSuffix(model, "/"+profile)
27+ return "Kronk profile of " + base + ": same model, its own settings in model_config.yaml"
28+}
29+
30+// kronkProfile returns the profile a Kronk model id names: the third
31+// segment of `provider/modelID/PROFILE`.
32+//
33+// kronkProfile("kronk", "mradermacher/Qwopus3.5-4B-Coder.Q8_0/AGENT") // "AGENT", true
34+func kronkProfile(provider, model string) (string, bool) {
35+ if provider != "kronk" || strings.Count(model, "/") != 2 {
36+ return "", false
37+ }
38+ return model[strings.LastIndex(model, "/")+1:], true
39+}
40+
41+// kronkFacts reads Kronk's model details (measured on Kronk 1.33.2): the
42+// GGUF metadata as strings — `general.architecture`, `<arch>.context_length`,
43+// `general.sampling.*`, `tokenizer.chat_template` — and the configuration
44+// it serves the model with, whose `context-window` is the window actually
45+// served (131072 for a model trained on 262144). The id holds a "/", so it
46+// goes in the path escaped.
47+func kronkFacts(ctx context.Context, base, model string) Facts {
48+ var details struct {
49+ Metadata map[string]string `json:"metadata"`
50+ Config struct {
51+ ContextWindow int `json:"context-window"`
52+ Sampling map[string]any `json:"sampling-parameters"`
53+ } `json:"model_config"`
54+ }
55+ url := root(base) + "/v1/kronk/models/" + neturl.PathEscape(model)
56+ if err := call(ctx, http.MethodGet, url, nil, 30*time.Second, &details); err != nil {
57+ return Facts{}
58+ }
59+ arch := details.Metadata["general.architecture"]
60+ f := Facts{Known: true, ServerFamily: arch, Sampling: map[string]float64{}, Thinking: templateThinking(details.Metadata["tokenizer.chat_template"])}
61+ f.ContextLength = details.Config.ContextWindow
62+ if f.ContextLength == 0 {
63+ f.ContextLength, _ = strconv.Atoi(details.Metadata[arch+".context_length"])
64+ }
65+ for key, value := range details.Metadata {
66+ if name, ok := strings.CutPrefix(key, "general.sampling."); ok {
67+ if n, err := strconv.ParseFloat(value, 64); err == nil {
68+ f.Sampling[samplingKey(name)] = n
69+ }
70+ }
71+ }
72+ if profile, ok := kronkProfile("kronk", model); ok {
73+ f.Profile, f.ProfileSampling = profile, profileSampling(details.Config.Sampling)
74+ }
75+ return f
76+}
77+
78+// profileSampling keeps, from a Kronk profile's `sampling-parameters`, the
79+// keys mm's file sets: the four sampling numbers, and max_tokens when the
80+// profile caps it (0 means no cap).
81+func profileSampling(params map[string]any) map[string]float64 {
82+ out := map[string]float64{}
83+ for _, k := range []string{"temperature", "top_p", "top_k", "min_p", "max_tokens"} {
84+ if n, ok := params[k].(float64); ok && (k != "max_tokens" || n > 0) {
85+ out[k] = n
86+ }
87+ }
88+ return out
89+}
added internal/agentinit/linewizard.go +95 -0
new file mode 100644
@@ -0,0 +1,95 @@
1+package agentinit
2+
3+import (
4+ "bufio"
5+ "fmt"
6+ "io"
7+ "mm/internal/elicit"
8+ "strings"
9+)
10+
11+// lineWizard asks the questions one per line (internal/elicit's format).
12+type lineWizard struct {
13+ in *bufio.Reader
14+ out io.Writer
15+ ended bool // the input ended: nobody is there to answer
16+}
17+
18+func (w *lineWizard) run(f *Flow) error {
19+ for {
20+ pending := f.Pending()
21+ if len(pending) == 0 {
22+ return nil
23+ }
24+ st := pending[0]
25+ // Without a model list, the model question itself says why
26+ // (Flow.typeModelPrompt): the window shows the same words.
27+ answer := w.ask(st)
28+ // Taking "no" for an answer would ask for another file that nobody
29+ // can give: stop here, the file untouched.
30+ if st.Key == "overwrite" && w.ended {
31+ return alreadyExists(f.output)
32+ }
33+ if answer == "" {
34+ return fmt.Errorf("%s: no answer", strings.ToLower(st.Title))
35+ }
36+ if err := f.Set(st.Key, answer); err != nil {
37+ fmt.Fprintln(w.out, "⚠️ "+err.Error())
38+ }
39+ }
40+}
41+
42+// ask asks one step until the line answers it; the end of the input or
43+// /skip take the default.
44+func (w *lineWizard) ask(st Step) string {
45+ q := elicit.Question{Prompt: st.Prompt, Kind: st.Kind, Default: st.Default}
46+ for _, o := range st.Options {
47+ q.Options = append(q.Options, o.Value)
48+ }
49+ w.showDetails(st)
50+ for {
51+ answer, done := w.readAnswer(q)
52+ if done {
53+ return answer
54+ }
55+ }
56+}
57+
58+// showDetails prints what the options need explained: the usages and the
59+// machines, each with its description; a model's rare note (a Kronk
60+// profile), above the list, with the identifier it explains.
61+func (w *lineWizard) showDetails(st Step) {
62+ switch st.Key {
63+ case "usage", "machine":
64+ for _, o := range st.Options {
65+ fmt.Fprintf(w.out, " %-12s %s\n", o.Label, o.Detail)
66+ }
67+ case "model":
68+ for _, o := range st.Options {
69+ if o.Detail != "" {
70+ fmt.Fprintf(w.out, " %s — %s\n", o.Label, o.Detail)
71+ }
72+ }
73+ }
74+}
75+
76+// readAnswer asks once: the question's lines, then one line read. done is
77+// false when the line answers nothing and input goes on: ask again. Here
78+// /skip and an empty line take the default; nothing is declined.
79+func (w *lineWizard) readAnswer(q elicit.Question) (string, bool) {
80+ lines := elicit.Lines(q)
81+ lines[len(lines)-1] = strings.Replace(lines[len(lines)-1], "/skip to decline", "Enter = the default", 1)
82+ for _, line := range lines {
83+ fmt.Fprintln(w.out, line)
84+ }
85+ fmt.Fprint(w.out, "> ")
86+ line, err := w.in.ReadString('\n')
87+ w.ended = err != nil
88+ if elicit.IsSkip(line) || (err != nil && strings.TrimSpace(line) == "") {
89+ return q.Default, true
90+ }
91+ if a, ok := elicit.ParseLine(q, line); ok && len(a.Values) > 0 {
92+ return a.Values[0], true
93+ }
94+ return q.Default, err != nil
95+}
new file mode 100644
@@ -0,0 +1,95 @@
1+package agentinit
2+
3+import (
4+ "bufio"
5+ "fmt"
6+ "io"
7+ "mm/internal/elicit"
8+ "strings"
9+)
10+
11+// lineWizard asks the questions one per line (internal/elicit's format).
12+type lineWizard struct {
13+ in *bufio.Reader
14+ out io.Writer
15+ ended bool // the input ended: nobody is there to answer
16+}
17+
18+func (w *lineWizard) run(f *Flow) error {
19+ for {
20+ pending := f.Pending()
21+ if len(pending) == 0 {
22+ return nil
23+ }
24+ st := pending[0]
25+ // Without a model list, the model question itself says why
26+ // (Flow.typeModelPrompt): the window shows the same words.
27+ answer := w.ask(st)
28+ // Taking "no" for an answer would ask for another file that nobody
29+ // can give: stop here, the file untouched.
30+ if st.Key == "overwrite" && w.ended {
31+ return alreadyExists(f.output)
32+ }
33+ if answer == "" {
34+ return fmt.Errorf("%s: no answer", strings.ToLower(st.Title))
35+ }
36+ if err := f.Set(st.Key, answer); err != nil {
37+ fmt.Fprintln(w.out, "⚠️ "+err.Error())
38+ }
39+ }
40+}
41+
42+// ask asks one step until the line answers it; the end of the input or
43+// /skip take the default.
44+func (w *lineWizard) ask(st Step) string {
45+ q := elicit.Question{Prompt: st.Prompt, Kind: st.Kind, Default: st.Default}
46+ for _, o := range st.Options {
47+ q.Options = append(q.Options, o.Value)
48+ }
49+ w.showDetails(st)
50+ for {
51+ answer, done := w.readAnswer(q)
52+ if done {
53+ return answer
54+ }
55+ }
56+}
57+
58+// showDetails prints what the options need explained: the usages and the
59+// machines, each with its description; a model's rare note (a Kronk
60+// profile), above the list, with the identifier it explains.
61+func (w *lineWizard) showDetails(st Step) {
62+ switch st.Key {
63+ case "usage", "machine":
64+ for _, o := range st.Options {
65+ fmt.Fprintf(w.out, " %-12s %s\n", o.Label, o.Detail)
66+ }
67+ case "model":
68+ for _, o := range st.Options {
69+ if o.Detail != "" {
70+ fmt.Fprintf(w.out, " %s — %s\n", o.Label, o.Detail)
71+ }
72+ }
73+ }
74+}
75+
76+// readAnswer asks once: the question's lines, then one line read. done is
77+// false when the line answers nothing and input goes on: ask again. Here
78+// /skip and an empty line take the default; nothing is declined.
79+func (w *lineWizard) readAnswer(q elicit.Question) (string, bool) {
80+ lines := elicit.Lines(q)
81+ lines[len(lines)-1] = strings.Replace(lines[len(lines)-1], "/skip to decline", "Enter = the default", 1)
82+ for _, line := range lines {
83+ fmt.Fprintln(w.out, line)
84+ }
85+ fmt.Fprint(w.out, "> ")
86+ line, err := w.in.ReadString('\n')
87+ w.ended = err != nil
88+ if elicit.IsSkip(line) || (err != nil && strings.TrimSpace(line) == "") {
89+ return q.Default, true
90+ }
91+ if a, ok := elicit.ParseLine(q, line); ok && len(a.Values) > 0 {
92+ return a.Values[0], true
93+ }
94+ return q.Default, err != nil
95+}
added internal/agentinit/models.go +124 -0
new file mode 100644
@@ -0,0 +1,124 @@
1+package agentinit
2+
3+import (
4+ "bytes"
5+ "context"
6+ "encoding/json"
7+ "fmt"
8+ "net/http"
9+ "os"
10+ "sort"
11+ "strings"
12+ "time"
13+)
14+
15+// root is a server's address without its OpenAI prefix: llmman's and
16+// Ollama's /api/*, llama.cpp's /props live there.
17+func root(base string) string {
18+ base = strings.TrimRight(base, "/")
19+ for _, suffix := range []string{"/engines/v1", "/v1"} {
20+ if strings.HasSuffix(base, suffix) {
21+ return strings.TrimSuffix(base, suffix)
22+ }
23+ }
24+ return base
25+}
26+
27+var client = &http.Client{}
28+
29+// keyContext carries the key a provider needs to list its models (the
30+// generic `openai` one: a remote API answers 401 to an anonymous request).
31+type keyContext struct{}
32+
33+func withKey(ctx context.Context, key string) context.Context {
34+ return context.WithValue(ctx, keyContext{}, key)
35+}
36+
37+func apiKey(ctx context.Context) string {
38+ key, _ := ctx.Value(keyContext{}).(string)
39+ return key
40+}
41+
42+func call(ctx context.Context, method, url string, body any, timeout time.Duration, out any) error {
43+ ctx, cancel := context.WithTimeout(ctx, timeout)
44+ defer cancel()
45+ var reader *bytes.Reader
46+ if body != nil {
47+ data, _ := json.Marshal(body)
48+ reader = bytes.NewReader(data)
49+ } else {
50+ reader = bytes.NewReader(nil)
51+ }
52+ req, err := http.NewRequestWithContext(ctx, method, url, reader)
53+ if err != nil {
54+ return err
55+ }
56+ req.Header.Set("Content-Type", "application/json")
57+ if key := apiKey(ctx); key != "" {
58+ req.Header.Set("Authorization", "Bearer "+key)
59+ }
60+ resp, err := client.Do(req)
61+ if err != nil {
62+ return err
63+ }
64+ defer resp.Body.Close()
65+ if resp.StatusCode != http.StatusOK {
66+ return fmt.Errorf("%s %s: %s", method, url, resp.Status)
67+ }
68+ return json.NewDecoder(resp.Body).Decode(out)
69+}
70+
71+// Models lists the models a server serves: llmman's and Ollama's /api/tags,
72+// the OpenAI /models of the others. Sorted. For `openai` the key is read
73+// from OPENAI_API_KEY; ListModels takes it from elsewhere.
74+//
75+// names, err := agentinit.Models(ctx, "llmman", "http://127.0.0.1:17434/v1")
76+func Models(ctx context.Context, provider, base string) ([]string, error) {
77+ key := ""
78+ if isOpenAI(provider) {
79+ key = os.Getenv("OPENAI_API_KEY")
80+ }
81+ return ListModels(ctx, provider, base, key)
82+}
83+
84+// ListModels is Models with the API key given (sent as a Bearer token when
85+// not empty) — the key of an OpenAI-compatible service, read from the
86+// variable the user named.
87+//
88+// names, err := agentinit.ListModels(ctx, "openai", "https://api.cerebras.ai/v1", os.Getenv("CEREBRAS_API_KEY"))
89+func ListModels(ctx context.Context, provider, base, key string) ([]string, error) {
90+ ctx = withKey(ctx, key)
91+ timeout := localListTimeout
92+ if isOpenAI(provider) {
93+ timeout = remoteListTimeout
94+ }
95+ var names []string
96+ switch provider {
97+ case "llmman", "ollama":
98+ var tags struct {
99+ Models []struct {
100+ Name string `json:"name"`
101+ } `json:"models"`
102+ }
103+ if err := call(ctx, http.MethodGet, root(base)+"/api/tags", nil, timeout, &tags); err != nil {
104+ return nil, err
105+ }
106+ for _, m := range tags.Models {
107+ names = append(names, m.Name)
108+ }
109+ default:
110+ var list struct {
111+ Data []struct {
112+ ID string `json:"id"`
113+ } `json:"data"`
114+ }
115+ if err := call(ctx, http.MethodGet, strings.TrimRight(base, "/")+"/models", nil, timeout, &list); err != nil {
116+ return nil, err
117+ }
118+ for _, m := range list.Data {
119+ names = append(names, m.ID)
120+ }
121+ }
122+ sort.Strings(names)
123+ return names, nil
124+}
new file mode 100644
@@ -0,0 +1,124 @@
1+package agentinit
2+
3+import (
4+ "bytes"
5+ "context"
6+ "encoding/json"
7+ "fmt"
8+ "net/http"
9+ "os"
10+ "sort"
11+ "strings"
12+ "time"
13+)
14+
15+// root is a server's address without its OpenAI prefix: llmman's and
16+// Ollama's /api/*, llama.cpp's /props live there.
17+func root(base string) string {
18+ base = strings.TrimRight(base, "/")
19+ for _, suffix := range []string{"/engines/v1", "/v1"} {
20+ if strings.HasSuffix(base, suffix) {
21+ return strings.TrimSuffix(base, suffix)
22+ }
23+ }
24+ return base
25+}
26+
27+var client = &http.Client{}
28+
29+// keyContext carries the key a provider needs to list its models (the
30+// generic `openai` one: a remote API answers 401 to an anonymous request).
31+type keyContext struct{}
32+
33+func withKey(ctx context.Context, key string) context.Context {
34+ return context.WithValue(ctx, keyContext{}, key)
35+}
36+
37+func apiKey(ctx context.Context) string {
38+ key, _ := ctx.Value(keyContext{}).(string)
39+ return key
40+}
41+
42+func call(ctx context.Context, method, url string, body any, timeout time.Duration, out any) error {
43+ ctx, cancel := context.WithTimeout(ctx, timeout)
44+ defer cancel()
45+ var reader *bytes.Reader
46+ if body != nil {
47+ data, _ := json.Marshal(body)
48+ reader = bytes.NewReader(data)
49+ } else {
50+ reader = bytes.NewReader(nil)
51+ }
52+ req, err := http.NewRequestWithContext(ctx, method, url, reader)
53+ if err != nil {
54+ return err
55+ }
56+ req.Header.Set("Content-Type", "application/json")
57+ if key := apiKey(ctx); key != "" {
58+ req.Header.Set("Authorization", "Bearer "+key)
59+ }
60+ resp, err := client.Do(req)
61+ if err != nil {
62+ return err
63+ }
64+ defer resp.Body.Close()
65+ if resp.StatusCode != http.StatusOK {
66+ return fmt.Errorf("%s %s: %s", method, url, resp.Status)
67+ }
68+ return json.NewDecoder(resp.Body).Decode(out)
69+}
70+
71+// Models lists the models a server serves: llmman's and Ollama's /api/tags,
72+// the OpenAI /models of the others. Sorted. For `openai` the key is read
73+// from OPENAI_API_KEY; ListModels takes it from elsewhere.
74+//
75+// names, err := agentinit.Models(ctx, "llmman", "http://127.0.0.1:17434/v1")
76+func Models(ctx context.Context, provider, base string) ([]string, error) {
77+ key := ""
78+ if isOpenAI(provider) {
79+ key = os.Getenv("OPENAI_API_KEY")
80+ }
81+ return ListModels(ctx, provider, base, key)
82+}
83+
84+// ListModels is Models with the API key given (sent as a Bearer token when
85+// not empty) — the key of an OpenAI-compatible service, read from the
86+// variable the user named.
87+//
88+// names, err := agentinit.ListModels(ctx, "openai", "https://api.cerebras.ai/v1", os.Getenv("CEREBRAS_API_KEY"))
89+func ListModels(ctx context.Context, provider, base, key string) ([]string, error) {
90+ ctx = withKey(ctx, key)
91+ timeout := localListTimeout
92+ if isOpenAI(provider) {
93+ timeout = remoteListTimeout
94+ }
95+ var names []string
96+ switch provider {
97+ case "llmman", "ollama":
98+ var tags struct {
99+ Models []struct {
100+ Name string `json:"name"`
101+ } `json:"models"`
102+ }
103+ if err := call(ctx, http.MethodGet, root(base)+"/api/tags", nil, timeout, &tags); err != nil {
104+ return nil, err
105+ }
106+ for _, m := range tags.Models {
107+ names = append(names, m.Name)
108+ }
109+ default:
110+ var list struct {
111+ Data []struct {
112+ ID string `json:"id"`
113+ } `json:"data"`
114+ }
115+ if err := call(ctx, http.MethodGet, strings.TrimRight(base, "/")+"/models", nil, timeout, &list); err != nil {
116+ return nil, err
117+ }
118+ for _, m := range list.Data {
119+ names = append(names, m.ID)
120+ }
121+ }
122+ sort.Strings(names)
123+ return names, nil
124+}
modified internal/agentinit/render.go +87 -227
@@ -2,14 +2,10 @@ package agentinit
22
33 import (
44 "fmt"
5- "net"
6- "net/url"
75 "strconv"
86 "strings"
97 "unicode"
108 "unicode/utf8"
11-
12- "mm/internal/engine"
139 )
1410
1511 // docsURL is where the documentation is read online: whoever runs `mm init`
@@ -21,113 +17,158 @@ const docsURL = "https://rickub.com/bots-garden/mini-me/blob/main/"
2117 // file teaches as it configures.
2218 func Render(s Settings) string {
2319 var b strings.Builder
20+ for _, write := range []func(*strings.Builder, Settings){
21+ writeHeader, writeServer, writeTop, writeUsageSections, writeSampling,
22+ writeContextAndSessions, writeAgentsMdAndACP, writeJSONExample, writeSystem, writeNotes, writeNext,
23+ } {
24+ write(&b, s)
25+ }
26+ return b.String()
27+}
28+
29+// writeHeader: what the agent is, where its values come from, how to run it.
30+func writeHeader(b *strings.Builder, s Settings) {
2431 c, u := s.Choices, s.Usage
25- fmt.Fprintf(&b, "# %s — %s.\n", c.Name, u.Description)
32+ fmt.Fprintf(b, "# %s — %s.\n", c.Name, u.Description)
2633 b.WriteString("#\n# Written by `mm init`. Every value says why it has that value; change\n")
2734 b.WriteString("# them as you watch the agent work:\n# " + docsURL + "guides/agent-settings-for-small-models.md\n#\n")
28- fmt.Fprintf(&b, "# model family: %s\n# usage: %s\n# machine: %s — %s\n", s.Family.Name, u.Name, s.Machine.Name, s.Machine.Description)
29- fmt.Fprintf(&b, "# model facts: %s\n", factsLine(s))
30- writeLegend(&b, s)
35+ fmt.Fprintf(b, "# model family: %s\n# usage: %s\n# machine: %s — %s\n", s.Family.Name, u.Name, s.Machine.Name, s.Machine.Description)
36+ fmt.Fprintf(b, "# model facts: %s\n", factsLine(s))
37+ writeLegend(b, s)
3138 if on(c.Project) {
3239 b.WriteString("#\n# mm or mm tui started from the project root (it finds .mm/agent.yaml)\n\n")
3340 } else {
34- fmt.Fprintf(&b, "#\n# mm %s or mm -tui %s\n\n", "-config <this file>", "<this file>")
41+ fmt.Fprintf(b, "#\n# mm %s or mm -tui %s\n\n", "-config <this file>", "<this file>")
3542 }
43+}
3644
37- fmt.Fprintf(&b, "provider: %s\n", c.Provider)
45+// writeServer: the provider, the model, the address, the key, autoStart.
46+func writeServer(b *strings.Builder, s Settings) {
47+ c := s.Choices
48+ fmt.Fprintf(b, "provider: %s\n", c.Provider)
3849 for _, line := range wrap(coupledTo(s), 76) {
39- fmt.Fprintf(&b, "# %s\n", line)
50+ fmt.Fprintf(b, "# %s\n", line)
4051 }
41- fmt.Fprintf(&b, "model: %s\n", quote(c.Model))
52+ fmt.Fprintf(b, "model: %s\n", quote(c.Model))
4253 if c.BaseURL != "" {
43- fmt.Fprintf(&b, "baseUrl: %s\n", quote(c.BaseURL))
54+ fmt.Fprintf(b, "baseUrl: %s\n", quote(c.BaseURL))
4455 } else {
45- writeDefaultURLs(&b, c.Provider)
56+ writeDefaultURLs(b, c.Provider)
4657 }
4758 if isOpenAI(c.Provider) {
48- writeKeyEnv(&b, c)
59+ writeKeyEnv(b, c)
4960 }
5061 if startsServer(c) && c.Provider == "llamacpp" {
51- writeLlamaCpp(&b, c)
62+ writeLlamaCpp(b, c)
5263 }
5364 if startsServer(c) && c.Provider == "razorbill" {
54- writeRazorbill(&b, c)
65+ writeRazorbill(b, c)
5566 }
5667 b.WriteString("\n")
68+}
5769
58- writeSettings(&b, "", s.Top)
70+// writeTop: the top-level settings.
71+func writeTop(b *strings.Builder, s Settings) {
72+ writeSettings(b, "", s.Top)
5973 b.WriteString("\n")
74+}
6075
61- if u.Docs {
76+// writeUsageSections: the doc search of a docs usage, the mmConfigs example
77+// of a coordinator.
78+func writeUsageSections(b *strings.Builder, s Settings) {
79+ if s.Usage.Docs {
6280 b.WriteString("# Documentation search (usage docs): /docs for you, search_docs for the model.\n")
6381 b.WriteString("docSearch:\n searchDocs: true\n autoSearchDocs: true\n dirs: [docs]\n extensions: [.md, .markdown, .txt, .adoc, .asciidoc, .rst]\n\n")
6482 }
65- if u.Coordinator {
83+ if s.Usage.Coordinator {
6684 b.WriteString("# The agents this coordinator hands questions to: one entry per agent,\n")
6785 b.WriteString("# with a description saying when to ask it:\n# " + docsURL + "docs/en/how-to/let-the-agent-call-other-agents.md\n")
6886 b.WriteString("# mmConfigs:\n# expert:\n# path: agent.expert.yaml\n# description: Answers programming questions.\n\n")
6987 }
88+}
7089
90+// writeSampling: the sampling block, its chat_template_kwargs, openai's
91+// reasoning-effort hint.
92+func writeSampling(b *strings.Builder, s Settings) {
7193 b.WriteString("sampling:\n")
72- writeSettings(&b, " ", s.Sampling)
94+ writeSettings(b, " ", s.Sampling)
7395 if len(s.Kwargs) > 0 {
7496 b.WriteString(" chat_template_kwargs:\n")
75- writeSettings(&b, " ", s.Kwargs)
97+ writeSettings(b, " ", s.Kwargs)
7698 }
77- if c.Provider == "openai" {
99+ if s.Choices.Provider == "openai" {
78100 b.WriteString(reasoningEffortHint)
79101 }
80102 b.WriteString("\n")
103+}
81104
105+// writeContextAndSessions: the context block, and sessions when asked for.
106+func writeContextAndSessions(b *strings.Builder, s Settings) {
82107 b.WriteString("context:\n")
83- writeSettings(&b, " ", s.Context)
108+ writeSettings(b, " ", s.Context)
84109 b.WriteString("\n")
85-
86110 if len(s.Sessions) > 0 {
87111 b.WriteString("sessions:\n")
88- writeSettings(&b, " ", s.Sessions)
112+ writeSettings(b, " ", s.Sessions)
89113 b.WriteString("\n")
90114 }
115+}
91116
117+// writeAgentsMdAndACP: AGENTS.md on, and the name an editor shows.
118+func writeAgentsMdAndACP(b *strings.Builder, s Settings) {
92119 b.WriteString("agentsMd:\n # An AGENTS.md in the project directory is added to the system prompt.\n enabled: true\n\n")
93- fmt.Fprintf(&b, "acp:\n name: %s\n title: %s\n\n", strings.ToLower(c.Name), quote(titleOf(c.Name, u)))
120+ fmt.Fprintf(b, "acp:\n name: %s\n title: %s\n\n", strings.ToLower(s.Choices.Name), quote(titleOf(s.Choices.Name, s.Usage)))
121+}
94122
95- if u.JSON {
96- b.WriteString("# The shape of every answer, as Go types:\n# " + docsURL + "docs/en/how-to/get-json-answers.md\n")
97- b.WriteString("# An EXAMPLE: replace it with your own. It forbids every tool.\n")
98- b.WriteString("structuredOutput: |\n")
99- for _, line := range strings.Split(jsonExample, "\n") {
100- fmt.Fprintf(&b, " %s\n", line)
101- }
102- b.WriteString("\n")
123+// writeJSONExample: a structuredOutput example for a JSON usage.
124+func writeJSONExample(b *strings.Builder, s Settings) {
125+ if !s.Usage.JSON {
126+ return
103127 }
128+ b.WriteString("# The shape of every answer, as Go types:\n# " + docsURL + "docs/en/how-to/get-json-answers.md\n")
129+ b.WriteString("# An EXAMPLE: replace it with your own. It forbids every tool.\n")
130+ b.WriteString("structuredOutput: |\n")
131+ for _, line := range strings.Split(jsonExample, "\n") {
132+ fmt.Fprintf(b, " %s\n", line)
133+ }
134+ b.WriteString("\n")
135+}
104136
137+// writeSystem: the system prompt, the agent's name first.
138+func writeSystem(b *strings.Builder, s Settings) {
105139 b.WriteString("# Variables: {{date}}, {{cwd}}, {{env.NAME}}, {{config.NAME}} (a variables: section) — replaced when a conversation starts.\n")
106140 b.WriteString("system: |\n")
107- if c.Name != "" {
108- fmt.Fprintf(&b, " Your name is %s.\n", c.Name)
141+ if s.Choices.Name != "" {
142+ fmt.Fprintf(b, " Your name is %s.\n", s.Choices.Name)
109143 }
110- for _, line := range strings.Split(strings.TrimRight(u.System, "\n"), "\n") {
144+ for _, line := range strings.Split(strings.TrimRight(s.Usage.System, "\n"), "\n") {
111145 if line == "" {
112146 b.WriteString("\n")
113147 continue
114148 }
115- fmt.Fprintf(&b, " %s\n", line)
149+ fmt.Fprintf(b, " %s\n", line)
116150 }
151+}
117152
118- if len(s.Notes) > 0 {
119- b.WriteString("\n")
120- for _, n := range s.Notes {
121- for _, line := range wrap(n, 74) {
122- fmt.Fprintf(&b, "# %s\n", line)
123- }
153+// writeNotes: the notes the decisions left, as comments.
154+func writeNotes(b *strings.Builder, s Settings) {
155+ if len(s.Notes) == 0 {
156+ return
157+ }
158+ b.WriteString("\n")
159+ for _, n := range s.Notes {
160+ for _, line := range wrap(n, 74) {
161+ fmt.Fprintf(b, "# %s\n", line)
124162 }
125163 }
164+}
165+
166+// writeNext: where to go next.
167+func writeNext(b *strings.Builder, _ Settings) {
126168 b.WriteString("\n# Next: skills " + docsURL + "docs/en/how-to/add-a-skill.md\n")
127169 b.WriteString("# MCP servers " + docsURL + "docs/en/tutorials/mcp-getting-started.md\n")
128170 b.WriteString("# hooks " + docsURL + "docs/en/how-to/guard-the-agent-with-hooks.md\n")
129171 b.WriteString("# sessions " + docsURL + "docs/en/how-to/keep-sessions.md\n")
130- return b.String()
131172 }
132173
133174 const jsonExample = `type Contact struct {
@@ -158,111 +199,6 @@ func writeSettings(b *strings.Builder, indent string, settings []Setting) {
158199 }
159200 }
160201
161-// legend explains each origin tag, in the order the header lists them.
162-var legend = []struct{ origin, text string }{
163- {OriginMeasured, "measured in a demo of mm — re-measure after a model or quant change"},
164- {OriginCard, "from the model card or the GGUF, not measured — re-read the new card"},
165- {OriginServer, "read from the server — run mm init again after a change"},
166- {OriginGuide, "the settings guide's row for this machine"},
167- {OriginRule, "a rule of thumb, not specific to this model"},
168-}
169-
170-// writeLegend explains the origin tags the file uses, and only those.
171-func writeLegend(b *strings.Builder, s Settings) {
172- used := map[string]bool{}
173- for _, block := range [][]Setting{s.Top, s.Sampling, s.Kwargs, s.Context} {
174- for _, st := range block {
175- used[st.Origin] = true
176- }
177- }
178- first := true
179- for _, l := range legend {
180- if !used[l.origin] {
181- continue
182- }
183- if first {
184- b.WriteString("#\n# Where the numbers come from (the tag before their comment):\n")
185- first = false
186- }
187- fmt.Fprintf(b, "# %-10s %s\n", "["+l.origin+"]", l.text)
188- }
189-}
190-
191-// factsLine is what the server said about the model when the file was
192-// written: what to compare with when the model or the server changes.
193-func factsLine(s Settings) string {
194- f := s.Facts
195- if !f.Known {
196- return "none — " + s.Choices.Provider + " said nothing about this model beyond its name"
197- }
198- var parts []string
199- if f.ContextLength > 0 {
200- parts = append(parts, fmt.Sprintf("native window %d tokens", f.ContextLength))
201- }
202- if len(f.Sampling) > 0 {
203- keys := make([]string, 0, len(f.Sampling))
204- for _, k := range []string{"temperature", "top_p", "top_k", "min_p"} {
205- if v, ok := f.Sampling[k]; ok {
206- keys = append(keys, k+" "+number(k, v))
207- }
208- }
209- parts = append(parts, "GGUF sampling "+strings.Join(keys, ", "))
210- }
211- if f.Profile != "" {
212- keys := make([]string, 0, len(f.ProfileSampling))
213- for _, k := range []string{"temperature", "top_p", "top_k", "min_p", "max_tokens"} {
214- if v, ok := f.ProfileSampling[k]; ok {
215- keys = append(keys, k+" "+number(k, v))
216- }
217- }
218- parts = append(parts, "Kronk profile "+f.Profile+" sampling "+strings.Join(keys, ", "))
219- }
220- if f.Thinking.Switch != "" {
221- sw := "reasoning switch " + f.Thinking.Switch
222- if f.Thinking.Default != "" {
223- sw += " (default " + f.Thinking.Default + ")"
224- }
225- parts = append(parts, sw)
226- }
227- if len(parts) == 0 {
228- return "read from " + s.Choices.Provider + ": nothing beyond the model's name"
229- }
230- return "read from " + s.Choices.Provider + ": " + strings.Join(parts, "; ")
231-}
232-
233-// coupledTo is the comment above the model line: the settings chosen for
234-// this model, which a change of model invalidates together.
235-func coupledTo(s Settings) string {
236- var sampling, kwargs []string
237- for _, st := range s.Sampling {
238- if st.Key != "parallel_tool_calls" {
239- sampling = append(sampling, st.Key)
240- }
241- }
242- for _, st := range s.Kwargs {
243- kwargs = append(kwargs, st.Key)
244- }
245- text := "The model. Chosen for it (family " + s.Family.Name + "): sampling (" + strings.Join(sampling, ", ") + ")"
246- if len(kwargs) > 0 {
247- text += " and sampling.chat_template_kwargs (" + strings.Join(kwargs, ", ") + ")"
248- }
249- return text + ". Change the model and redo them together — running mm init again is the quick way."
250-}
251-
252-// writeKeyEnv says where the openai provider reads the API key: the variable
253-// the user named (written as apiKeyEnv) or OPENAI_API_KEY, the default.
254-func writeKeyEnv(b *strings.Builder, c Choices) {
255- if c.APIKeyEnv != "" {
256- fmt.Fprintf(b, "# The API key is read from %s: export it — it never goes in this file.\n", c.APIKeyEnv)
257- fmt.Fprintf(b, "apiKeyEnv: %s\n", c.APIKeyEnv)
258- } else {
259- b.WriteString("# The API key is read from OPENAI_API_KEY (or the variable apiKeyEnv names):\n# export it — it never goes in this file.\n")
260- }
261- if c.BaseURL == "" {
262- b.WriteString("# The default is the OpenAI API: set baseUrl for any other OpenAI-compatible service.\n")
263- }
264-}
265-
266202 // reasoningEffortHint goes at the end of the sampling block of an openai
267203 // file, ready to uncomment (ticket 177). mm speaks /v1/chat/completions and
268204 // always sends tools; some OpenAI models refuse both together while they
@@ -275,27 +211,6 @@ const reasoningEffortHint = ` # Uncomment if the API answers "Function tools wi
275211 # reasoning_effort: none
276212 `
277213
278-// writeDefaultURLs records, as comments, the addresses a file without
279-// baseUrl relies on: the provider's defaults may change, and the file then
280-// still says what they were when it was written. Uncommented, they are the
281-// same settings, written out.
282-func writeDefaultURLs(b *strings.Builder, provider string) {
283- base, fallback, ok := engine.DefaultURLs(provider)
284- if !ok {
285- return
286- }
287- fmt.Fprintf(b, "# No baseUrl: %s's defaults apply. For the record:\n", provider)
288- fmt.Fprintf(b, "# baseUrl: %s\n", quote(base))
289- for _, alt := range engine.LocalURLs(provider)[1:] {
290- fmt.Fprintf(b, "# (%s also tries %s on this machine when baseUrl does not answer)\n", provider, alt)
291- }
292- if fallback != "" {
293- fmt.Fprintf(b, "# fallback: %s # tried when baseUrl does not answer\n", quote(fallback))
294- } else {
295- fmt.Fprintf(b, "# (%s has no fallback address)\n", provider)
296- }
297-}
298-
299214 func titleOf(name string, u Usage) string {
300215 if name == "" {
301216 return u.Description
@@ -329,43 +244,6 @@ func wrap(text string, width int) []string {
329244 return out
330245 }
331246
332-// writeLlamaCpp writes the llamacpp block (tickets 223, 257): autoStart as
333-// answered (yes when not asked), and the launch settings when asked for —
334-// the values the Llama app starts its server with.
335-func writeLlamaCpp(b *strings.Builder, c Choices) {
336- if !autoStartOn(c.AutoStart) {
337- b.WriteString("# true: mm starts llama-server when nothing answers, and stops it with the\n# last mm session using it.\nllamacpp:\n autoStart: false\n")
338- return
339- }
340- b.WriteString(`# Nothing answers at this address: mm starts llama-server (router mode, this
341-# model, downloaded on first use) and stops it with the last mm session using
342-# it. A server you started yourself is never stopped. false: start it yourself.
343-llamacpp:
344- autoStart: true
345-`)
346- if on(c.Launch) {
347- b.WriteString(llamaLaunch)
348- }
349-}
350-
351-// writeRazorbill writes the razorbill block (ticket 264): autoStart as
352-// answered (yes when not asked), the other keys as comments.
353-func writeRazorbill(b *strings.Builder, c Choices) {
354- if !autoStartOn(c.AutoStart) {
355- b.WriteString("# true: mm starts rzb serve when nothing answers (macOS, mm on the Mac\n# itself), and stops it with the last mm session using it.\nrazorbill:\n autoStart: false\n")
356- return
357- }
358- b.WriteString(`# Nothing answers at this address: mm starts rzb serve (and rzb models pull
359-# when this model is missing) and stops it with the last mm session using it.
360-# macOS only, with mm running on the Mac itself — not in a container or a
361-# sandbox. A server you started yourself is never stopped.
362-razorbill:
363- autoStart: true
364- # config: rzb-server.yaml # rzb serve --config (relative to this file)
365- # serverArgs: [] # any other rzb serve flag
366-`)
367-}
368-
369247 // llamaLaunch is the launch settings block: the Llama app's values. Each
370248 // key is one llama-server flag; a key removed takes llama-server's default.
371249 const llamaLaunch = ` # Launch settings, the Llama app's values: each key is one llama-server
@@ -378,21 +256,3 @@ const llamaLaunch = ` # Launch settings, the Llama app's values: each key is on
378256 specDefault: true # --spec-default: default speculative decoding
379257 # serverArgs: [] # any other flag
380258 `
381-
382-// localURL reports whether a base URL is on this machine — the default
383-// (empty) or a loopback host: the only place mm can start a server.
384-func localURL(base string) bool {
385- if base == "" {
386- return true
387- }
388- u, err := url.Parse(base)
389- if err != nil {
390- return false
391- }
392- h := u.Hostname()
393- if h == "localhost" {
394- return true
395- }
396- ip := net.ParseIP(h)
397- return ip != nil && ip.IsLoopback()
398-}
@@ -2,14 +2,10 @@ package agentinit
2 2
3 import (3 import (
4 "fmt"4 "fmt"
5- "net"
6- "net/url"
7 "strconv"5 "strconv"
8 "strings"6 "strings"
9 "unicode"7 "unicode"
10 "unicode/utf8"8 "unicode/utf8"
11-
12- "mm/internal/engine"
13 )9 )
14 10
15 // docsURL is where the documentation is read online: whoever runs `mm init`11 // docsURL is where the documentation is read online: whoever runs `mm init`
@@ -21,113 +17,158 @@ const docsURL = "https://rickub.com/bots-garden/mini-me/blob/main/"
21 // file teaches as it configures.17 // file teaches as it configures.
22 func Render(s Settings) string {18 func Render(s Settings) string {
23 var b strings.Builder19 var b strings.Builder
20+ for _, write := range []func(*strings.Builder, Settings){
21+ writeHeader, writeServer, writeTop, writeUsageSections, writeSampling,
22+ writeContextAndSessions, writeAgentsMdAndACP, writeJSONExample, writeSystem, writeNotes, writeNext,
23+ } {
24+ write(&b, s)
25+ }
26+ return b.String()
27+}
28+
29+// writeHeader: what the agent is, where its values come from, how to run it.
30+func writeHeader(b *strings.Builder, s Settings) {
24 c, u := s.Choices, s.Usage31 c, u := s.Choices, s.Usage
25- fmt.Fprintf(&b, "# %s — %s.\n", c.Name, u.Description)32+ fmt.Fprintf(b, "# %s — %s.\n", c.Name, u.Description)
26 b.WriteString("#\n# Written by `mm init`. Every value says why it has that value; change\n")33 b.WriteString("#\n# Written by `mm init`. Every value says why it has that value; change\n")
27 b.WriteString("# them as you watch the agent work:\n# " + docsURL + "guides/agent-settings-for-small-models.md\n#\n")34 b.WriteString("# them as you watch the agent work:\n# " + docsURL + "guides/agent-settings-for-small-models.md\n#\n")
28- fmt.Fprintf(&b, "# model family: %s\n# usage: %s\n# machine: %s — %s\n", s.Family.Name, u.Name, s.Machine.Name, s.Machine.Description)35+ fmt.Fprintf(b, "# model family: %s\n# usage: %s\n# machine: %s — %s\n", s.Family.Name, u.Name, s.Machine.Name, s.Machine.Description)
29- fmt.Fprintf(&b, "# model facts: %s\n", factsLine(s))36+ fmt.Fprintf(b, "# model facts: %s\n", factsLine(s))
30- writeLegend(&b, s)37+ writeLegend(b, s)
31 if on(c.Project) {38 if on(c.Project) {
32 b.WriteString("#\n# mm or mm tui started from the project root (it finds .mm/agent.yaml)\n\n")39 b.WriteString("#\n# mm or mm tui started from the project root (it finds .mm/agent.yaml)\n\n")
33 } else {40 } else {
34- fmt.Fprintf(&b, "#\n# mm %s or mm -tui %s\n\n", "-config <this file>", "<this file>")41+ fmt.Fprintf(b, "#\n# mm %s or mm -tui %s\n\n", "-config <this file>", "<this file>")
35 }42 }
43+}
36 44
37- fmt.Fprintf(&b, "provider: %s\n", c.Provider)45+// writeServer: the provider, the model, the address, the key, autoStart.
46+func writeServer(b *strings.Builder, s Settings) {
47+ c := s.Choices
48+ fmt.Fprintf(b, "provider: %s\n", c.Provider)
38 for _, line := range wrap(coupledTo(s), 76) {49 for _, line := range wrap(coupledTo(s), 76) {
39- fmt.Fprintf(&b, "# %s\n", line)50+ fmt.Fprintf(b, "# %s\n", line)
40 }51 }
41- fmt.Fprintf(&b, "model: %s\n", quote(c.Model))52+ fmt.Fprintf(b, "model: %s\n", quote(c.Model))
42 if c.BaseURL != "" {53 if c.BaseURL != "" {
43- fmt.Fprintf(&b, "baseUrl: %s\n", quote(c.BaseURL))54+ fmt.Fprintf(b, "baseUrl: %s\n", quote(c.BaseURL))
44 } else {55 } else {
45- writeDefaultURLs(&b, c.Provider)56+ writeDefaultURLs(b, c.Provider)
46 }57 }
47 if isOpenAI(c.Provider) {58 if isOpenAI(c.Provider) {
48- writeKeyEnv(&b, c)59+ writeKeyEnv(b, c)
49 }60 }
50 if startsServer(c) && c.Provider == "llamacpp" {61 if startsServer(c) && c.Provider == "llamacpp" {
51- writeLlamaCpp(&b, c)62+ writeLlamaCpp(b, c)
52 }63 }
53 if startsServer(c) && c.Provider == "razorbill" {64 if startsServer(c) && c.Provider == "razorbill" {
54- writeRazorbill(&b, c)65+ writeRazorbill(b, c)
55 }66 }
56 b.WriteString("\n")67 b.WriteString("\n")
68+}
57 69
58- writeSettings(&b, "", s.Top)70+// writeTop: the top-level settings.
71+func writeTop(b *strings.Builder, s Settings) {
72+ writeSettings(b, "", s.Top)
59 b.WriteString("\n")73 b.WriteString("\n")
74+}
60 75
61- if u.Docs {76+// writeUsageSections: the doc search of a docs usage, the mmConfigs example
77+// of a coordinator.
78+func writeUsageSections(b *strings.Builder, s Settings) {
79+ if s.Usage.Docs {
62 b.WriteString("# Documentation search (usage docs): /docs for you, search_docs for the model.\n")80 b.WriteString("# Documentation search (usage docs): /docs for you, search_docs for the model.\n")
63 b.WriteString("docSearch:\n searchDocs: true\n autoSearchDocs: true\n dirs: [docs]\n extensions: [.md, .markdown, .txt, .adoc, .asciidoc, .rst]\n\n")81 b.WriteString("docSearch:\n searchDocs: true\n autoSearchDocs: true\n dirs: [docs]\n extensions: [.md, .markdown, .txt, .adoc, .asciidoc, .rst]\n\n")
64 }82 }
65- if u.Coordinator {83+ if s.Usage.Coordinator {
66 b.WriteString("# The agents this coordinator hands questions to: one entry per agent,\n")84 b.WriteString("# The agents this coordinator hands questions to: one entry per agent,\n")
67 b.WriteString("# with a description saying when to ask it:\n# " + docsURL + "docs/en/how-to/let-the-agent-call-other-agents.md\n")85 b.WriteString("# with a description saying when to ask it:\n# " + docsURL + "docs/en/how-to/let-the-agent-call-other-agents.md\n")
68 b.WriteString("# mmConfigs:\n# expert:\n# path: agent.expert.yaml\n# description: Answers programming questions.\n\n")86 b.WriteString("# mmConfigs:\n# expert:\n# path: agent.expert.yaml\n# description: Answers programming questions.\n\n")
69 }87 }
88+}
70 89
90+// writeSampling: the sampling block, its chat_template_kwargs, openai's
91+// reasoning-effort hint.
92+func writeSampling(b *strings.Builder, s Settings) {
71 b.WriteString("sampling:\n")93 b.WriteString("sampling:\n")
72- writeSettings(&b, " ", s.Sampling)94+ writeSettings(b, " ", s.Sampling)
73 if len(s.Kwargs) > 0 {95 if len(s.Kwargs) > 0 {
74 b.WriteString(" chat_template_kwargs:\n")96 b.WriteString(" chat_template_kwargs:\n")
75- writeSettings(&b, " ", s.Kwargs)97+ writeSettings(b, " ", s.Kwargs)
76 }98 }
77- if c.Provider == "openai" {99+ if s.Choices.Provider == "openai" {
78 b.WriteString(reasoningEffortHint)100 b.WriteString(reasoningEffortHint)
79 }101 }
80 b.WriteString("\n")102 b.WriteString("\n")
103+}
81 104
105+// writeContextAndSessions: the context block, and sessions when asked for.
106+func writeContextAndSessions(b *strings.Builder, s Settings) {
82 b.WriteString("context:\n")107 b.WriteString("context:\n")
83- writeSettings(&b, " ", s.Context)108+ writeSettings(b, " ", s.Context)
84 b.WriteString("\n")109 b.WriteString("\n")
85-
86 if len(s.Sessions) > 0 {110 if len(s.Sessions) > 0 {
87 b.WriteString("sessions:\n")111 b.WriteString("sessions:\n")
88- writeSettings(&b, " ", s.Sessions)112+ writeSettings(b, " ", s.Sessions)
89 b.WriteString("\n")113 b.WriteString("\n")
90 }114 }
115+}
91 116
117+// writeAgentsMdAndACP: AGENTS.md on, and the name an editor shows.
118+func writeAgentsMdAndACP(b *strings.Builder, s Settings) {
92 b.WriteString("agentsMd:\n # An AGENTS.md in the project directory is added to the system prompt.\n enabled: true\n\n")119 b.WriteString("agentsMd:\n # An AGENTS.md in the project directory is added to the system prompt.\n enabled: true\n\n")
93- fmt.Fprintf(&b, "acp:\n name: %s\n title: %s\n\n", strings.ToLower(c.Name), quote(titleOf(c.Name, u)))120+ fmt.Fprintf(b, "acp:\n name: %s\n title: %s\n\n", strings.ToLower(s.Choices.Name), quote(titleOf(s.Choices.Name, s.Usage)))
121+}
94 122
95- if u.JSON {123+// writeJSONExample: a structuredOutput example for a JSON usage.
96- b.WriteString("# The shape of every answer, as Go types:\n# " + docsURL + "docs/en/how-to/get-json-answers.md\n")124+func writeJSONExample(b *strings.Builder, s Settings) {
97- b.WriteString("# An EXAMPLE: replace it with your own. It forbids every tool.\n")125+ if !s.Usage.JSON {
98- b.WriteString("structuredOutput: |\n")126+ return
99- for _, line := range strings.Split(jsonExample, "\n") {
100- fmt.Fprintf(&b, " %s\n", line)
101- }
102- b.WriteString("\n")
103 }127 }
128+ b.WriteString("# The shape of every answer, as Go types:\n# " + docsURL + "docs/en/how-to/get-json-answers.md\n")
129+ b.WriteString("# An EXAMPLE: replace it with your own. It forbids every tool.\n")
130+ b.WriteString("structuredOutput: |\n")
131+ for _, line := range strings.Split(jsonExample, "\n") {
132+ fmt.Fprintf(b, " %s\n", line)
133+ }
134+ b.WriteString("\n")
135+}
104 136
137+// writeSystem: the system prompt, the agent's name first.
138+func writeSystem(b *strings.Builder, s Settings) {
105 b.WriteString("# Variables: {{date}}, {{cwd}}, {{env.NAME}}, {{config.NAME}} (a variables: section) — replaced when a conversation starts.\n")139 b.WriteString("# Variables: {{date}}, {{cwd}}, {{env.NAME}}, {{config.NAME}} (a variables: section) — replaced when a conversation starts.\n")
106 b.WriteString("system: |\n")140 b.WriteString("system: |\n")
107- if c.Name != "" {141+ if s.Choices.Name != "" {
108- fmt.Fprintf(&b, " Your name is %s.\n", c.Name)142+ fmt.Fprintf(b, " Your name is %s.\n", s.Choices.Name)
109 }143 }
110- for _, line := range strings.Split(strings.TrimRight(u.System, "\n"), "\n") {144+ for _, line := range strings.Split(strings.TrimRight(s.Usage.System, "\n"), "\n") {
111 if line == "" {145 if line == "" {
112 b.WriteString("\n")146 b.WriteString("\n")
113 continue147 continue
114 }148 }
115- fmt.Fprintf(&b, " %s\n", line)149+ fmt.Fprintf(b, " %s\n", line)
116 }150 }
151+}
117 152
118- if len(s.Notes) > 0 {153+// writeNotes: the notes the decisions left, as comments.
119- b.WriteString("\n")154+func writeNotes(b *strings.Builder, s Settings) {
120- for _, n := range s.Notes {155+ if len(s.Notes) == 0 {
121- for _, line := range wrap(n, 74) {156+ return
122- fmt.Fprintf(&b, "# %s\n", line)157+ }
123- }158+ b.WriteString("\n")
159+ for _, n := range s.Notes {
160+ for _, line := range wrap(n, 74) {
161+ fmt.Fprintf(b, "# %s\n", line)
124 }162 }
125 }163 }
164+}
165+
166+// writeNext: where to go next.
167+func writeNext(b *strings.Builder, _ Settings) {
126 b.WriteString("\n# Next: skills " + docsURL + "docs/en/how-to/add-a-skill.md\n")168 b.WriteString("\n# Next: skills " + docsURL + "docs/en/how-to/add-a-skill.md\n")
127 b.WriteString("# MCP servers " + docsURL + "docs/en/tutorials/mcp-getting-started.md\n")169 b.WriteString("# MCP servers " + docsURL + "docs/en/tutorials/mcp-getting-started.md\n")
128 b.WriteString("# hooks " + docsURL + "docs/en/how-to/guard-the-agent-with-hooks.md\n")170 b.WriteString("# hooks " + docsURL + "docs/en/how-to/guard-the-agent-with-hooks.md\n")
129 b.WriteString("# sessions " + docsURL + "docs/en/how-to/keep-sessions.md\n")171 b.WriteString("# sessions " + docsURL + "docs/en/how-to/keep-sessions.md\n")
130- return b.String()
131 }172 }
132 173
133 const jsonExample = `type Contact struct {174 const jsonExample = `type Contact struct {
@@ -158,111 +199,6 @@ func writeSettings(b *strings.Builder, indent string, settings []Setting) {
158 }199 }
159 }200 }
160 201
161-// legend explains each origin tag, in the order the header lists them.
162-var legend = []struct{ origin, text string }{
163- {OriginMeasured, "measured in a demo of mm — re-measure after a model or quant change"},
164- {OriginCard, "from the model card or the GGUF, not measured — re-read the new card"},
165- {OriginServer, "read from the server — run mm init again after a change"},
166- {OriginGuide, "the settings guide's row for this machine"},
167- {OriginRule, "a rule of thumb, not specific to this model"},
168-}
169-
170-// writeLegend explains the origin tags the file uses, and only those.
171-func writeLegend(b *strings.Builder, s Settings) {
172- used := map[string]bool{}
173- for _, block := range [][]Setting{s.Top, s.Sampling, s.Kwargs, s.Context} {
174- for _, st := range block {
175- used[st.Origin] = true
176- }
177- }
178- first := true
179- for _, l := range legend {
180- if !used[l.origin] {
181- continue
182- }
183- if first {
184- b.WriteString("#\n# Where the numbers come from (the tag before their comment):\n")
185- first = false
186- }
187- fmt.Fprintf(b, "# %-10s %s\n", "["+l.origin+"]", l.text)
188- }
189-}
190-
191-// factsLine is what the server said about the model when the file was
192-// written: what to compare with when the model or the server changes.
193-func factsLine(s Settings) string {
194- f := s.Facts
195- if !f.Known {
196- return "none — " + s.Choices.Provider + " said nothing about this model beyond its name"
197- }
198- var parts []string
199- if f.ContextLength > 0 {
200- parts = append(parts, fmt.Sprintf("native window %d tokens", f.ContextLength))
201- }
202- if len(f.Sampling) > 0 {
203- keys := make([]string, 0, len(f.Sampling))
204- for _, k := range []string{"temperature", "top_p", "top_k", "min_p"} {
205- if v, ok := f.Sampling[k]; ok {
206- keys = append(keys, k+" "+number(k, v))
207- }
208- }
209- parts = append(parts, "GGUF sampling "+strings.Join(keys, ", "))
210- }
211- if f.Profile != "" {
212- keys := make([]string, 0, len(f.ProfileSampling))
213- for _, k := range []string{"temperature", "top_p", "top_k", "min_p", "max_tokens"} {
214- if v, ok := f.ProfileSampling[k]; ok {
215- keys = append(keys, k+" "+number(k, v))
216- }
217- }
218- parts = append(parts, "Kronk profile "+f.Profile+" sampling "+strings.Join(keys, ", "))
219- }
220- if f.Thinking.Switch != "" {
221- sw := "reasoning switch " + f.Thinking.Switch
222- if f.Thinking.Default != "" {
223- sw += " (default " + f.Thinking.Default + ")"
224- }
225- parts = append(parts, sw)
226- }
227- if len(parts) == 0 {
228- return "read from " + s.Choices.Provider + ": nothing beyond the model's name"
229- }
230- return "read from " + s.Choices.Provider + ": " + strings.Join(parts, "; ")
231-}
232-
233-// coupledTo is the comment above the model line: the settings chosen for
234-// this model, which a change of model invalidates together.
235-func coupledTo(s Settings) string {
236- var sampling, kwargs []string
237- for _, st := range s.Sampling {
238- if st.Key != "parallel_tool_calls" {
239- sampling = append(sampling, st.Key)
240- }
241- }
242- for _, st := range s.Kwargs {
243- kwargs = append(kwargs, st.Key)
244- }
245- text := "The model. Chosen for it (family " + s.Family.Name + "): sampling (" + strings.Join(sampling, ", ") + ")"
246- if len(kwargs) > 0 {
247- text += " and sampling.chat_template_kwargs (" + strings.Join(kwargs, ", ") + ")"
248- }
249- return text + ". Change the model and redo them together — running mm init again is the quick way."
250-}
251-
252-// writeKeyEnv says where the openai provider reads the API key: the variable
253-// the user named (written as apiKeyEnv) or OPENAI_API_KEY, the default.
254-func writeKeyEnv(b *strings.Builder, c Choices) {
255- if c.APIKeyEnv != "" {
256- fmt.Fprintf(b, "# The API key is read from %s: export it — it never goes in this file.\n", c.APIKeyEnv)
257- fmt.Fprintf(b, "apiKeyEnv: %s\n", c.APIKeyEnv)
258- } else {
259- b.WriteString("# The API key is read from OPENAI_API_KEY (or the variable apiKeyEnv names):\n# export it — it never goes in this file.\n")
260- }
261- if c.BaseURL == "" {
262- b.WriteString("# The default is the OpenAI API: set baseUrl for any other OpenAI-compatible service.\n")
263- }
264-}
265-
266 // reasoningEffortHint goes at the end of the sampling block of an openai202 // reasoningEffortHint goes at the end of the sampling block of an openai
267 // file, ready to uncomment (ticket 177). mm speaks /v1/chat/completions and203 // file, ready to uncomment (ticket 177). mm speaks /v1/chat/completions and
268 // always sends tools; some OpenAI models refuse both together while they204 // always sends tools; some OpenAI models refuse both together while they
@@ -275,27 +211,6 @@ const reasoningEffortHint = ` # Uncomment if the API answers "Function tools wi
275 # reasoning_effort: none211 # reasoning_effort: none
276 `212 `
277 213
278-// writeDefaultURLs records, as comments, the addresses a file without
279-// baseUrl relies on: the provider's defaults may change, and the file then
280-// still says what they were when it was written. Uncommented, they are the
281-// same settings, written out.
282-func writeDefaultURLs(b *strings.Builder, provider string) {
283- base, fallback, ok := engine.DefaultURLs(provider)
284- if !ok {
285- return
286- }
287- fmt.Fprintf(b, "# No baseUrl: %s's defaults apply. For the record:\n", provider)
288- fmt.Fprintf(b, "# baseUrl: %s\n", quote(base))
289- for _, alt := range engine.LocalURLs(provider)[1:] {
290- fmt.Fprintf(b, "# (%s also tries %s on this machine when baseUrl does not answer)\n", provider, alt)
291- }
292- if fallback != "" {
293- fmt.Fprintf(b, "# fallback: %s # tried when baseUrl does not answer\n", quote(fallback))
294- } else {
295- fmt.Fprintf(b, "# (%s has no fallback address)\n", provider)
296- }
297-}
298-
299 func titleOf(name string, u Usage) string {214 func titleOf(name string, u Usage) string {
300 if name == "" {215 if name == "" {
301 return u.Description216 return u.Description
@@ -329,43 +244,6 @@ func wrap(text string, width int) []string {
329 return out244 return out
330 }245 }
331 246
332-// writeLlamaCpp writes the llamacpp block (tickets 223, 257): autoStart as
333-// answered (yes when not asked), and the launch settings when asked for —
334-// the values the Llama app starts its server with.
335-func writeLlamaCpp(b *strings.Builder, c Choices) {
336- if !autoStartOn(c.AutoStart) {
337- b.WriteString("# true: mm starts llama-server when nothing answers, and stops it with the\n# last mm session using it.\nllamacpp:\n autoStart: false\n")
338- return
339- }
340- b.WriteString(`# Nothing answers at this address: mm starts llama-server (router mode, this
341-# model, downloaded on first use) and stops it with the last mm session using
342-# it. A server you started yourself is never stopped. false: start it yourself.
343-llamacpp:
344- autoStart: true
345-`)
346- if on(c.Launch) {
347- b.WriteString(llamaLaunch)
348- }
349-}
350-
351-// writeRazorbill writes the razorbill block (ticket 264): autoStart as
352-// answered (yes when not asked), the other keys as comments.
353-func writeRazorbill(b *strings.Builder, c Choices) {
354- if !autoStartOn(c.AutoStart) {
355- b.WriteString("# true: mm starts rzb serve when nothing answers (macOS, mm on the Mac\n# itself), and stops it with the last mm session using it.\nrazorbill:\n autoStart: false\n")
356- return
357- }
358- b.WriteString(`# Nothing answers at this address: mm starts rzb serve (and rzb models pull
359-# when this model is missing) and stops it with the last mm session using it.
360-# macOS only, with mm running on the Mac itself — not in a container or a
361-# sandbox. A server you started yourself is never stopped.
362-razorbill:
363- autoStart: true
364- # config: rzb-server.yaml # rzb serve --config (relative to this file)
365- # serverArgs: [] # any other rzb serve flag
366-`)
367-}
368-
369 // llamaLaunch is the launch settings block: the Llama app's values. Each247 // llamaLaunch is the launch settings block: the Llama app's values. Each
370 // key is one llama-server flag; a key removed takes llama-server's default.248 // key is one llama-server flag; a key removed takes llama-server's default.
371 const llamaLaunch = ` # Launch settings, the Llama app's values: each key is one llama-server249 const llamaLaunch = ` # Launch settings, the Llama app's values: each key is one llama-server
@@ -378,21 +256,3 @@ const llamaLaunch = ` # Launch settings, the Llama app's values: each key is on
378 specDefault: true # --spec-default: default speculative decoding256 specDefault: true # --spec-default: default speculative decoding
379 # serverArgs: [] # any other flag257 # serverArgs: [] # any other flag
380 `258 `
381-
382-// localURL reports whether a base URL is on this machine — the default
383-// (empty) or a loopback host: the only place mm can start a server.
384-func localURL(base string) bool {
385- if base == "" {
386- return true
387- }
388- u, err := url.Parse(base)
389- if err != nil {
390- return false
391- }
392- h := u.Hostname()
393- if h == "localhost" {
394- return true
395- }
396- ip := net.ParseIP(h)
397- return ip != nil && ip.IsLoopback()
398-}
added internal/agentinit/render_header.go +77 -0
new file mode 100644
@@ -0,0 +1,77 @@
1+package agentinit
2+
3+import (
4+ "fmt"
5+ "strings"
6+)
7+
8+// legend explains each origin tag, in the order the header lists them.
9+var legend = []struct{ origin, text string }{
10+ {OriginMeasured, "measured in a demo of mm — re-measure after a model or quant change"},
11+ {OriginCard, "from the model card or the GGUF, not measured — re-read the new card"},
12+ {OriginServer, "read from the server — run mm init again after a change"},
13+ {OriginGuide, "the settings guide's row for this machine"},
14+ {OriginRule, "a rule of thumb, not specific to this model"},
15+}
16+
17+// writeLegend explains the origin tags the file uses, and only those.
18+func writeLegend(b *strings.Builder, s Settings) {
19+ used := map[string]bool{}
20+ for _, block := range [][]Setting{s.Top, s.Sampling, s.Kwargs, s.Context} {
21+ for _, st := range block {
22+ used[st.Origin] = true
23+ }
24+ }
25+ first := true
26+ for _, l := range legend {
27+ if !used[l.origin] {
28+ continue
29+ }
30+ if first {
31+ b.WriteString("#\n# Where the numbers come from (the tag before their comment):\n")
32+ first = false
33+ }
34+ fmt.Fprintf(b, "# %-10s %s\n", "["+l.origin+"]", l.text)
35+ }
36+}
37+
38+// factsLine is what the server said about the model when the file was
39+// written: what to compare with when the model or the server changes.
40+func factsLine(s Settings) string {
41+ f := s.Facts
42+ if !f.Known {
43+ return "none — " + s.Choices.Provider + " said nothing about this model beyond its name"
44+ }
45+ var parts []string
46+ if f.ContextLength > 0 {
47+ parts = append(parts, fmt.Sprintf("native window %d tokens", f.ContextLength))
48+ }
49+ if len(f.Sampling) > 0 {
50+ parts = append(parts, "GGUF sampling "+samplingList(f.Sampling, "temperature", "top_p", "top_k", "min_p"))
51+ }
52+ if f.Profile != "" {
53+ parts = append(parts, "Kronk profile "+f.Profile+" sampling "+samplingList(f.ProfileSampling, "temperature", "top_p", "top_k", "min_p", "max_tokens"))
54+ }
55+ if f.Thinking.Switch != "" {
56+ sw := "reasoning switch " + f.Thinking.Switch
57+ if f.Thinking.Default != "" {
58+ sw += " (default " + f.Thinking.Default + ")"
59+ }
60+ parts = append(parts, sw)
61+ }
62+ if len(parts) == 0 {
63+ return "read from " + s.Choices.Provider + ": nothing beyond the model's name"
64+ }
65+ return "read from " + s.Choices.Provider + ": " + strings.Join(parts, "; ")
66+}
67+
68+// samplingList is "key value" for each key of values, in the order given.
69+func samplingList(values map[string]float64, keys ...string) string {
70+ out := make([]string, 0, len(keys))
71+ for _, k := range keys {
72+ if v, ok := values[k]; ok {
73+ out = append(out, k+" "+number(k, v))
74+ }
75+ }
76+ return strings.Join(out, ", ")
77+}
new file mode 100644
@@ -0,0 +1,77 @@
1+package agentinit
2+
3+import (
4+ "fmt"
5+ "strings"
6+)
7+
8+// legend explains each origin tag, in the order the header lists them.
9+var legend = []struct{ origin, text string }{
10+ {OriginMeasured, "measured in a demo of mm — re-measure after a model or quant change"},
11+ {OriginCard, "from the model card or the GGUF, not measured — re-read the new card"},
12+ {OriginServer, "read from the server — run mm init again after a change"},
13+ {OriginGuide, "the settings guide's row for this machine"},
14+ {OriginRule, "a rule of thumb, not specific to this model"},
15+}
16+
17+// writeLegend explains the origin tags the file uses, and only those.
18+func writeLegend(b *strings.Builder, s Settings) {
19+ used := map[string]bool{}
20+ for _, block := range [][]Setting{s.Top, s.Sampling, s.Kwargs, s.Context} {
21+ for _, st := range block {
22+ used[st.Origin] = true
23+ }
24+ }
25+ first := true
26+ for _, l := range legend {
27+ if !used[l.origin] {
28+ continue
29+ }
30+ if first {
31+ b.WriteString("#\n# Where the numbers come from (the tag before their comment):\n")
32+ first = false
33+ }
34+ fmt.Fprintf(b, "# %-10s %s\n", "["+l.origin+"]", l.text)
35+ }
36+}
37+
38+// factsLine is what the server said about the model when the file was
39+// written: what to compare with when the model or the server changes.
40+func factsLine(s Settings) string {
41+ f := s.Facts
42+ if !f.Known {
43+ return "none — " + s.Choices.Provider + " said nothing about this model beyond its name"
44+ }
45+ var parts []string
46+ if f.ContextLength > 0 {
47+ parts = append(parts, fmt.Sprintf("native window %d tokens", f.ContextLength))
48+ }
49+ if len(f.Sampling) > 0 {
50+ parts = append(parts, "GGUF sampling "+samplingList(f.Sampling, "temperature", "top_p", "top_k", "min_p"))
51+ }
52+ if f.Profile != "" {
53+ parts = append(parts, "Kronk profile "+f.Profile+" sampling "+samplingList(f.ProfileSampling, "temperature", "top_p", "top_k", "min_p", "max_tokens"))
54+ }
55+ if f.Thinking.Switch != "" {
56+ sw := "reasoning switch " + f.Thinking.Switch
57+ if f.Thinking.Default != "" {
58+ sw += " (default " + f.Thinking.Default + ")"
59+ }
60+ parts = append(parts, sw)
61+ }
62+ if len(parts) == 0 {
63+ return "read from " + s.Choices.Provider + ": nothing beyond the model's name"
64+ }
65+ return "read from " + s.Choices.Provider + ": " + strings.Join(parts, "; ")
66+}
67+
68+// samplingList is "key value" for each key of values, in the order given.
69+func samplingList(values map[string]float64, keys ...string) string {
70+ out := make([]string, 0, len(keys))
71+ for _, k := range keys {
72+ if v, ok := values[k]; ok {
73+ out = append(out, k+" "+number(k, v))
74+ }
75+ }
76+ return strings.Join(out, ", ")
77+}
added internal/agentinit/render_server.go +118 -0
new file mode 100644
@@ -0,0 +1,118 @@
1+package agentinit
2+
3+import (
4+ "fmt"
5+ "mm/internal/engine"
6+ "net"
7+ "net/url"
8+ "strings"
9+)
10+
11+// coupledTo is the comment above the model line: the settings chosen for
12+// this model, which a change of model invalidates together.
13+func coupledTo(s Settings) string {
14+ var sampling, kwargs []string
15+ for _, st := range s.Sampling {
16+ if st.Key != "parallel_tool_calls" {
17+ sampling = append(sampling, st.Key)
18+ }
19+ }
20+ for _, st := range s.Kwargs {
21+ kwargs = append(kwargs, st.Key)
22+ }
23+ text := "The model. Chosen for it (family " + s.Family.Name + "): sampling (" + strings.Join(sampling, ", ") + ")"
24+ if len(kwargs) > 0 {
25+ text += " and sampling.chat_template_kwargs (" + strings.Join(kwargs, ", ") + ")"
26+ }
27+ return text + ". Change the model and redo them together — running mm init again is the quick way."
28+}
29+
30+// writeKeyEnv says where the openai provider reads the API key: the variable
31+// the user named (written as apiKeyEnv) or OPENAI_API_KEY, the default.
32+func writeKeyEnv(b *strings.Builder, c Choices) {
33+ if c.APIKeyEnv != "" {
34+ fmt.Fprintf(b, "# The API key is read from %s: export it — it never goes in this file.\n", c.APIKeyEnv)
35+ fmt.Fprintf(b, "apiKeyEnv: %s\n", c.APIKeyEnv)
36+ } else {
37+ b.WriteString("# The API key is read from OPENAI_API_KEY (or the variable apiKeyEnv names):\n# export it — it never goes in this file.\n")
38+ }
39+ if c.BaseURL == "" {
40+ b.WriteString("# The default is the OpenAI API: set baseUrl for any other OpenAI-compatible service.\n")
41+ }
42+}
43+
44+// writeDefaultURLs records, as comments, the addresses a file without
45+// baseUrl relies on: the provider's defaults may change, and the file then
46+// still says what they were when it was written. Uncommented, they are the
47+// same settings, written out.
48+func writeDefaultURLs(b *strings.Builder, provider string) {
49+ base, fallback, ok := engine.DefaultURLs(provider)
50+ if !ok {
51+ return
52+ }
53+ fmt.Fprintf(b, "# No baseUrl: %s's defaults apply. For the record:\n", provider)
54+ fmt.Fprintf(b, "# baseUrl: %s\n", quote(base))
55+ for _, alt := range engine.LocalURLs(provider)[1:] {
56+ fmt.Fprintf(b, "# (%s also tries %s on this machine when baseUrl does not answer)\n", provider, alt)
57+ }
58+ if fallback != "" {
59+ fmt.Fprintf(b, "# fallback: %s # tried when baseUrl does not answer\n", quote(fallback))
60+ } else {
61+ fmt.Fprintf(b, "# (%s has no fallback address)\n", provider)
62+ }
63+}
64+
65+// writeLlamaCpp writes the llamacpp block (tickets 223, 257): autoStart as
66+// answered (yes when not asked), and the launch settings when asked for —
67+// the values the Llama app starts its server with.
68+func writeLlamaCpp(b *strings.Builder, c Choices) {
69+ if !autoStartOn(c.AutoStart) {
70+ b.WriteString("# true: mm starts llama-server when nothing answers, and stops it with the\n# last mm session using it.\nllamacpp:\n autoStart: false\n")
71+ return
72+ }
73+ b.WriteString(`# Nothing answers at this address: mm starts llama-server (router mode, this
74+# model, downloaded on first use) and stops it with the last mm session using
75+# it. A server you started yourself is never stopped. false: start it yourself.
76+llamacpp:
77+ autoStart: true
78+`)
79+ if on(c.Launch) {
80+ b.WriteString(llamaLaunch)
81+ }
82+}
83+
84+// writeRazorbill writes the razorbill block (ticket 264): autoStart as
85+// answered (yes when not asked), the other keys as comments.
86+func writeRazorbill(b *strings.Builder, c Choices) {
87+ if !autoStartOn(c.AutoStart) {
88+ b.WriteString("# true: mm starts rzb serve when nothing answers (macOS, mm on the Mac\n# itself), and stops it with the last mm session using it.\nrazorbill:\n autoStart: false\n")
89+ return
90+ }
91+ b.WriteString(`# Nothing answers at this address: mm starts rzb serve (and rzb models pull
92+# when this model is missing) and stops it with the last mm session using it.
93+# macOS only, with mm running on the Mac itself — not in a container or a
94+# sandbox. A server you started yourself is never stopped.
95+razorbill:
96+ autoStart: true
97+ # config: rzb-server.yaml # rzb serve --config (relative to this file)
98+ # serverArgs: [] # any other rzb serve flag
99+`)
100+}
101+
102+// localURL reports whether a base URL is on this machine — the default
103+// (empty) or a loopback host: the only place mm can start a server.
104+func localURL(base string) bool {
105+ if base == "" {
106+ return true
107+ }
108+ u, err := url.Parse(base)
109+ if err != nil {
110+ return false
111+ }
112+ h := u.Hostname()
113+ if h == "localhost" {
114+ return true
115+ }
116+ ip := net.ParseIP(h)
117+ return ip != nil && ip.IsLoopback()
118+}
new file mode 100644
@@ -0,0 +1,118 @@
1+package agentinit
2+
3+import (
4+ "fmt"
5+ "mm/internal/engine"
6+ "net"
7+ "net/url"
8+ "strings"
9+)
10+
11+// coupledTo is the comment above the model line: the settings chosen for
12+// this model, which a change of model invalidates together.
13+func coupledTo(s Settings) string {
14+ var sampling, kwargs []string
15+ for _, st := range s.Sampling {
16+ if st.Key != "parallel_tool_calls" {
17+ sampling = append(sampling, st.Key)
18+ }
19+ }
20+ for _, st := range s.Kwargs {
21+ kwargs = append(kwargs, st.Key)
22+ }
23+ text := "The model. Chosen for it (family " + s.Family.Name + "): sampling (" + strings.Join(sampling, ", ") + ")"
24+ if len(kwargs) > 0 {
25+ text += " and sampling.chat_template_kwargs (" + strings.Join(kwargs, ", ") + ")"
26+ }
27+ return text + ". Change the model and redo them together — running mm init again is the quick way."
28+}
29+
30+// writeKeyEnv says where the openai provider reads the API key: the variable
31+// the user named (written as apiKeyEnv) or OPENAI_API_KEY, the default.
32+func writeKeyEnv(b *strings.Builder, c Choices) {
33+ if c.APIKeyEnv != "" {
34+ fmt.Fprintf(b, "# The API key is read from %s: export it — it never goes in this file.\n", c.APIKeyEnv)
35+ fmt.Fprintf(b, "apiKeyEnv: %s\n", c.APIKeyEnv)
36+ } else {
37+ b.WriteString("# The API key is read from OPENAI_API_KEY (or the variable apiKeyEnv names):\n# export it — it never goes in this file.\n")
38+ }
39+ if c.BaseURL == "" {
40+ b.WriteString("# The default is the OpenAI API: set baseUrl for any other OpenAI-compatible service.\n")
41+ }
42+}
43+
44+// writeDefaultURLs records, as comments, the addresses a file without
45+// baseUrl relies on: the provider's defaults may change, and the file then
46+// still says what they were when it was written. Uncommented, they are the
47+// same settings, written out.
48+func writeDefaultURLs(b *strings.Builder, provider string) {
49+ base, fallback, ok := engine.DefaultURLs(provider)
50+ if !ok {
51+ return
52+ }
53+ fmt.Fprintf(b, "# No baseUrl: %s's defaults apply. For the record:\n", provider)
54+ fmt.Fprintf(b, "# baseUrl: %s\n", quote(base))
55+ for _, alt := range engine.LocalURLs(provider)[1:] {
56+ fmt.Fprintf(b, "# (%s also tries %s on this machine when baseUrl does not answer)\n", provider, alt)
57+ }
58+ if fallback != "" {
59+ fmt.Fprintf(b, "# fallback: %s # tried when baseUrl does not answer\n", quote(fallback))
60+ } else {
61+ fmt.Fprintf(b, "# (%s has no fallback address)\n", provider)
62+ }
63+}
64+
65+// writeLlamaCpp writes the llamacpp block (tickets 223, 257): autoStart as
66+// answered (yes when not asked), and the launch settings when asked for —
67+// the values the Llama app starts its server with.
68+func writeLlamaCpp(b *strings.Builder, c Choices) {
69+ if !autoStartOn(c.AutoStart) {
70+ b.WriteString("# true: mm starts llama-server when nothing answers, and stops it with the\n# last mm session using it.\nllamacpp:\n autoStart: false\n")
71+ return
72+ }
73+ b.WriteString(`# Nothing answers at this address: mm starts llama-server (router mode, this
74+# model, downloaded on first use) and stops it with the last mm session using
75+# it. A server you started yourself is never stopped. false: start it yourself.
76+llamacpp:
77+ autoStart: true
78+`)
79+ if on(c.Launch) {
80+ b.WriteString(llamaLaunch)
81+ }
82+}
83+
84+// writeRazorbill writes the razorbill block (ticket 264): autoStart as
85+// answered (yes when not asked), the other keys as comments.
86+func writeRazorbill(b *strings.Builder, c Choices) {
87+ if !autoStartOn(c.AutoStart) {
88+ b.WriteString("# true: mm starts rzb serve when nothing answers (macOS, mm on the Mac\n# itself), and stops it with the last mm session using it.\nrazorbill:\n autoStart: false\n")
89+ return
90+ }
91+ b.WriteString(`# Nothing answers at this address: mm starts rzb serve (and rzb models pull
92+# when this model is missing) and stops it with the last mm session using it.
93+# macOS only, with mm running on the Mac itself — not in a container or a
94+# sandbox. A server you started yourself is never stopped.
95+razorbill:
96+ autoStart: true
97+ # config: rzb-server.yaml # rzb serve --config (relative to this file)
98+ # serverArgs: [] # any other rzb serve flag
99+`)
100+}
101+
102+// localURL reports whether a base URL is on this machine — the default
103+// (empty) or a loopback host: the only place mm can start a server.
104+func localURL(base string) bool {
105+ if base == "" {
106+ return true
107+ }
108+ u, err := url.Parse(base)
109+ if err != nil {
110+ return false
111+ }
112+ h := u.Hostname()
113+ if h == "localhost" {
114+ return true
115+ }
116+ ip := net.ParseIP(h)
117+ return ip != nil && ip.IsLoopback()
118+}
added internal/agentinit/sampling.go +129 -0
new file mode 100644
@@ -0,0 +1,129 @@
1+package agentinit
2+
3+import (
4+ "fmt"
5+ "strings"
6+)
7+
8+func (s *Settings) decideSampling() {
9+ sv := s.familySampling()
10+ f := s.Facts
11+ for k, v := range f.Sampling {
12+ sv.set(k, v, "the GGUF's own sampling, read from the server", OriginServer)
13+ }
14+ fam := s.Family
15+ if !s.Thinking && s.Usage.Precise && fam.Precise != nil {
16+ sv.set("temperature", *fam.Precise, fmt.Sprintf("precise temperature for a %s agent without reasoning (family %s)", s.Usage.Name, fam.Name), fam.Origin["precise"])
17+ }
18+ if s.Thinking && sv.values["temperature"] < 0.5 {
19+ sv.set("temperature", 0.6, "reasoning is on: a thinking model loops at a low temperature", OriginRule)
20+ }
21+ for k, v := range f.ProfileSampling {
22+ if k != "max_tokens" {
23+ sv.set(k, v, s.profileReason(), OriginServer)
24+ }
25+ }
26+ for _, k := range []string{"temperature", "top_p", "top_k", "min_p"} {
27+ if v, ok := sv.values[k]; ok {
28+ s.Sampling = append(s.Sampling, Setting{Key: k, Value: number(k, v), Reason: sv.reasons[k], Origin: sv.origins[k]})
29+ }
30+ }
31+ s.Sampling = append(s.Sampling, s.maxTokens())
32+ if s.anyTool() {
33+ s.Sampling = append(s.Sampling, Setting{Key: "parallel_tool_calls", Value: "false", Reason: "one tool call per reply: small models run a check before the change it checks has landed otherwise"})
34+ }
35+ s.decideKwargs()
36+}
37+
38+// samplingValues are the sampling values decided so far, each with why and
39+// where it comes from.
40+type samplingValues struct {
41+ values map[string]float64
42+ reasons, origins map[string]string
43+}
44+
45+func (sv *samplingValues) set(key string, v float64, reason, origin string) {
46+ sv.values[key], sv.reasons[key], sv.origins[key] = v, reason, origin
47+}
48+
49+// familySampling starts from the family's general values — its thinking
50+// ones when reasoning is on and the family has some.
51+func (s *Settings) familySampling() *samplingValues {
52+ fam := s.Family
53+ base, source, origin := fam.General, "family "+fam.Name+": "+fam.Source, fam.Origin["general"]
54+ if s.Thinking && fam.Thinking.Temperature != nil {
55+ base, origin = fam.Thinking, fam.Origin["thinking"]
56+ }
57+ sv := &samplingValues{values: map[string]float64{}, reasons: map[string]string{}, origins: map[string]string{}}
58+ put := func(key string, v *float64) {
59+ if v != nil {
60+ sv.set(key, *v, source, origin)
61+ }
62+ }
63+ put("temperature", base.Temperature)
64+ put("top_p", base.TopP)
65+ put("min_p", base.MinP)
66+ if base.TopK != nil {
67+ sv.set("top_k", float64(*base.TopK), source, origin)
68+ }
69+ return sv
70+}
71+
72+// profileReason says why a Kronk profile's value is copied.
73+func (s *Settings) profileReason() string {
74+ return "Kronk profile " + s.Facts.Profile + " (model_config.yaml), read from the server: mm's values replace a profile's, so they are copied here"
75+}
76+
77+// maxTokens is the answer limit: room for an answer or a whole file, more
78+// with reasoning on, a Kronk profile's own value when it has one, under the
79+// name the family uses.
80+func (s *Settings) maxTokens() Setting {
81+ tokens, reason := "4096", "room for an answer or a whole file in one tool call"
82+ if s.Thinking {
83+ tokens, reason = "16384", "reasoning on: room for the thoughts plus a whole tool call"
84+ }
85+ origin := OriginRule
86+ if n, ok := s.Facts.ProfileSampling["max_tokens"]; ok {
87+ tokens, reason, origin = fmt.Sprint(int(n)), s.profileReason(), OriginServer
88+ }
89+ key := "max_tokens"
90+ if s.Family.MaxTokensKey != "" {
91+ key, reason = s.Family.MaxTokensKey, reason+" (family "+s.Family.Name+" names it "+s.Family.MaxTokensKey+")"
92+ }
93+ return Setting{Key: key, Value: tokens, Reason: reason, Origin: origin}
94+}
95+
96+func (s *Settings) decideKwargs() {
97+ sw := s.Facts.Thinking.Switch
98+ source := "read from the chat template"
99+ if sw == "" {
100+ sw, source = s.Family.Reasoning, "family "+s.Family.Name
101+ }
102+ switch sw {
103+ case "enable_thinking":
104+ why := "reasoning off: short, direct answers"
105+ if s.Family.ThinkingOff {
106+ why = "reasoning off: family " + s.Family.Name + " is kept off — see the note at the end of the file"
107+ }
108+ if s.Thinking {
109+ why = "reasoning on: code and multi-step work"
110+ }
111+ if d := s.Facts.Thinking.Default; d != "" {
112+ why += "; the template's default is " + d
113+ }
114+ s.Kwargs = append(s.Kwargs, Setting{Key: "enable_thinking", Value: boolYAML(s.Thinking), Reason: why + " (" + source + ")"})
115+ case "reasoning_effort":
116+ values := s.Facts.Thinking.EffortValues
117+ if len(values) == 0 {
118+ values = s.Family.EffortValues
119+ }
120+ effort := "low"
121+ if s.Thinking {
122+ effort = "medium"
123+ }
124+ if len(values) > 0 && !contains(values, effort) {
125+ effort = values[0]
126+ }
127+ s.Kwargs = append(s.Kwargs, Setting{Key: "reasoning_effort", Value: effort, Reason: fmt.Sprintf("one of %s (%s); a value the template does not know may make every request fail", strings.Join(values, ", "), source)})
128+ }
129+}
new file mode 100644
@@ -0,0 +1,129 @@
1+package agentinit
2+
3+import (
4+ "fmt"
5+ "strings"
6+)
7+
8+func (s *Settings) decideSampling() {
9+ sv := s.familySampling()
10+ f := s.Facts
11+ for k, v := range f.Sampling {
12+ sv.set(k, v, "the GGUF's own sampling, read from the server", OriginServer)
13+ }
14+ fam := s.Family
15+ if !s.Thinking && s.Usage.Precise && fam.Precise != nil {
16+ sv.set("temperature", *fam.Precise, fmt.Sprintf("precise temperature for a %s agent without reasoning (family %s)", s.Usage.Name, fam.Name), fam.Origin["precise"])
17+ }
18+ if s.Thinking && sv.values["temperature"] < 0.5 {
19+ sv.set("temperature", 0.6, "reasoning is on: a thinking model loops at a low temperature", OriginRule)
20+ }
21+ for k, v := range f.ProfileSampling {
22+ if k != "max_tokens" {
23+ sv.set(k, v, s.profileReason(), OriginServer)
24+ }
25+ }
26+ for _, k := range []string{"temperature", "top_p", "top_k", "min_p"} {
27+ if v, ok := sv.values[k]; ok {
28+ s.Sampling = append(s.Sampling, Setting{Key: k, Value: number(k, v), Reason: sv.reasons[k], Origin: sv.origins[k]})
29+ }
30+ }
31+ s.Sampling = append(s.Sampling, s.maxTokens())
32+ if s.anyTool() {
33+ s.Sampling = append(s.Sampling, Setting{Key: "parallel_tool_calls", Value: "false", Reason: "one tool call per reply: small models run a check before the change it checks has landed otherwise"})
34+ }
35+ s.decideKwargs()
36+}
37+
38+// samplingValues are the sampling values decided so far, each with why and
39+// where it comes from.
40+type samplingValues struct {
41+ values map[string]float64
42+ reasons, origins map[string]string
43+}
44+
45+func (sv *samplingValues) set(key string, v float64, reason, origin string) {
46+ sv.values[key], sv.reasons[key], sv.origins[key] = v, reason, origin
47+}
48+
49+// familySampling starts from the family's general values — its thinking
50+// ones when reasoning is on and the family has some.
51+func (s *Settings) familySampling() *samplingValues {
52+ fam := s.Family
53+ base, source, origin := fam.General, "family "+fam.Name+": "+fam.Source, fam.Origin["general"]
54+ if s.Thinking && fam.Thinking.Temperature != nil {
55+ base, origin = fam.Thinking, fam.Origin["thinking"]
56+ }
57+ sv := &samplingValues{values: map[string]float64{}, reasons: map[string]string{}, origins: map[string]string{}}
58+ put := func(key string, v *float64) {
59+ if v != nil {
60+ sv.set(key, *v, source, origin)
61+ }
62+ }
63+ put("temperature", base.Temperature)
64+ put("top_p", base.TopP)
65+ put("min_p", base.MinP)
66+ if base.TopK != nil {
67+ sv.set("top_k", float64(*base.TopK), source, origin)
68+ }
69+ return sv
70+}
71+
72+// profileReason says why a Kronk profile's value is copied.
73+func (s *Settings) profileReason() string {
74+ return "Kronk profile " + s.Facts.Profile + " (model_config.yaml), read from the server: mm's values replace a profile's, so they are copied here"
75+}
76+
77+// maxTokens is the answer limit: room for an answer or a whole file, more
78+// with reasoning on, a Kronk profile's own value when it has one, under the
79+// name the family uses.
80+func (s *Settings) maxTokens() Setting {
81+ tokens, reason := "4096", "room for an answer or a whole file in one tool call"
82+ if s.Thinking {
83+ tokens, reason = "16384", "reasoning on: room for the thoughts plus a whole tool call"
84+ }
85+ origin := OriginRule
86+ if n, ok := s.Facts.ProfileSampling["max_tokens"]; ok {
87+ tokens, reason, origin = fmt.Sprint(int(n)), s.profileReason(), OriginServer
88+ }
89+ key := "max_tokens"
90+ if s.Family.MaxTokensKey != "" {
91+ key, reason = s.Family.MaxTokensKey, reason+" (family "+s.Family.Name+" names it "+s.Family.MaxTokensKey+")"
92+ }
93+ return Setting{Key: key, Value: tokens, Reason: reason, Origin: origin}
94+}
95+
96+func (s *Settings) decideKwargs() {
97+ sw := s.Facts.Thinking.Switch
98+ source := "read from the chat template"
99+ if sw == "" {
100+ sw, source = s.Family.Reasoning, "family "+s.Family.Name
101+ }
102+ switch sw {
103+ case "enable_thinking":
104+ why := "reasoning off: short, direct answers"
105+ if s.Family.ThinkingOff {
106+ why = "reasoning off: family " + s.Family.Name + " is kept off — see the note at the end of the file"
107+ }
108+ if s.Thinking {
109+ why = "reasoning on: code and multi-step work"
110+ }
111+ if d := s.Facts.Thinking.Default; d != "" {
112+ why += "; the template's default is " + d
113+ }
114+ s.Kwargs = append(s.Kwargs, Setting{Key: "enable_thinking", Value: boolYAML(s.Thinking), Reason: why + " (" + source + ")"})
115+ case "reasoning_effort":
116+ values := s.Facts.Thinking.EffortValues
117+ if len(values) == 0 {
118+ values = s.Family.EffortValues
119+ }
120+ effort := "low"
121+ if s.Thinking {
122+ effort = "medium"
123+ }
124+ if len(values) > 0 && !contains(values, effort) {
125+ effort = values[0]
126+ }
127+ s.Kwargs = append(s.Kwargs, Setting{Key: "reasoning_effort", Value: effort, Reason: fmt.Sprintf("one of %s (%s); a value the template does not know may make every request fail", strings.Join(values, ", "), source)})
128+ }
129+}
modified internal/agentinit/wizard.go +36 -410
@@ -4,18 +4,9 @@ import (
44 "bufio"
55 "context"
66 "errors"
7- "flag"
87 "fmt"
98 "io"
10- "os"
11- "os/exec"
12- "path/filepath"
139 "strings"
14- "time"
15-
16- "mm/internal/config"
17- "mm/internal/elicit"
18- "mm/internal/engine"
1910 )
2011
2112 // providers are the servers mm speaks to, in the order they are offered.
@@ -60,120 +51,54 @@ func Main(args []string, stdin io.Reader, stdout io.Writer, opts ...Options) int
6051 if !ok {
6152 return code
6253 }
63- if a.Yes && a.Output != "" && a.Output != "-" && exists(a.Output) {
64- fmt.Fprintln(stdout, "⚠️ "+alreadyExists(a.Output).Error())
65- return 1
66- }
6754 ctx := context.Background()
68- flow, err := a.Flow(ctx)
55+ flow, err := prepareFlow(ctx, a)
56+ if err == nil {
57+ err = answerFlow(ctx, a, o, flow, &lineWizard{in: bufio.NewReader(stdin), out: stdout})
58+ }
6959 if err != nil {
70- fmt.Fprintln(stdout, "⚠️ "+err.Error())
60+ reportFailure(stdout, err)
7161 return 1
7262 }
73-
74- switch {
75- case a.Yes:
76- if err := flow.takeDefaults(); err != nil {
77- fmt.Fprintln(stdout, "⚠️ "+err.Error())
78- return 1
79- }
80- case o.Window != nil && !a.Line && o.Terminal != nil && o.Terminal():
81- done, err := o.Window(ctx, flow)
82- if err != nil {
83- fmt.Fprintln(stdout, "⚠️ "+err.Error())
84- return 1
85- }
86- if !done {
87- fmt.Fprintln(stdout, "nothing written")
88- return 1
89- }
90- default:
91- w := &lineWizard{in: bufio.NewReader(stdin), out: stdout}
92- if err := w.run(flow); err != nil {
93- fmt.Fprintln(stdout, "⚠️ "+err.Error())
94- return 1
95- }
96- }
9763 return finish(flow, stdout, a.Check)
9864 }
9965
100-// Args are mm init's flags, read: the answers they give, the file, and the
101-// line mode's own switches (Check, Yes, Line — not offered by mm
102-// acp-create, which has no use for them).
103-type Args struct {
104- Choices Choices
105- Output string
106- Check, Yes, Line bool
107- presets Presets
108-}
66+// errNothingWritten: the window was closed before the end.
67+var errNothingWritten = errors.New("nothing written")
10968
110-// ParseArgs reads mm init's flags (name is the command shown by -h). With
111-// lineSwitches false, --check, --yes and --line are not offered. ok is
112-// false when the command must stop: -h (code 0), a bad flag (2) or presets
113-// that do not load (1); the reason is already written to out.
114-func ParseArgs(name string, args []string, out io.Writer, lineSwitches bool) (a Args, code int, ok bool) {
115- fs := flag.NewFlagSet(name, flag.ContinueOnError)
116- fs.SetOutput(out)
117- c := &a.Choices
118- var yolo, project, sessions, skills, autostart, launch string
119- fs.StringVar(&c.Provider, "provider", "", "model server: "+strings.Join(providers, ", "))
120- fs.StringVar(&c.BaseURL, "base-url", "", "the server's OpenAI-compatible address (default: the provider's); for openai, the endpoint question")
121- fs.StringVar(&c.APIKeyEnv, "api-key-env", "", "openai: the environment variable that holds the API key (default OPENAI_API_KEY)")
122- fs.StringVar(&c.Model, "model", "", "the model, as the server names it")
123- fs.StringVar(&c.Family, "family", "", "the model family (default: detected from the name)")
124- fs.StringVar(&c.Usage, "usage", "", "what the agent is for (developer, translator, docs, json…)")
125- fs.StringVar(&c.Machine, "machine", "", "small, medium or large")
126- fs.StringVar(&c.Name, "name", "", "the agent's name")
127- fs.StringVar(&yolo, "yolo", "", "yes: tools run without asking; no: every change waits for your answer (default: the usage's)")
128- fs.StringVar(&project, "project", "", "yes: create .mm/ and write .mm/agent.yaml, paths from the project root; no: one agent.yaml (default: no)")
129- fs.StringVar(&sessions, "sessions", "", "yes: write a sessions section that saves every conversation; no: none (default: no)")
130- fs.StringVar(&skills, "skills", "", "yes: write skillsDir and create the folder (skills/, or .mm/skills/ with --project yes); no: skillsDir: no-skills (default: no)")
131- fs.StringVar(&autostart, "autostart", "", "llamacpp or razorbill on this machine — yes: mm starts llama-server (rzb) when it is not running and stops it with the last session; no: you start it (default: yes)")
132- fs.StringVar(&launch, "launch-settings", "", "llamacpp with --autostart yes — yes: write llama-server's launch settings (the Llama app's values); no: llama-server's defaults (default: no)")
133- fs.StringVar(&a.Output, "o", "", "the file to write (default agent.yaml, .mm/agent.yaml with --project yes; - for stdout, which creates nothing); an existing file is replaced only if you agree, never with --yes")
134- fs.StringVar(&a.Output, "output", "", "same as -o")
135- if lineSwitches {
136- fs.BoolVar(&a.Check, "check", false, "after writing, ask the model one question to prove it answers")
137- fs.BoolVar(&a.Yes, "yes", false, "ask nothing: every unanswered question takes its default")
138- fs.BoolVar(&a.Line, "line", false, "ask line by line even in a terminal (no window)")
139- }
140- if err := fs.Parse(args); err != nil {
141- if errors.Is(err, flag.ErrHelp) {
142- return a, 0, false
143- }
144- return a, 2, false
69+// reportFailure says why nothing was written: "nothing written" as it is,
70+// anything else as a warning.
71+func reportFailure(out io.Writer, err error) {
72+ if errors.Is(err, errNothingWritten) {
73+ fmt.Fprintln(out, err.Error())
74+ return
14575 }
146- presets, err := LoadPresets()
147- if err != nil {
148- fmt.Fprintln(out, "⚠️ "+err.Error())
149- return a, 1, false
150- }
151- a.presets = presets
152- if yolo != "" {
153- on := yolo == "yes" || yolo == "true"
154- c.Yolo = &on
155- }
156- for flagName, value := range map[string]struct {
157- text string
158- target **bool
159- }{"project": {project, &c.Project}, "sessions": {sessions, &c.Sessions}, "skills": {skills, &c.Skills}, "autostart": {autostart, &c.AutoStart}, "launch-settings": {launch, &c.Launch}} {
160- if value.text == "" {
161- continue
162- }
163- if err := setYesNo("--"+flagName, value.text, value.target); err != nil {
164- fmt.Fprintln(out, "⚠️ "+err.Error())
165- return a, 2, false
166- }
76+ fmt.Fprintln(out, "⚠️ "+err.Error())
77+}
78+
79+// prepareFlow refuses --yes onto an existing file (no question would ask
80+// whether to overwrite it), then builds the flow from the arguments.
81+func prepareFlow(ctx context.Context, a Args) (*Flow, error) {
82+ if a.Yes && a.Output != "" && a.Output != "-" && exists(a.Output) {
83+ return nil, alreadyExists(a.Output)
16784 }
168- return a, 0, true
85+ return a.Flow(ctx)
16986 }
17087
171-// Flow starts a flow from the flags: what they gave is answered, and
172-// checked as if typed. Each call is a new flow (mm acp-create: one per
173-// session).
174-func (a Args) Flow(ctx context.Context) (*Flow, error) {
175- flow := NewFlow(ctx, a.presets, a.Choices, a.Output)
176- return flow, flow.validateGiven()
88+// answerFlow answers the questions: the defaults with --yes, the window on
89+// a terminal, else the line mode (line).
90+func answerFlow(ctx context.Context, a Args, o Options, flow *Flow, line *lineWizard) error {
91+ switch {
92+ case a.Yes:
93+ return flow.takeDefaults()
94+ case o.Window != nil && !a.Line && o.Terminal != nil && o.Terminal():
95+ done, err := o.Window(ctx, flow)
96+ if err == nil && !done {
97+ err = errNothingWritten
98+ }
99+ return err
100+ }
101+ return line.run(flow)
177102 }
178103
179104 // finish writes the file the flow describes, loads it, and checks it.
@@ -192,75 +117,6 @@ func finish(flow *Flow, stdout io.Writer, check bool) int {
192117 return 0
193118 }
194119
195-// WriteFile writes the file the answered flow describes — or prints it, for
196-// "-" — creates the skills folder, and proves mm loads it, reporting each
197-// step on out. It returns the file as the flow names it (relative to the
198-// flow's dir, see Flow.SetDir) and whether everything went well.
199-func WriteFile(flow *Flow, out io.Writer) (string, bool) {
200- choices, facts, output := flow.Result()
201- if choices.Model == "" {
202- fmt.Fprintln(out, "⚠️ no model: nothing written")
203- return output, false
204- }
205- text := Render(Decide(flow.presets, choices, facts))
206- if output == "-" {
207- fmt.Fprint(out, text)
208- return output, true
209- }
210- path := flow.Path(output)
211- // The Project layout's file lives in .mm/, which may not exist yet.
212- if on(choices.Project) {
213- if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
214- fmt.Fprintln(out, "⚠️ "+err.Error())
215- return output, false
216- }
217- }
218- write := writeNew
219- if flow.Overwrite() {
220- write = replaceFile
221- }
222- if err := write(path, text); err != nil {
223- fmt.Fprintln(out, "⚠️ "+err.Error())
224- return output, false
225- }
226- fmt.Fprintf(out, "✅ wrote %s\n", output)
227- if err := createSkillsFolder(choices, path, out); err != nil {
228- fmt.Fprintln(out, "⚠️ "+err.Error())
229- return output, false
230- }
231- if _, err := config.Load(path); err != nil {
232- fmt.Fprintf(out, "⚠️ mm does not load it: %v\n", err)
233- return output, false
234- }
235- fmt.Fprintln(out, "✅ mm loads it")
236- return output, true
237-}
238-
239-// createSkillsFolder makes the folder skillsDir names, when skills are on
240-// (ticket 205), once the file is written: in the file's base directory —
241-// the project root for .mm/agent.yaml — where mm started there reads it.
242-// Never called for "-": a preview creates nothing.
243-func createSkillsFolder(c Choices, output string, stdout io.Writer) error {
244- if !on(c.Skills) {
245- return nil
246- }
247- dir := filepath.Join(config.BaseDir(output), c.SkillsDir())
248- if err := os.MkdirAll(dir, 0o755); err != nil {
249- return err
250- }
251- fmt.Fprintf(stdout, "✅ skills folder %s\n", c.SkillsDir())
252- return nil
253-}
254-
255-// nextLine says how to start the agent: a plain `mm` for .mm/agent.yaml,
256-// which mm finds on its own (ticket 204), -config otherwise.
257-func nextLine(output string) string {
258- if output == filepath.Join(config.ProjectDir, config.DefaultPath) {
259- return "Next: mm (or mm tui), started from this directory"
260- }
261- return fmt.Sprintf("Next: mm -config %s (or mm -tui %s)", output, output)
262-}
263-
264120 // validateGiven refuses a flag value no question would accept.
265121 func (f *Flow) validateGiven() error {
266122 for _, key := range stepKeys {
@@ -298,233 +154,3 @@ func (f *Flow) takeDefaults() error {
298154 }
299155 }
300156 }
301-
302-// lineWizard asks the questions one per line (internal/elicit's format).
303-type lineWizard struct {
304- in *bufio.Reader
305- out io.Writer
306- ended bool // the input ended: nobody is there to answer
307-}
308-
309-func (w *lineWizard) run(f *Flow) error {
310- for {
311- pending := f.Pending()
312- if len(pending) == 0 {
313- return nil
314- }
315- st := pending[0]
316- // Without a model list, the model question itself says why
317- // (Flow.typeModelPrompt): the window shows the same words.
318- answer := w.ask(st)
319- // Taking "no" for an answer would ask for another file that nobody
320- // can give: stop here, the file untouched.
321- if st.Key == "overwrite" && w.ended {
322- return alreadyExists(f.output)
323- }
324- if answer == "" {
325- return fmt.Errorf("%s: no answer", strings.ToLower(st.Title))
326- }
327- if err := f.Set(st.Key, answer); err != nil {
328- fmt.Fprintln(w.out, "⚠️ "+err.Error())
329- }
330- }
331-}
332-
333-// ask asks one step until the line answers it; the end of the input or
334-// /skip take the default.
335-func (w *lineWizard) ask(st Step) string {
336- q := elicit.Question{Prompt: st.Prompt, Kind: st.Kind, Default: st.Default}
337- for _, o := range st.Options {
338- q.Options = append(q.Options, o.Value)
339- }
340- if st.Key == "usage" || st.Key == "machine" {
341- for _, o := range st.Options {
342- fmt.Fprintf(w.out, " %-12s %s\n", o.Label, o.Detail)
343- }
344- }
345- // A model rarely needs a word; when one does (a Kronk profile), the
346- // note goes above the list, with the identifier it explains.
347- if st.Key == "model" {
348- for _, o := range st.Options {
349- if o.Detail != "" {
350- fmt.Fprintf(w.out, " %s — %s\n", o.Label, o.Detail)
351- }
352- }
353- }
354- for {
355- lines := elicit.Lines(q)
356- // Here /skip and an empty line take the default; nothing is declined.
357- lines[len(lines)-1] = strings.Replace(lines[len(lines)-1], "/skip to decline", "Enter = the default", 1)
358- for _, line := range lines {
359- fmt.Fprintln(w.out, line)
360- }
361- fmt.Fprint(w.out, "> ")
362- line, err := w.in.ReadString('\n')
363- w.ended = err != nil
364- if elicit.IsSkip(line) || (err != nil && strings.TrimSpace(line) == "") {
365- return q.Default
366- }
367- if a, ok := elicit.ParseLine(q, line); ok && len(a.Values) > 0 {
368- return a.Values[0]
369- }
370- if err != nil {
371- return q.Default
372- }
373- }
374-}
375-
376-// resolveBase is the server's address the wizard lists models from: the
377-// flag's, else the one the environment imposes (AGENT_BASE_URL…), else the
378-// first that answers of the provider's local addresses, then its fallback
379-// (chooseBase).
380-//
381-// Ticket 214: it used to take the engine's own resolution, whose probe gives
382-// the default address 2 s on /models and switches to the container fallback
383-// (host.docker.internal) without a word. mm on a Mac with Docker Desktop —
384-// where that name resolves on the host too — then listed Ollama's models
385-// from the container address. The written file is not concerned: it carries
386-// no baseUrl for the default address.
387-func resolveBase(ctx context.Context, c Choices) string {
388- if c.BaseURL != "" {
389- return c.BaseURL
390- }
391- if env := engine.EnvBaseURL(c.Provider); env != "" {
392- return env
393- }
394- if _, fallback, ok := engine.DefaultURLs(c.Provider); ok {
395- return chooseBase(engine.LocalURLs(c.Provider), fallback, func(url string) bool {
396- _, err := Models(ctx, c.Provider, url)
397- return err == nil
398- })
399- }
400- return engineBase(c)
401-}
402-
403-// chooseBase picks the address to list models from: the first that lists
404-// them among the local ones — locals is the provider's default, then its
405-// alternates (engine.LocalURLs), each with its localAddresses — else the
406-// fallback when it does, else the default, whose error the model question
407-// then shows. A provider with one address and no fallback (openai) is not
408-// probed at all: there is nothing to choose, and openai's default is a
409-// remote service nobody asked mm to call yet.
410-//
411-// chooseBase([]string{"http://127.0.0.1:9931/v1", "http://127.0.0.1:8080/v1"}, "http://host.docker.internal:9931/v1", lists)
412-func chooseBase(locals []string, fallback string, lists func(string) bool) string {
413- base := locals[0]
414- if fallback == "" && len(locals) == 1 {
415- return base
416- }
417- for _, local := range locals {
418- for _, url := range localAddresses(local) {
419- if lists(url) {
420- return url
421- }
422- }
423- }
424- if fallback != "" && lists(fallback) {
425- return fallback
426- }
427- return base
428-}
429-
430-// localAddresses is the default address, then — when it names localhost —
431-// the same with 127.0.0.1: a server listening on IPv4 only does not answer
432-// a localhost that resolves to ::1 first.
433-//
434-// localAddresses("http://localhost:11434/v1") // [http://localhost:11434/v1 http://127.0.0.1:11434/v1]
435-func localAddresses(base string) []string {
436- out := []string{base}
437- if strings.Contains(base, "://localhost:") || strings.HasSuffix(base, "://localhost") {
438- out = append(out, strings.Replace(base, "://localhost", "://127.0.0.1", 1))
439- }
440- return out
441-}
442-
443-// engineBase is the engine's own resolution, for a provider the wizard has
444-// no addresses for.
445-func engineBase(c Choices) string {
446- p, err := engine.Lookup(c.Provider)
447- if err != nil {
448- return ""
449- }
450- b, err := p.Resolve(config.Config{Provider: c.Provider, Model: "probe"})
451- if err != nil {
452- return ""
453- }
454- return b.BaseURL
455-}
456-
457-func exists(path string) bool {
458- _, err := os.Stat(path)
459- return err == nil
460-}
461-
462-func alreadyExists(path string) error {
463- return fmt.Errorf("%s already exists — nothing was written; choose another name with -o", path)
464-}
465-
466-// replaceFile replaces a file the user agreed to overwrite. The new text is
467-// proved first, on a file beside it: an agent.yaml mm would refuse must not
468-// cost the user the one that worked.
469-func replaceFile(path, text string) error {
470- info, err := os.Stat(path)
471- if err != nil {
472- return err
473- }
474- tmp, err := os.CreateTemp(filepath.Dir(path), ".mm-init-*.yaml")
475- if err != nil {
476- return err
477- }
478- defer os.Remove(tmp.Name())
479- _, err = tmp.WriteString(text)
480- if closeErr := tmp.Close(); err == nil {
481- err = closeErr
482- }
483- if err != nil {
484- return err
485- }
486- if err := os.Chmod(tmp.Name(), info.Mode().Perm()); err != nil {
487- return err
488- }
489- if _, err := config.Load(tmp.Name()); err != nil {
490- return fmt.Errorf("mm would not load the new file: %v — %s is unchanged", err, path)
491- }
492- return os.Rename(tmp.Name(), path)
493-}
494-
495-// writeNew writes a file that must not exist yet: an existing agent.yaml is
496-// someone's work, replaced only through replaceFile.
497-func writeNew(path, text string) error {
498- f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
499- if errors.Is(err, os.ErrExist) {
500- return alreadyExists(path)
501- }
502- if err != nil {
503- return err
504- }
505- if _, err := f.WriteString(text); err != nil {
506- f.Close()
507- return err
508- }
509- return f.Close()
510-}
511-
512-// checkFile runs this same mm on the new file with one question.
513-func checkFile(stdout io.Writer, path string) int {
514- self, err := os.Executable()
515- if err != nil {
516- fmt.Fprintln(stdout, "⚠️ "+err.Error())
517- return 1
518- }
519- fmt.Fprintln(stdout, "… asking the model one question (the first answer loads the model)")
520- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
521- defer cancel()
522- out, err := exec.CommandContext(ctx, self, "-config", path, "-p", "Say hello in one line.").CombinedOutput()
523- fmt.Fprintln(stdout, strings.TrimSpace(string(out)))
524- if err != nil {
525- fmt.Fprintf(stdout, "⚠️ the check failed: %v\n", err)
526- return 1
527- }
528- fmt.Fprintln(stdout, "✅ the model answers")
529- return 0
530-}
@@ -4,18 +4,9 @@ import (
4 "bufio"4 "bufio"
5 "context"5 "context"
6 "errors"6 "errors"
7- "flag"
8 "fmt"7 "fmt"
9 "io"8 "io"
10- "os"
11- "os/exec"
12- "path/filepath"
13 "strings"9 "strings"
14- "time"
15-
16- "mm/internal/config"
17- "mm/internal/elicit"
18- "mm/internal/engine"
19 )10 )
20 11
21 // providers are the servers mm speaks to, in the order they are offered.12 // providers are the servers mm speaks to, in the order they are offered.
@@ -60,120 +51,54 @@ func Main(args []string, stdin io.Reader, stdout io.Writer, opts ...Options) int
60 if !ok {51 if !ok {
61 return code52 return code
62 }53 }
63- if a.Yes && a.Output != "" && a.Output != "-" && exists(a.Output) {
64- fmt.Fprintln(stdout, "⚠️ "+alreadyExists(a.Output).Error())
65- return 1
66- }
67 ctx := context.Background()54 ctx := context.Background()
68- flow, err := a.Flow(ctx)55+ flow, err := prepareFlow(ctx, a)
56+ if err == nil {
57+ err = answerFlow(ctx, a, o, flow, &lineWizard{in: bufio.NewReader(stdin), out: stdout})
58+ }
69 if err != nil {59 if err != nil {
70- fmt.Fprintln(stdout, "⚠️ "+err.Error())60+ reportFailure(stdout, err)
71 return 161 return 1
72 }62 }
73-
74- switch {
75- case a.Yes:
76- if err := flow.takeDefaults(); err != nil {
77- fmt.Fprintln(stdout, "⚠️ "+err.Error())
78- return 1
79- }
80- case o.Window != nil && !a.Line && o.Terminal != nil && o.Terminal():
81- done, err := o.Window(ctx, flow)
82- if err != nil {
83- fmt.Fprintln(stdout, "⚠️ "+err.Error())
84- return 1
85- }
86- if !done {
87- fmt.Fprintln(stdout, "nothing written")
88- return 1
89- }
90- default:
91- w := &lineWizard{in: bufio.NewReader(stdin), out: stdout}
92- if err := w.run(flow); err != nil {
93- fmt.Fprintln(stdout, "⚠️ "+err.Error())
94- return 1
95- }
96- }
97 return finish(flow, stdout, a.Check)63 return finish(flow, stdout, a.Check)
98 }64 }
99 65
100-// Args are mm init's flags, read: the answers they give, the file, and the66+// errNothingWritten: the window was closed before the end.
101-// line mode's own switches (Check, Yes, Line — not offered by mm67+var errNothingWritten = errors.New("nothing written")
102-// acp-create, which has no use for them).
103-type Args struct {
104- Choices Choices
105- Output string
106- Check, Yes, Line bool
107- presets Presets
108-}
109 68
110-// ParseArgs reads mm init's flags (name is the command shown by -h). With69+// reportFailure says why nothing was written: "nothing written" as it is,
111-// lineSwitches false, --check, --yes and --line are not offered. ok is70+// anything else as a warning.
112-// false when the command must stop: -h (code 0), a bad flag (2) or presets71+func reportFailure(out io.Writer, err error) {
113-// that do not load (1); the reason is already written to out.72+ if errors.Is(err, errNothingWritten) {
114-func ParseArgs(name string, args []string, out io.Writer, lineSwitches bool) (a Args, code int, ok bool) {73+ fmt.Fprintln(out, err.Error())
115- fs := flag.NewFlagSet(name, flag.ContinueOnError)74+ return
116- fs.SetOutput(out)
117- c := &a.Choices
118- var yolo, project, sessions, skills, autostart, launch string
119- fs.StringVar(&c.Provider, "provider", "", "model server: "+strings.Join(providers, ", "))
120- fs.StringVar(&c.BaseURL, "base-url", "", "the server's OpenAI-compatible address (default: the provider's); for openai, the endpoint question")
121- fs.StringVar(&c.APIKeyEnv, "api-key-env", "", "openai: the environment variable that holds the API key (default OPENAI_API_KEY)")
122- fs.StringVar(&c.Model, "model", "", "the model, as the server names it")
123- fs.StringVar(&c.Family, "family", "", "the model family (default: detected from the name)")
124- fs.StringVar(&c.Usage, "usage", "", "what the agent is for (developer, translator, docs, json…)")
125- fs.StringVar(&c.Machine, "machine", "", "small, medium or large")
126- fs.StringVar(&c.Name, "name", "", "the agent's name")
127- fs.StringVar(&yolo, "yolo", "", "yes: tools run without asking; no: every change waits for your answer (default: the usage's)")
128- fs.StringVar(&project, "project", "", "yes: create .mm/ and write .mm/agent.yaml, paths from the project root; no: one agent.yaml (default: no)")
129- fs.StringVar(&sessions, "sessions", "", "yes: write a sessions section that saves every conversation; no: none (default: no)")
130- fs.StringVar(&skills, "skills", "", "yes: write skillsDir and create the folder (skills/, or .mm/skills/ with --project yes); no: skillsDir: no-skills (default: no)")
131- fs.StringVar(&autostart, "autostart", "", "llamacpp or razorbill on this machine — yes: mm starts llama-server (rzb) when it is not running and stops it with the last session; no: you start it (default: yes)")
132- fs.StringVar(&launch, "launch-settings", "", "llamacpp with --autostart yes — yes: write llama-server's launch settings (the Llama app's values); no: llama-server's defaults (default: no)")
133- fs.StringVar(&a.Output, "o", "", "the file to write (default agent.yaml, .mm/agent.yaml with --project yes; - for stdout, which creates nothing); an existing file is replaced only if you agree, never with --yes")
134- fs.StringVar(&a.Output, "output", "", "same as -o")
135- if lineSwitches {
136- fs.BoolVar(&a.Check, "check", false, "after writing, ask the model one question to prove it answers")
137- fs.BoolVar(&a.Yes, "yes", false, "ask nothing: every unanswered question takes its default")
138- fs.BoolVar(&a.Line, "line", false, "ask line by line even in a terminal (no window)")
139- }
140- if err := fs.Parse(args); err != nil {
141- if errors.Is(err, flag.ErrHelp) {
142- return a, 0, false
143- }
144- return a, 2, false
145 }75 }
146- presets, err := LoadPresets()76+ fmt.Fprintln(out, "⚠️ "+err.Error())
147- if err != nil {77+}
148- fmt.Fprintln(out, "⚠️ "+err.Error())78+
149- return a, 1, false79+// prepareFlow refuses --yes onto an existing file (no question would ask
150- }80+// whether to overwrite it), then builds the flow from the arguments.
151- a.presets = presets81+func prepareFlow(ctx context.Context, a Args) (*Flow, error) {
152- if yolo != "" {82+ if a.Yes && a.Output != "" && a.Output != "-" && exists(a.Output) {
153- on := yolo == "yes" || yolo == "true"83+ return nil, alreadyExists(a.Output)
154- c.Yolo = &on
155- }
156- for flagName, value := range map[string]struct {
157- text string
158- target **bool
159- }{"project": {project, &c.Project}, "sessions": {sessions, &c.Sessions}, "skills": {skills, &c.Skills}, "autostart": {autostart, &c.AutoStart}, "launch-settings": {launch, &c.Launch}} {
160- if value.text == "" {
161- continue
162- }
163- if err := setYesNo("--"+flagName, value.text, value.target); err != nil {
164- fmt.Fprintln(out, "⚠️ "+err.Error())
165- return a, 2, false
166- }
167 }84 }
168- return a, 0, true85+ return a.Flow(ctx)
169 }86 }
170 87
171-// Flow starts a flow from the flags: what they gave is answered, and88+// answerFlow answers the questions: the defaults with --yes, the window on
172-// checked as if typed. Each call is a new flow (mm acp-create: one per89+// a terminal, else the line mode (line).
173-// session).90+func answerFlow(ctx context.Context, a Args, o Options, flow *Flow, line *lineWizard) error {
174-func (a Args) Flow(ctx context.Context) (*Flow, error) {91+ switch {
175- flow := NewFlow(ctx, a.presets, a.Choices, a.Output)92+ case a.Yes:
176- return flow, flow.validateGiven()93+ return flow.takeDefaults()
94+ case o.Window != nil && !a.Line && o.Terminal != nil && o.Terminal():
95+ done, err := o.Window(ctx, flow)
96+ if err == nil && !done {
97+ err = errNothingWritten
98+ }
99+ return err
100+ }
101+ return line.run(flow)
177 }102 }
178 103
179 // finish writes the file the flow describes, loads it, and checks it.104 // finish writes the file the flow describes, loads it, and checks it.
@@ -192,75 +117,6 @@ func finish(flow *Flow, stdout io.Writer, check bool) int {
192 return 0117 return 0
193 }118 }
194 119
195-// WriteFile writes the file the answered flow describes — or prints it, for
196-// "-" — creates the skills folder, and proves mm loads it, reporting each
197-// step on out. It returns the file as the flow names it (relative to the
198-// flow's dir, see Flow.SetDir) and whether everything went well.
199-func WriteFile(flow *Flow, out io.Writer) (string, bool) {
200- choices, facts, output := flow.Result()
201- if choices.Model == "" {
202- fmt.Fprintln(out, "⚠️ no model: nothing written")
203- return output, false
204- }
205- text := Render(Decide(flow.presets, choices, facts))
206- if output == "-" {
207- fmt.Fprint(out, text)
208- return output, true
209- }
210- path := flow.Path(output)
211- // The Project layout's file lives in .mm/, which may not exist yet.
212- if on(choices.Project) {
213- if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
214- fmt.Fprintln(out, "⚠️ "+err.Error())
215- return output, false
216- }
217- }
218- write := writeNew
219- if flow.Overwrite() {
220- write = replaceFile
221- }
222- if err := write(path, text); err != nil {
223- fmt.Fprintln(out, "⚠️ "+err.Error())
224- return output, false
225- }
226- fmt.Fprintf(out, "✅ wrote %s\n", output)
227- if err := createSkillsFolder(choices, path, out); err != nil {
228- fmt.Fprintln(out, "⚠️ "+err.Error())
229- return output, false
230- }
231- if _, err := config.Load(path); err != nil {
232- fmt.Fprintf(out, "⚠️ mm does not load it: %v\n", err)
233- return output, false
234- }
235- fmt.Fprintln(out, "✅ mm loads it")
236- return output, true
237-}
238-
239-// createSkillsFolder makes the folder skillsDir names, when skills are on
240-// (ticket 205), once the file is written: in the file's base directory —
241-// the project root for .mm/agent.yaml — where mm started there reads it.
242-// Never called for "-": a preview creates nothing.
243-func createSkillsFolder(c Choices, output string, stdout io.Writer) error {
244- if !on(c.Skills) {
245- return nil
246- }
247- dir := filepath.Join(config.BaseDir(output), c.SkillsDir())
248- if err := os.MkdirAll(dir, 0o755); err != nil {
249- return err
250- }
251- fmt.Fprintf(stdout, "✅ skills folder %s\n", c.SkillsDir())
252- return nil
253-}
254-
255-// nextLine says how to start the agent: a plain `mm` for .mm/agent.yaml,
256-// which mm finds on its own (ticket 204), -config otherwise.
257-func nextLine(output string) string {
258- if output == filepath.Join(config.ProjectDir, config.DefaultPath) {
259- return "Next: mm (or mm tui), started from this directory"
260- }
261- return fmt.Sprintf("Next: mm -config %s (or mm -tui %s)", output, output)
262-}
263-
264 // validateGiven refuses a flag value no question would accept.120 // validateGiven refuses a flag value no question would accept.
265 func (f *Flow) validateGiven() error {121 func (f *Flow) validateGiven() error {
266 for _, key := range stepKeys {122 for _, key := range stepKeys {
@@ -298,233 +154,3 @@ func (f *Flow) takeDefaults() error {
298 }154 }
299 }155 }
300 }156 }
301-
302-// lineWizard asks the questions one per line (internal/elicit's format).
303-type lineWizard struct {
304- in *bufio.Reader
305- out io.Writer
306- ended bool // the input ended: nobody is there to answer
307-}
308-
309-func (w *lineWizard) run(f *Flow) error {
310- for {
311- pending := f.Pending()
312- if len(pending) == 0 {
313- return nil
314- }
315- st := pending[0]
316- // Without a model list, the model question itself says why
317- // (Flow.typeModelPrompt): the window shows the same words.
318- answer := w.ask(st)
319- // Taking "no" for an answer would ask for another file that nobody
320- // can give: stop here, the file untouched.
321- if st.Key == "overwrite" && w.ended {
322- return alreadyExists(f.output)
323- }
324- if answer == "" {
325- return fmt.Errorf("%s: no answer", strings.ToLower(st.Title))
326- }
327- if err := f.Set(st.Key, answer); err != nil {
328- fmt.Fprintln(w.out, "⚠️ "+err.Error())
329- }
330- }
331-}
332-
333-// ask asks one step until the line answers it; the end of the input or
334-// /skip take the default.
335-func (w *lineWizard) ask(st Step) string {
336- q := elicit.Question{Prompt: st.Prompt, Kind: st.Kind, Default: st.Default}
337- for _, o := range st.Options {
338- q.Options = append(q.Options, o.Value)
339- }
340- if st.Key == "usage" || st.Key == "machine" {
341- for _, o := range st.Options {
342- fmt.Fprintf(w.out, " %-12s %s\n", o.Label, o.Detail)
343- }
344- }
345- // A model rarely needs a word; when one does (a Kronk profile), the
346- // note goes above the list, with the identifier it explains.
347- if st.Key == "model" {
348- for _, o := range st.Options {
349- if o.Detail != "" {
350- fmt.Fprintf(w.out, " %s — %s\n", o.Label, o.Detail)
351- }
352- }
353- }
354- for {
355- lines := elicit.Lines(q)
356- // Here /skip and an empty line take the default; nothing is declined.
357- lines[len(lines)-1] = strings.Replace(lines[len(lines)-1], "/skip to decline", "Enter = the default", 1)
358- for _, line := range lines {
359- fmt.Fprintln(w.out, line)
360- }
361- fmt.Fprint(w.out, "> ")
362- line, err := w.in.ReadString('\n')
363- w.ended = err != nil
364- if elicit.IsSkip(line) || (err != nil && strings.TrimSpace(line) == "") {
365- return q.Default
366- }
367- if a, ok := elicit.ParseLine(q, line); ok && len(a.Values) > 0 {
368- return a.Values[0]
369- }
370- if err != nil {
371- return q.Default
372- }
373- }
374-}
375-
376-// resolveBase is the server's address the wizard lists models from: the
377-// flag's, else the one the environment imposes (AGENT_BASE_URL…), else the
378-// first that answers of the provider's local addresses, then its fallback
379-// (chooseBase).
380-//
381-// Ticket 214: it used to take the engine's own resolution, whose probe gives
382-// the default address 2 s on /models and switches to the container fallback
383-// (host.docker.internal) without a word. mm on a Mac with Docker Desktop —
384-// where that name resolves on the host too — then listed Ollama's models
385-// from the container address. The written file is not concerned: it carries
386-// no baseUrl for the default address.
387-func resolveBase(ctx context.Context, c Choices) string {
388- if c.BaseURL != "" {
389- return c.BaseURL
390- }
391- if env := engine.EnvBaseURL(c.Provider); env != "" {
392- return env
393- }
394- if _, fallback, ok := engine.DefaultURLs(c.Provider); ok {
395- return chooseBase(engine.LocalURLs(c.Provider), fallback, func(url string) bool {
396- _, err := Models(ctx, c.Provider, url)
397- return err == nil
398- })
399- }
400- return engineBase(c)
401-}
402-
403-// chooseBase picks the address to list models from: the first that lists
404-// them among the local ones — locals is the provider's default, then its
405-// alternates (engine.LocalURLs), each with its localAddresses — else the
406-// fallback when it does, else the default, whose error the model question
407-// then shows. A provider with one address and no fallback (openai) is not
408-// probed at all: there is nothing to choose, and openai's default is a
409-// remote service nobody asked mm to call yet.
410-//
411-// chooseBase([]string{"http://127.0.0.1:9931/v1", "http://127.0.0.1:8080/v1"}, "http://host.docker.internal:9931/v1", lists)
412-func chooseBase(locals []string, fallback string, lists func(string) bool) string {
413- base := locals[0]
414- if fallback == "" && len(locals) == 1 {
415- return base
416- }
417- for _, local := range locals {
418- for _, url := range localAddresses(local) {
419- if lists(url) {
420- return url
421- }
422- }
423- }
424- if fallback != "" && lists(fallback) {
425- return fallback
426- }
427- return base
428-}
429-
430-// localAddresses is the default address, then — when it names localhost —
431-// the same with 127.0.0.1: a server listening on IPv4 only does not answer
432-// a localhost that resolves to ::1 first.
433-//
434-// localAddresses("http://localhost:11434/v1") // [http://localhost:11434/v1 http://127.0.0.1:11434/v1]
435-func localAddresses(base string) []string {
436- out := []string{base}
437- if strings.Contains(base, "://localhost:") || strings.HasSuffix(base, "://localhost") {
438- out = append(out, strings.Replace(base, "://localhost", "://127.0.0.1", 1))
439- }
440- return out
441-}
442-
443-// engineBase is the engine's own resolution, for a provider the wizard has
444-// no addresses for.
445-func engineBase(c Choices) string {
446- p, err := engine.Lookup(c.Provider)
447- if err != nil {
448- return ""
449- }
450- b, err := p.Resolve(config.Config{Provider: c.Provider, Model: "probe"})
451- if err != nil {
452- return ""
453- }
454- return b.BaseURL
455-}
456-
457-func exists(path string) bool {
458- _, err := os.Stat(path)
459- return err == nil
460-}
461-
462-func alreadyExists(path string) error {
463- return fmt.Errorf("%s already exists — nothing was written; choose another name with -o", path)
464-}
465-
466-// replaceFile replaces a file the user agreed to overwrite. The new text is
467-// proved first, on a file beside it: an agent.yaml mm would refuse must not
468-// cost the user the one that worked.
469-func replaceFile(path, text string) error {
470- info, err := os.Stat(path)
471- if err != nil {
472- return err
473- }
474- tmp, err := os.CreateTemp(filepath.Dir(path), ".mm-init-*.yaml")
475- if err != nil {
476- return err
477- }
478- defer os.Remove(tmp.Name())
479- _, err = tmp.WriteString(text)
480- if closeErr := tmp.Close(); err == nil {
481- err = closeErr
482- }
483- if err != nil {
484- return err
485- }
486- if err := os.Chmod(tmp.Name(), info.Mode().Perm()); err != nil {
487- return err
488- }
489- if _, err := config.Load(tmp.Name()); err != nil {
490- return fmt.Errorf("mm would not load the new file: %v — %s is unchanged", err, path)
491- }
492- return os.Rename(tmp.Name(), path)
493-}
494-
495-// writeNew writes a file that must not exist yet: an existing agent.yaml is
496-// someone's work, replaced only through replaceFile.
497-func writeNew(path, text string) error {
498- f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
499- if errors.Is(err, os.ErrExist) {
500- return alreadyExists(path)
501- }
502- if err != nil {
503- return err
504- }
505- if _, err := f.WriteString(text); err != nil {
506- f.Close()
507- return err
508- }
509- return f.Close()
510-}
511-
512-// checkFile runs this same mm on the new file with one question.
513-func checkFile(stdout io.Writer, path string) int {
514- self, err := os.Executable()
515- if err != nil {
516- fmt.Fprintln(stdout, "⚠️ "+err.Error())
517- return 1
518- }
519- fmt.Fprintln(stdout, "… asking the model one question (the first answer loads the model)")
520- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
521- defer cancel()
522- out, err := exec.CommandContext(ctx, self, "-config", path, "-p", "Say hello in one line.").CombinedOutput()
523- fmt.Fprintln(stdout, strings.TrimSpace(string(out)))
524- if err != nil {
525- fmt.Fprintf(stdout, "⚠️ the check failed: %v\n", err)
526- return 1
527- }
528- fmt.Fprintln(stdout, "✅ the model answers")
529- return 0
530-}
added internal/agentinit/write.go +182 -0
new file mode 100644
@@ -0,0 +1,182 @@
1+package agentinit
2+
3+import (
4+ "context"
5+ "errors"
6+ "fmt"
7+ "io"
8+ "mm/internal/config"
9+ "os"
10+ "os/exec"
11+ "path/filepath"
12+ "strings"
13+ "time"
14+)
15+
16+// WriteFile writes the file the answered flow describes — or prints it, for
17+// "-" — creates the skills folder, and proves mm loads it, reporting each
18+// step on out. It returns the file as the flow names it (relative to the
19+// flow's dir, see Flow.SetDir) and whether everything went well.
20+func WriteFile(flow *Flow, out io.Writer) (string, bool) {
21+ choices, facts, output := flow.Result()
22+ if choices.Model == "" {
23+ fmt.Fprintln(out, "⚠️ no model: nothing written")
24+ return output, false
25+ }
26+ text := Render(Decide(flow.presets, choices, facts))
27+ if output == "-" {
28+ fmt.Fprint(out, text)
29+ return output, true
30+ }
31+ path := flow.Path(output)
32+ if err := saveAgentFile(flow, choices, path, text); err != nil {
33+ fmt.Fprintln(out, "⚠️ "+err.Error())
34+ return output, false
35+ }
36+ fmt.Fprintf(out, "✅ wrote %s\n", output)
37+ if err := checkWritten(choices, path, out); err != nil {
38+ fmt.Fprintln(out, "⚠️ "+err.Error())
39+ return output, false
40+ }
41+ fmt.Fprintln(out, "✅ mm loads it")
42+ return output, true
43+}
44+
45+// saveAgentFile writes text at path: a new file, or the existing one
46+// replaced when the user said so. The Project layout's file lives in .mm/,
47+// which may not exist yet.
48+func saveAgentFile(flow *Flow, choices Choices, path, text string) error {
49+ if on(choices.Project) {
50+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
51+ return err
52+ }
53+ }
54+ write := writeNew
55+ if flow.Overwrite() {
56+ write = replaceFile
57+ }
58+ return write(path, text)
59+}
60+
61+// checkWritten creates the skills folder when asked for, and checks that mm
62+// loads the file it just wrote.
63+func checkWritten(choices Choices, path string, out io.Writer) error {
64+ if err := createSkillsFolder(choices, path, out); err != nil {
65+ return err
66+ }
67+ if _, err := config.Load(path); err != nil {
68+ return fmt.Errorf("mm does not load it: %v", err)
69+ }
70+ return nil
71+}
72+
73+// createSkillsFolder makes the folder skillsDir names, when skills are on
74+// (ticket 205), once the file is written: in the file's base directory —
75+// the project root for .mm/agent.yaml — where mm started there reads it.
76+// Never called for "-": a preview creates nothing.
77+func createSkillsFolder(c Choices, output string, stdout io.Writer) error {
78+ if !on(c.Skills) {
79+ return nil
80+ }
81+ dir := filepath.Join(config.BaseDir(output), c.SkillsDir())
82+ if err := os.MkdirAll(dir, 0o755); err != nil {
83+ return err
84+ }
85+ fmt.Fprintf(stdout, "✅ skills folder %s\n", c.SkillsDir())
86+ return nil
87+}
88+
89+// nextLine says how to start the agent: a plain `mm` for .mm/agent.yaml,
90+// which mm finds on its own (ticket 204), -config otherwise.
91+func nextLine(output string) string {
92+ if output == filepath.Join(config.ProjectDir, config.DefaultPath) {
93+ return "Next: mm (or mm tui), started from this directory"
94+ }
95+ return fmt.Sprintf("Next: mm -config %s (or mm -tui %s)", output, output)
96+}
97+
98+func exists(path string) bool {
99+ _, err := os.Stat(path)
100+ return err == nil
101+}
102+
103+func alreadyExists(path string) error {
104+ return fmt.Errorf("%s already exists — nothing was written; choose another name with -o", path)
105+}
106+
107+// replaceFile replaces a file the user agreed to overwrite. The new text is
108+// proved first, on a file beside it: an agent.yaml mm would refuse must not
109+// cost the user the one that worked.
110+func replaceFile(path, text string) error {
111+ info, err := os.Stat(path)
112+ if err != nil {
113+ return err
114+ }
115+ tmp, err := writeTemp(filepath.Dir(path), text, info.Mode().Perm())
116+ if err != nil {
117+ return err
118+ }
119+ defer os.Remove(tmp)
120+ if _, err := config.Load(tmp); err != nil {
121+ return fmt.Errorf("mm would not load the new file: %v — %s is unchanged", err, path)
122+ }
123+ return os.Rename(tmp, path)
124+}
125+
126+// writeTemp writes text to a new temporary file in dir, with perm, and
127+// returns its name; on an error nothing is left behind.
128+func writeTemp(dir, text string, perm os.FileMode) (string, error) {
129+ tmp, err := os.CreateTemp(dir, ".mm-init-*.yaml")
130+ if err != nil {
131+ return "", err
132+ }
133+ _, err = tmp.WriteString(text)
134+ if closeErr := tmp.Close(); err == nil {
135+ err = closeErr
136+ }
137+ if err == nil {
138+ err = os.Chmod(tmp.Name(), perm)
139+ }
140+ if err != nil {
141+ _ = os.Remove(tmp.Name())
142+ return "", err
143+ }
144+ return tmp.Name(), nil
145+}
146+
147+// writeNew writes a file that must not exist yet: an existing agent.yaml is
148+// someone's work, replaced only through replaceFile.
149+func writeNew(path, text string) error {
150+ f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
151+ if errors.Is(err, os.ErrExist) {
152+ return alreadyExists(path)
153+ }
154+ if err != nil {
155+ return err
156+ }
157+ if _, err := f.WriteString(text); err != nil {
158+ f.Close()
159+ return err
160+ }
161+ return f.Close()
162+}
163+
164+// checkFile runs this same mm on the new file with one question.
165+func checkFile(stdout io.Writer, path string) int {
166+ self, err := os.Executable()
167+ if err != nil {
168+ fmt.Fprintln(stdout, "⚠️ "+err.Error())
169+ return 1
170+ }
171+ fmt.Fprintln(stdout, "… asking the model one question (the first answer loads the model)")
172+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
173+ defer cancel()
174+ out, err := exec.CommandContext(ctx, self, "-config", path, "-p", "Say hello in one line.").CombinedOutput()
175+ fmt.Fprintln(stdout, strings.TrimSpace(string(out)))
176+ if err != nil {
177+ fmt.Fprintf(stdout, "⚠️ the check failed: %v\n", err)
178+ return 1
179+ }
180+ fmt.Fprintln(stdout, "✅ the model answers")
181+ return 0
182+}
new file mode 100644
@@ -0,0 +1,182 @@
1+package agentinit
2+
3+import (
4+ "context"
5+ "errors"
6+ "fmt"
7+ "io"
8+ "mm/internal/config"
9+ "os"
10+ "os/exec"
11+ "path/filepath"
12+ "strings"
13+ "time"
14+)
15+
16+// WriteFile writes the file the answered flow describes — or prints it, for
17+// "-" — creates the skills folder, and proves mm loads it, reporting each
18+// step on out. It returns the file as the flow names it (relative to the
19+// flow's dir, see Flow.SetDir) and whether everything went well.
20+func WriteFile(flow *Flow, out io.Writer) (string, bool) {
21+ choices, facts, output := flow.Result()
22+ if choices.Model == "" {
23+ fmt.Fprintln(out, "⚠️ no model: nothing written")
24+ return output, false
25+ }
26+ text := Render(Decide(flow.presets, choices, facts))
27+ if output == "-" {
28+ fmt.Fprint(out, text)
29+ return output, true
30+ }
31+ path := flow.Path(output)
32+ if err := saveAgentFile(flow, choices, path, text); err != nil {
33+ fmt.Fprintln(out, "⚠️ "+err.Error())
34+ return output, false
35+ }
36+ fmt.Fprintf(out, "✅ wrote %s\n", output)
37+ if err := checkWritten(choices, path, out); err != nil {
38+ fmt.Fprintln(out, "⚠️ "+err.Error())
39+ return output, false
40+ }
41+ fmt.Fprintln(out, "✅ mm loads it")
42+ return output, true
43+}
44+
45+// saveAgentFile writes text at path: a new file, or the existing one
46+// replaced when the user said so. The Project layout's file lives in .mm/,
47+// which may not exist yet.
48+func saveAgentFile(flow *Flow, choices Choices, path, text string) error {
49+ if on(choices.Project) {
50+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
51+ return err
52+ }
53+ }
54+ write := writeNew
55+ if flow.Overwrite() {
56+ write = replaceFile
57+ }
58+ return write(path, text)
59+}
60+
61+// checkWritten creates the skills folder when asked for, and checks that mm
62+// loads the file it just wrote.
63+func checkWritten(choices Choices, path string, out io.Writer) error {
64+ if err := createSkillsFolder(choices, path, out); err != nil {
65+ return err
66+ }
67+ if _, err := config.Load(path); err != nil {
68+ return fmt.Errorf("mm does not load it: %v", err)
69+ }
70+ return nil
71+}
72+
73+// createSkillsFolder makes the folder skillsDir names, when skills are on
74+// (ticket 205), once the file is written: in the file's base directory —
75+// the project root for .mm/agent.yaml — where mm started there reads it.
76+// Never called for "-": a preview creates nothing.
77+func createSkillsFolder(c Choices, output string, stdout io.Writer) error {
78+ if !on(c.Skills) {
79+ return nil
80+ }
81+ dir := filepath.Join(config.BaseDir(output), c.SkillsDir())
82+ if err := os.MkdirAll(dir, 0o755); err != nil {
83+ return err
84+ }
85+ fmt.Fprintf(stdout, "✅ skills folder %s\n", c.SkillsDir())
86+ return nil
87+}
88+
89+// nextLine says how to start the agent: a plain `mm` for .mm/agent.yaml,
90+// which mm finds on its own (ticket 204), -config otherwise.
91+func nextLine(output string) string {
92+ if output == filepath.Join(config.ProjectDir, config.DefaultPath) {
93+ return "Next: mm (or mm tui), started from this directory"
94+ }
95+ return fmt.Sprintf("Next: mm -config %s (or mm -tui %s)", output, output)
96+}
97+
98+func exists(path string) bool {
99+ _, err := os.Stat(path)
100+ return err == nil
101+}
102+
103+func alreadyExists(path string) error {
104+ return fmt.Errorf("%s already exists — nothing was written; choose another name with -o", path)
105+}
106+
107+// replaceFile replaces a file the user agreed to overwrite. The new text is
108+// proved first, on a file beside it: an agent.yaml mm would refuse must not
109+// cost the user the one that worked.
110+func replaceFile(path, text string) error {
111+ info, err := os.Stat(path)
112+ if err != nil {
113+ return err
114+ }
115+ tmp, err := writeTemp(filepath.Dir(path), text, info.Mode().Perm())
116+ if err != nil {
117+ return err
118+ }
119+ defer os.Remove(tmp)
120+ if _, err := config.Load(tmp); err != nil {
121+ return fmt.Errorf("mm would not load the new file: %v — %s is unchanged", err, path)
122+ }
123+ return os.Rename(tmp, path)
124+}
125+
126+// writeTemp writes text to a new temporary file in dir, with perm, and
127+// returns its name; on an error nothing is left behind.
128+func writeTemp(dir, text string, perm os.FileMode) (string, error) {
129+ tmp, err := os.CreateTemp(dir, ".mm-init-*.yaml")
130+ if err != nil {
131+ return "", err
132+ }
133+ _, err = tmp.WriteString(text)
134+ if closeErr := tmp.Close(); err == nil {
135+ err = closeErr
136+ }
137+ if err == nil {
138+ err = os.Chmod(tmp.Name(), perm)
139+ }
140+ if err != nil {
141+ _ = os.Remove(tmp.Name())
142+ return "", err
143+ }
144+ return tmp.Name(), nil
145+}
146+
147+// writeNew writes a file that must not exist yet: an existing agent.yaml is
148+// someone's work, replaced only through replaceFile.
149+func writeNew(path, text string) error {
150+ f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
151+ if errors.Is(err, os.ErrExist) {
152+ return alreadyExists(path)
153+ }
154+ if err != nil {
155+ return err
156+ }
157+ if _, err := f.WriteString(text); err != nil {
158+ f.Close()
159+ return err
160+ }
161+ return f.Close()
162+}
163+
164+// checkFile runs this same mm on the new file with one question.
165+func checkFile(stdout io.Writer, path string) int {
166+ self, err := os.Executable()
167+ if err != nil {
168+ fmt.Fprintln(stdout, "⚠️ "+err.Error())
169+ return 1
170+ }
171+ fmt.Fprintln(stdout, "… asking the model one question (the first answer loads the model)")
172+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
173+ defer cancel()
174+ out, err := exec.CommandContext(ctx, self, "-config", path, "-p", "Say hello in one line.").CombinedOutput()
175+ fmt.Fprintln(stdout, strings.TrimSpace(string(out)))
176+ if err != nil {
177+ fmt.Fprintf(stdout, "⚠️ the check failed: %v\n", err)
178+ return 1
179+ }
180+ fmt.Fprintln(stdout, "✅ the model answers")
181+ return 0
182+}