bots-garden/mini-mepublic Fork
⑂ 7817163
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/agent without smells (8 → 0)

- Run (complexity 144) as a repl type: step, next, question, command
  (askCommand, a2aCommand, historyCommand), then the turn in turn.go:
  compactIfDue, expand, startTurn, wait, finish, report, typed,
  steerOrQueue
- the ⚙ line built once (statsLine/printTurnStats) for Run and RunPrompt
- Run and RunPrompt take an agent.Setup (engine, system, tools,
  detector) instead of six parameters; RunPrompt's unused detector gone
- the 'generating' flag dropped: it was always false at the prompt
- history.go and recap.go by theme

Checked old vs new binary against a scripted fake OpenAI server, piped
and paced input (steering, /queue, /abort, a tool call, /sessions, /new,
/compact, /resume, /quit) and SIGINT during a turn and at the prompt:
identical output.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
agent committed 2026-11-28T12:16:26+01:00 Browse files
7817163 parent: dddb66d
modified internal/agent/agent.go +153 -568
@@ -12,46 +12,38 @@ import (
1212
1313 "mm/internal/agentsmd"
1414 "mm/internal/ask"
15- "mm/internal/clipboard"
1615 "mm/internal/command"
17- "mm/internal/compact"
18- "mm/internal/config"
1916 "mm/internal/consent"
20- "mm/internal/decide"
2117 "mm/internal/detector"
22- "mm/internal/docsearch"
2318 "mm/internal/elicit"
2419 "mm/internal/engine"
25- "mm/internal/hooks"
26- "mm/internal/mention"
27- "mm/internal/saved"
2820 "mm/internal/session"
29- "mm/internal/skills"
3021 "mm/internal/spinner"
3122 "mm/internal/store"
32- "mm/internal/tools"
3323
3424 "github.com/firebase/genkit/go/ai"
3525 )
3626
37-type genResult struct {
38- resp *ai.ModelResponse
39- // history is the FULL conversation returned by engine.Generate — tool turns
40- // included. Genkit only hands back the last message; without this field the
41- // agent forgets the commands it just ran and starts telling stories instead
42- // of re-reading.
43- history []*ai.Message
44- err error
27+// Setup is what an agent runs with: the engine, the system prompt as the
28+// config gives it (AGENTS.md is added at the start of each conversation),
29+// the tools the model may call and the loop detector watching them.
30+//
31+// agent.Run(ctx, agent.Setup{Engine: e, System: cfg.System, Tools: tools, Detector: d}, pool)
32+type Setup struct {
33+ Engine *engine.Engine
34+ System string
35+ Tools []ai.ToolRef
36+ Detector *detector.LoopDetector
4537 }
4638
4739 // Run starts the loop: read user input → generate (with automatic tool calls) →
4840 // print → start over, keeping the history.
4941 //
5042 // pool runs the /ask commands (another mm agent); nil when none is configured.
51-func Run(ctx context.Context, e *engine.Engine, system string, tools []ai.ToolRef, d *detector.LoopDetector, pool ask.Runner) {
43+func Run(ctx context.Context, s Setup, pool ask.Runner) {
5244 // The project's AGENTS.md joins the prompt at the start of every
5345 // conversation — here, /new and /resume — never in the middle of one.
54- messages := session.Fresh(agentsmd.System(system, ""))
46+ messages := session.Fresh(agentsmd.System(s.System, ""))
5547 ctx, cancelAll := context.WithCancel(ctx)
5648 defer cancelAll()
5749
@@ -60,554 +52,174 @@ func Run(ctx context.Context, e *engine.Engine, system string, tools []ai.ToolRe
6052 // tool's own working directory.
6153 cwd, _ := os.Getwd()
6254
63- // Persistence, when on (config `sessions`): this run is a new session,
64- // saved from its first turn; earlier ones are a /resume away. See
65- // store.Keeper.
66- keep := store.NewKeeper(cwd)
67-
68- // sigCh captures Ctrl+C (SIGINT).
69- sigCh := make(chan os.Signal, 1)
70- signal.Notify(sigCh, os.Interrupt)
71-
72- // inputCh receives commands from the reader goroutine.
73- inputCh := make(chan string)
55+ r := &repl{
56+ Setup: s, ctx: ctx, pool: pool, cwd: cwd, messages: messages,
57+ // Persistence, when on (config `sessions`): this run is a new
58+ // session, saved from its first turn; earlier ones are a /resume
59+ // away. See store.Keeper.
60+ keep: store.NewKeeper(cwd),
61+ // sigCh captures Ctrl+C (SIGINT).
62+ sigCh: make(chan os.Signal, 1),
63+ // inputCh receives every line typed — or piped — from the reader
64+ // goroutine.
65+ inputCh: make(chan string),
66+ // The permission prompt (yolo: false, MCP tools marked "ask"): the
67+ // tools post their question, the waiting room prints it and routes
68+ // the next typed line to it. The ask_user tool's questions take the
69+ // same way.
70+ prompt: newLinePrompt(),
71+ // queue holds what was typed during a generation (ticket 155): it
72+ // runs here, in order, before anything new is read.
73+ queue: &inbox{},
74+ }
75+ signal.Notify(r.sigCh, os.Interrupt)
76+ go readInput(ctx, os.Stdin, r.inputCh)
77+ defer consent.SetPrompter(r.prompt.allow)()
78+ defer elicit.SetPrompter(r.prompt.ask)()
7479
75- // The reader goroutine: every line typed — or piped — goes to inputCh.
76- go readInput(ctx, os.Stdin, inputCh)
80+ r.greet()
81+ for r.step() {
82+ }
83+}
7784
78- // The permission prompt (yolo: false, MCP tools marked "ask"): the tools
79- // post their question, the waiting rooms below print it and route the
80- // next typed line to it.
81- prompt := newLinePrompt()
82- defer consent.SetPrompter(prompt.allow)()
83- // The ask_user tool's questions take the same way.
84- defer elicit.SetPrompter(prompt.ask)()
85+// repl is the line mode's state between two turns: the setup, the
86+// conversation, where its lines come from and where they wait.
87+type repl struct {
88+ Setup
89+ ctx context.Context
90+ pool ask.Runner
91+ cwd string
92+ keep *store.Keeper
93+ sigCh chan os.Signal
94+ inputCh chan string
95+ prompt *linePrompt
96+ queue *inbox
97+ messages []*ai.Message
98+}
8599
100+// greet prints the commands and where the sessions go.
101+func (r *repl) greet() {
86102 fmt.Println(`Agent ready. Commands: "/quit" to exit, "/abort" to stop current generation, "/compact" to compress the history, "/new" to start a new session, "/sessions" and "/resume" for stored sessions, "/help" to list them.`)
87103 fmt.Println(`Shortcut: Ctrl+C to abort generation, or Ctrl+C at prompt to quit.`)
88- if hint := keep.Hint(); hint != "" {
104+ if hint := r.keep.Hint(); hint != "" {
89105 dimln(hint)
90106 }
91-
92- generating := false
93- // queue holds what was typed during a generation (ticket 155): it runs
94- // here, in order, before anything new is read.
95- queue := &inbox{}
96-
97- for {
98- fmt.Print("\n> ")
99-
100- // 1. Take the next queued line, else wait for the next user input OR
101- // a quit signal. A queued line is echoed after the prompt, so the
102- // transcript reads as if it had been typed there.
103- input, queued := queue.pop()
104- var ok bool
105-
106- if queued {
107- fmt.Println(input)
108- } else {
109- select {
110- case <-sigCh:
111- if !generating {
112- fmt.Println("\nGoodbye.")
113- return
114- }
115- // If generating, we let the generation loop handle the SIGINT.
116- // We fall through to wait for the next input (which will be the prompt).
117- case input, ok = <-inputCh:
118- if !ok {
119- return
120- }
121- }
122- }
123-
124- // 2. Basic Command Handling — the names come from the shared table
125- // (internal/command), the same one the editor and the window read.
126- if command.Is(input, command.Quit) {
127- break
128- }
129- if input == "" {
130- continue
131- }
132- if command.Is(input, command.Abort) {
133- spinner.Stop()
134- fmt.Println("⚠️ No generation in progress.")
135- continue
136- }
137- // /queue between two turns: nothing to wait for, the question runs.
138- if q, isQueue := queueArg(input); isQueue {
139- if q == "" {
140- fmt.Println(queueNeedsQuestion)
141- continue
142- }
143- input = q
144- }
145- // The commands that move the history — /compact, /new, /sessions,
146- // /resume — are only reachable here, between two generations: Genkit
147- // holds its own copy of the conversation while it runs, and a
148- // tool_call/tool_result pair in flight must not move under it. Typed
149- // DURING a generation, such a command waits in the queue (ticket 155)
150- // and comes back here once the turn has settled — so it always
151- // applies to the finished history.
152- // /ask-bob and its family: another agent answers, and its answer
153- // joins the history for the next question. Between two generations
154- // too, for the same reason as the commands below.
155- if req, ok, err := command.ParseAsk(input); ok {
156- if err != nil {
157- fmt.Println("⚠️ " + err.Error())
158- continue
159- }
160- var quit bool
161- messages, quit = asking{pool: pool, cwd: cwd, keep: keep, sigCh: sigCh, inputCh: inputCh, prompt: prompt, queue: queue}.run(ctx, req, messages)
162- if quit {
163- fmt.Println("Goodbye.")
164- return
165- }
166- continue
167- }
168- // /a2a-alice: a remote A2A agent answers (ticket 263), its answer
169- // joins the history like /ask's.
170- if req, ok, err := command.ParseA2A(input); ok {
171- if err != nil {
172- fmt.Println("⚠️ " + err.Error())
173- continue
174- }
175- messages = a2aLine(ctx, req, messages, sigCh)
176- save(keep, messages)
177- continue
178- }
179- if next, handled := (&loop{ctx: ctx, e: e, d: d, keep: keep, system: system}).historyCommand(input, messages); handled {
180- messages = next
181- continue
182- }
183-
184- // 3. Normal message: Add to history and start generation.
185- //
186- // The automatic compression runs BEFORE the question is appended and
187- // BEFORE `before` is computed: that index is what the rollback
188- // (`messages[:before-1]`) and the ⚙ line (`res.history[before:]`)
189- // rely on, and a history that shrinks after it is taken would break
190- // both. The server's own count of the last context is preferred to
191- // the estimate when it is larger — it sees the tools' JSON and the
192- // chat template, which the estimate cannot. The window is the one the
193- // Engine knows: the yaml's contextWindow, or what the probe learned.
194- //
195- // That probe ran once, at start-up. A llama-server started AFTER bob
196- // left `ctx: unknown` for the whole session — observed — and the
197- // compression could then only trigger on maxMessages. So, while the
198- // window is unknown and compression is on, ask the server again
199- // before deciding; once known, never again. A probe that still
200- // fails prints nothing: the start-up warning already said so.
201- if c := config.Cfg.Context; c.Enabled && e.ContextWindow == 0 {
202- if w, src := e.EnsureContextWindow(ctx); w > 0 {
203- dimln(fmt.Sprintf("ctx: %d (%s)", w, src))
204- }
205- }
206- if dec := compact.Decide(messages, e.LastInputTokens(), e.ContextWindow, config.Cfg.Context); dec.Compact {
207- messages = compactHistory(ctx, e, keep, messages, false)
208- save(keep, messages)
209- }
210- // "@path" in the question names a file for the model to look at. The
211- // text stays as typed; each existing path is appended as an
212- // [attached file: …] line — what an editor's @-mention becomes over
213- // ACP — and echoed here so the user sees the notation was understood.
214- typed := input
215- input, attached := mention.Expand(input, cwd)
216- for _, a := range attached {
217- dimln("📎 " + a.Path)
218- }
219- // "$skill" names a procedure to carry out, with the rest of the line
220- // as its parameters — the same notation the window's `$` picker
221- // writes, so it means the same thing typed by hand.
222- input, refs := skills.ExpandRefs(input, skills.Declared())
223- for _, ref := range refs {
224- dimln("📖 $" + ref.Name)
225- }
226- // No `$skill` named: the decider, when there is one, may pick it.
227- input, routed := decide.RouteSkill(ctx, typed, input, len(refs), skills.Declared())
228- if routed != "" {
229- dimln(routed)
230- }
231- messages = append(messages, ai.NewUserTextMessage(input))
232- before := len(messages)
233- fmt.Println()
234-
235- // Create a cancellable context for this specific generation cycle.
236- genCtx, cancelGen := context.WithCancel(ctx)
237- generating = true
238-
239- // Hooks that ran outside a turn (an /ask) are not this turn's.
240- hooks.Turn.Take()
241-
242- // A question typed during the turn steers it (ticket 265).
243- steer := newTurnSteer(cwd)
244- steerCtx := steer.context(genCtx)
245-
246- // Launch generation in a goroutine.
247- resultCh := make(chan genResult, 1)
248- go func() {
249- resp, history, err := e.Generate(steerCtx, messages, tools)
250- resultCh <- genResult{resp: resp, history: history, err: err}
251- }()
252-
253- // 4. The "Waiting Room": Listen for completion, interruption, OR new
254- // command. typing goes nil when stdin closes (the end of a pipe), so
255- // the closed channel is not read in a loop; the main loop sees the
256- // end of the input once the queue is empty.
257- typing := inputCh
258- generationRunning := true
259- for generationRunning {
260- select {
261- case res := <-resultCh:
262- generationRunning = false
263- generating = false
264- prompt.drop()
265-
266- // We take the FULL history returned by engine.Generate, not just
267- // resp.Message — and we take it EVEN when the generation failed
268- // or was interrupted: on an abort (Ctrl+C, /abort), a maxTurns
269- // overrun or a silence caught by the watchdog, all the work of
270- // the turn is in `history`, and Genkit itself returns nothing.
271- // (resp.History() will not do: empty on the streamed path.)
272- asked := messages // question included, for the error record below
273- messages = session.AfterTurn(messages, before, res.resp, res.history, res.err)
274- save(keep, messages)
275-
276- if res.err != nil {
277- if genCtx.Err() == context.Canceled {
278- fmt.Println("\n🔴 Generation aborted.")
279- } else {
280- // One line, in the provider's words: see engine.Explain —
281- // and the same line in the session file, for whoever
282- // asks later why this turn failed.
283- explained := e.Explain(res.err)
284- fmt.Println("\n[error: " + explained + "]")
285- record(keep, messages, store.NewFailure(asked, store.FailGeneration, explained, res.err))
286- }
287- } else {
288- // --- Global Loop Detection ---
289- // We check the tool calls in the model response.
290- if res.resp != nil && res.resp.Message != nil {
291- for _, part := range res.resp.Message.Content {
292- if part.IsToolRequest() && part.ToolRequest != nil {
293- d.Record(detector.Action{
294- ToolName: part.ToolRequest.Name,
295- Input: fmt.Sprintf("%v", part.ToolRequest.Input),
296- Output: "[tool_call]",
297- })
298- }
299- }
300- }
301- fmt.Println()
302- }
303-
304- // The command count is the only visible proof that the model
305- // worked rather than improvised. Zero is normal on a
306- // conversational question; zero on "read this file" is not.
307- turn := res.history[min(before, len(res.history)):]
308- cmds := engine.CommandList(turn)
309- ops := engine.FileOps(turn)
310- line := fmt.Sprintf("⚙ %d command(s)", len(cmds))
311- // The file tools have their own column: the A/B of this part
312- // is "edits through bash" versus "edits through tools", and
313- // a single number would add up what it is meant to separate.
314- if len(ops) > 0 {
315- line += fmt.Sprintf(" · 📝 %d file op(s)", len(ops))
316- }
317- // Always shown when the agent has skills, 0 included: see
318- // engine.SkillsAvailable.
319- if engine.SkillsAvailable() {
320- line += fmt.Sprintf(" · 📖 %d skill(s)", engine.Skills(turn))
321- }
322- if k := engine.LSPCalls(turn); k > 0 {
323- line += fmt.Sprintf(" · 🔎 %d lsp call(s)", k)
324- }
325- if spinner.Styled() {
326- fmt.Printf("\033[2m%s\033[0m\n", line)
327- } else {
328- fmt.Println(line)
329- }
330- if config.Cfg.DisplayCommands {
331- printCommands(cmds)
332- printCommands(ops)
333- }
334- printHookRuns(os.Stdout)
335- // Questions sent after the model's last call run next.
336- if late := steer.late(); len(late) > 0 {
337- queue.pushFront(late)
338- fmt.Printf("⏳ %d message(s) came after the model's last call — sent as the next question\n", len(late))
339- }
340-
341- case <-sigCh:
342- // Handle Ctrl+C during generation.
343- // Stop() first: the spinner is running during the generation,
344- // and without it this message lands on its line — the next
345- // frame would erase it. Same rule as in dmr.emit.
346- spinner.Stop()
347- prompt.drop()
348- fmt.Println("\n🔴 Interrupted (Ctrl+C).")
349- cancelGen()
350- // We don't set generationRunning=false; we wait for resultCh to catch the Canceled error.
351-
352- case req := <-prompt.requestCh():
353- prompt.show(req)
354-
355- case nextInput, open := <-typing:
356- if !open {
357- typing = nil
358- continue
359- }
360- // A line typed while a tool waits for permission is its answer;
361- // /abort and /quit stop the turn; anything else waits for it.
362- if prompt.answer(nextInput) {
363- continue
364- }
365- switch {
366- case command.Is(nextInput, command.Abort):
367- prompt.drop()
368- spinner.Stop() // le spinner tourne : on lui reprend la ligne
369- cancelGen()
370- fmt.Println("🔴 Aborting...")
371- case command.Is(nextInput, command.Quit):
372- prompt.drop()
373- spinner.Stop()
374- cancelGen()
375- fmt.Println("Goodbye.")
376- return
377- default:
378- // Ticket 265: a question steers the turn — the model reads
379- // it after its current step. A slash command, and
380- // `/queue <question>`, wait in the queue and run once the
381- // turn has settled (ticket 155).
382- if q, isQueue := queueArg(nextInput); isQueue {
383- if q == "" {
384- spinner.Stop()
385- fmt.Println("\n" + queueNeedsQuestion)
386- continue
387- }
388- nextInput = q
389- } else if notice, steered := steer.offer(nextInput); steered {
390- spinner.Stop()
391- fmt.Println("\n" + notice)
392- continue
393- }
394- if notice := queue.push(nextInput); notice != "" {
395- spinner.Stop()
396- fmt.Println("\n" + notice)
397- }
398- }
399- }
400- }
401- // Final cleanup for this cycle.
402- cancelGen()
403- }
404107 }
405108
406-// printCommands recaps the commands of the turn, in green.
407-//
408-// The count says HOW MANY, the list says WHAT: it reads at a glance once the
409-// answer is written, whereas the 🛠️ lines are scattered through the output of
410-// the commands. Green separates it from both the grey of the tools and the
411-// model's own text — and it only comes out on a terminal, like every other
412-// colour here.
413-func printCommands(cmds []string) {
414- if len(cmds) == 0 {
415- return
109+// step reads one line at the prompt and acts on it: a command, or a turn.
110+// It reports whether the loop goes on — false on /quit, Ctrl+C at the
111+// prompt, or the end of the input.
112+func (r *repl) step() bool {
113+ fmt.Print("\n> ")
114+ input, ok := r.next()
115+ // The names come from the shared table (internal/command), the same one
116+ // the editor and the window read.
117+ if !ok || command.Is(input, command.Quit) {
118+ return false
416119 }
417- green, off := "", ""
418- if spinner.Styled() {
419- green, off = "\033[32m", "\033[0m"
120+ input, ok = r.question(input)
121+ if !ok {
122+ return true
420123 }
421-
422- var b strings.Builder
423- for i, c := range cmds {
424- b.WriteString(green + fmt.Sprintf(" %d. %s", i+1, oneLine(c)) + off + "\n")
124+ if handled, quit := r.command(input); handled {
125+ return !quit
425126 }
426- fmt.Print(b.String())
127+ return r.turn(input)
427128 }
428129
429-// printHookRuns lists, under the commands, the hooks that ran during the turn
430-// (hooks.Turn) when displayHooks is on — in the same colour, so the recap of a
431-// turn reads as one block.
432-//
433-// 🪝 1. preGeneration · node "$MM_CONFIG_DIR/hooks/guards.js" → context (214 chars)
434-func printHookRuns(w io.Writer) {
435- if !config.Cfg.DisplayHooks {
436- return
130+// next is the next queued line, else the next line typed. A queued line is
131+// echoed after the prompt, so the transcript reads as if it had been typed
132+// there. ok is false on Ctrl+C (Goodbye) and at the end of the input.
133+func (r *repl) next() (string, bool) {
134+ if input, queued := r.queue.pop(); queued {
135+ fmt.Println(input)
136+ return input, true
437137 }
438- green, off := "", ""
439- if spinner.Styled() {
440- green, off = "\033[32m", "\033[0m"
441- }
442- for _, line := range hooks.Lines(hooks.Turn.Take()) {
443- _, _ = fmt.Fprintln(w, green+" "+line+off)
138+ select {
139+ case <-r.sigCh:
140+ fmt.Println("\nGoodbye.")
141+ return "", false
142+ case input, ok := <-r.inputCh:
143+ return input, ok
444144 }
445145 }
446146
447-// maxCommandWidth is the width beyond which a command is cut. A hundred
448-// columns: that fits a demo terminal without overflowing it.
449-const maxCommandWidth = 100
450-
451-// oneLine folds a command onto ONE line and truncates it when needed.
452-//
453-// A command can be long and span several lines — a heredoc, a trailing &&. The
454-// recap is there to scan what the agent did, not to re-read its code: spread
455-// over several lines it would grow longer than the output it summarises, and
456-// the numbering would stop being readable.
457-func oneLine(s string) string {
458- // Fields splits on ALL whitespace, line breaks included: that is exactly
459- // the folding we want, heredoc indentation and all.
460- s = strings.Join(strings.Fields(s), " ")
461- r := []rune(s)
462- if len(r) <= maxCommandWidth {
463- return s
147+// question is the line as a question: nothing for an empty line or /abort
148+// (there is no generation to stop), and the question of /queue — between
149+// two turns, nothing to wait for, it runs now.
150+func (r *repl) question(input string) (string, bool) {
151+ if input == "" {
152+ return "", false
464153 }
465- return string(r[:maxCommandWidth-1]) + "…"
466-}
467-
468-// compactHistory replaces the old turns of `msgs` by a model-written summary
469-// and says so in one line. On ANY failure — server down, watchdog, empty or
470-// malformed result — it returns `msgs` unchanged: the compression exists to
471-// keep the next question possible, so it must never cost one.
472-//
473-// `forced` is the /compact command: it skips the threshold, not the "is there
474-// anything older than the kept turns" check, and it says so when there is not.
475-// The loop detector is deliberately not touched: it records what the agent
476-// DOES, and forgetting a conversation does not make a repeated command new.
477-func compactHistory(ctx context.Context, e *engine.Engine, keep *store.Keeper, msgs []*ai.Message, forced bool) []*ai.Message {
478- cfg := config.Cfg.Context
479-
480- // The summary is the longest prefill of the session and prints nothing
481- // while it runs: without a label the agent looks hung, exactly the case
482- // the spinner exists for.
483- spinner.Start("Compressing")
484- out, line, outcome := compact.Apply(ctx, msgs, cfg, func(ctx context.Context, request []*ai.Message) (string, error) {
485- return e.Summarize(ctx, request, cfg.SummaryMaxTokens)
486- }, e.Explain)
487- spinner.Stop()
488-
489- switch outcome {
490- case compact.Nothing:
491- if forced {
492- dimln(line)
493- }
494- case compact.Failed:
495- fmt.Println(line)
496- record(keep, msgs, store.NewFailure(msgs, store.FailCompaction, line, nil))
497- case compact.Compressed:
498- // The server's last measure described the history we just replaced.
499- e.ForgetInputTokens()
500- if cfg.ShowStats {
501- dimln(line)
502- }
154+ if command.Is(input, command.Abort) {
155+ spinner.Stop()
156+ fmt.Println("⚠️ No generation in progress.")
157+ return "", false
503158 }
504- return out
505-}
506-
507-// save rewrites the session file and reports a failure in one line: a
508-// read-only project still gets an agent.
509-func save(keep *store.Keeper, msgs []*ai.Message) {
510- if err := keep.Save(msgs); err != nil {
511- fmt.Println("[sessions: not saved: " + err.Error() + "]")
159+ q, isQueue := queueArg(input)
160+ if !isQueue {
161+ return input, true
512162 }
513-}
514-
515-// record writes the error just printed into the session file (see
516-// store.Keeper.Fail): the red line on screen is gone with the scrollback,
517-// the file keeps it for whoever investigates the run later.
518-func record(keep *store.Keeper, msgs []*ai.Message, f store.Failure) {
519- if err := keep.Fail(msgs, f); err != nil {
520- fmt.Println("[sessions: error not recorded: " + err.Error() + "]")
163+ if q == "" {
164+ fmt.Println(queueNeedsQuestion)
165+ return "", false
521166 }
167+ return q, true
522168 }
523169
524-// startNewSession forgets the conversation and returns the history of a fresh
525-// one: the system prompt alone. Three things make up "the session" here, and
526-// all three are reset — the messages, the server's token count of the last
527-// context (it described a history that no longer exists, same rule as after a
528-// compression), and the loop detector (a new session is a new task: a command
529-// repeated in the old one must not be flagged as a loop in this one — the
530-// opposite of compactHistory's choice, where the task continues).
170+// command runs the commands that move the history — /ask, /a2a, /compact,
171+// /new, /sessions, /resume… — and reports whether input was one, and
172+// whether /quit was typed meanwhile.
531173 //
532-// It says in one line how much was forgotten, so a /new on an empty session
533-// visibly did nothing rather than silently nothing.
534-func startNewSession(e *engine.Engine, d *detector.LoopDetector, system string, old []*ai.Message) []*ai.Message {
535- forgotten := session.Forgotten(old)
536- e.ForgetInputTokens()
537- d.Reset()
538- // Plans belong to the conversation /new just closed (ticket 109).
539- tools.ClearPlans("")
540- dimln(fmt.Sprintf("🆕 new session: %d message(s) forgotten", forgotten))
541- return session.Fresh(agentsmd.System(system, ""))
542-}
543-
544-// dimln prints one line, dimmed on a terminal and plain in a pipe — the same
545-// rule as the ⚙ line: `bob | jq` must not receive escape codes.
546-func dimln(line string) {
547- if spinner.Styled() {
548- fmt.Printf("\033[2m%s\033[0m\n", line)
549- } else {
550- fmt.Println(line)
174+// They are only reachable here, between two generations: Genkit holds its
175+// own copy of the conversation while it runs, and a tool_call/tool_result
176+// pair in flight must not move under it. Typed DURING a generation, such a
177+// command waits in the queue (ticket 155) and comes back here once the turn
178+// has settled — so it always applies to the finished history.
179+func (r *repl) command(input string) (handled, quit bool) {
180+ if handled, quit := r.askCommand(input); handled {
181+ return true, quit
551182 }
183+ if r.a2aCommand(input) {
184+ return true, false
185+ }
186+ next, handled := (&loop{ctx: r.ctx, e: r.Engine, d: r.Detector, keep: r.keep, system: r.System}).historyCommand(input, r.messages)
187+ r.messages = next
188+ return handled, false
552189 }
553190
554-// loop is what the REPL's commands act on: the engine, the loop detector,
555-// the session keeper and the system prompt Run was given.
556-type loop struct {
557- ctx context.Context
558- e *engine.Engine
559- d *detector.LoopDetector
560- keep *store.Keeper
561- system string
191+// askCommand runs /ask-bob and its family: another agent answers, and its
192+// answer joins the history for the next question.
193+func (r *repl) askCommand(input string) (handled, quit bool) {
194+ req, ok, err := command.ParseAsk(input)
195+ if !ok {
196+ return false, false
197+ }
198+ if err != nil {
199+ fmt.Println("⚠️ " + err.Error())
200+ return true, false
201+ }
202+ r.messages, quit = asking{pool: r.pool, cwd: r.cwd, keep: r.keep, sigCh: r.sigCh, inputCh: r.inputCh, prompt: r.prompt, queue: r.queue}.run(r.ctx, req, r.messages)
203+ if quit {
204+ fmt.Println("Goodbye.")
205+ }
206+ return true, quit
562207 }
563208
564-// historyCommand runs the slash commands that replace the history — /compact,
565-// /new, and the stored-session pair /sessions and /resume — plus /help, and
566-// reports whether input was one of them. Run only calls it between two
567-// generations. A resumed session is a new task for the loop detector too,
568-// and the server's token count described another history.
569-func (l *loop) historyCommand(input string, messages []*ai.Message) ([]*ai.Message, bool) {
570- cmd, arg, ok := command.Parse(input)
209+// a2aCommand runs /a2a-alice: a remote A2A agent answers (ticket 263), its
210+// answer joins the history like /ask's.
211+func (r *repl) a2aCommand(input string) bool {
212+ req, ok, err := command.ParseA2A(input)
571213 if !ok {
572- return messages, false
214+ return false
573215 }
574- switch cmd.Name {
575- case command.Compact:
576- messages = compactHistory(l.ctx, l.e, l.keep, messages, true)
577- save(l.keep, messages)
578- case command.New:
579- messages = startNewSession(l.e, l.d, l.system, messages)
580- l.keep.Renew()
581- case command.Sessions:
582- fmt.Println(l.keep.Listing())
583- case command.Help:
584- fmt.Println(command.Usage(command.Terminal))
585- case command.Copy:
586- fmt.Println(copyAnswer(messages, arg, clipboard.New(terminalOSC52())))
587- case command.Save:
588- fmt.Println(saved.Command(modelAnswers(messages), arg))
589- case command.Unload:
590- fmt.Println("🧹 " + l.e.Unload(l.ctx, arg))
591- case command.Memory:
592- fmt.Println(l.keep.Memory(arg, messages))
593- case command.Docs:
594- fmt.Println(docsearch.Answer("", arg, 0))
595- case command.Resume:
596- resumed, line, err := l.keep.Resume(arg, agentsmd.System(l.system, ""))
597- if err != nil {
598- fmt.Println("⚠️ " + err.Error())
599- record(l.keep, messages, store.NewFailure(messages, store.FailResume, err.Error(), err))
600- break
601- }
602- messages = resumed
603- l.d.Reset()
604- l.e.ForgetInputTokens()
605- tools.ClearPlans("") // the plans in memory were the previous conversation's
606- fmt.Println(line)
607- default:
608- return messages, false
216+ if err != nil {
217+ fmt.Println("⚠️ " + err.Error())
218+ return true
609219 }
610- return messages, true
220+ r.messages = a2aLine(r.ctx, req, r.messages, r.sigCh)
221+ save(r.keep, r.messages)
222+ return true
611223 }
612224
613225 // RunPrompt executes a single prompt and displays the result. This is the
@@ -621,49 +233,22 @@ func (l *loop) historyCommand(input string, messages []*ai.Message) ([]*ai.Messa
621233 // was parsed). A turn stopped on purpose by a preGeneration hook is an answer:
622234 // 0.
623235 //
624-// os.Exit(agent.RunPrompt(ctx, e, cfg.System, tools, detector, "list the files"))
625-func RunPrompt(ctx context.Context, e *engine.Engine, system string, tools []ai.ToolRef, d *detector.LoopDetector, prompt string) int {
626- messages := session.Fresh(agentsmd.System(system, ""))
627-
628- // Add the user's prompt to the history
236+// os.Exit(agent.RunPrompt(ctx, agent.Setup{Engine: e, System: cfg.System, Tools: tools}, "list the files"))
237+func RunPrompt(ctx context.Context, s Setup, prompt string) int {
238+ messages := session.Fresh(agentsmd.System(s.System, ""))
629239 messages = append(messages, ai.NewUserTextMessage(prompt))
630240 before := len(messages)
631241
632242 fmt.Println()
633243
634- // Execute generation
635- resp, history, err := e.Generate(ctx, messages, tools)
244+ resp, history, err := s.Engine.Generate(ctx, messages, s.Tools)
636245 if err != nil {
637246 fmt.Printf("⚠️ Generation failed: %v\n", err)
638247 return 1
639248 }
640249
641- // Display command stats like the regular mode
642- turn := history[min(before, len(history)):]
643- cmds := engine.CommandList(turn)
644- ops := engine.FileOps(turn)
645- line := fmt.Sprintf("⚙ %d command(s)", len(cmds))
646- if len(ops) > 0 {
647- line += fmt.Sprintf(" · 📝 %d file op(s)", len(ops))
648- }
649- if engine.SkillsAvailable() {
650- line += fmt.Sprintf(" · 📖 %d skill(s)", engine.Skills(turn))
651- }
652- if k := engine.LSPCalls(turn); k > 0 {
653- line += fmt.Sprintf(" · 🔎 %d lsp call(s)", k)
654- }
655- if spinner.Styled() {
656- fmt.Printf("\033[2m%s\033[0m\n", line)
657- } else {
658- fmt.Println(line)
659- }
660- if config.Cfg.DisplayCommands {
661- printCommands(cmds)
662- printCommands(ops)
663- }
664- printHookRuns(os.Stdout)
665-
666- // Display the response
250+ // The command stats, like the regular mode, then the answer.
251+ printTurnStats(history[min(before, len(history)):])
667252 if resp != nil && resp.Message != nil {
668253 for _, part := range resp.Message.Content {
669254 fmt.Print(part.Text)
@@ -12,46 +12,38 @@ import (
12 12
13 "mm/internal/agentsmd"13 "mm/internal/agentsmd"
14 "mm/internal/ask"14 "mm/internal/ask"
15- "mm/internal/clipboard"
16 "mm/internal/command"15 "mm/internal/command"
17- "mm/internal/compact"
18- "mm/internal/config"
19 "mm/internal/consent"16 "mm/internal/consent"
20- "mm/internal/decide"
21 "mm/internal/detector"17 "mm/internal/detector"
22- "mm/internal/docsearch"
23 "mm/internal/elicit"18 "mm/internal/elicit"
24 "mm/internal/engine"19 "mm/internal/engine"
25- "mm/internal/hooks"
26- "mm/internal/mention"
27- "mm/internal/saved"
28 "mm/internal/session"20 "mm/internal/session"
29- "mm/internal/skills"
30 "mm/internal/spinner"21 "mm/internal/spinner"
31 "mm/internal/store"22 "mm/internal/store"
32- "mm/internal/tools"
33 23
34 "github.com/firebase/genkit/go/ai"24 "github.com/firebase/genkit/go/ai"
35 )25 )
36 26
37-type genResult struct {27+// Setup is what an agent runs with: the engine, the system prompt as the
38- resp *ai.ModelResponse28+// config gives it (AGENTS.md is added at the start of each conversation),
39- // history is the FULL conversation returned by engine.Generate — tool turns29+// the tools the model may call and the loop detector watching them.
40- // included. Genkit only hands back the last message; without this field the30+//
41- // agent forgets the commands it just ran and starts telling stories instead31+// agent.Run(ctx, agent.Setup{Engine: e, System: cfg.System, Tools: tools, Detector: d}, pool)
42- // of re-reading.32+type Setup struct {
43- history []*ai.Message33+ Engine *engine.Engine
44- err error34+ System string
35+ Tools []ai.ToolRef
36+ Detector *detector.LoopDetector
45 }37 }
46 38
47 // Run starts the loop: read user input → generate (with automatic tool calls) →39 // Run starts the loop: read user input → generate (with automatic tool calls) →
48 // print → start over, keeping the history.40 // print → start over, keeping the history.
49 //41 //
50 // pool runs the /ask commands (another mm agent); nil when none is configured.42 // pool runs the /ask commands (another mm agent); nil when none is configured.
51-func Run(ctx context.Context, e *engine.Engine, system string, tools []ai.ToolRef, d *detector.LoopDetector, pool ask.Runner) {43+func Run(ctx context.Context, s Setup, pool ask.Runner) {
52 // The project's AGENTS.md joins the prompt at the start of every44 // The project's AGENTS.md joins the prompt at the start of every
53 // conversation — here, /new and /resume — never in the middle of one.45 // conversation — here, /new and /resume — never in the middle of one.
54- messages := session.Fresh(agentsmd.System(system, ""))46+ messages := session.Fresh(agentsmd.System(s.System, ""))
55 ctx, cancelAll := context.WithCancel(ctx)47 ctx, cancelAll := context.WithCancel(ctx)
56 defer cancelAll()48 defer cancelAll()
57 49
@@ -60,554 +52,174 @@ func Run(ctx context.Context, e *engine.Engine, system string, tools []ai.ToolRe
60 // tool's own working directory.52 // tool's own working directory.
61 cwd, _ := os.Getwd()53 cwd, _ := os.Getwd()
62 54
63- // Persistence, when on (config `sessions`): this run is a new session,55+ r := &repl{
64- // saved from its first turn; earlier ones are a /resume away. See56+ Setup: s, ctx: ctx, pool: pool, cwd: cwd, messages: messages,
65- // store.Keeper.57+ // Persistence, when on (config `sessions`): this run is a new
66- keep := store.NewKeeper(cwd)58+ // session, saved from its first turn; earlier ones are a /resume
67-59+ // away. See store.Keeper.
68- // sigCh captures Ctrl+C (SIGINT).60+ keep: store.NewKeeper(cwd),
69- sigCh := make(chan os.Signal, 1)61+ // sigCh captures Ctrl+C (SIGINT).
70- signal.Notify(sigCh, os.Interrupt)62+ sigCh: make(chan os.Signal, 1),
71-63+ // inputCh receives every line typed — or piped — from the reader
72- // inputCh receives commands from the reader goroutine.64+ // goroutine.
73- inputCh := make(chan string)65+ inputCh: make(chan string),
66+ // The permission prompt (yolo: false, MCP tools marked "ask"): the
67+ // tools post their question, the waiting room prints it and routes
68+ // the next typed line to it. The ask_user tool's questions take the
69+ // same way.
70+ prompt: newLinePrompt(),
71+ // queue holds what was typed during a generation (ticket 155): it
72+ // runs here, in order, before anything new is read.
73+ queue: &inbox{},
74+ }
75+ signal.Notify(r.sigCh, os.Interrupt)
76+ go readInput(ctx, os.Stdin, r.inputCh)
77+ defer consent.SetPrompter(r.prompt.allow)()
78+ defer elicit.SetPrompter(r.prompt.ask)()
74 79
75- // The reader goroutine: every line typed — or piped — goes to inputCh.80+ r.greet()
76- go readInput(ctx, os.Stdin, inputCh)81+ for r.step() {
82+ }
83+}
77 84
78- // The permission prompt (yolo: false, MCP tools marked "ask"): the tools85+// repl is the line mode's state between two turns: the setup, the
79- // post their question, the waiting rooms below print it and route the86+// conversation, where its lines come from and where they wait.
80- // next typed line to it.87+type repl struct {
81- prompt := newLinePrompt()88+ Setup
82- defer consent.SetPrompter(prompt.allow)()89+ ctx context.Context
83- // The ask_user tool's questions take the same way.90+ pool ask.Runner
84- defer elicit.SetPrompter(prompt.ask)()91+ cwd string
92+ keep *store.Keeper
93+ sigCh chan os.Signal
94+ inputCh chan string
95+ prompt *linePrompt
96+ queue *inbox
97+ messages []*ai.Message
98+}
85 99
100+// greet prints the commands and where the sessions go.
101+func (r *repl) greet() {
86 fmt.Println(`Agent ready. Commands: "/quit" to exit, "/abort" to stop current generation, "/compact" to compress the history, "/new" to start a new session, "/sessions" and "/resume" for stored sessions, "/help" to list them.`)102 fmt.Println(`Agent ready. Commands: "/quit" to exit, "/abort" to stop current generation, "/compact" to compress the history, "/new" to start a new session, "/sessions" and "/resume" for stored sessions, "/help" to list them.`)
87 fmt.Println(`Shortcut: Ctrl+C to abort generation, or Ctrl+C at prompt to quit.`)103 fmt.Println(`Shortcut: Ctrl+C to abort generation, or Ctrl+C at prompt to quit.`)
88- if hint := keep.Hint(); hint != "" {104+ if hint := r.keep.Hint(); hint != "" {
89 dimln(hint)105 dimln(hint)
90 }106 }
91-
92- generating := false
93- // queue holds what was typed during a generation (ticket 155): it runs
94- // here, in order, before anything new is read.
95- queue := &inbox{}
96-
97- for {
98- fmt.Print("\n> ")
99-
100- // 1. Take the next queued line, else wait for the next user input OR
101- // a quit signal. A queued line is echoed after the prompt, so the
102- // transcript reads as if it had been typed there.
103- input, queued := queue.pop()
104- var ok bool
105-
106- if queued {
107- fmt.Println(input)
108- } else {
109- select {
110- case <-sigCh:
111- if !generating {
112- fmt.Println("\nGoodbye.")
113- return
114- }
115- // If generating, we let the generation loop handle the SIGINT.
116- // We fall through to wait for the next input (which will be the prompt).
117- case input, ok = <-inputCh:
118- if !ok {
119- return
120- }
121- }
122- }
123-
124- // 2. Basic Command Handling — the names come from the shared table
125- // (internal/command), the same one the editor and the window read.
126- if command.Is(input, command.Quit) {
127- break
128- }
129- if input == "" {
130- continue
131- }
132- if command.Is(input, command.Abort) {
133- spinner.Stop()
134- fmt.Println("⚠️ No generation in progress.")
135- continue
136- }
137- // /queue between two turns: nothing to wait for, the question runs.
138- if q, isQueue := queueArg(input); isQueue {
139- if q == "" {
140- fmt.Println(queueNeedsQuestion)
141- continue
142- }
143- input = q
144- }
145- // The commands that move the history — /compact, /new, /sessions,
146- // /resume — are only reachable here, between two generations: Genkit
147- // holds its own copy of the conversation while it runs, and a
148- // tool_call/tool_result pair in flight must not move under it. Typed
149- // DURING a generation, such a command waits in the queue (ticket 155)
150- // and comes back here once the turn has settled — so it always
151- // applies to the finished history.
152- // /ask-bob and its family: another agent answers, and its answer
153- // joins the history for the next question. Between two generations
154- // too, for the same reason as the commands below.
155- if req, ok, err := command.ParseAsk(input); ok {
156- if err != nil {
157- fmt.Println("⚠️ " + err.Error())
158- continue
159- }
160- var quit bool
161- messages, quit = asking{pool: pool, cwd: cwd, keep: keep, sigCh: sigCh, inputCh: inputCh, prompt: prompt, queue: queue}.run(ctx, req, messages)
162- if quit {
163- fmt.Println("Goodbye.")
164- return
165- }
166- continue
167- }
168- // /a2a-alice: a remote A2A agent answers (ticket 263), its answer
169- // joins the history like /ask's.
170- if req, ok, err := command.ParseA2A(input); ok {
171- if err != nil {
172- fmt.Println("⚠️ " + err.Error())
173- continue
174- }
175- messages = a2aLine(ctx, req, messages, sigCh)
176- save(keep, messages)
177- continue
178- }
179- if next, handled := (&loop{ctx: ctx, e: e, d: d, keep: keep, system: system}).historyCommand(input, messages); handled {
180- messages = next
181- continue
182- }
183-
184- // 3. Normal message: Add to history and start generation.
185- //
186- // The automatic compression runs BEFORE the question is appended and
187- // BEFORE `before` is computed: that index is what the rollback
188- // (`messages[:before-1]`) and the ⚙ line (`res.history[before:]`)
189- // rely on, and a history that shrinks after it is taken would break
190- // both. The server's own count of the last context is preferred to
191- // the estimate when it is larger — it sees the tools' JSON and the
192- // chat template, which the estimate cannot. The window is the one the
193- // Engine knows: the yaml's contextWindow, or what the probe learned.
194- //
195- // That probe ran once, at start-up. A llama-server started AFTER bob
196- // left `ctx: unknown` for the whole session — observed — and the
197- // compression could then only trigger on maxMessages. So, while the
198- // window is unknown and compression is on, ask the server again
199- // before deciding; once known, never again. A probe that still
200- // fails prints nothing: the start-up warning already said so.
201- if c := config.Cfg.Context; c.Enabled && e.ContextWindow == 0 {
202- if w, src := e.EnsureContextWindow(ctx); w > 0 {
203- dimln(fmt.Sprintf("ctx: %d (%s)", w, src))
204- }
205- }
206- if dec := compact.Decide(messages, e.LastInputTokens(), e.ContextWindow, config.Cfg.Context); dec.Compact {
207- messages = compactHistory(ctx, e, keep, messages, false)
208- save(keep, messages)
209- }
210- // "@path" in the question names a file for the model to look at. The
211- // text stays as typed; each existing path is appended as an
212- // [attached file: …] line — what an editor's @-mention becomes over
213- // ACP — and echoed here so the user sees the notation was understood.
214- typed := input
215- input, attached := mention.Expand(input, cwd)
216- for _, a := range attached {
217- dimln("📎 " + a.Path)
218- }
219- // "$skill" names a procedure to carry out, with the rest of the line
220- // as its parameters — the same notation the window's `$` picker
221- // writes, so it means the same thing typed by hand.
222- input, refs := skills.ExpandRefs(input, skills.Declared())
223- for _, ref := range refs {
224- dimln("📖 $" + ref.Name)
225- }
226- // No `$skill` named: the decider, when there is one, may pick it.
227- input, routed := decide.RouteSkill(ctx, typed, input, len(refs), skills.Declared())
228- if routed != "" {
229- dimln(routed)
230- }
231- messages = append(messages, ai.NewUserTextMessage(input))
232- before := len(messages)
233- fmt.Println()
234-
235- // Create a cancellable context for this specific generation cycle.
236- genCtx, cancelGen := context.WithCancel(ctx)
237- generating = true
238-
239- // Hooks that ran outside a turn (an /ask) are not this turn's.
240- hooks.Turn.Take()
241-
242- // A question typed during the turn steers it (ticket 265).
243- steer := newTurnSteer(cwd)
244- steerCtx := steer.context(genCtx)
245-
246- // Launch generation in a goroutine.
247- resultCh := make(chan genResult, 1)
248- go func() {
249- resp, history, err := e.Generate(steerCtx, messages, tools)
250- resultCh <- genResult{resp: resp, history: history, err: err}
251- }()
252-
253- // 4. The "Waiting Room": Listen for completion, interruption, OR new
254- // command. typing goes nil when stdin closes (the end of a pipe), so
255- // the closed channel is not read in a loop; the main loop sees the
256- // end of the input once the queue is empty.
257- typing := inputCh
258- generationRunning := true
259- for generationRunning {
260- select {
261- case res := <-resultCh:
262- generationRunning = false
263- generating = false
264- prompt.drop()
265-
266- // We take the FULL history returned by engine.Generate, not just
267- // resp.Message — and we take it EVEN when the generation failed
268- // or was interrupted: on an abort (Ctrl+C, /abort), a maxTurns
269- // overrun or a silence caught by the watchdog, all the work of
270- // the turn is in `history`, and Genkit itself returns nothing.
271- // (resp.History() will not do: empty on the streamed path.)
272- asked := messages // question included, for the error record below
273- messages = session.AfterTurn(messages, before, res.resp, res.history, res.err)
274- save(keep, messages)
275-
276- if res.err != nil {
277- if genCtx.Err() == context.Canceled {
278- fmt.Println("\n🔴 Generation aborted.")
279- } else {
280- // One line, in the provider's words: see engine.Explain —
281- // and the same line in the session file, for whoever
282- // asks later why this turn failed.
283- explained := e.Explain(res.err)
284- fmt.Println("\n[error: " + explained + "]")
285- record(keep, messages, store.NewFailure(asked, store.FailGeneration, explained, res.err))
286- }
287- } else {
288- // --- Global Loop Detection ---
289- // We check the tool calls in the model response.
290- if res.resp != nil && res.resp.Message != nil {
291- for _, part := range res.resp.Message.Content {
292- if part.IsToolRequest() && part.ToolRequest != nil {
293- d.Record(detector.Action{
294- ToolName: part.ToolRequest.Name,
295- Input: fmt.Sprintf("%v", part.ToolRequest.Input),
296- Output: "[tool_call]",
297- })
298- }
299- }
300- }
301- fmt.Println()
302- }
303-
304- // The command count is the only visible proof that the model
305- // worked rather than improvised. Zero is normal on a
306- // conversational question; zero on "read this file" is not.
307- turn := res.history[min(before, len(res.history)):]
308- cmds := engine.CommandList(turn)
309- ops := engine.FileOps(turn)
310- line := fmt.Sprintf("⚙ %d command(s)", len(cmds))
311- // The file tools have their own column: the A/B of this part
312- // is "edits through bash" versus "edits through tools", and
313- // a single number would add up what it is meant to separate.
314- if len(ops) > 0 {
315- line += fmt.Sprintf(" · 📝 %d file op(s)", len(ops))
316- }
317- // Always shown when the agent has skills, 0 included: see
318- // engine.SkillsAvailable.
319- if engine.SkillsAvailable() {
320- line += fmt.Sprintf(" · 📖 %d skill(s)", engine.Skills(turn))
321- }
322- if k := engine.LSPCalls(turn); k > 0 {
323- line += fmt.Sprintf(" · 🔎 %d lsp call(s)", k)
324- }
325- if spinner.Styled() {
326- fmt.Printf("\033[2m%s\033[0m\n", line)
327- } else {
328- fmt.Println(line)
329- }
330- if config.Cfg.DisplayCommands {
331- printCommands(cmds)
332- printCommands(ops)
333- }
334- printHookRuns(os.Stdout)
335- // Questions sent after the model's last call run next.
336- if late := steer.late(); len(late) > 0 {
337- queue.pushFront(late)
338- fmt.Printf("⏳ %d message(s) came after the model's last call — sent as the next question\n", len(late))
339- }
340-
341- case <-sigCh:
342- // Handle Ctrl+C during generation.
343- // Stop() first: the spinner is running during the generation,
344- // and without it this message lands on its line — the next
345- // frame would erase it. Same rule as in dmr.emit.
346- spinner.Stop()
347- prompt.drop()
348- fmt.Println("\n🔴 Interrupted (Ctrl+C).")
349- cancelGen()
350- // We don't set generationRunning=false; we wait for resultCh to catch the Canceled error.
351-
352- case req := <-prompt.requestCh():
353- prompt.show(req)
354-
355- case nextInput, open := <-typing:
356- if !open {
357- typing = nil
358- continue
359- }
360- // A line typed while a tool waits for permission is its answer;
361- // /abort and /quit stop the turn; anything else waits for it.
362- if prompt.answer(nextInput) {
363- continue
364- }
365- switch {
366- case command.Is(nextInput, command.Abort):
367- prompt.drop()
368- spinner.Stop() // le spinner tourne : on lui reprend la ligne
369- cancelGen()
370- fmt.Println("🔴 Aborting...")
371- case command.Is(nextInput, command.Quit):
372- prompt.drop()
373- spinner.Stop()
374- cancelGen()
375- fmt.Println("Goodbye.")
376- return
377- default:
378- // Ticket 265: a question steers the turn — the model reads
379- // it after its current step. A slash command, and
380- // `/queue <question>`, wait in the queue and run once the
381- // turn has settled (ticket 155).
382- if q, isQueue := queueArg(nextInput); isQueue {
383- if q == "" {
384- spinner.Stop()
385- fmt.Println("\n" + queueNeedsQuestion)
386- continue
387- }
388- nextInput = q
389- } else if notice, steered := steer.offer(nextInput); steered {
390- spinner.Stop()
391- fmt.Println("\n" + notice)
392- continue
393- }
394- if notice := queue.push(nextInput); notice != "" {
395- spinner.Stop()
396- fmt.Println("\n" + notice)
397- }
398- }
399- }
400- }
401- // Final cleanup for this cycle.
402- cancelGen()
403- }
404 }107 }
405 108
406-// printCommands recaps the commands of the turn, in green.109+// step reads one line at the prompt and acts on it: a command, or a turn.
407-//110+// It reports whether the loop goes on — false on /quit, Ctrl+C at the
408-// The count says HOW MANY, the list says WHAT: it reads at a glance once the111+// prompt, or the end of the input.
409-// answer is written, whereas the 🛠️ lines are scattered through the output of112+func (r *repl) step() bool {
410-// the commands. Green separates it from both the grey of the tools and the113+ fmt.Print("\n> ")
411-// model's own text — and it only comes out on a terminal, like every other114+ input, ok := r.next()
412-// colour here.115+ // The names come from the shared table (internal/command), the same one
413-func printCommands(cmds []string) {116+ // the editor and the window read.
414- if len(cmds) == 0 {117+ if !ok || command.Is(input, command.Quit) {
415- return118+ return false
416 }119 }
417- green, off := "", ""120+ input, ok = r.question(input)
418- if spinner.Styled() {121+ if !ok {
419- green, off = "\033[32m", "\033[0m"122+ return true
420 }123 }
421-124+ if handled, quit := r.command(input); handled {
422- var b strings.Builder125+ return !quit
423- for i, c := range cmds {
424- b.WriteString(green + fmt.Sprintf(" %d. %s", i+1, oneLine(c)) + off + "\n")
425 }126 }
426- fmt.Print(b.String())127+ return r.turn(input)
427 }128 }
428 129
429-// printHookRuns lists, under the commands, the hooks that ran during the turn130+// next is the next queued line, else the next line typed. A queued line is
430-// (hooks.Turn) when displayHooks is on — in the same colour, so the recap of a131+// echoed after the prompt, so the transcript reads as if it had been typed
431-// turn reads as one block.132+// there. ok is false on Ctrl+C (Goodbye) and at the end of the input.
432-//133+func (r *repl) next() (string, bool) {
433-// 🪝 1. preGeneration · node "$MM_CONFIG_DIR/hooks/guards.js" → context (214 chars)134+ if input, queued := r.queue.pop(); queued {
434-func printHookRuns(w io.Writer) {135+ fmt.Println(input)
435- if !config.Cfg.DisplayHooks {136+ return input, true
436- return
437 }137 }
438- green, off := "", ""138+ select {
439- if spinner.Styled() {139+ case <-r.sigCh:
440- green, off = "\033[32m", "\033[0m"140+ fmt.Println("\nGoodbye.")
441- }141+ return "", false
442- for _, line := range hooks.Lines(hooks.Turn.Take()) {142+ case input, ok := <-r.inputCh:
443- _, _ = fmt.Fprintln(w, green+" "+line+off)143+ return input, ok
444 }144 }
445 }145 }
446 146
447-// maxCommandWidth is the width beyond which a command is cut. A hundred147+// question is the line as a question: nothing for an empty line or /abort
448-// columns: that fits a demo terminal without overflowing it.148+// (there is no generation to stop), and the question of /queue — between
449-const maxCommandWidth = 100149+// two turns, nothing to wait for, it runs now.
450-150+func (r *repl) question(input string) (string, bool) {
451-// oneLine folds a command onto ONE line and truncates it when needed.151+ if input == "" {
452-//152+ return "", false
453-// A command can be long and span several lines — a heredoc, a trailing &&. The
454-// recap is there to scan what the agent did, not to re-read its code: spread
455-// over several lines it would grow longer than the output it summarises, and
456-// the numbering would stop being readable.
457-func oneLine(s string) string {
458- // Fields splits on ALL whitespace, line breaks included: that is exactly
459- // the folding we want, heredoc indentation and all.
460- s = strings.Join(strings.Fields(s), " ")
461- r := []rune(s)
462- if len(r) <= maxCommandWidth {
463- return s
464 }153 }
465- return string(r[:maxCommandWidth-1]) + "…"154+ if command.Is(input, command.Abort) {
466-}155+ spinner.Stop()
467-156+ fmt.Println("⚠️ No generation in progress.")
468-// compactHistory replaces the old turns of `msgs` by a model-written summary157+ return "", false
469-// and says so in one line. On ANY failure — server down, watchdog, empty or
470-// malformed result — it returns `msgs` unchanged: the compression exists to
471-// keep the next question possible, so it must never cost one.
472-//
473-// `forced` is the /compact command: it skips the threshold, not the "is there
474-// anything older than the kept turns" check, and it says so when there is not.
475-// The loop detector is deliberately not touched: it records what the agent
476-// DOES, and forgetting a conversation does not make a repeated command new.
477-func compactHistory(ctx context.Context, e *engine.Engine, keep *store.Keeper, msgs []*ai.Message, forced bool) []*ai.Message {
478- cfg := config.Cfg.Context
479-
480- // The summary is the longest prefill of the session and prints nothing
481- // while it runs: without a label the agent looks hung, exactly the case
482- // the spinner exists for.
483- spinner.Start("Compressing")
484- out, line, outcome := compact.Apply(ctx, msgs, cfg, func(ctx context.Context, request []*ai.Message) (string, error) {
485- return e.Summarize(ctx, request, cfg.SummaryMaxTokens)
486- }, e.Explain)
487- spinner.Stop()
488-
489- switch outcome {
490- case compact.Nothing:
491- if forced {
492- dimln(line)
493- }
494- case compact.Failed:
495- fmt.Println(line)
496- record(keep, msgs, store.NewFailure(msgs, store.FailCompaction, line, nil))
497- case compact.Compressed:
498- // The server's last measure described the history we just replaced.
499- e.ForgetInputTokens()
500- if cfg.ShowStats {
501- dimln(line)
502- }
503 }158 }
504- return out159+ q, isQueue := queueArg(input)
505-}160+ if !isQueue {
506-161+ return input, true
507-// save rewrites the session file and reports a failure in one line: a
508-// read-only project still gets an agent.
509-func save(keep *store.Keeper, msgs []*ai.Message) {
510- if err := keep.Save(msgs); err != nil {
511- fmt.Println("[sessions: not saved: " + err.Error() + "]")
512 }162 }
513-}163+ if q == "" {
514-164+ fmt.Println(queueNeedsQuestion)
515-// record writes the error just printed into the session file (see165+ return "", false
516-// store.Keeper.Fail): the red line on screen is gone with the scrollback,
517-// the file keeps it for whoever investigates the run later.
518-func record(keep *store.Keeper, msgs []*ai.Message, f store.Failure) {
519- if err := keep.Fail(msgs, f); err != nil {
520- fmt.Println("[sessions: error not recorded: " + err.Error() + "]")
521 }166 }
167+ return q, true
522 }168 }
523 169
524-// startNewSession forgets the conversation and returns the history of a fresh170+// command runs the commands that move the history — /ask, /a2a, /compact,
525-// one: the system prompt alone. Three things make up "the session" here, and171+// /new, /sessions, /resume… — and reports whether input was one, and
526-// all three are reset — the messages, the server's token count of the last172+// whether /quit was typed meanwhile.
527-// context (it described a history that no longer exists, same rule as after a
528-// compression), and the loop detector (a new session is a new task: a command
529-// repeated in the old one must not be flagged as a loop in this one — the
530-// opposite of compactHistory's choice, where the task continues).
531 //173 //
532-// It says in one line how much was forgotten, so a /new on an empty session174+// They are only reachable here, between two generations: Genkit holds its
533-// visibly did nothing rather than silently nothing.175+// own copy of the conversation while it runs, and a tool_call/tool_result
534-func startNewSession(e *engine.Engine, d *detector.LoopDetector, system string, old []*ai.Message) []*ai.Message {176+// pair in flight must not move under it. Typed DURING a generation, such a
535- forgotten := session.Forgotten(old)177+// command waits in the queue (ticket 155) and comes back here once the turn
536- e.ForgetInputTokens()178+// has settled — so it always applies to the finished history.
537- d.Reset()179+func (r *repl) command(input string) (handled, quit bool) {
538- // Plans belong to the conversation /new just closed (ticket 109).180+ if handled, quit := r.askCommand(input); handled {
539- tools.ClearPlans("")181+ return true, quit
540- dimln(fmt.Sprintf("🆕 new session: %d message(s) forgotten", forgotten))
541- return session.Fresh(agentsmd.System(system, ""))
542-}
543-
544-// dimln prints one line, dimmed on a terminal and plain in a pipe — the same
545-// rule as the ⚙ line: `bob | jq` must not receive escape codes.
546-func dimln(line string) {
547- if spinner.Styled() {
548- fmt.Printf("\033[2m%s\033[0m\n", line)
549- } else {
550- fmt.Println(line)
551 }182 }
183+ if r.a2aCommand(input) {
184+ return true, false
185+ }
186+ next, handled := (&loop{ctx: r.ctx, e: r.Engine, d: r.Detector, keep: r.keep, system: r.System}).historyCommand(input, r.messages)
187+ r.messages = next
188+ return handled, false
552 }189 }
553 190
554-// loop is what the REPL's commands act on: the engine, the loop detector,191+// askCommand runs /ask-bob and its family: another agent answers, and its
555-// the session keeper and the system prompt Run was given.192+// answer joins the history for the next question.
556-type loop struct {193+func (r *repl) askCommand(input string) (handled, quit bool) {
557- ctx context.Context194+ req, ok, err := command.ParseAsk(input)
558- e *engine.Engine195+ if !ok {
559- d *detector.LoopDetector196+ return false, false
560- keep *store.Keeper197+ }
561- system string198+ if err != nil {
199+ fmt.Println("⚠️ " + err.Error())
200+ return true, false
201+ }
202+ r.messages, quit = asking{pool: r.pool, cwd: r.cwd, keep: r.keep, sigCh: r.sigCh, inputCh: r.inputCh, prompt: r.prompt, queue: r.queue}.run(r.ctx, req, r.messages)
203+ if quit {
204+ fmt.Println("Goodbye.")
205+ }
206+ return true, quit
562 }207 }
563 208
564-// historyCommand runs the slash commands that replace the history — /compact,209+// a2aCommand runs /a2a-alice: a remote A2A agent answers (ticket 263), its
565-// /new, and the stored-session pair /sessions and /resume — plus /help, and210+// answer joins the history like /ask's.
566-// reports whether input was one of them. Run only calls it between two211+func (r *repl) a2aCommand(input string) bool {
567-// generations. A resumed session is a new task for the loop detector too,212+ req, ok, err := command.ParseA2A(input)
568-// and the server's token count described another history.
569-func (l *loop) historyCommand(input string, messages []*ai.Message) ([]*ai.Message, bool) {
570- cmd, arg, ok := command.Parse(input)
571 if !ok {213 if !ok {
572- return messages, false214+ return false
573 }215 }
574- switch cmd.Name {216+ if err != nil {
575- case command.Compact:217+ fmt.Println("⚠️ " + err.Error())
576- messages = compactHistory(l.ctx, l.e, l.keep, messages, true)218+ return true
577- save(l.keep, messages)
578- case command.New:
579- messages = startNewSession(l.e, l.d, l.system, messages)
580- l.keep.Renew()
581- case command.Sessions:
582- fmt.Println(l.keep.Listing())
583- case command.Help:
584- fmt.Println(command.Usage(command.Terminal))
585- case command.Copy:
586- fmt.Println(copyAnswer(messages, arg, clipboard.New(terminalOSC52())))
587- case command.Save:
588- fmt.Println(saved.Command(modelAnswers(messages), arg))
589- case command.Unload:
590- fmt.Println("🧹 " + l.e.Unload(l.ctx, arg))
591- case command.Memory:
592- fmt.Println(l.keep.Memory(arg, messages))
593- case command.Docs:
594- fmt.Println(docsearch.Answer("", arg, 0))
595- case command.Resume:
596- resumed, line, err := l.keep.Resume(arg, agentsmd.System(l.system, ""))
597- if err != nil {
598- fmt.Println("⚠️ " + err.Error())
599- record(l.keep, messages, store.NewFailure(messages, store.FailResume, err.Error(), err))
600- break
601- }
602- messages = resumed
603- l.d.Reset()
604- l.e.ForgetInputTokens()
605- tools.ClearPlans("") // the plans in memory were the previous conversation's
606- fmt.Println(line)
607- default:
608- return messages, false
609 }219 }
610- return messages, true220+ r.messages = a2aLine(r.ctx, req, r.messages, r.sigCh)
221+ save(r.keep, r.messages)
222+ return true
611 }223 }
612 224
613 // RunPrompt executes a single prompt and displays the result. This is the225 // RunPrompt executes a single prompt and displays the result. This is the
@@ -621,49 +233,22 @@ func (l *loop) historyCommand(input string, messages []*ai.Message) ([]*ai.Messa
621 // was parsed). A turn stopped on purpose by a preGeneration hook is an answer:233 // was parsed). A turn stopped on purpose by a preGeneration hook is an answer:
622 // 0.234 // 0.
623 //235 //
624-// os.Exit(agent.RunPrompt(ctx, e, cfg.System, tools, detector, "list the files"))236+// os.Exit(agent.RunPrompt(ctx, agent.Setup{Engine: e, System: cfg.System, Tools: tools}, "list the files"))
625-func RunPrompt(ctx context.Context, e *engine.Engine, system string, tools []ai.ToolRef, d *detector.LoopDetector, prompt string) int {237+func RunPrompt(ctx context.Context, s Setup, prompt string) int {
626- messages := session.Fresh(agentsmd.System(system, ""))238+ messages := session.Fresh(agentsmd.System(s.System, ""))
627-
628- // Add the user's prompt to the history
629 messages = append(messages, ai.NewUserTextMessage(prompt))239 messages = append(messages, ai.NewUserTextMessage(prompt))
630 before := len(messages)240 before := len(messages)
631 241
632 fmt.Println()242 fmt.Println()
633 243
634- // Execute generation244+ resp, history, err := s.Engine.Generate(ctx, messages, s.Tools)
635- resp, history, err := e.Generate(ctx, messages, tools)
636 if err != nil {245 if err != nil {
637 fmt.Printf("⚠️ Generation failed: %v\n", err)246 fmt.Printf("⚠️ Generation failed: %v\n", err)
638 return 1247 return 1
639 }248 }
640 249
641- // Display command stats like the regular mode250+ // The command stats, like the regular mode, then the answer.
642- turn := history[min(before, len(history)):]251+ printTurnStats(history[min(before, len(history)):])
643- cmds := engine.CommandList(turn)
644- ops := engine.FileOps(turn)
645- line := fmt.Sprintf("⚙ %d command(s)", len(cmds))
646- if len(ops) > 0 {
647- line += fmt.Sprintf(" · 📝 %d file op(s)", len(ops))
648- }
649- if engine.SkillsAvailable() {
650- line += fmt.Sprintf(" · 📖 %d skill(s)", engine.Skills(turn))
651- }
652- if k := engine.LSPCalls(turn); k > 0 {
653- line += fmt.Sprintf(" · 🔎 %d lsp call(s)", k)
654- }
655- if spinner.Styled() {
656- fmt.Printf("\033[2m%s\033[0m\n", line)
657- } else {
658- fmt.Println(line)
659- }
660- if config.Cfg.DisplayCommands {
661- printCommands(cmds)
662- printCommands(ops)
663- }
664- printHookRuns(os.Stdout)
665-
666- // Display the response
667 if resp != nil && resp.Message != nil {252 if resp != nil && resp.Message != nil {
668 for _, part := range resp.Message.Content {253 for _, part := range resp.Message.Content {
669 fmt.Print(part.Text)254 fmt.Print(part.Text)
added internal/agent/history.go +156 -0
new file mode 100644
@@ -0,0 +1,156 @@
1+package agent
2+
3+import (
4+ "context"
5+ "fmt"
6+ "mm/internal/agentsmd"
7+ "mm/internal/clipboard"
8+ "mm/internal/command"
9+ "mm/internal/compact"
10+ "mm/internal/config"
11+ "mm/internal/detector"
12+ "mm/internal/docsearch"
13+ "mm/internal/engine"
14+ "mm/internal/saved"
15+ "mm/internal/session"
16+ "mm/internal/spinner"
17+ "mm/internal/store"
18+ "mm/internal/tools"
19+
20+ "github.com/firebase/genkit/go/ai"
21+)
22+
23+// compactHistory replaces the old turns of `msgs` by a model-written summary
24+// and says so in one line. On ANY failure — server down, watchdog, empty or
25+// malformed result — it returns `msgs` unchanged: the compression exists to
26+// keep the next question possible, so it must never cost one.
27+//
28+// `forced` is the /compact command: it skips the threshold, not the "is there
29+// anything older than the kept turns" check, and it says so when there is not.
30+// The loop detector is deliberately not touched: it records what the agent
31+// DOES, and forgetting a conversation does not make a repeated command new.
32+func compactHistory(ctx context.Context, e *engine.Engine, keep *store.Keeper, msgs []*ai.Message, forced bool) []*ai.Message {
33+ cfg := config.Cfg.Context
34+
35+ // The summary is the longest prefill of the session and prints nothing
36+ // while it runs: without a label the agent looks hung, exactly the case
37+ // the spinner exists for.
38+ spinner.Start("Compressing")
39+ out, line, outcome := compact.Apply(ctx, msgs, cfg, func(ctx context.Context, request []*ai.Message) (string, error) {
40+ return e.Summarize(ctx, request, cfg.SummaryMaxTokens)
41+ }, e.Explain)
42+ spinner.Stop()
43+
44+ switch outcome {
45+ case compact.Nothing:
46+ if forced {
47+ dimln(line)
48+ }
49+ case compact.Failed:
50+ fmt.Println(line)
51+ record(keep, msgs, store.NewFailure(msgs, store.FailCompaction, line, nil))
52+ case compact.Compressed:
53+ // The server's last measure described the history we just replaced.
54+ e.ForgetInputTokens()
55+ if cfg.ShowStats {
56+ dimln(line)
57+ }
58+ }
59+ return out
60+}
61+
62+// save rewrites the session file and reports a failure in one line: a
63+// read-only project still gets an agent.
64+func save(keep *store.Keeper, msgs []*ai.Message) {
65+ if err := keep.Save(msgs); err != nil {
66+ fmt.Println("[sessions: not saved: " + err.Error() + "]")
67+ }
68+}
69+
70+// record writes the error just printed into the session file (see
71+// store.Keeper.Fail): the red line on screen is gone with the scrollback,
72+// the file keeps it for whoever investigates the run later.
73+func record(keep *store.Keeper, msgs []*ai.Message, f store.Failure) {
74+ if err := keep.Fail(msgs, f); err != nil {
75+ fmt.Println("[sessions: error not recorded: " + err.Error() + "]")
76+ }
77+}
78+
79+// startNewSession forgets the conversation and returns the history of a fresh
80+// one: the system prompt alone. Three things make up "the session" here, and
81+// all three are reset — the messages, the server's token count of the last
82+// context (it described a history that no longer exists, same rule as after a
83+// compression), and the loop detector (a new session is a new task: a command
84+// repeated in the old one must not be flagged as a loop in this one — the
85+// opposite of compactHistory's choice, where the task continues).
86+//
87+// It says in one line how much was forgotten, so a /new on an empty session
88+// visibly did nothing rather than silently nothing.
89+func startNewSession(e *engine.Engine, d *detector.LoopDetector, system string, old []*ai.Message) []*ai.Message {
90+ forgotten := session.Forgotten(old)
91+ e.ForgetInputTokens()
92+ d.Reset()
93+ // Plans belong to the conversation /new just closed (ticket 109).
94+ tools.ClearPlans("")
95+ dimln(fmt.Sprintf("🆕 new session: %d message(s) forgotten", forgotten))
96+ return session.Fresh(agentsmd.System(system, ""))
97+}
98+
99+// loop is what the REPL's commands act on: the engine, the loop detector,
100+// the session keeper and the system prompt Run was given.
101+type loop struct {
102+ ctx context.Context
103+ e *engine.Engine
104+ d *detector.LoopDetector
105+ keep *store.Keeper
106+ system string
107+}
108+
109+// historyCommand runs the slash commands that replace the history — /compact,
110+// /new, and the stored-session pair /sessions and /resume — plus /help, and
111+// reports whether input was one of them. Run only calls it between two
112+// generations. A resumed session is a new task for the loop detector too,
113+// and the server's token count described another history.
114+func (l *loop) historyCommand(input string, messages []*ai.Message) ([]*ai.Message, bool) {
115+ cmd, arg, ok := command.Parse(input)
116+ if !ok {
117+ return messages, false
118+ }
119+ switch cmd.Name {
120+ case command.Compact:
121+ messages = compactHistory(l.ctx, l.e, l.keep, messages, true)
122+ save(l.keep, messages)
123+ case command.New:
124+ messages = startNewSession(l.e, l.d, l.system, messages)
125+ l.keep.Renew()
126+ case command.Sessions:
127+ fmt.Println(l.keep.Listing())
128+ case command.Help:
129+ fmt.Println(command.Usage(command.Terminal))
130+ case command.Copy:
131+ fmt.Println(copyAnswer(messages, arg, clipboard.New(terminalOSC52())))
132+ case command.Save:
133+ fmt.Println(saved.Command(modelAnswers(messages), arg))
134+ case command.Unload:
135+ fmt.Println("🧹 " + l.e.Unload(l.ctx, arg))
136+ case command.Memory:
137+ fmt.Println(l.keep.Memory(arg, messages))
138+ case command.Docs:
139+ fmt.Println(docsearch.Answer("", arg, 0))
140+ case command.Resume:
141+ resumed, line, err := l.keep.Resume(arg, agentsmd.System(l.system, ""))
142+ if err != nil {
143+ fmt.Println("⚠️ " + err.Error())
144+ record(l.keep, messages, store.NewFailure(messages, store.FailResume, err.Error(), err))
145+ break
146+ }
147+ messages = resumed
148+ l.d.Reset()
149+ l.e.ForgetInputTokens()
150+ tools.ClearPlans("") // the plans in memory were the previous conversation's
151+ fmt.Println(line)
152+ default:
153+ return messages, false
154+ }
155+ return messages, true
156+}
new file mode 100644
@@ -0,0 +1,156 @@
1+package agent
2+
3+import (
4+ "context"
5+ "fmt"
6+ "mm/internal/agentsmd"
7+ "mm/internal/clipboard"
8+ "mm/internal/command"
9+ "mm/internal/compact"
10+ "mm/internal/config"
11+ "mm/internal/detector"
12+ "mm/internal/docsearch"
13+ "mm/internal/engine"
14+ "mm/internal/saved"
15+ "mm/internal/session"
16+ "mm/internal/spinner"
17+ "mm/internal/store"
18+ "mm/internal/tools"
19+
20+ "github.com/firebase/genkit/go/ai"
21+)
22+
23+// compactHistory replaces the old turns of `msgs` by a model-written summary
24+// and says so in one line. On ANY failure — server down, watchdog, empty or
25+// malformed result — it returns `msgs` unchanged: the compression exists to
26+// keep the next question possible, so it must never cost one.
27+//
28+// `forced` is the /compact command: it skips the threshold, not the "is there
29+// anything older than the kept turns" check, and it says so when there is not.
30+// The loop detector is deliberately not touched: it records what the agent
31+// DOES, and forgetting a conversation does not make a repeated command new.
32+func compactHistory(ctx context.Context, e *engine.Engine, keep *store.Keeper, msgs []*ai.Message, forced bool) []*ai.Message {
33+ cfg := config.Cfg.Context
34+
35+ // The summary is the longest prefill of the session and prints nothing
36+ // while it runs: without a label the agent looks hung, exactly the case
37+ // the spinner exists for.
38+ spinner.Start("Compressing")
39+ out, line, outcome := compact.Apply(ctx, msgs, cfg, func(ctx context.Context, request []*ai.Message) (string, error) {
40+ return e.Summarize(ctx, request, cfg.SummaryMaxTokens)
41+ }, e.Explain)
42+ spinner.Stop()
43+
44+ switch outcome {
45+ case compact.Nothing:
46+ if forced {
47+ dimln(line)
48+ }
49+ case compact.Failed:
50+ fmt.Println(line)
51+ record(keep, msgs, store.NewFailure(msgs, store.FailCompaction, line, nil))
52+ case compact.Compressed:
53+ // The server's last measure described the history we just replaced.
54+ e.ForgetInputTokens()
55+ if cfg.ShowStats {
56+ dimln(line)
57+ }
58+ }
59+ return out
60+}
61+
62+// save rewrites the session file and reports a failure in one line: a
63+// read-only project still gets an agent.
64+func save(keep *store.Keeper, msgs []*ai.Message) {
65+ if err := keep.Save(msgs); err != nil {
66+ fmt.Println("[sessions: not saved: " + err.Error() + "]")
67+ }
68+}
69+
70+// record writes the error just printed into the session file (see
71+// store.Keeper.Fail): the red line on screen is gone with the scrollback,
72+// the file keeps it for whoever investigates the run later.
73+func record(keep *store.Keeper, msgs []*ai.Message, f store.Failure) {
74+ if err := keep.Fail(msgs, f); err != nil {
75+ fmt.Println("[sessions: error not recorded: " + err.Error() + "]")
76+ }
77+}
78+
79+// startNewSession forgets the conversation and returns the history of a fresh
80+// one: the system prompt alone. Three things make up "the session" here, and
81+// all three are reset — the messages, the server's token count of the last
82+// context (it described a history that no longer exists, same rule as after a
83+// compression), and the loop detector (a new session is a new task: a command
84+// repeated in the old one must not be flagged as a loop in this one — the
85+// opposite of compactHistory's choice, where the task continues).
86+//
87+// It says in one line how much was forgotten, so a /new on an empty session
88+// visibly did nothing rather than silently nothing.
89+func startNewSession(e *engine.Engine, d *detector.LoopDetector, system string, old []*ai.Message) []*ai.Message {
90+ forgotten := session.Forgotten(old)
91+ e.ForgetInputTokens()
92+ d.Reset()
93+ // Plans belong to the conversation /new just closed (ticket 109).
94+ tools.ClearPlans("")
95+ dimln(fmt.Sprintf("🆕 new session: %d message(s) forgotten", forgotten))
96+ return session.Fresh(agentsmd.System(system, ""))
97+}
98+
99+// loop is what the REPL's commands act on: the engine, the loop detector,
100+// the session keeper and the system prompt Run was given.
101+type loop struct {
102+ ctx context.Context
103+ e *engine.Engine
104+ d *detector.LoopDetector
105+ keep *store.Keeper
106+ system string
107+}
108+
109+// historyCommand runs the slash commands that replace the history — /compact,
110+// /new, and the stored-session pair /sessions and /resume — plus /help, and
111+// reports whether input was one of them. Run only calls it between two
112+// generations. A resumed session is a new task for the loop detector too,
113+// and the server's token count described another history.
114+func (l *loop) historyCommand(input string, messages []*ai.Message) ([]*ai.Message, bool) {
115+ cmd, arg, ok := command.Parse(input)
116+ if !ok {
117+ return messages, false
118+ }
119+ switch cmd.Name {
120+ case command.Compact:
121+ messages = compactHistory(l.ctx, l.e, l.keep, messages, true)
122+ save(l.keep, messages)
123+ case command.New:
124+ messages = startNewSession(l.e, l.d, l.system, messages)
125+ l.keep.Renew()
126+ case command.Sessions:
127+ fmt.Println(l.keep.Listing())
128+ case command.Help:
129+ fmt.Println(command.Usage(command.Terminal))
130+ case command.Copy:
131+ fmt.Println(copyAnswer(messages, arg, clipboard.New(terminalOSC52())))
132+ case command.Save:
133+ fmt.Println(saved.Command(modelAnswers(messages), arg))
134+ case command.Unload:
135+ fmt.Println("🧹 " + l.e.Unload(l.ctx, arg))
136+ case command.Memory:
137+ fmt.Println(l.keep.Memory(arg, messages))
138+ case command.Docs:
139+ fmt.Println(docsearch.Answer("", arg, 0))
140+ case command.Resume:
141+ resumed, line, err := l.keep.Resume(arg, agentsmd.System(l.system, ""))
142+ if err != nil {
143+ fmt.Println("⚠️ " + err.Error())
144+ record(l.keep, messages, store.NewFailure(messages, store.FailResume, err.Error(), err))
145+ break
146+ }
147+ messages = resumed
148+ l.d.Reset()
149+ l.e.ForgetInputTokens()
150+ tools.ClearPlans("") // the plans in memory were the previous conversation's
151+ fmt.Println(line)
152+ default:
153+ return messages, false
154+ }
155+ return messages, true
156+}
added internal/agent/recap.go +82 -0
new file mode 100644
@@ -0,0 +1,82 @@
1+package agent
2+
3+import (
4+ "fmt"
5+ "io"
6+ "mm/internal/config"
7+ "mm/internal/hooks"
8+ "mm/internal/spinner"
9+ "strings"
10+)
11+
12+// printCommands recaps the commands of the turn, in green.
13+//
14+// The count says HOW MANY, the list says WHAT: it reads at a glance once the
15+// answer is written, whereas the 🛠️ lines are scattered through the output of
16+// the commands. Green separates it from both the grey of the tools and the
17+// model's own text — and it only comes out on a terminal, like every other
18+// colour here.
19+func printCommands(cmds []string) {
20+ if len(cmds) == 0 {
21+ return
22+ }
23+ green, off := "", ""
24+ if spinner.Styled() {
25+ green, off = "\033[32m", "\033[0m"
26+ }
27+
28+ var b strings.Builder
29+ for i, c := range cmds {
30+ b.WriteString(green + fmt.Sprintf(" %d. %s", i+1, oneLine(c)) + off + "\n")
31+ }
32+ fmt.Print(b.String())
33+}
34+
35+// printHookRuns lists, under the commands, the hooks that ran during the turn
36+// (hooks.Turn) when displayHooks is on — in the same colour, so the recap of a
37+// turn reads as one block.
38+//
39+// 🪝 1. preGeneration · node "$MM_CONFIG_DIR/hooks/guards.js" → context (214 chars)
40+func printHookRuns(w io.Writer) {
41+ if !config.Cfg.DisplayHooks {
42+ return
43+ }
44+ green, off := "", ""
45+ if spinner.Styled() {
46+ green, off = "\033[32m", "\033[0m"
47+ }
48+ for _, line := range hooks.Lines(hooks.Turn.Take()) {
49+ _, _ = fmt.Fprintln(w, green+" "+line+off)
50+ }
51+}
52+
53+// maxCommandWidth is the width beyond which a command is cut. A hundred
54+// columns: that fits a demo terminal without overflowing it.
55+const maxCommandWidth = 100
56+
57+// oneLine folds a command onto ONE line and truncates it when needed.
58+//
59+// A command can be long and span several lines — a heredoc, a trailing &&. The
60+// recap is there to scan what the agent did, not to re-read its code: spread
61+// over several lines it would grow longer than the output it summarises, and
62+// the numbering would stop being readable.
63+func oneLine(s string) string {
64+ // Fields splits on ALL whitespace, line breaks included: that is exactly
65+ // the folding we want, heredoc indentation and all.
66+ s = strings.Join(strings.Fields(s), " ")
67+ r := []rune(s)
68+ if len(r) <= maxCommandWidth {
69+ return s
70+ }
71+ return string(r[:maxCommandWidth-1]) + "…"
72+}
73+
74+// dimln prints one line, dimmed on a terminal and plain in a pipe — the same
75+// rule as the ⚙ line: `bob | jq` must not receive escape codes.
76+func dimln(line string) {
77+ if spinner.Styled() {
78+ fmt.Printf("\033[2m%s\033[0m\n", line)
79+ } else {
80+ fmt.Println(line)
81+ }
82+}
new file mode 100644
@@ -0,0 +1,82 @@
1+package agent
2+
3+import (
4+ "fmt"
5+ "io"
6+ "mm/internal/config"
7+ "mm/internal/hooks"
8+ "mm/internal/spinner"
9+ "strings"
10+)
11+
12+// printCommands recaps the commands of the turn, in green.
13+//
14+// The count says HOW MANY, the list says WHAT: it reads at a glance once the
15+// answer is written, whereas the 🛠️ lines are scattered through the output of
16+// the commands. Green separates it from both the grey of the tools and the
17+// model's own text — and it only comes out on a terminal, like every other
18+// colour here.
19+func printCommands(cmds []string) {
20+ if len(cmds) == 0 {
21+ return
22+ }
23+ green, off := "", ""
24+ if spinner.Styled() {
25+ green, off = "\033[32m", "\033[0m"
26+ }
27+
28+ var b strings.Builder
29+ for i, c := range cmds {
30+ b.WriteString(green + fmt.Sprintf(" %d. %s", i+1, oneLine(c)) + off + "\n")
31+ }
32+ fmt.Print(b.String())
33+}
34+
35+// printHookRuns lists, under the commands, the hooks that ran during the turn
36+// (hooks.Turn) when displayHooks is on — in the same colour, so the recap of a
37+// turn reads as one block.
38+//
39+// 🪝 1. preGeneration · node "$MM_CONFIG_DIR/hooks/guards.js" → context (214 chars)
40+func printHookRuns(w io.Writer) {
41+ if !config.Cfg.DisplayHooks {
42+ return
43+ }
44+ green, off := "", ""
45+ if spinner.Styled() {
46+ green, off = "\033[32m", "\033[0m"
47+ }
48+ for _, line := range hooks.Lines(hooks.Turn.Take()) {
49+ _, _ = fmt.Fprintln(w, green+" "+line+off)
50+ }
51+}
52+
53+// maxCommandWidth is the width beyond which a command is cut. A hundred
54+// columns: that fits a demo terminal without overflowing it.
55+const maxCommandWidth = 100
56+
57+// oneLine folds a command onto ONE line and truncates it when needed.
58+//
59+// A command can be long and span several lines — a heredoc, a trailing &&. The
60+// recap is there to scan what the agent did, not to re-read its code: spread
61+// over several lines it would grow longer than the output it summarises, and
62+// the numbering would stop being readable.
63+func oneLine(s string) string {
64+ // Fields splits on ALL whitespace, line breaks included: that is exactly
65+ // the folding we want, heredoc indentation and all.
66+ s = strings.Join(strings.Fields(s), " ")
67+ r := []rune(s)
68+ if len(r) <= maxCommandWidth {
69+ return s
70+ }
71+ return string(r[:maxCommandWidth-1]) + "…"
72+}
73+
74+// dimln prints one line, dimmed on a terminal and plain in a pipe — the same
75+// rule as the ⚙ line: `bob | jq` must not receive escape codes.
76+func dimln(line string) {
77+ if spinner.Styled() {
78+ fmt.Printf("\033[2m%s\033[0m\n", line)
79+ } else {
80+ fmt.Println(line)
81+ }
82+}
modified internal/agent/runprompt_test.go +2 -2
@@ -14,7 +14,7 @@ import (
1414 // success for `mm -p`.
1515 func TestRunPromptExitsZeroOnAnAnswer(t *testing.T) {
1616 e := fakeModel(t, "hello")
17- if code := RunPrompt(context.Background(), e, "system", nil, detector.NewLoopDetector(10, 3), "hi"); code != 0 {
17+ if code := RunPrompt(context.Background(), Setup{Engine: e, System: "system", Detector: detector.NewLoopDetector(10, 3)}, "hi"); code != 0 {
1818 t.Errorf("RunPrompt = %d, want 0", code)
1919 }
2020 }
@@ -37,7 +37,7 @@ func TestRunPromptExitsOneWhenTheGenerationFails(t *testing.T) {
3737 }
3838 e := &engine.Engine{G: g, Model: model, Provider: p, Backend: b}
3939
40- if code := RunPrompt(context.Background(), e, "system", nil, detector.NewLoopDetector(10, 3), "hi"); code != 1 {
40+ if code := RunPrompt(context.Background(), Setup{Engine: e, System: "system", Detector: detector.NewLoopDetector(10, 3)}, "hi"); code != 1 {
4141 t.Errorf("RunPrompt = %d, want 1", code)
4242 }
4343 }
@@ -14,7 +14,7 @@ import (
14 // success for `mm -p`.14 // success for `mm -p`.
15 func TestRunPromptExitsZeroOnAnAnswer(t *testing.T) {15 func TestRunPromptExitsZeroOnAnAnswer(t *testing.T) {
16 e := fakeModel(t, "hello")16 e := fakeModel(t, "hello")
17- if code := RunPrompt(context.Background(), e, "system", nil, detector.NewLoopDetector(10, 3), "hi"); code != 0 {17+ if code := RunPrompt(context.Background(), Setup{Engine: e, System: "system", Detector: detector.NewLoopDetector(10, 3)}, "hi"); code != 0 {
18 t.Errorf("RunPrompt = %d, want 0", code)18 t.Errorf("RunPrompt = %d, want 0", code)
19 }19 }
20 }20 }
@@ -37,7 +37,7 @@ func TestRunPromptExitsOneWhenTheGenerationFails(t *testing.T) {
37 }37 }
38 e := &engine.Engine{G: g, Model: model, Provider: p, Backend: b}38 e := &engine.Engine{G: g, Model: model, Provider: p, Backend: b}
39 39
40- if code := RunPrompt(context.Background(), e, "system", nil, detector.NewLoopDetector(10, 3), "hi"); code != 1 {40+ if code := RunPrompt(context.Background(), Setup{Engine: e, System: "system", Detector: detector.NewLoopDetector(10, 3)}, "hi"); code != 1 {
41 t.Errorf("RunPrompt = %d, want 1", code)41 t.Errorf("RunPrompt = %d, want 1", code)
42 }42 }
43 }43 }
added internal/agent/turn.go +304 -0
new file mode 100644
@@ -0,0 +1,304 @@
1+package agent
2+
3+import (
4+ "context"
5+ "fmt"
6+ "os"
7+
8+ "mm/internal/command"
9+ "mm/internal/compact"
10+ "mm/internal/config"
11+ "mm/internal/decide"
12+ "mm/internal/detector"
13+ "mm/internal/engine"
14+ "mm/internal/hooks"
15+ "mm/internal/mention"
16+ "mm/internal/session"
17+ "mm/internal/skills"
18+ "mm/internal/spinner"
19+ "mm/internal/store"
20+
21+ "github.com/firebase/genkit/go/ai"
22+)
23+
24+// genResult is what a generation hands back to the waiting room.
25+type genResult struct {
26+ resp *ai.ModelResponse
27+ // history is the FULL conversation returned by engine.Generate — tool turns
28+ // included. Genkit only hands back the last message; without this field the
29+ // agent forgets the commands it just ran and starts telling stories instead
30+ // of re-reading.
31+ history []*ai.Message
32+ err error
33+}
34+
35+// turn asks the model the question, waits for the answer while it listens
36+// to the keyboard, and reports whether the loop goes on (false on /quit
37+// typed during the turn).
38+func (r *repl) turn(input string) bool {
39+ r.compactIfDue()
40+ r.messages = append(r.messages, ai.NewUserTextMessage(r.expand(input)))
41+ t := r.startTurn()
42+ defer t.cancel()
43+ return t.wait()
44+}
45+
46+// compactIfDue runs the automatic compression before the question is
47+// appended — and so before the turn's `before` is taken: that index is what
48+// the rollback (`messages[:before-1]`) and the ⚙ line (`res.history[before:]`)
49+// rely on, and a history that shrinks after it is taken would break both.
50+// The server's own count of the last context is preferred to the estimate
51+// when it is larger — it sees the tools' JSON and the chat template, which
52+// the estimate cannot. The window is the one the Engine knows: the yaml's
53+// contextWindow, or what the probe learned.
54+//
55+// That probe ran once, at start-up. A llama-server started AFTER bob left
56+// `ctx: unknown` for the whole session — observed — and the compression
57+// could then only trigger on maxMessages. So, while the window is unknown
58+// and compression is on, ask the server again before deciding; once known,
59+// never again. A probe that still fails prints nothing: the start-up
60+// warning already said so.
61+func (r *repl) compactIfDue() {
62+ if c := config.Cfg.Context; c.Enabled && r.Engine.ContextWindow == 0 {
63+ if w, src := r.Engine.EnsureContextWindow(r.ctx); w > 0 {
64+ dimln(fmt.Sprintf("ctx: %d (%s)", w, src))
65+ }
66+ }
67+ if dec := compact.Decide(r.messages, r.Engine.LastInputTokens(), r.Engine.ContextWindow, config.Cfg.Context); dec.Compact {
68+ r.messages = compactHistory(r.ctx, r.Engine, r.keep, r.messages, false)
69+ save(r.keep, r.messages)
70+ }
71+}
72+
73+// expand is the question as the model reads it.
74+//
75+// "@path" names a file for the model to look at: the text stays as typed;
76+// each existing path is appended as an [attached file: …] line — what an
77+// editor's @-mention becomes over ACP — and echoed here so the user sees the
78+// notation was understood. "$skill" names a procedure to carry out, with the
79+// rest of the line as its parameters — the same notation the window's `$`
80+// picker writes. No `$skill` named: the decider, when there is one, may pick
81+// it.
82+func (r *repl) expand(input string) string {
83+ typed := input
84+ input, attached := mention.Expand(input, r.cwd)
85+ for _, a := range attached {
86+ dimln("📎 " + a.Path)
87+ }
88+ input, refs := skills.ExpandRefs(input, skills.Declared())
89+ for _, ref := range refs {
90+ dimln("📖 $" + ref.Name)
91+ }
92+ input, routed := decide.RouteSkill(r.ctx, typed, input, len(refs), skills.Declared())
93+ if routed != "" {
94+ dimln(routed)
95+ }
96+ return input
97+}
98+
99+// lineTurn is one generation of the line mode and its waiting room.
100+type lineTurn struct {
101+ *repl
102+ before int // the history's length with the question, before the answer
103+ genCtx context.Context
104+ cancel context.CancelFunc
105+ steer *turnSteer
106+ result chan genResult
107+}
108+
109+// startTurn launches the generation of the history as it stands, in a
110+// goroutine, with its own cancellable context.
111+func (r *repl) startTurn() *lineTurn {
112+ t := &lineTurn{repl: r, before: len(r.messages), result: make(chan genResult, 1)}
113+ fmt.Println()
114+ t.genCtx, t.cancel = context.WithCancel(r.ctx)
115+ // Hooks that ran outside a turn (an /ask) are not this turn's.
116+ hooks.Turn.Take()
117+ // A question typed during the turn steers it (ticket 265).
118+ t.steer = newTurnSteer(r.cwd)
119+ steerCtx := t.steer.context(t.genCtx)
120+ messages := r.messages
121+ go func() {
122+ resp, history, err := r.Engine.Generate(steerCtx, messages, r.Tools)
123+ t.result <- genResult{resp: resp, history: history, err: err}
124+ }()
125+ return t
126+}
127+
128+// wait is the "waiting room": it listens for the completion, an
129+// interruption, a permission to ask, or a new line. typing goes nil when
130+// stdin closes (the end of a pipe), so the closed channel is not read in a
131+// loop; the main loop sees the end of the input once the queue is empty.
132+func (t *lineTurn) wait() bool {
133+ typing := t.inputCh
134+ for {
135+ select {
136+ case res := <-t.result:
137+ t.finish(res)
138+ return true
139+ case <-t.sigCh:
140+ // Stop() first: the spinner is running during the generation,
141+ // and without it this message lands on its line — the next
142+ // frame would erase it. Same rule as in dmr.emit. The turn ends
143+ // when the result comes back with its Canceled error.
144+ spinner.Stop()
145+ t.prompt.drop()
146+ fmt.Println("\n🔴 Interrupted (Ctrl+C).")
147+ t.cancel()
148+ case req := <-t.prompt.requestCh():
149+ t.prompt.show(req)
150+ case line, open := <-typing:
151+ if !open {
152+ typing = nil
153+ continue
154+ }
155+ if !t.typed(line) {
156+ return false
157+ }
158+ }
159+ }
160+}
161+
162+// finish settles the turn: the history, the outcome, the ⚙ line, and the
163+// questions that came too late to steer it.
164+func (t *lineTurn) finish(res genResult) {
165+ t.prompt.drop()
166+ // We take the FULL history returned by engine.Generate, not just
167+ // resp.Message — and we take it EVEN when the generation failed or was
168+ // interrupted: on an abort (Ctrl+C, /abort), a maxTurns overrun or a
169+ // silence caught by the watchdog, all the work of the turn is in
170+ // `history`, and Genkit itself returns nothing. (resp.History() will not
171+ // do: empty on the streamed path.)
172+ asked := t.messages // question included, for the error record below
173+ t.messages = session.AfterTurn(t.messages, t.before, res.resp, res.history, res.err)
174+ save(t.keep, t.messages)
175+ t.report(res, asked)
176+ printTurnStats(res.history[min(t.before, len(res.history)):])
177+ // Questions sent after the model's last call run next.
178+ if late := t.steer.late(); len(late) > 0 {
179+ t.queue.pushFront(late)
180+ fmt.Printf("⏳ %d message(s) came after the model's last call — sent as the next question\n", len(late))
181+ }
182+}
183+
184+// report says how the turn ended: answered (its tool calls go to the loop
185+// detector), aborted, or failed — one line, in the provider's words (see
186+// engine.Explain), and the same line in the session file, for whoever asks
187+// later why this turn failed.
188+func (t *lineTurn) report(res genResult, asked []*ai.Message) {
189+ switch {
190+ case res.err == nil:
191+ recordToolCalls(t.Detector, res.resp)
192+ fmt.Println()
193+ case t.genCtx.Err() == context.Canceled:
194+ fmt.Println("\n🔴 Generation aborted.")
195+ default:
196+ explained := t.Engine.Explain(res.err)
197+ fmt.Println("\n[error: " + explained + "]")
198+ record(t.keep, t.messages, store.NewFailure(asked, store.FailGeneration, explained, res.err))
199+ }
200+}
201+
202+// recordToolCalls gives the global loop detector the tool calls of the
203+// model's answer.
204+func recordToolCalls(d *detector.LoopDetector, resp *ai.ModelResponse) {
205+ if resp == nil || resp.Message == nil {
206+ return
207+ }
208+ for _, part := range resp.Message.Content {
209+ if part.IsToolRequest() && part.ToolRequest != nil {
210+ d.Record(detector.Action{
211+ ToolName: part.ToolRequest.Name,
212+ Input: fmt.Sprintf("%v", part.ToolRequest.Input),
213+ Output: "[tool_call]",
214+ })
215+ }
216+ }
217+}
218+
219+// typed handles a line typed during the turn: the answer to a tool waiting
220+// for permission, /abort and /quit stop the turn; anything else steers it or
221+// waits. It reports false on /quit.
222+func (t *lineTurn) typed(line string) bool {
223+ if t.prompt.answer(line) {
224+ return true
225+ }
226+ switch {
227+ case command.Is(line, command.Abort):
228+ t.prompt.drop()
229+ spinner.Stop() // the spinner is running: take its line back
230+ t.cancel()
231+ fmt.Println("🔴 Aborting...")
232+ case command.Is(line, command.Quit):
233+ t.prompt.drop()
234+ spinner.Stop()
235+ t.cancel()
236+ fmt.Println("Goodbye.")
237+ return false
238+ default:
239+ t.steerOrQueue(line)
240+ }
241+ return true
242+}
243+
244+// steerOrQueue: a question steers the turn — the model reads it after its
245+// current step (ticket 265). A slash command, and `/queue <question>`, wait
246+// in the queue and run once the turn has settled (ticket 155).
247+func (t *lineTurn) steerOrQueue(line string) {
248+ if q, isQueue := queueArg(line); isQueue {
249+ if q == "" {
250+ notify(queueNeedsQuestion)
251+ return
252+ }
253+ line = q
254+ } else if notice, steered := t.steer.offer(line); steered {
255+ notify(notice)
256+ return
257+ }
258+ if notice := t.queue.push(line); notice != "" {
259+ notify(notice)
260+ }
261+}
262+
263+// notify prints a notice during the turn, on a line of its own: the spinner
264+// stopped first, so its next frame does not erase it.
265+func notify(line string) {
266+ spinner.Stop()
267+ fmt.Println("\n" + line)
268+}
269+
270+// printTurnStats prints the ⚙ line of a turn, then — when displayCommands is
271+// on — its commands and file operations, and the hooks that ran.
272+func printTurnStats(turn []*ai.Message) {
273+ cmds := engine.CommandList(turn)
274+ ops := engine.FileOps(turn)
275+ dimln(statsLine(turn, cmds, ops))
276+ if config.Cfg.DisplayCommands {
277+ printCommands(cmds)
278+ printCommands(ops)
279+ }
280+ printHookRuns(os.Stdout)
281+}
282+
283+// statsLine is the ⚙ line. The command count is the only visible proof that
284+// the model worked rather than improvised: zero is normal on a
285+// conversational question; zero on "read this file" is not. The file tools
286+// have their own column: the A/B of this part is "edits through bash" versus
287+// "edits through tools", and a single number would add up what it is meant
288+// to separate. The skills are always shown when the agent has some, 0
289+// included: see engine.SkillsAvailable.
290+//
291+// ⚙ 2 command(s) · 📝 1 file op(s) · 📖 0 skill(s)
292+func statsLine(turn []*ai.Message, cmds, ops []string) string {
293+ line := fmt.Sprintf("⚙ %d command(s)", len(cmds))
294+ if len(ops) > 0 {
295+ line += fmt.Sprintf(" · 📝 %d file op(s)", len(ops))
296+ }
297+ if engine.SkillsAvailable() {
298+ line += fmt.Sprintf(" · 📖 %d skill(s)", engine.Skills(turn))
299+ }
300+ if k := engine.LSPCalls(turn); k > 0 {
301+ line += fmt.Sprintf(" · 🔎 %d lsp call(s)", k)
302+ }
303+ return line
304+}
new file mode 100644
@@ -0,0 +1,304 @@
1+package agent
2+
3+import (
4+ "context"
5+ "fmt"
6+ "os"
7+
8+ "mm/internal/command"
9+ "mm/internal/compact"
10+ "mm/internal/config"
11+ "mm/internal/decide"
12+ "mm/internal/detector"
13+ "mm/internal/engine"
14+ "mm/internal/hooks"
15+ "mm/internal/mention"
16+ "mm/internal/session"
17+ "mm/internal/skills"
18+ "mm/internal/spinner"
19+ "mm/internal/store"
20+
21+ "github.com/firebase/genkit/go/ai"
22+)
23+
24+// genResult is what a generation hands back to the waiting room.
25+type genResult struct {
26+ resp *ai.ModelResponse
27+ // history is the FULL conversation returned by engine.Generate — tool turns
28+ // included. Genkit only hands back the last message; without this field the
29+ // agent forgets the commands it just ran and starts telling stories instead
30+ // of re-reading.
31+ history []*ai.Message
32+ err error
33+}
34+
35+// turn asks the model the question, waits for the answer while it listens
36+// to the keyboard, and reports whether the loop goes on (false on /quit
37+// typed during the turn).
38+func (r *repl) turn(input string) bool {
39+ r.compactIfDue()
40+ r.messages = append(r.messages, ai.NewUserTextMessage(r.expand(input)))
41+ t := r.startTurn()
42+ defer t.cancel()
43+ return t.wait()
44+}
45+
46+// compactIfDue runs the automatic compression before the question is
47+// appended — and so before the turn's `before` is taken: that index is what
48+// the rollback (`messages[:before-1]`) and the ⚙ line (`res.history[before:]`)
49+// rely on, and a history that shrinks after it is taken would break both.
50+// The server's own count of the last context is preferred to the estimate
51+// when it is larger — it sees the tools' JSON and the chat template, which
52+// the estimate cannot. The window is the one the Engine knows: the yaml's
53+// contextWindow, or what the probe learned.
54+//
55+// That probe ran once, at start-up. A llama-server started AFTER bob left
56+// `ctx: unknown` for the whole session — observed — and the compression
57+// could then only trigger on maxMessages. So, while the window is unknown
58+// and compression is on, ask the server again before deciding; once known,
59+// never again. A probe that still fails prints nothing: the start-up
60+// warning already said so.
61+func (r *repl) compactIfDue() {
62+ if c := config.Cfg.Context; c.Enabled && r.Engine.ContextWindow == 0 {
63+ if w, src := r.Engine.EnsureContextWindow(r.ctx); w > 0 {
64+ dimln(fmt.Sprintf("ctx: %d (%s)", w, src))
65+ }
66+ }
67+ if dec := compact.Decide(r.messages, r.Engine.LastInputTokens(), r.Engine.ContextWindow, config.Cfg.Context); dec.Compact {
68+ r.messages = compactHistory(r.ctx, r.Engine, r.keep, r.messages, false)
69+ save(r.keep, r.messages)
70+ }
71+}
72+
73+// expand is the question as the model reads it.
74+//
75+// "@path" names a file for the model to look at: the text stays as typed;
76+// each existing path is appended as an [attached file: …] line — what an
77+// editor's @-mention becomes over ACP — and echoed here so the user sees the
78+// notation was understood. "$skill" names a procedure to carry out, with the
79+// rest of the line as its parameters — the same notation the window's `$`
80+// picker writes. No `$skill` named: the decider, when there is one, may pick
81+// it.
82+func (r *repl) expand(input string) string {
83+ typed := input
84+ input, attached := mention.Expand(input, r.cwd)
85+ for _, a := range attached {
86+ dimln("📎 " + a.Path)
87+ }
88+ input, refs := skills.ExpandRefs(input, skills.Declared())
89+ for _, ref := range refs {
90+ dimln("📖 $" + ref.Name)
91+ }
92+ input, routed := decide.RouteSkill(r.ctx, typed, input, len(refs), skills.Declared())
93+ if routed != "" {
94+ dimln(routed)
95+ }
96+ return input
97+}
98+
99+// lineTurn is one generation of the line mode and its waiting room.
100+type lineTurn struct {
101+ *repl
102+ before int // the history's length with the question, before the answer
103+ genCtx context.Context
104+ cancel context.CancelFunc
105+ steer *turnSteer
106+ result chan genResult
107+}
108+
109+// startTurn launches the generation of the history as it stands, in a
110+// goroutine, with its own cancellable context.
111+func (r *repl) startTurn() *lineTurn {
112+ t := &lineTurn{repl: r, before: len(r.messages), result: make(chan genResult, 1)}
113+ fmt.Println()
114+ t.genCtx, t.cancel = context.WithCancel(r.ctx)
115+ // Hooks that ran outside a turn (an /ask) are not this turn's.
116+ hooks.Turn.Take()
117+ // A question typed during the turn steers it (ticket 265).
118+ t.steer = newTurnSteer(r.cwd)
119+ steerCtx := t.steer.context(t.genCtx)
120+ messages := r.messages
121+ go func() {
122+ resp, history, err := r.Engine.Generate(steerCtx, messages, r.Tools)
123+ t.result <- genResult{resp: resp, history: history, err: err}
124+ }()
125+ return t
126+}
127+
128+// wait is the "waiting room": it listens for the completion, an
129+// interruption, a permission to ask, or a new line. typing goes nil when
130+// stdin closes (the end of a pipe), so the closed channel is not read in a
131+// loop; the main loop sees the end of the input once the queue is empty.
132+func (t *lineTurn) wait() bool {
133+ typing := t.inputCh
134+ for {
135+ select {
136+ case res := <-t.result:
137+ t.finish(res)
138+ return true
139+ case <-t.sigCh:
140+ // Stop() first: the spinner is running during the generation,
141+ // and without it this message lands on its line — the next
142+ // frame would erase it. Same rule as in dmr.emit. The turn ends
143+ // when the result comes back with its Canceled error.
144+ spinner.Stop()
145+ t.prompt.drop()
146+ fmt.Println("\n🔴 Interrupted (Ctrl+C).")
147+ t.cancel()
148+ case req := <-t.prompt.requestCh():
149+ t.prompt.show(req)
150+ case line, open := <-typing:
151+ if !open {
152+ typing = nil
153+ continue
154+ }
155+ if !t.typed(line) {
156+ return false
157+ }
158+ }
159+ }
160+}
161+
162+// finish settles the turn: the history, the outcome, the ⚙ line, and the
163+// questions that came too late to steer it.
164+func (t *lineTurn) finish(res genResult) {
165+ t.prompt.drop()
166+ // We take the FULL history returned by engine.Generate, not just
167+ // resp.Message — and we take it EVEN when the generation failed or was
168+ // interrupted: on an abort (Ctrl+C, /abort), a maxTurns overrun or a
169+ // silence caught by the watchdog, all the work of the turn is in
170+ // `history`, and Genkit itself returns nothing. (resp.History() will not
171+ // do: empty on the streamed path.)
172+ asked := t.messages // question included, for the error record below
173+ t.messages = session.AfterTurn(t.messages, t.before, res.resp, res.history, res.err)
174+ save(t.keep, t.messages)
175+ t.report(res, asked)
176+ printTurnStats(res.history[min(t.before, len(res.history)):])
177+ // Questions sent after the model's last call run next.
178+ if late := t.steer.late(); len(late) > 0 {
179+ t.queue.pushFront(late)
180+ fmt.Printf("⏳ %d message(s) came after the model's last call — sent as the next question\n", len(late))
181+ }
182+}
183+
184+// report says how the turn ended: answered (its tool calls go to the loop
185+// detector), aborted, or failed — one line, in the provider's words (see
186+// engine.Explain), and the same line in the session file, for whoever asks
187+// later why this turn failed.
188+func (t *lineTurn) report(res genResult, asked []*ai.Message) {
189+ switch {
190+ case res.err == nil:
191+ recordToolCalls(t.Detector, res.resp)
192+ fmt.Println()
193+ case t.genCtx.Err() == context.Canceled:
194+ fmt.Println("\n🔴 Generation aborted.")
195+ default:
196+ explained := t.Engine.Explain(res.err)
197+ fmt.Println("\n[error: " + explained + "]")
198+ record(t.keep, t.messages, store.NewFailure(asked, store.FailGeneration, explained, res.err))
199+ }
200+}
201+
202+// recordToolCalls gives the global loop detector the tool calls of the
203+// model's answer.
204+func recordToolCalls(d *detector.LoopDetector, resp *ai.ModelResponse) {
205+ if resp == nil || resp.Message == nil {
206+ return
207+ }
208+ for _, part := range resp.Message.Content {
209+ if part.IsToolRequest() && part.ToolRequest != nil {
210+ d.Record(detector.Action{
211+ ToolName: part.ToolRequest.Name,
212+ Input: fmt.Sprintf("%v", part.ToolRequest.Input),
213+ Output: "[tool_call]",
214+ })
215+ }
216+ }
217+}
218+
219+// typed handles a line typed during the turn: the answer to a tool waiting
220+// for permission, /abort and /quit stop the turn; anything else steers it or
221+// waits. It reports false on /quit.
222+func (t *lineTurn) typed(line string) bool {
223+ if t.prompt.answer(line) {
224+ return true
225+ }
226+ switch {
227+ case command.Is(line, command.Abort):
228+ t.prompt.drop()
229+ spinner.Stop() // the spinner is running: take its line back
230+ t.cancel()
231+ fmt.Println("🔴 Aborting...")
232+ case command.Is(line, command.Quit):
233+ t.prompt.drop()
234+ spinner.Stop()
235+ t.cancel()
236+ fmt.Println("Goodbye.")
237+ return false
238+ default:
239+ t.steerOrQueue(line)
240+ }
241+ return true
242+}
243+
244+// steerOrQueue: a question steers the turn — the model reads it after its
245+// current step (ticket 265). A slash command, and `/queue <question>`, wait
246+// in the queue and run once the turn has settled (ticket 155).
247+func (t *lineTurn) steerOrQueue(line string) {
248+ if q, isQueue := queueArg(line); isQueue {
249+ if q == "" {
250+ notify(queueNeedsQuestion)
251+ return
252+ }
253+ line = q
254+ } else if notice, steered := t.steer.offer(line); steered {
255+ notify(notice)
256+ return
257+ }
258+ if notice := t.queue.push(line); notice != "" {
259+ notify(notice)
260+ }
261+}
262+
263+// notify prints a notice during the turn, on a line of its own: the spinner
264+// stopped first, so its next frame does not erase it.
265+func notify(line string) {
266+ spinner.Stop()
267+ fmt.Println("\n" + line)
268+}
269+
270+// printTurnStats prints the ⚙ line of a turn, then — when displayCommands is
271+// on — its commands and file operations, and the hooks that ran.
272+func printTurnStats(turn []*ai.Message) {
273+ cmds := engine.CommandList(turn)
274+ ops := engine.FileOps(turn)
275+ dimln(statsLine(turn, cmds, ops))
276+ if config.Cfg.DisplayCommands {
277+ printCommands(cmds)
278+ printCommands(ops)
279+ }
280+ printHookRuns(os.Stdout)
281+}
282+
283+// statsLine is the ⚙ line. The command count is the only visible proof that
284+// the model worked rather than improvised: zero is normal on a
285+// conversational question; zero on "read this file" is not. The file tools
286+// have their own column: the A/B of this part is "edits through bash" versus
287+// "edits through tools", and a single number would add up what it is meant
288+// to separate. The skills are always shown when the agent has some, 0
289+// included: see engine.SkillsAvailable.
290+//
291+// ⚙ 2 command(s) · 📝 1 file op(s) · 📖 0 skill(s)
292+func statsLine(turn []*ai.Message, cmds, ops []string) string {
293+ line := fmt.Sprintf("⚙ %d command(s)", len(cmds))
294+ if len(ops) > 0 {
295+ line += fmt.Sprintf(" · 📝 %d file op(s)", len(ops))
296+ }
297+ if engine.SkillsAvailable() {
298+ line += fmt.Sprintf(" · 📖 %d skill(s)", engine.Skills(turn))
299+ }
300+ if k := engine.LSPCalls(turn); k > 0 {
301+ line += fmt.Sprintf(" · 🔎 %d lsp call(s)", k)
302+ }
303+ return line
304+}
modified main.go +8 -3
@@ -170,6 +170,11 @@ type agentSession struct {
170170 asker *ask.Pool
171171 }
172172
173+// setup is what the line mode and `-p` run with.
174+func (s agentSession) setup() agent.Setup {
175+ return agent.Setup{Engine: s.e, System: config.Cfg.System, Tools: s.tools, Detector: s.detector}
176+}
177+
173178 // assemble builds the tool set and the routers. A decider declares no tool
174179 // source (checked before the tools are assembled, so no MCP or language
175180 // server is started for a file about to be refused); a structuredOutput
@@ -208,7 +213,7 @@ func (s agentSession) runPrompt(ctx context.Context, prompt string, set toolSet)
208213 case config.Cfg.OutputSchema != nil:
209214 exit(runStructuredPrompt(ctx, s.e, prompt))
210215 }
211- if code := agent.RunPrompt(ctx, s.e, config.Cfg.System, s.tools, s.detector, prompt); code != 0 {
216+ if code := agent.RunPrompt(ctx, s.setup(), prompt); code != 0 {
212217 set.close()
213218 s.asker.Close()
214219 exit(code)
@@ -231,7 +236,7 @@ func (s agentSession) runFrontEnd(ctx context.Context, cli cliOptions, window bo
231236 case window:
232237 runWindow(ctx, s, strings.TrimSpace(banner.String()))
233238 default:
234- agent.Run(ctx, s.e, config.Cfg.System, s.tools, s.detector, s.asker)
239+ agent.Run(ctx, s.setup(), s.asker)
235240 }
236241 }
237242
@@ -291,7 +296,7 @@ func runWindow(ctx context.Context, s agentSession, banner string) {
291296 say("[tui: %v — running the line mode]", err)
292297 }
293298 say("%s", banner)
294- agent.Run(ctx, e, config.Cfg.System, agentTools, d, asker)
299+ agent.Run(ctx, agent.Setup{Engine: e, System: config.Cfg.System, Tools: agentTools, Detector: d}, asker)
295300 }
296301
297302 // say prints one line of human-facing text where it belongs (ui.Out). A
@@ -170,6 +170,11 @@ type agentSession struct {
170 asker *ask.Pool170 asker *ask.Pool
171 }171 }
172 172
173+// setup is what the line mode and `-p` run with.
174+func (s agentSession) setup() agent.Setup {
175+ return agent.Setup{Engine: s.e, System: config.Cfg.System, Tools: s.tools, Detector: s.detector}
176+}
177+
173 // assemble builds the tool set and the routers. A decider declares no tool178 // assemble builds the tool set and the routers. A decider declares no tool
174 // source (checked before the tools are assembled, so no MCP or language179 // source (checked before the tools are assembled, so no MCP or language
175 // server is started for a file about to be refused); a structuredOutput180 // server is started for a file about to be refused); a structuredOutput
@@ -208,7 +213,7 @@ func (s agentSession) runPrompt(ctx context.Context, prompt string, set toolSet)
208 case config.Cfg.OutputSchema != nil:213 case config.Cfg.OutputSchema != nil:
209 exit(runStructuredPrompt(ctx, s.e, prompt))214 exit(runStructuredPrompt(ctx, s.e, prompt))
210 }215 }
211- if code := agent.RunPrompt(ctx, s.e, config.Cfg.System, s.tools, s.detector, prompt); code != 0 {216+ if code := agent.RunPrompt(ctx, s.setup(), prompt); code != 0 {
212 set.close()217 set.close()
213 s.asker.Close()218 s.asker.Close()
214 exit(code)219 exit(code)
@@ -231,7 +236,7 @@ func (s agentSession) runFrontEnd(ctx context.Context, cli cliOptions, window bo
231 case window:236 case window:
232 runWindow(ctx, s, strings.TrimSpace(banner.String()))237 runWindow(ctx, s, strings.TrimSpace(banner.String()))
233 default:238 default:
234- agent.Run(ctx, s.e, config.Cfg.System, s.tools, s.detector, s.asker)239+ agent.Run(ctx, s.setup(), s.asker)
235 }240 }
236 }241 }
237 242
@@ -291,7 +296,7 @@ func runWindow(ctx context.Context, s agentSession, banner string) {
291 say("[tui: %v — running the line mode]", err)296 say("[tui: %v — running the line mode]", err)
292 }297 }
293 say("%s", banner)298 say("%s", banner)
294- agent.Run(ctx, e, config.Cfg.System, agentTools, d, asker)299+ agent.Run(ctx, agent.Setup{Engine: e, System: config.Cfg.System, Tools: agentTools, Detector: d}, asker)
295 }300 }
296 301
297 // say prints one line of human-facing text where it belongs (ui.Out). A302 // say prints one line of human-facing text where it belongs (ui.Out). A