bots-garden/mini-mepublic Fork
⑂ 9c248b3
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/tools without smells (7 → 0)

- runArgv's ending as runOutcome (start failure, timeout, cancel, exit)
- askA2A: a2aProblem, sendA2A, and the generic whileWaiting[T] instead of
  its own copy of the heartbeat loop
- ask_agent's evented takes a handOff (input, request, title, identity);
  askUserEvented computes its key
- files_evented.go, plan_store.go, plan_status.go, declared_args.go

Checked: go test; live old vs new binary with a fake model calling
ask_a2a_agent on a second mm served over A2A — answered, unknown agent,
empty message — in line mode and over ACP, and a bash call: identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
agent committed 2026-11-28T12:25:50+01:00 Browse files
9c248b3 parent: f5f2d92
modified internal/tools/a2a.go +31 -31
@@ -96,46 +96,19 @@ Agents:`)
9696 }
9797
9898 func askA2A(ctx context.Context, d *detector.LoopDetector, in askA2AInput) (string, error) {
99- _, ok := config.Cfg.A2A.Agents[in.Agent]
10099 key := in.Agent + ": " + in.Message
101100 title := "ask_a2a_agent: " + in.Agent
102- if !ok {
103- out := fmt.Sprintf("[ask_a2a_agent: no agent %q — use one of: %s]", in.Agent, strings.Join(config.A2AAgentNames(), ", "))
104- return recordFailure(d, "ask_a2a_agent", key, out)
105- }
106- if strings.TrimSpace(in.Message) == "" {
107- return recordFailure(d, "ask_a2a_agent", key, "[ask_a2a_agent: empty message — say something to the agent]")
101+ if problem := a2aProblem(in); problem != "" {
102+ return recordFailure(d, "ask_a2a_agent", key, problem)
108103 }
109104
110105 // The remote agent's model can think for minutes, and nothing streams
111106 // back meanwhile: the call beats the generation's watchdog every second
112107 // (like ask_user waiting for a person), bounded by a2aTimeout instead.
113108 beat := engine.Heartbeat(ctx)
114- call := func() (string, bool) {
115- answer, err := A2ASend(ctx, in.Agent, in.Message, in.NewConversation)
116- if err != nil {
117- return fmt.Sprintf("[ask_a2a_agent: %s did not answer — %v]", in.Agent, err), true
118- }
119- return answer, false
120- }
121109 run := func() (string, bool) {
122- type result struct {
123- out string
124- failed bool
125- }
126- done := make(chan result, 1)
127- go func() { out, failed := call(); done <- result{out, failed} }()
128- ticker := time.NewTicker(time.Second)
129- defer ticker.Stop()
130- for {
131- select {
132- case r := <-done:
133- beat()
134- return r.out, r.failed
135- case <-ticker.C:
136- beat()
137- }
138- }
110+ r := whileWaiting(beat, func() a2aAnswer { return sendA2A(ctx, in) })
111+ return r.out, r.failed
139112 }
140113
141114 if s := ui.ActiveSink(); s != nil {
@@ -154,3 +127,30 @@ func askA2A(ctx context.Context, d *detector.LoopDetector, in askA2AInput) (stri
154127 spinner.Suspend(func() { echoOutput(out) })
155128 return recordOutcome(d, "ask_a2a_agent", key, out, failed)
156129 }
130+
131+// a2aProblem is what the model reads for a call that cannot be sent: an
132+// agent the config does not name, or an empty message.
133+func a2aProblem(in askA2AInput) string {
134+ if _, ok := config.Cfg.A2A.Agents[in.Agent]; !ok {
135+ return fmt.Sprintf("[ask_a2a_agent: no agent %q — use one of: %s]", in.Agent, strings.Join(config.A2AAgentNames(), ", "))
136+ }
137+ if strings.TrimSpace(in.Message) == "" {
138+ return "[ask_a2a_agent: empty message — say something to the agent]"
139+ }
140+ return ""
141+}
142+
143+// a2aAnswer is the remote agent's answer, or why it did not come.
144+type a2aAnswer struct {
145+ out string
146+ failed bool
147+}
148+
149+// sendA2A sends the message and waits for the answer.
150+func sendA2A(ctx context.Context, in askA2AInput) a2aAnswer {
151+ answer, err := A2ASend(ctx, in.Agent, in.Message, in.NewConversation)
152+ if err != nil {
153+ return a2aAnswer{fmt.Sprintf("[ask_a2a_agent: %s did not answer — %v]", in.Agent, err), true}
154+ }
155+ return a2aAnswer{answer, false}
156+}
@@ -96,46 +96,19 @@ Agents:`)
96 }96 }
97 97
98 func askA2A(ctx context.Context, d *detector.LoopDetector, in askA2AInput) (string, error) {98 func askA2A(ctx context.Context, d *detector.LoopDetector, in askA2AInput) (string, error) {
99- _, ok := config.Cfg.A2A.Agents[in.Agent]
100 key := in.Agent + ": " + in.Message99 key := in.Agent + ": " + in.Message
101 title := "ask_a2a_agent: " + in.Agent100 title := "ask_a2a_agent: " + in.Agent
102- if !ok {101+ if problem := a2aProblem(in); problem != "" {
103- out := fmt.Sprintf("[ask_a2a_agent: no agent %q — use one of: %s]", in.Agent, strings.Join(config.A2AAgentNames(), ", "))102+ return recordFailure(d, "ask_a2a_agent", key, problem)
104- return recordFailure(d, "ask_a2a_agent", key, out)
105- }
106- if strings.TrimSpace(in.Message) == "" {
107- return recordFailure(d, "ask_a2a_agent", key, "[ask_a2a_agent: empty message — say something to the agent]")
108 }103 }
109 104
110 // The remote agent's model can think for minutes, and nothing streams105 // The remote agent's model can think for minutes, and nothing streams
111 // back meanwhile: the call beats the generation's watchdog every second106 // back meanwhile: the call beats the generation's watchdog every second
112 // (like ask_user waiting for a person), bounded by a2aTimeout instead.107 // (like ask_user waiting for a person), bounded by a2aTimeout instead.
113 beat := engine.Heartbeat(ctx)108 beat := engine.Heartbeat(ctx)
114- call := func() (string, bool) {
115- answer, err := A2ASend(ctx, in.Agent, in.Message, in.NewConversation)
116- if err != nil {
117- return fmt.Sprintf("[ask_a2a_agent: %s did not answer — %v]", in.Agent, err), true
118- }
119- return answer, false
120- }
121 run := func() (string, bool) {109 run := func() (string, bool) {
122- type result struct {110+ r := whileWaiting(beat, func() a2aAnswer { return sendA2A(ctx, in) })
123- out string111+ return r.out, r.failed
124- failed bool
125- }
126- done := make(chan result, 1)
127- go func() { out, failed := call(); done <- result{out, failed} }()
128- ticker := time.NewTicker(time.Second)
129- defer ticker.Stop()
130- for {
131- select {
132- case r := <-done:
133- beat()
134- return r.out, r.failed
135- case <-ticker.C:
136- beat()
137- }
138- }
139 }112 }
140 113
141 if s := ui.ActiveSink(); s != nil {114 if s := ui.ActiveSink(); s != nil {
@@ -154,3 +127,30 @@ func askA2A(ctx context.Context, d *detector.LoopDetector, in askA2AInput) (stri
154 spinner.Suspend(func() { echoOutput(out) })127 spinner.Suspend(func() { echoOutput(out) })
155 return recordOutcome(d, "ask_a2a_agent", key, out, failed)128 return recordOutcome(d, "ask_a2a_agent", key, out, failed)
156 }129 }
130+
131+// a2aProblem is what the model reads for a call that cannot be sent: an
132+// agent the config does not name, or an empty message.
133+func a2aProblem(in askA2AInput) string {
134+ if _, ok := config.Cfg.A2A.Agents[in.Agent]; !ok {
135+ return fmt.Sprintf("[ask_a2a_agent: no agent %q — use one of: %s]", in.Agent, strings.Join(config.A2AAgentNames(), ", "))
136+ }
137+ if strings.TrimSpace(in.Message) == "" {
138+ return "[ask_a2a_agent: empty message — say something to the agent]"
139+ }
140+ return ""
141+}
142+
143+// a2aAnswer is the remote agent's answer, or why it did not come.
144+type a2aAnswer struct {
145+ out string
146+ failed bool
147+}
148+
149+// sendA2A sends the message and waits for the answer.
150+func sendA2A(ctx context.Context, in askA2AInput) a2aAnswer {
151+ answer, err := A2ASend(ctx, in.Agent, in.Message, in.NewConversation)
152+ if err != nil {
153+ return a2aAnswer{fmt.Sprintf("[ask_a2a_agent: %s did not answer — %v]", in.Agent, err), true}
154+ }
155+ return a2aAnswer{answer, false}
156+}
modified internal/tools/askagent.go +12 -2
@@ -106,7 +106,7 @@ func (call askAgentCall) run(ctx context.Context, in askAgentInput) (string, err
106106 id := ask.Identify(ref.Path)
107107 title := fmt.Sprintf("ask_agent: %s (%s)", in.Agent, ask.Describe(ref.Path))
108108 if s := ui.ActiveSink(); s != nil {
109- return call.evented(ctx, s, in, req, title, id)
109+ return call.evented(ctx, s, handOff{in: in, req: req, title: title, id: id})
110110 }
111111
112112 announce("🗣 " + title + " — " + firstLine(in.Prompt))
@@ -125,11 +125,21 @@ func (call askAgentCall) run(ctx context.Context, in askAgentInput) (string, err
125125 return recordOutcome(call.detector, "ask_agent", key, out, err != nil)
126126 }
127127
128+// handOff is one ask_agent call: the model's input, the request made of it,
129+// the call's title and the asked agent's identity.
130+type handOff struct {
131+ in askAgentInput
132+ req ask.Request
133+ title string
134+ id ask.Identity
135+}
136+
128137 // evented is ask_agent for an event-consuming front end (the window, an
129138 // editor): one tool call for the hand-off, the asked agent's own events
130139 // inside it, and — for a sink that is a ui.Speaker — the asked agent named
131140 // while it answers.
132-func (call askAgentCall) evented(ctx context.Context, s ui.Sink, in askAgentInput, req ask.Request, title string, id ask.Identity) (string, error) {
141+func (call askAgentCall) evented(ctx context.Context, s ui.Sink, h handOff) (string, error) {
142+ in, req, title, id := h.in, h.req, h.title, h.id
133143 key := in.Agent + ": " + in.Prompt
134144 ev := ui.ToolEvent{
135145 ID: ui.NextCallID(),
@@ -106,7 +106,7 @@ func (call askAgentCall) run(ctx context.Context, in askAgentInput) (string, err
106 id := ask.Identify(ref.Path)106 id := ask.Identify(ref.Path)
107 title := fmt.Sprintf("ask_agent: %s (%s)", in.Agent, ask.Describe(ref.Path))107 title := fmt.Sprintf("ask_agent: %s (%s)", in.Agent, ask.Describe(ref.Path))
108 if s := ui.ActiveSink(); s != nil {108 if s := ui.ActiveSink(); s != nil {
109- return call.evented(ctx, s, in, req, title, id)109+ return call.evented(ctx, s, handOff{in: in, req: req, title: title, id: id})
110 }110 }
111 111
112 announce("🗣 " + title + " — " + firstLine(in.Prompt))112 announce("🗣 " + title + " — " + firstLine(in.Prompt))
@@ -125,11 +125,21 @@ func (call askAgentCall) run(ctx context.Context, in askAgentInput) (string, err
125 return recordOutcome(call.detector, "ask_agent", key, out, err != nil)125 return recordOutcome(call.detector, "ask_agent", key, out, err != nil)
126 }126 }
127 127
128+// handOff is one ask_agent call: the model's input, the request made of it,
129+// the call's title and the asked agent's identity.
130+type handOff struct {
131+ in askAgentInput
132+ req ask.Request
133+ title string
134+ id ask.Identity
135+}
136+
128 // evented is ask_agent for an event-consuming front end (the window, an137 // evented is ask_agent for an event-consuming front end (the window, an
129 // editor): one tool call for the hand-off, the asked agent's own events138 // editor): one tool call for the hand-off, the asked agent's own events
130 // inside it, and — for a sink that is a ui.Speaker — the asked agent named139 // inside it, and — for a sink that is a ui.Speaker — the asked agent named
131 // while it answers.140 // while it answers.
132-func (call askAgentCall) evented(ctx context.Context, s ui.Sink, in askAgentInput, req ask.Request, title string, id ask.Identity) (string, error) {141+func (call askAgentCall) evented(ctx context.Context, s ui.Sink, h handOff) (string, error) {
142+ in, req, title, id := h.in, h.req, h.title, h.id
133 key := in.Agent + ": " + in.Prompt143 key := in.Agent + ": " + in.Prompt
134 ev := ui.ToolEvent{144 ev := ui.ToolEvent{
135 ID: ui.NextCallID(),145 ID: ui.NextCallID(),
modified internal/tools/askagent_test.go +4 -4
@@ -86,7 +86,7 @@ func TestAskAgentEvented(t *testing.T) {
8686 a := &fakeAgentAsker{answer: "Implemented R1 and R2."}
8787 sink := &speakingSink{recordingSink: recordingSink{dir: "/proj"}}
8888
89- out, err := newAskAgentCall(a).evented(context.Background(), sink, askAgentInput{Agent: "homer", Prompt: "Implement specs/x.spec.md"}, ask.Request{Agent: "homer", Question: "Implement specs/x.spec.md", Via: hooks.ViaTool}, "ask_agent: homer (?)", askIdentity("Homer (coder)"))
89+ out, err := newAskAgentCall(a).evented(context.Background(), sink, handOff{in: askAgentInput{Agent: "homer", Prompt: "Implement specs/x.spec.md"}, req: ask.Request{Agent: "homer", Question: "Implement specs/x.spec.md", Via: hooks.ViaTool}, title: "ask_agent: homer (?)", id: askIdentity("Homer (coder)")})
9090 if err != nil || out != "Implemented R1 and R2." {
9191 t.Fatalf("result %q, err %v", out, err)
9292 }
@@ -107,7 +107,7 @@ func TestAskAgentRefused(t *testing.T) {
107107 withAgents(t, map[string]config.AgentRef{"homer": {Path: "/nowhere/homer.yaml"}})
108108 a := &fakeAgentAsker{answer: "never"}
109109 sink := &speakingSink{recordingSink: recordingSink{allow: false}}
110- out, _ := newAskAgentCall(a).evented(context.Background(), sink, askAgentInput{Agent: "homer", Prompt: "p"}, ask.Request{Agent: "homer", Question: "p"}, "t", askIdentity(""))
110+ out, _ := newAskAgentCall(a).evented(context.Background(), sink, handOff{in: askAgentInput{Agent: "homer", Prompt: "p"}, req: ask.Request{Agent: "homer", Question: "p"}, title: "t", id: askIdentity("")})
111111 if a.calls != 0 || out != "[ask_agent rejected by the user]" || sink.asked != 1 || len(sink.spoke) != 0 {
112112 t.Errorf("calls %d, out %q, asked %d, spoke %v", a.calls, out, sink.asked, sink.spoke)
113113 }
@@ -168,7 +168,7 @@ func TestAskAgentDeniedByAHook(t *testing.T) {
168168 withAgents(t, map[string]config.AgentRef{"homer": {Path: "/nowhere/homer.yaml"}})
169169 a := &fakeAgentAsker{result: &ask.Result{Question: "p"}, err: &ask.DeniedError{Agent: "homer", Reason: "budget spent"}}
170170 sink := &speakingSink{}
171- out, _ := newAskAgentCall(a).evented(context.Background(), sink, askAgentInput{Agent: "homer", Prompt: "p"}, ask.Request{Agent: "homer", Question: "p", Via: hooks.ViaTool}, "t", askIdentity(""))
171+ out, _ := newAskAgentCall(a).evented(context.Background(), sink, handOff{in: askAgentInput{Agent: "homer", Prompt: "p"}, req: ask.Request{Agent: "homer", Question: "p", Via: hooks.ViaTool}, title: "t", id: askIdentity("")})
172172 if out != "[ask denied by a hook: budget spent]" || !sink.ended.Failed || sink.ended.Output != out {
173173 t.Errorf("out %q, ended %+v", out, sink.ended)
174174 }
@@ -201,7 +201,7 @@ func TestAskAgentReadsThePostAskResult(t *testing.T) {
201201 withAgents(t, map[string]config.AgentRef{"homer": {Path: "/nowhere/homer.yaml"}})
202202 a := &fakeAgentAsker{result: &ask.Result{Question: "p", Answer: "short", Replaced: true, Context: []string{"no code block"}}}
203203 sink := &speakingSink{}
204- out, _ := newAskAgentCall(a).evented(context.Background(), sink, askAgentInput{Agent: "homer", Prompt: "p"}, ask.Request{Agent: "homer", Question: "p"}, "t", askIdentity(""))
204+ out, _ := newAskAgentCall(a).evented(context.Background(), sink, handOff{in: askAgentInput{Agent: "homer", Prompt: "p"}, req: ask.Request{Agent: "homer", Question: "p"}, title: "t", id: askIdentity("")})
205205 if want := "short\n\n" + hooks.ContextLabel + "no code block"; out != want {
206206 t.Errorf("out = %q, want %q", out, want)
207207 }
@@ -86,7 +86,7 @@ func TestAskAgentEvented(t *testing.T) {
86 a := &fakeAgentAsker{answer: "Implemented R1 and R2."}86 a := &fakeAgentAsker{answer: "Implemented R1 and R2."}
87 sink := &speakingSink{recordingSink: recordingSink{dir: "/proj"}}87 sink := &speakingSink{recordingSink: recordingSink{dir: "/proj"}}
88 88
89- out, err := newAskAgentCall(a).evented(context.Background(), sink, askAgentInput{Agent: "homer", Prompt: "Implement specs/x.spec.md"}, ask.Request{Agent: "homer", Question: "Implement specs/x.spec.md", Via: hooks.ViaTool}, "ask_agent: homer (?)", askIdentity("Homer (coder)"))89+ out, err := newAskAgentCall(a).evented(context.Background(), sink, handOff{in: askAgentInput{Agent: "homer", Prompt: "Implement specs/x.spec.md"}, req: ask.Request{Agent: "homer", Question: "Implement specs/x.spec.md", Via: hooks.ViaTool}, title: "ask_agent: homer (?)", id: askIdentity("Homer (coder)")})
90 if err != nil || out != "Implemented R1 and R2." {90 if err != nil || out != "Implemented R1 and R2." {
91 t.Fatalf("result %q, err %v", out, err)91 t.Fatalf("result %q, err %v", out, err)
92 }92 }
@@ -107,7 +107,7 @@ func TestAskAgentRefused(t *testing.T) {
107 withAgents(t, map[string]config.AgentRef{"homer": {Path: "/nowhere/homer.yaml"}})107 withAgents(t, map[string]config.AgentRef{"homer": {Path: "/nowhere/homer.yaml"}})
108 a := &fakeAgentAsker{answer: "never"}108 a := &fakeAgentAsker{answer: "never"}
109 sink := &speakingSink{recordingSink: recordingSink{allow: false}}109 sink := &speakingSink{recordingSink: recordingSink{allow: false}}
110- out, _ := newAskAgentCall(a).evented(context.Background(), sink, askAgentInput{Agent: "homer", Prompt: "p"}, ask.Request{Agent: "homer", Question: "p"}, "t", askIdentity(""))110+ out, _ := newAskAgentCall(a).evented(context.Background(), sink, handOff{in: askAgentInput{Agent: "homer", Prompt: "p"}, req: ask.Request{Agent: "homer", Question: "p"}, title: "t", id: askIdentity("")})
111 if a.calls != 0 || out != "[ask_agent rejected by the user]" || sink.asked != 1 || len(sink.spoke) != 0 {111 if a.calls != 0 || out != "[ask_agent rejected by the user]" || sink.asked != 1 || len(sink.spoke) != 0 {
112 t.Errorf("calls %d, out %q, asked %d, spoke %v", a.calls, out, sink.asked, sink.spoke)112 t.Errorf("calls %d, out %q, asked %d, spoke %v", a.calls, out, sink.asked, sink.spoke)
113 }113 }
@@ -168,7 +168,7 @@ func TestAskAgentDeniedByAHook(t *testing.T) {
168 withAgents(t, map[string]config.AgentRef{"homer": {Path: "/nowhere/homer.yaml"}})168 withAgents(t, map[string]config.AgentRef{"homer": {Path: "/nowhere/homer.yaml"}})
169 a := &fakeAgentAsker{result: &ask.Result{Question: "p"}, err: &ask.DeniedError{Agent: "homer", Reason: "budget spent"}}169 a := &fakeAgentAsker{result: &ask.Result{Question: "p"}, err: &ask.DeniedError{Agent: "homer", Reason: "budget spent"}}
170 sink := &speakingSink{}170 sink := &speakingSink{}
171- out, _ := newAskAgentCall(a).evented(context.Background(), sink, askAgentInput{Agent: "homer", Prompt: "p"}, ask.Request{Agent: "homer", Question: "p", Via: hooks.ViaTool}, "t", askIdentity(""))171+ out, _ := newAskAgentCall(a).evented(context.Background(), sink, handOff{in: askAgentInput{Agent: "homer", Prompt: "p"}, req: ask.Request{Agent: "homer", Question: "p", Via: hooks.ViaTool}, title: "t", id: askIdentity("")})
172 if out != "[ask denied by a hook: budget spent]" || !sink.ended.Failed || sink.ended.Output != out {172 if out != "[ask denied by a hook: budget spent]" || !sink.ended.Failed || sink.ended.Output != out {
173 t.Errorf("out %q, ended %+v", out, sink.ended)173 t.Errorf("out %q, ended %+v", out, sink.ended)
174 }174 }
@@ -201,7 +201,7 @@ func TestAskAgentReadsThePostAskResult(t *testing.T) {
201 withAgents(t, map[string]config.AgentRef{"homer": {Path: "/nowhere/homer.yaml"}})201 withAgents(t, map[string]config.AgentRef{"homer": {Path: "/nowhere/homer.yaml"}})
202 a := &fakeAgentAsker{result: &ask.Result{Question: "p", Answer: "short", Replaced: true, Context: []string{"no code block"}}}202 a := &fakeAgentAsker{result: &ask.Result{Question: "p", Answer: "short", Replaced: true, Context: []string{"no code block"}}}
203 sink := &speakingSink{}203 sink := &speakingSink{}
204- out, _ := newAskAgentCall(a).evented(context.Background(), sink, askAgentInput{Agent: "homer", Prompt: "p"}, ask.Request{Agent: "homer", Question: "p"}, "t", askIdentity(""))204+ out, _ := newAskAgentCall(a).evented(context.Background(), sink, handOff{in: askAgentInput{Agent: "homer", Prompt: "p"}, req: ask.Request{Agent: "homer", Question: "p"}, title: "t", id: askIdentity("")})
205 if want := "short\n\n" + hooks.ContextLabel + "no code block"; out != want {205 if want := "short\n\n" + hooks.ContextLabel + "no code block"; out != want {
206 t.Errorf("out = %q, want %q", out, want)206 t.Errorf("out = %q, want %q", out, want)
207 }207 }
modified internal/tools/askuser.go +5 -5
@@ -86,7 +86,7 @@ func askUser(ctx context.Context, d *detector.LoopDetector, input map[string]any
8686 return recordFailure(d, "ask_user", key, problem)
8787 }
8888 if s := ui.ActiveSink(); s != nil {
89- return askUserEvented(ctx, d, s, input, form, key)
89+ return askUserEvented(ctx, d, s, input, form)
9090 }
9191 // The questions themselves are printed by the prompter, just below.
9292 announce(fmt.Sprintf("❓ ask_user: %d question(s)", len(form.Questions)))
@@ -96,7 +96,7 @@ func askUser(ctx context.Context, d *detector.LoopDetector, input map[string]any
9696
9797 // askUserEvented is ask_user for an event-consuming front end: one tool call,
9898 // the questions asked by the sink when it can ask (ui.Elicitor).
99-func askUserEvented(ctx context.Context, d *detector.LoopDetector, s ui.Sink, input map[string]any, form elicit.Form, key string) (string, error) {
99+func askUserEvented(ctx context.Context, d *detector.LoopDetector, s ui.Sink, input map[string]any, form elicit.Form) (string, error) {
100100 ev := ui.ToolEvent{
101101 ID: ui.NextCallID(),
102102 Tool: "ask_user",
@@ -112,15 +112,15 @@ func askUserEvented(ctx context.Context, d *detector.LoopDetector, s ui.Sink, in
112112 }
113113 out := res.Text(form)
114114 s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: res.Status != elicit.Answered})
115- return recordOutcome(d, "ask_user", key, out, res.Status != elicit.Answered)
115+ return recordOutcome(d, "ask_user", askUserKey(input), out, res.Status != elicit.Answered)
116116 }
117117
118118 // whileWaiting runs ask and beats a watchdog (beat) every second until it
119119 // returns: a question waiting for a human is not a hung server, and the
120120 // watchdog keeps counting while a tool runs. A stopped turn still ends the
121121 // wait — ask watches the turn's context.
122-func whileWaiting(beat func(), ask func() elicit.Result) elicit.Result {
123- done := make(chan elicit.Result, 1)
122+func whileWaiting[T any](beat func(), ask func() T) T {
123+ done := make(chan T, 1)
124124 go func() { done <- ask() }()
125125 ticker := time.NewTicker(time.Second)
126126 defer ticker.Stop()
@@ -86,7 +86,7 @@ func askUser(ctx context.Context, d *detector.LoopDetector, input map[string]any
86 return recordFailure(d, "ask_user", key, problem)86 return recordFailure(d, "ask_user", key, problem)
87 }87 }
88 if s := ui.ActiveSink(); s != nil {88 if s := ui.ActiveSink(); s != nil {
89- return askUserEvented(ctx, d, s, input, form, key)89+ return askUserEvented(ctx, d, s, input, form)
90 }90 }
91 // The questions themselves are printed by the prompter, just below.91 // The questions themselves are printed by the prompter, just below.
92 announce(fmt.Sprintf("❓ ask_user: %d question(s)", len(form.Questions)))92 announce(fmt.Sprintf("❓ ask_user: %d question(s)", len(form.Questions)))
@@ -96,7 +96,7 @@ func askUser(ctx context.Context, d *detector.LoopDetector, input map[string]any
96 96
97 // askUserEvented is ask_user for an event-consuming front end: one tool call,97 // askUserEvented is ask_user for an event-consuming front end: one tool call,
98 // the questions asked by the sink when it can ask (ui.Elicitor).98 // the questions asked by the sink when it can ask (ui.Elicitor).
99-func askUserEvented(ctx context.Context, d *detector.LoopDetector, s ui.Sink, input map[string]any, form elicit.Form, key string) (string, error) {99+func askUserEvented(ctx context.Context, d *detector.LoopDetector, s ui.Sink, input map[string]any, form elicit.Form) (string, error) {
100 ev := ui.ToolEvent{100 ev := ui.ToolEvent{
101 ID: ui.NextCallID(),101 ID: ui.NextCallID(),
102 Tool: "ask_user",102 Tool: "ask_user",
@@ -112,15 +112,15 @@ func askUserEvented(ctx context.Context, d *detector.LoopDetector, s ui.Sink, in
112 }112 }
113 out := res.Text(form)113 out := res.Text(form)
114 s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: res.Status != elicit.Answered})114 s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: res.Status != elicit.Answered})
115- return recordOutcome(d, "ask_user", key, out, res.Status != elicit.Answered)115+ return recordOutcome(d, "ask_user", askUserKey(input), out, res.Status != elicit.Answered)
116 }116 }
117 117
118 // whileWaiting runs ask and beats a watchdog (beat) every second until it118 // whileWaiting runs ask and beats a watchdog (beat) every second until it
119 // returns: a question waiting for a human is not a hung server, and the119 // returns: a question waiting for a human is not a hung server, and the
120 // watchdog keeps counting while a tool runs. A stopped turn still ends the120 // watchdog keeps counting while a tool runs. A stopped turn still ends the
121 // wait — ask watches the turn's context.121 // wait — ask watches the turn's context.
122-func whileWaiting(beat func(), ask func() elicit.Result) elicit.Result {122+func whileWaiting[T any](beat func(), ask func() T) T {
123- done := make(chan elicit.Result, 1)123+ done := make(chan T, 1)
124 go func() { done <- ask() }()124 go func() { done <- ask() }()
125 ticker := time.NewTicker(time.Second)125 ticker := time.NewTicker(time.Second)
126 defer ticker.Stop()126 defer ticker.Stop()
modified internal/tools/declared.go +0 -132
@@ -2,13 +2,9 @@ package tools
22
33 import (
44 "context"
5- "encoding/json"
65 "fmt"
7- "maps"
86 "os"
97 "path/filepath"
10- "slices"
11- "strconv"
128 "strings"
139 "time"
1410
@@ -231,131 +227,3 @@ func (c declaredCall) timeout() time.Duration {
231227 }
232228 return config.Cfg.BashTimeout
233229 }
234-
235-// buildArgv checks a call against the tool's parameters and, when it holds,
236-// returns the command with every placeholder replaced. problem is the text
237-// the model gets instead when it does not — every fault at once, what it
238-// sent, and what the tool expects.
239-//
240-// buildArgv(release, map[string]any{"version": "1.4.2", "channel": "beta"})
241-// // ["./scripts/release.sh", "1.4.2", "beta"], ""
242-func buildArgv(t config.DeclaredTool, in map[string]any) (argv []string, problem string) {
243- values, faults := callValues(t, in)
244- if len(faults) > 0 {
245- return nil, invalidCall(t, in, faults)
246- }
247- for _, entry := range t.Command {
248- if name, alone := onlyPlaceholder(entry); alone {
249- if _, given := values[name]; !given {
250- // An optional parameter left out removes its argument
251- // rather than passing an empty one.
252- continue
253- }
254- }
255- argv = append(argv, config.ReplacePlaceholders(entry, func(name string) string {
256- if v, given := values[name]; given {
257- return argText(v)
258- }
259- return ""
260- }))
261- }
262- return argv, ""
263-}
264-
265-// wasmInput checks a call like buildArgv does and, when it holds, returns
266-// the module's stdin: the parameters given or defaulted, typed, as JSON.
267-//
268-// wasmInput(wordStats, map[string]any{"text": "a b", "top": "3"})
269-// // {"text":"a b","top":3}, ""
270-func wasmInput(t config.DeclaredTool, in map[string]any) (input []byte, problem string) {
271- values, faults := callValues(t, in)
272- if len(faults) > 0 {
273- return nil, invalidCall(t, in, faults)
274- }
275- input, err := json.Marshal(values)
276- if err != nil {
277- return nil, fmt.Sprintf("[%s: the call cannot be written as JSON: %v]", t.Name, err)
278- }
279- return input, ""
280-}
281-
282-// callValues coerces each parameter of the call to its declared type,
283-// applying defaults; faults lists what is wrong. A parameter left out with
284-// no default is absent from values.
285-func callValues(t config.DeclaredTool, in map[string]any) (values map[string]any, faults []string) {
286- values = map[string]any{}
287- for _, key := range slices.Sorted(maps.Keys(in)) {
288- if _, ok := t.Parameters.Find(key); !ok {
289- faults = append(faults, fmt.Sprintf("%q is not a parameter of this tool", key))
290- }
291- }
292- for _, p := range t.Parameters {
293- raw, given := in[p.Name]
294- if !given || raw == nil {
295- switch {
296- case p.Default != nil:
297- raw = p.Default
298- case p.IsRequired():
299- faults = append(faults, p.Name+" is missing")
300- continue
301- default:
302- continue
303- }
304- }
305- v, err := p.Coerce(raw)
306- if err != nil {
307- faults = append(faults, fmt.Sprintf("%s: %v", p.Name, err))
308- continue
309- }
310- if !p.Allows(v) {
311- faults = append(faults, fmt.Sprintf("%s: %v is not one of %s", p.Name, raw, p.EnumText()))
312- continue
313- }
314- values[p.Name] = v
315- }
316- return values, faults
317-}
318-
319-// invalidCall is the refusal the model reads. It quotes the call back: a
320-// model that packed two arguments into one field sees it written out.
321-func invalidCall(t config.DeclaredTool, in map[string]any, faults []string) string {
322- var expected []string
323- for _, p := range t.Parameters {
324- expected = append(expected, fmt.Sprintf("%s (%s, %s)", p.Name, p.Type, parameterDescription(p)))
325- }
326- return fmt.Sprintf("[%s: invalid call, nothing was run — %s. You sent: %s. Expected: %s. Call %s again with each parameter as its own field.]",
327- t.Name, strings.Join(faults, "; "), inputText(in), strings.Join(expected, "; "), t.Name)
328-}
329-
330-// onlyPlaceholder reports whether entry is exactly one {{name}}.
331-func onlyPlaceholder(entry string) (name string, alone bool) {
332- names := config.Placeholders(entry)
333- if len(names) != 1 {
334- return "", false
335- }
336- return names[0], strings.TrimSpace(config.ReplacePlaceholders(entry, func(string) string { return "" })) == ""
337-}
338-
339-// argText renders a coerced value as one argv entry: integers without a
340-// decimal point, numbers without an exponent, booleans as true/false.
341-func argText(v any) string {
342- switch x := v.(type) {
343- case int64:
344- return strconv.FormatInt(x, 10)
345- case float64:
346- return strconv.FormatFloat(x, 'f', -1, 64)
347- case bool:
348- return strconv.FormatBool(x)
349- default:
350- return fmt.Sprint(x)
351- }
352-}
353-
354-// inputText is the call's input as compact JSON, keys sorted.
355-func inputText(in map[string]any) string {
356- b, err := json.Marshal(in)
357- if err != nil {
358- return fmt.Sprint(in)
359- }
360- return string(b)
361-}
@@ -2,13 +2,9 @@ package tools
2 2
3 import (3 import (
4 "context"4 "context"
5- "encoding/json"
6 "fmt"5 "fmt"
7- "maps"
8 "os"6 "os"
9 "path/filepath"7 "path/filepath"
10- "slices"
11- "strconv"
12 "strings"8 "strings"
13 "time"9 "time"
14 10
@@ -231,131 +227,3 @@ func (c declaredCall) timeout() time.Duration {
231 }227 }
232 return config.Cfg.BashTimeout228 return config.Cfg.BashTimeout
233 }229 }
234-
235-// buildArgv checks a call against the tool's parameters and, when it holds,
236-// returns the command with every placeholder replaced. problem is the text
237-// the model gets instead when it does not — every fault at once, what it
238-// sent, and what the tool expects.
239-//
240-// buildArgv(release, map[string]any{"version": "1.4.2", "channel": "beta"})
241-// // ["./scripts/release.sh", "1.4.2", "beta"], ""
242-func buildArgv(t config.DeclaredTool, in map[string]any) (argv []string, problem string) {
243- values, faults := callValues(t, in)
244- if len(faults) > 0 {
245- return nil, invalidCall(t, in, faults)
246- }
247- for _, entry := range t.Command {
248- if name, alone := onlyPlaceholder(entry); alone {
249- if _, given := values[name]; !given {
250- // An optional parameter left out removes its argument
251- // rather than passing an empty one.
252- continue
253- }
254- }
255- argv = append(argv, config.ReplacePlaceholders(entry, func(name string) string {
256- if v, given := values[name]; given {
257- return argText(v)
258- }
259- return ""
260- }))
261- }
262- return argv, ""
263-}
264-
265-// wasmInput checks a call like buildArgv does and, when it holds, returns
266-// the module's stdin: the parameters given or defaulted, typed, as JSON.
267-//
268-// wasmInput(wordStats, map[string]any{"text": "a b", "top": "3"})
269-// // {"text":"a b","top":3}, ""
270-func wasmInput(t config.DeclaredTool, in map[string]any) (input []byte, problem string) {
271- values, faults := callValues(t, in)
272- if len(faults) > 0 {
273- return nil, invalidCall(t, in, faults)
274- }
275- input, err := json.Marshal(values)
276- if err != nil {
277- return nil, fmt.Sprintf("[%s: the call cannot be written as JSON: %v]", t.Name, err)
278- }
279- return input, ""
280-}
281-
282-// callValues coerces each parameter of the call to its declared type,
283-// applying defaults; faults lists what is wrong. A parameter left out with
284-// no default is absent from values.
285-func callValues(t config.DeclaredTool, in map[string]any) (values map[string]any, faults []string) {
286- values = map[string]any{}
287- for _, key := range slices.Sorted(maps.Keys(in)) {
288- if _, ok := t.Parameters.Find(key); !ok {
289- faults = append(faults, fmt.Sprintf("%q is not a parameter of this tool", key))
290- }
291- }
292- for _, p := range t.Parameters {
293- raw, given := in[p.Name]
294- if !given || raw == nil {
295- switch {
296- case p.Default != nil:
297- raw = p.Default
298- case p.IsRequired():
299- faults = append(faults, p.Name+" is missing")
300- continue
301- default:
302- continue
303- }
304- }
305- v, err := p.Coerce(raw)
306- if err != nil {
307- faults = append(faults, fmt.Sprintf("%s: %v", p.Name, err))
308- continue
309- }
310- if !p.Allows(v) {
311- faults = append(faults, fmt.Sprintf("%s: %v is not one of %s", p.Name, raw, p.EnumText()))
312- continue
313- }
314- values[p.Name] = v
315- }
316- return values, faults
317-}
318-
319-// invalidCall is the refusal the model reads. It quotes the call back: a
320-// model that packed two arguments into one field sees it written out.
321-func invalidCall(t config.DeclaredTool, in map[string]any, faults []string) string {
322- var expected []string
323- for _, p := range t.Parameters {
324- expected = append(expected, fmt.Sprintf("%s (%s, %s)", p.Name, p.Type, parameterDescription(p)))
325- }
326- return fmt.Sprintf("[%s: invalid call, nothing was run — %s. You sent: %s. Expected: %s. Call %s again with each parameter as its own field.]",
327- t.Name, strings.Join(faults, "; "), inputText(in), strings.Join(expected, "; "), t.Name)
328-}
329-
330-// onlyPlaceholder reports whether entry is exactly one {{name}}.
331-func onlyPlaceholder(entry string) (name string, alone bool) {
332- names := config.Placeholders(entry)
333- if len(names) != 1 {
334- return "", false
335- }
336- return names[0], strings.TrimSpace(config.ReplacePlaceholders(entry, func(string) string { return "" })) == ""
337-}
338-
339-// argText renders a coerced value as one argv entry: integers without a
340-// decimal point, numbers without an exponent, booleans as true/false.
341-func argText(v any) string {
342- switch x := v.(type) {
343- case int64:
344- return strconv.FormatInt(x, 10)
345- case float64:
346- return strconv.FormatFloat(x, 'f', -1, 64)
347- case bool:
348- return strconv.FormatBool(x)
349- default:
350- return fmt.Sprint(x)
351- }
352-}
353-
354-// inputText is the call's input as compact JSON, keys sorted.
355-func inputText(in map[string]any) string {
356- b, err := json.Marshal(in)
357- if err != nil {
358- return fmt.Sprint(in)
359- }
360- return string(b)
361-}
added internal/tools/declared_args.go +140 -0
new file mode 100644
@@ -0,0 +1,140 @@
1+package tools
2+
3+import (
4+ "encoding/json"
5+ "fmt"
6+ "maps"
7+ "slices"
8+ "strconv"
9+ "strings"
10+
11+ "mm/internal/config"
12+)
13+
14+// buildArgv checks a call against the tool's parameters and, when it holds,
15+// returns the command with every placeholder replaced. problem is the text
16+// the model gets instead when it does not — every fault at once, what it
17+// sent, and what the tool expects.
18+//
19+// buildArgv(release, map[string]any{"version": "1.4.2", "channel": "beta"})
20+// // ["./scripts/release.sh", "1.4.2", "beta"], ""
21+func buildArgv(t config.DeclaredTool, in map[string]any) (argv []string, problem string) {
22+ values, faults := callValues(t, in)
23+ if len(faults) > 0 {
24+ return nil, invalidCall(t, in, faults)
25+ }
26+ for _, entry := range t.Command {
27+ if name, alone := onlyPlaceholder(entry); alone {
28+ if _, given := values[name]; !given {
29+ // An optional parameter left out removes its argument
30+ // rather than passing an empty one.
31+ continue
32+ }
33+ }
34+ argv = append(argv, config.ReplacePlaceholders(entry, func(name string) string {
35+ if v, given := values[name]; given {
36+ return argText(v)
37+ }
38+ return ""
39+ }))
40+ }
41+ return argv, ""
42+}
43+
44+// wasmInput checks a call like buildArgv does and, when it holds, returns
45+// the module's stdin: the parameters given or defaulted, typed, as JSON.
46+//
47+// wasmInput(wordStats, map[string]any{"text": "a b", "top": "3"})
48+// // {"text":"a b","top":3}, ""
49+func wasmInput(t config.DeclaredTool, in map[string]any) (input []byte, problem string) {
50+ values, faults := callValues(t, in)
51+ if len(faults) > 0 {
52+ return nil, invalidCall(t, in, faults)
53+ }
54+ input, err := json.Marshal(values)
55+ if err != nil {
56+ return nil, fmt.Sprintf("[%s: the call cannot be written as JSON: %v]", t.Name, err)
57+ }
58+ return input, ""
59+}
60+
61+// callValues coerces each parameter of the call to its declared type,
62+// applying defaults; faults lists what is wrong. A parameter left out with
63+// no default is absent from values.
64+func callValues(t config.DeclaredTool, in map[string]any) (values map[string]any, faults []string) {
65+ values = map[string]any{}
66+ for _, key := range slices.Sorted(maps.Keys(in)) {
67+ if _, ok := t.Parameters.Find(key); !ok {
68+ faults = append(faults, fmt.Sprintf("%q is not a parameter of this tool", key))
69+ }
70+ }
71+ for _, p := range t.Parameters {
72+ raw, given := in[p.Name]
73+ if !given || raw == nil {
74+ switch {
75+ case p.Default != nil:
76+ raw = p.Default
77+ case p.IsRequired():
78+ faults = append(faults, p.Name+" is missing")
79+ continue
80+ default:
81+ continue
82+ }
83+ }
84+ v, err := p.Coerce(raw)
85+ if err != nil {
86+ faults = append(faults, fmt.Sprintf("%s: %v", p.Name, err))
87+ continue
88+ }
89+ if !p.Allows(v) {
90+ faults = append(faults, fmt.Sprintf("%s: %v is not one of %s", p.Name, raw, p.EnumText()))
91+ continue
92+ }
93+ values[p.Name] = v
94+ }
95+ return values, faults
96+}
97+
98+// invalidCall is the refusal the model reads. It quotes the call back: a
99+// model that packed two arguments into one field sees it written out.
100+func invalidCall(t config.DeclaredTool, in map[string]any, faults []string) string {
101+ var expected []string
102+ for _, p := range t.Parameters {
103+ expected = append(expected, fmt.Sprintf("%s (%s, %s)", p.Name, p.Type, parameterDescription(p)))
104+ }
105+ return fmt.Sprintf("[%s: invalid call, nothing was run — %s. You sent: %s. Expected: %s. Call %s again with each parameter as its own field.]",
106+ t.Name, strings.Join(faults, "; "), inputText(in), strings.Join(expected, "; "), t.Name)
107+}
108+
109+// onlyPlaceholder reports whether entry is exactly one {{name}}.
110+func onlyPlaceholder(entry string) (name string, alone bool) {
111+ names := config.Placeholders(entry)
112+ if len(names) != 1 {
113+ return "", false
114+ }
115+ return names[0], strings.TrimSpace(config.ReplacePlaceholders(entry, func(string) string { return "" })) == ""
116+}
117+
118+// argText renders a coerced value as one argv entry: integers without a
119+// decimal point, numbers without an exponent, booleans as true/false.
120+func argText(v any) string {
121+ switch x := v.(type) {
122+ case int64:
123+ return strconv.FormatInt(x, 10)
124+ case float64:
125+ return strconv.FormatFloat(x, 'f', -1, 64)
126+ case bool:
127+ return strconv.FormatBool(x)
128+ default:
129+ return fmt.Sprint(x)
130+ }
131+}
132+
133+// inputText is the call's input as compact JSON, keys sorted.
134+func inputText(in map[string]any) string {
135+ b, err := json.Marshal(in)
136+ if err != nil {
137+ return fmt.Sprint(in)
138+ }
139+ return string(b)
140+}
new file mode 100644
@@ -0,0 +1,140 @@
1+package tools
2+
3+import (
4+ "encoding/json"
5+ "fmt"
6+ "maps"
7+ "slices"
8+ "strconv"
9+ "strings"
10+
11+ "mm/internal/config"
12+)
13+
14+// buildArgv checks a call against the tool's parameters and, when it holds,
15+// returns the command with every placeholder replaced. problem is the text
16+// the model gets instead when it does not — every fault at once, what it
17+// sent, and what the tool expects.
18+//
19+// buildArgv(release, map[string]any{"version": "1.4.2", "channel": "beta"})
20+// // ["./scripts/release.sh", "1.4.2", "beta"], ""
21+func buildArgv(t config.DeclaredTool, in map[string]any) (argv []string, problem string) {
22+ values, faults := callValues(t, in)
23+ if len(faults) > 0 {
24+ return nil, invalidCall(t, in, faults)
25+ }
26+ for _, entry := range t.Command {
27+ if name, alone := onlyPlaceholder(entry); alone {
28+ if _, given := values[name]; !given {
29+ // An optional parameter left out removes its argument
30+ // rather than passing an empty one.
31+ continue
32+ }
33+ }
34+ argv = append(argv, config.ReplacePlaceholders(entry, func(name string) string {
35+ if v, given := values[name]; given {
36+ return argText(v)
37+ }
38+ return ""
39+ }))
40+ }
41+ return argv, ""
42+}
43+
44+// wasmInput checks a call like buildArgv does and, when it holds, returns
45+// the module's stdin: the parameters given or defaulted, typed, as JSON.
46+//
47+// wasmInput(wordStats, map[string]any{"text": "a b", "top": "3"})
48+// // {"text":"a b","top":3}, ""
49+func wasmInput(t config.DeclaredTool, in map[string]any) (input []byte, problem string) {
50+ values, faults := callValues(t, in)
51+ if len(faults) > 0 {
52+ return nil, invalidCall(t, in, faults)
53+ }
54+ input, err := json.Marshal(values)
55+ if err != nil {
56+ return nil, fmt.Sprintf("[%s: the call cannot be written as JSON: %v]", t.Name, err)
57+ }
58+ return input, ""
59+}
60+
61+// callValues coerces each parameter of the call to its declared type,
62+// applying defaults; faults lists what is wrong. A parameter left out with
63+// no default is absent from values.
64+func callValues(t config.DeclaredTool, in map[string]any) (values map[string]any, faults []string) {
65+ values = map[string]any{}
66+ for _, key := range slices.Sorted(maps.Keys(in)) {
67+ if _, ok := t.Parameters.Find(key); !ok {
68+ faults = append(faults, fmt.Sprintf("%q is not a parameter of this tool", key))
69+ }
70+ }
71+ for _, p := range t.Parameters {
72+ raw, given := in[p.Name]
73+ if !given || raw == nil {
74+ switch {
75+ case p.Default != nil:
76+ raw = p.Default
77+ case p.IsRequired():
78+ faults = append(faults, p.Name+" is missing")
79+ continue
80+ default:
81+ continue
82+ }
83+ }
84+ v, err := p.Coerce(raw)
85+ if err != nil {
86+ faults = append(faults, fmt.Sprintf("%s: %v", p.Name, err))
87+ continue
88+ }
89+ if !p.Allows(v) {
90+ faults = append(faults, fmt.Sprintf("%s: %v is not one of %s", p.Name, raw, p.EnumText()))
91+ continue
92+ }
93+ values[p.Name] = v
94+ }
95+ return values, faults
96+}
97+
98+// invalidCall is the refusal the model reads. It quotes the call back: a
99+// model that packed two arguments into one field sees it written out.
100+func invalidCall(t config.DeclaredTool, in map[string]any, faults []string) string {
101+ var expected []string
102+ for _, p := range t.Parameters {
103+ expected = append(expected, fmt.Sprintf("%s (%s, %s)", p.Name, p.Type, parameterDescription(p)))
104+ }
105+ return fmt.Sprintf("[%s: invalid call, nothing was run — %s. You sent: %s. Expected: %s. Call %s again with each parameter as its own field.]",
106+ t.Name, strings.Join(faults, "; "), inputText(in), strings.Join(expected, "; "), t.Name)
107+}
108+
109+// onlyPlaceholder reports whether entry is exactly one {{name}}.
110+func onlyPlaceholder(entry string) (name string, alone bool) {
111+ names := config.Placeholders(entry)
112+ if len(names) != 1 {
113+ return "", false
114+ }
115+ return names[0], strings.TrimSpace(config.ReplacePlaceholders(entry, func(string) string { return "" })) == ""
116+}
117+
118+// argText renders a coerced value as one argv entry: integers without a
119+// decimal point, numbers without an exponent, booleans as true/false.
120+func argText(v any) string {
121+ switch x := v.(type) {
122+ case int64:
123+ return strconv.FormatInt(x, 10)
124+ case float64:
125+ return strconv.FormatFloat(x, 'f', -1, 64)
126+ case bool:
127+ return strconv.FormatBool(x)
128+ default:
129+ return fmt.Sprint(x)
130+ }
131+}
132+
133+// inputText is the call's input as compact JSON, keys sorted.
134+func inputText(in map[string]any) string {
135+ b, err := json.Marshal(in)
136+ if err != nil {
137+ return fmt.Sprint(in)
138+ }
139+ return string(b)
140+}
modified internal/tools/files.go +0 -147
@@ -1,13 +1,9 @@
11 package tools
22
33 import (
4- "context"
54 "fmt"
6- "os"
7- "path/filepath"
85 "strings"
96
10- "mm/internal/consent"
117 "mm/internal/detector"
128 "mm/internal/fileedit"
139 "mm/internal/spinner"
@@ -234,146 +230,3 @@ func editKey(in editFileInput) string {
234230 }
235231 return b.String()
236232 }
237-
238-// --- the same three tools, for an event-consuming front end (ACP) -------------
239-//
240-// The information is the same as the terminal path prints; only the channel
241-// changes. Two things exist here that the terminal never had: write_file and
242-// edit_file ask the client's user for permission before touching a file, and a
243-// successful change travels as a structured diff the editor can render. Paths
244-// resolve against the SESSION's working directory (the project open in the
245-// editor), not the process's — that is ui.Resolve.
246-
247-// absolute is the location a client can jump to: ACP wants absolute paths.
248-func absolute(path string) string {
249- if abs, err := filepath.Abs(path); err == nil {
250- return abs
251- }
252- return path
253-}
254-
255-func readFileEvented(s ui.Sink, d *detector.LoopDetector, in readFileInput, where string) (string, error) {
256- path := ui.Resolve(in.Path)
257- ev := ui.ToolEvent{
258- ID: ui.NextCallID(),
259- Tool: "read_file",
260- Title: "read_file: " + where,
261- Kind: "read",
262- Input: map[string]any{"path": in.Path},
263- Path: absolute(path),
264- }
265- // Reading is not gated: the permission dialog exists to protect the user's
266- // files from changes and their shell from commands, and asking before every
267- // read teaches them to stop reading the dialogs.
268- s.ToolStart(ev)
269- s.ToolRunning(ev.ID)
270-
271- content, err := fileedit.Read(path, in.Start, in.End, in.Numbered)
272- if err != nil {
273- out := err.Error()
274- s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: true})
275- return recordFailure(d, "read_file", where, out)
276- }
277- out := truncate(content) + diagnosticsAfterRead(path)
278- s.ToolEnd(ev.ID, ui.ToolResult{Output: out})
279- return record(d, "read_file", where, out)
280-}
281-
282-func writeFileEvented(ctx context.Context, s ui.Sink, d *detector.LoopDetector, in writeFileInput) (string, error) {
283- path := ui.Resolve(in.Path)
284- ev := ui.ToolEvent{
285- ID: ui.NextCallID(),
286- Tool: "write_file",
287- Title: fmt.Sprintf("write_file: %s (%d bytes)", in.Path, len(in.Content)),
288- Kind: "edit",
289- Input: map[string]any{"path": in.Path},
290- Path: absolute(path),
291- }
292- s.ToolStart(ev)
293- if !consent.Gate(ctx, s, ev) {
294- out := "[write_file rejected by the user]"
295- s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: true})
296- return recordFailure(d, "write_file", in.Path, out)
297- }
298- s.ToolRunning(ev.ID)
299-
300- // The old content is read BEFORE the write, for the diff the client
301- // renders. Best effort: an unreadable file simply means "created".
302- before, readErr := os.ReadFile(path)
303-
304- r, err := fileedit.Write(path, in.Content)
305- if err != nil {
306- out := err.Error()
307- s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: true})
308- return recordFailure(d, "write_file", in.Path, out)
309- }
310- out := resultText(r) + diagnosticsAfter(r)
311- res := ui.ToolResult{Output: out}
312- if r.Changed {
313- res.Diff = &ui.Diff{Path: absolute(path), OldText: string(before), NewText: in.Content, Created: readErr != nil}
314- }
315- s.ToolEnd(ev.ID, res)
316- return record(d, "write_file", in.Path, truncate(out))
317-}
318-
319-func editFileEvented(ctx context.Context, s ui.Sink, d *detector.LoopDetector, in editFileInput, what string) (string, error) {
320- path := ui.Resolve(in.Path)
321- ev := ui.ToolEvent{
322- ID: ui.NextCallID(),
323- Tool: "edit_file",
324- Title: "edit_file: " + what,
325- Kind: "edit",
326- Input: map[string]any{"path": in.Path, "edits": len(in.Edits), "dry_run": in.DryRun},
327- Path: absolute(path),
328- }
329- s.ToolStart(ev)
330- if !consent.Gate(ctx, s, ev) {
331- out := "[edit_file rejected by the user]"
332- s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: true})
333- return recordFailure(d, "edit_file", editKey(in), out)
334- }
335- s.ToolRunning(ev.ID)
336-
337- before, _ := os.ReadFile(path)
338-
339- r, err := fileedit.Replace(path, in.Edits, in.DryRun)
340- if err != nil {
341- // A refused edit (text not found, ambiguous, overlapping) is the
342- // NORMAL path of this tool: failed status for the client, text for the
343- // model — which reads the rule and fixes its `old`.
344- out := err.Error()
345- s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: true})
346- return recordFailure(d, "edit_file", editKey(in), out)
347- }
348- out := resultText(r) + diagnosticsAfter(r)
349- res := ui.ToolResult{Output: out}
350- if r.Changed && !in.DryRun {
351- after, readErr := os.ReadFile(path)
352- if readErr == nil {
353- res.Diff = &ui.Diff{Path: absolute(path), OldText: string(before), NewText: string(after)}
354- }
355- }
356- s.ToolEnd(ev.ID, res)
357- return record(d, "edit_file", editKey(in), truncate(out))
358-}
359-
360-// resultText is what report() builds for the model, without the echo: the
361-// headline, then the numbered diff.
362-func resultText(r fileedit.Result) string {
363- out := r.Headline
364- if r.Diff != "" {
365- out += "\n" + strings.TrimRight(r.Diff, "\n")
366- }
367- return out
368-}
369-
370-// report echoes a write/edit result to the user — headline then diff, dimmed
371-// and capped by previewLines like a command's output — and returns the same
372-// text to the model, capped by maxOutput. The user sees the change BEFORE the
373-// model comments on it: what the file became no longer depends on what the
374-// model chooses to say about it.
375-func report(d *detector.LoopDetector, tool, key string, r fileedit.Result) (string, error) {
376- out := resultText(r) + diagnosticsAfter(r)
377- spinner.Suspend(func() { echoOutput(out) })
378- return record(d, tool, key, truncate(out))
379-}
@@ -1,13 +1,9 @@
1 package tools1 package tools
2 2
3 import (3 import (
4- "context"
5 "fmt"4 "fmt"
6- "os"
7- "path/filepath"
8 "strings"5 "strings"
9 6
10- "mm/internal/consent"
11 "mm/internal/detector"7 "mm/internal/detector"
12 "mm/internal/fileedit"8 "mm/internal/fileedit"
13 "mm/internal/spinner"9 "mm/internal/spinner"
@@ -234,146 +230,3 @@ func editKey(in editFileInput) string {
234 }230 }
235 return b.String()231 return b.String()
236 }232 }
237-
238-// --- the same three tools, for an event-consuming front end (ACP) -------------
239-//
240-// The information is the same as the terminal path prints; only the channel
241-// changes. Two things exist here that the terminal never had: write_file and
242-// edit_file ask the client's user for permission before touching a file, and a
243-// successful change travels as a structured diff the editor can render. Paths
244-// resolve against the SESSION's working directory (the project open in the
245-// editor), not the process's — that is ui.Resolve.
246-
247-// absolute is the location a client can jump to: ACP wants absolute paths.
248-func absolute(path string) string {
249- if abs, err := filepath.Abs(path); err == nil {
250- return abs
251- }
252- return path
253-}
254-
255-func readFileEvented(s ui.Sink, d *detector.LoopDetector, in readFileInput, where string) (string, error) {
256- path := ui.Resolve(in.Path)
257- ev := ui.ToolEvent{
258- ID: ui.NextCallID(),
259- Tool: "read_file",
260- Title: "read_file: " + where,
261- Kind: "read",
262- Input: map[string]any{"path": in.Path},
263- Path: absolute(path),
264- }
265- // Reading is not gated: the permission dialog exists to protect the user's
266- // files from changes and their shell from commands, and asking before every
267- // read teaches them to stop reading the dialogs.
268- s.ToolStart(ev)
269- s.ToolRunning(ev.ID)
270-
271- content, err := fileedit.Read(path, in.Start, in.End, in.Numbered)
272- if err != nil {
273- out := err.Error()
274- s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: true})
275- return recordFailure(d, "read_file", where, out)
276- }
277- out := truncate(content) + diagnosticsAfterRead(path)
278- s.ToolEnd(ev.ID, ui.ToolResult{Output: out})
279- return record(d, "read_file", where, out)
280-}
281-
282-func writeFileEvented(ctx context.Context, s ui.Sink, d *detector.LoopDetector, in writeFileInput) (string, error) {
283- path := ui.Resolve(in.Path)
284- ev := ui.ToolEvent{
285- ID: ui.NextCallID(),
286- Tool: "write_file",
287- Title: fmt.Sprintf("write_file: %s (%d bytes)", in.Path, len(in.Content)),
288- Kind: "edit",
289- Input: map[string]any{"path": in.Path},
290- Path: absolute(path),
291- }
292- s.ToolStart(ev)
293- if !consent.Gate(ctx, s, ev) {
294- out := "[write_file rejected by the user]"
295- s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: true})
296- return recordFailure(d, "write_file", in.Path, out)
297- }
298- s.ToolRunning(ev.ID)
299-
300- // The old content is read BEFORE the write, for the diff the client
301- // renders. Best effort: an unreadable file simply means "created".
302- before, readErr := os.ReadFile(path)
303-
304- r, err := fileedit.Write(path, in.Content)
305- if err != nil {
306- out := err.Error()
307- s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: true})
308- return recordFailure(d, "write_file", in.Path, out)
309- }
310- out := resultText(r) + diagnosticsAfter(r)
311- res := ui.ToolResult{Output: out}
312- if r.Changed {
313- res.Diff = &ui.Diff{Path: absolute(path), OldText: string(before), NewText: in.Content, Created: readErr != nil}
314- }
315- s.ToolEnd(ev.ID, res)
316- return record(d, "write_file", in.Path, truncate(out))
317-}
318-
319-func editFileEvented(ctx context.Context, s ui.Sink, d *detector.LoopDetector, in editFileInput, what string) (string, error) {
320- path := ui.Resolve(in.Path)
321- ev := ui.ToolEvent{
322- ID: ui.NextCallID(),
323- Tool: "edit_file",
324- Title: "edit_file: " + what,
325- Kind: "edit",
326- Input: map[string]any{"path": in.Path, "edits": len(in.Edits), "dry_run": in.DryRun},
327- Path: absolute(path),
328- }
329- s.ToolStart(ev)
330- if !consent.Gate(ctx, s, ev) {
331- out := "[edit_file rejected by the user]"
332- s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: true})
333- return recordFailure(d, "edit_file", editKey(in), out)
334- }
335- s.ToolRunning(ev.ID)
336-
337- before, _ := os.ReadFile(path)
338-
339- r, err := fileedit.Replace(path, in.Edits, in.DryRun)
340- if err != nil {
341- // A refused edit (text not found, ambiguous, overlapping) is the
342- // NORMAL path of this tool: failed status for the client, text for the
343- // model — which reads the rule and fixes its `old`.
344- out := err.Error()
345- s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: true})
346- return recordFailure(d, "edit_file", editKey(in), out)
347- }
348- out := resultText(r) + diagnosticsAfter(r)
349- res := ui.ToolResult{Output: out}
350- if r.Changed && !in.DryRun {
351- after, readErr := os.ReadFile(path)
352- if readErr == nil {
353- res.Diff = &ui.Diff{Path: absolute(path), OldText: string(before), NewText: string(after)}
354- }
355- }
356- s.ToolEnd(ev.ID, res)
357- return record(d, "edit_file", editKey(in), truncate(out))
358-}
359-
360-// resultText is what report() builds for the model, without the echo: the
361-// headline, then the numbered diff.
362-func resultText(r fileedit.Result) string {
363- out := r.Headline
364- if r.Diff != "" {
365- out += "\n" + strings.TrimRight(r.Diff, "\n")
366- }
367- return out
368-}
369-
370-// report echoes a write/edit result to the user — headline then diff, dimmed
371-// and capped by previewLines like a command's output — and returns the same
372-// text to the model, capped by maxOutput. The user sees the change BEFORE the
373-// model comments on it: what the file became no longer depends on what the
374-// model chooses to say about it.
375-func report(d *detector.LoopDetector, tool, key string, r fileedit.Result) (string, error) {
376- out := resultText(r) + diagnosticsAfter(r)
377- spinner.Suspend(func() { echoOutput(out) })
378- return record(d, tool, key, truncate(out))
379-}
added internal/tools/files_evented.go +158 -0
new file mode 100644
@@ -0,0 +1,158 @@
1+package tools
2+
3+import (
4+ "context"
5+ "fmt"
6+ "os"
7+ "path/filepath"
8+ "strings"
9+
10+ "mm/internal/consent"
11+ "mm/internal/detector"
12+ "mm/internal/fileedit"
13+ "mm/internal/spinner"
14+ "mm/internal/ui"
15+)
16+
17+// The same three tools, for an event-consuming front end (ACP).
18+//
19+// The information is the same as the terminal path prints; only the channel
20+// changes. Two things exist here that the terminal never had: write_file and
21+// edit_file ask the client's user for permission before touching a file, and a
22+// successful change travels as a structured diff the editor can render. Paths
23+// resolve against the SESSION's working directory (the project open in the
24+// editor), not the process's — that is ui.Resolve.
25+
26+// absolute is the location a client can jump to: ACP wants absolute paths.
27+func absolute(path string) string {
28+ if abs, err := filepath.Abs(path); err == nil {
29+ return abs
30+ }
31+ return path
32+}
33+
34+func readFileEvented(s ui.Sink, d *detector.LoopDetector, in readFileInput, where string) (string, error) {
35+ path := ui.Resolve(in.Path)
36+ ev := ui.ToolEvent{
37+ ID: ui.NextCallID(),
38+ Tool: "read_file",
39+ Title: "read_file: " + where,
40+ Kind: "read",
41+ Input: map[string]any{"path": in.Path},
42+ Path: absolute(path),
43+ }
44+ // Reading is not gated: the permission dialog exists to protect the user's
45+ // files from changes and their shell from commands, and asking before every
46+ // read teaches them to stop reading the dialogs.
47+ s.ToolStart(ev)
48+ s.ToolRunning(ev.ID)
49+
50+ content, err := fileedit.Read(path, in.Start, in.End, in.Numbered)
51+ if err != nil {
52+ out := err.Error()
53+ s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: true})
54+ return recordFailure(d, "read_file", where, out)
55+ }
56+ out := truncate(content) + diagnosticsAfterRead(path)
57+ s.ToolEnd(ev.ID, ui.ToolResult{Output: out})
58+ return record(d, "read_file", where, out)
59+}
60+
61+func writeFileEvented(ctx context.Context, s ui.Sink, d *detector.LoopDetector, in writeFileInput) (string, error) {
62+ path := ui.Resolve(in.Path)
63+ ev := ui.ToolEvent{
64+ ID: ui.NextCallID(),
65+ Tool: "write_file",
66+ Title: fmt.Sprintf("write_file: %s (%d bytes)", in.Path, len(in.Content)),
67+ Kind: "edit",
68+ Input: map[string]any{"path": in.Path},
69+ Path: absolute(path),
70+ }
71+ s.ToolStart(ev)
72+ if !consent.Gate(ctx, s, ev) {
73+ out := "[write_file rejected by the user]"
74+ s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: true})
75+ return recordFailure(d, "write_file", in.Path, out)
76+ }
77+ s.ToolRunning(ev.ID)
78+
79+ // The old content is read BEFORE the write, for the diff the client
80+ // renders. Best effort: an unreadable file simply means "created".
81+ before, readErr := os.ReadFile(path)
82+
83+ r, err := fileedit.Write(path, in.Content)
84+ if err != nil {
85+ out := err.Error()
86+ s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: true})
87+ return recordFailure(d, "write_file", in.Path, out)
88+ }
89+ out := resultText(r) + diagnosticsAfter(r)
90+ res := ui.ToolResult{Output: out}
91+ if r.Changed {
92+ res.Diff = &ui.Diff{Path: absolute(path), OldText: string(before), NewText: in.Content, Created: readErr != nil}
93+ }
94+ s.ToolEnd(ev.ID, res)
95+ return record(d, "write_file", in.Path, truncate(out))
96+}
97+
98+func editFileEvented(ctx context.Context, s ui.Sink, d *detector.LoopDetector, in editFileInput, what string) (string, error) {
99+ path := ui.Resolve(in.Path)
100+ ev := ui.ToolEvent{
101+ ID: ui.NextCallID(),
102+ Tool: "edit_file",
103+ Title: "edit_file: " + what,
104+ Kind: "edit",
105+ Input: map[string]any{"path": in.Path, "edits": len(in.Edits), "dry_run": in.DryRun},
106+ Path: absolute(path),
107+ }
108+ s.ToolStart(ev)
109+ if !consent.Gate(ctx, s, ev) {
110+ out := "[edit_file rejected by the user]"
111+ s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: true})
112+ return recordFailure(d, "edit_file", editKey(in), out)
113+ }
114+ s.ToolRunning(ev.ID)
115+
116+ before, _ := os.ReadFile(path)
117+
118+ r, err := fileedit.Replace(path, in.Edits, in.DryRun)
119+ if err != nil {
120+ // A refused edit (text not found, ambiguous, overlapping) is the
121+ // NORMAL path of this tool: failed status for the client, text for the
122+ // model — which reads the rule and fixes its `old`.
123+ out := err.Error()
124+ s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: true})
125+ return recordFailure(d, "edit_file", editKey(in), out)
126+ }
127+ out := resultText(r) + diagnosticsAfter(r)
128+ res := ui.ToolResult{Output: out}
129+ if r.Changed && !in.DryRun {
130+ after, readErr := os.ReadFile(path)
131+ if readErr == nil {
132+ res.Diff = &ui.Diff{Path: absolute(path), OldText: string(before), NewText: string(after)}
133+ }
134+ }
135+ s.ToolEnd(ev.ID, res)
136+ return record(d, "edit_file", editKey(in), truncate(out))
137+}
138+
139+// resultText is what report() builds for the model, without the echo: the
140+// headline, then the numbered diff.
141+func resultText(r fileedit.Result) string {
142+ out := r.Headline
143+ if r.Diff != "" {
144+ out += "\n" + strings.TrimRight(r.Diff, "\n")
145+ }
146+ return out
147+}
148+
149+// report echoes a write/edit result to the user — headline then diff, dimmed
150+// and capped by previewLines like a command's output — and returns the same
151+// text to the model, capped by maxOutput. The user sees the change BEFORE the
152+// model comments on it: what the file became no longer depends on what the
153+// model chooses to say about it.
154+func report(d *detector.LoopDetector, tool, key string, r fileedit.Result) (string, error) {
155+ out := resultText(r) + diagnosticsAfter(r)
156+ spinner.Suspend(func() { echoOutput(out) })
157+ return record(d, tool, key, truncate(out))
158+}
new file mode 100644
@@ -0,0 +1,158 @@
1+package tools
2+
3+import (
4+ "context"
5+ "fmt"
6+ "os"
7+ "path/filepath"
8+ "strings"
9+
10+ "mm/internal/consent"
11+ "mm/internal/detector"
12+ "mm/internal/fileedit"
13+ "mm/internal/spinner"
14+ "mm/internal/ui"
15+)
16+
17+// The same three tools, for an event-consuming front end (ACP).
18+//
19+// The information is the same as the terminal path prints; only the channel
20+// changes. Two things exist here that the terminal never had: write_file and
21+// edit_file ask the client's user for permission before touching a file, and a
22+// successful change travels as a structured diff the editor can render. Paths
23+// resolve against the SESSION's working directory (the project open in the
24+// editor), not the process's — that is ui.Resolve.
25+
26+// absolute is the location a client can jump to: ACP wants absolute paths.
27+func absolute(path string) string {
28+ if abs, err := filepath.Abs(path); err == nil {
29+ return abs
30+ }
31+ return path
32+}
33+
34+func readFileEvented(s ui.Sink, d *detector.LoopDetector, in readFileInput, where string) (string, error) {
35+ path := ui.Resolve(in.Path)
36+ ev := ui.ToolEvent{
37+ ID: ui.NextCallID(),
38+ Tool: "read_file",
39+ Title: "read_file: " + where,
40+ Kind: "read",
41+ Input: map[string]any{"path": in.Path},
42+ Path: absolute(path),
43+ }
44+ // Reading is not gated: the permission dialog exists to protect the user's
45+ // files from changes and their shell from commands, and asking before every
46+ // read teaches them to stop reading the dialogs.
47+ s.ToolStart(ev)
48+ s.ToolRunning(ev.ID)
49+
50+ content, err := fileedit.Read(path, in.Start, in.End, in.Numbered)
51+ if err != nil {
52+ out := err.Error()
53+ s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: true})
54+ return recordFailure(d, "read_file", where, out)
55+ }
56+ out := truncate(content) + diagnosticsAfterRead(path)
57+ s.ToolEnd(ev.ID, ui.ToolResult{Output: out})
58+ return record(d, "read_file", where, out)
59+}
60+
61+func writeFileEvented(ctx context.Context, s ui.Sink, d *detector.LoopDetector, in writeFileInput) (string, error) {
62+ path := ui.Resolve(in.Path)
63+ ev := ui.ToolEvent{
64+ ID: ui.NextCallID(),
65+ Tool: "write_file",
66+ Title: fmt.Sprintf("write_file: %s (%d bytes)", in.Path, len(in.Content)),
67+ Kind: "edit",
68+ Input: map[string]any{"path": in.Path},
69+ Path: absolute(path),
70+ }
71+ s.ToolStart(ev)
72+ if !consent.Gate(ctx, s, ev) {
73+ out := "[write_file rejected by the user]"
74+ s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: true})
75+ return recordFailure(d, "write_file", in.Path, out)
76+ }
77+ s.ToolRunning(ev.ID)
78+
79+ // The old content is read BEFORE the write, for the diff the client
80+ // renders. Best effort: an unreadable file simply means "created".
81+ before, readErr := os.ReadFile(path)
82+
83+ r, err := fileedit.Write(path, in.Content)
84+ if err != nil {
85+ out := err.Error()
86+ s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: true})
87+ return recordFailure(d, "write_file", in.Path, out)
88+ }
89+ out := resultText(r) + diagnosticsAfter(r)
90+ res := ui.ToolResult{Output: out}
91+ if r.Changed {
92+ res.Diff = &ui.Diff{Path: absolute(path), OldText: string(before), NewText: in.Content, Created: readErr != nil}
93+ }
94+ s.ToolEnd(ev.ID, res)
95+ return record(d, "write_file", in.Path, truncate(out))
96+}
97+
98+func editFileEvented(ctx context.Context, s ui.Sink, d *detector.LoopDetector, in editFileInput, what string) (string, error) {
99+ path := ui.Resolve(in.Path)
100+ ev := ui.ToolEvent{
101+ ID: ui.NextCallID(),
102+ Tool: "edit_file",
103+ Title: "edit_file: " + what,
104+ Kind: "edit",
105+ Input: map[string]any{"path": in.Path, "edits": len(in.Edits), "dry_run": in.DryRun},
106+ Path: absolute(path),
107+ }
108+ s.ToolStart(ev)
109+ if !consent.Gate(ctx, s, ev) {
110+ out := "[edit_file rejected by the user]"
111+ s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: true})
112+ return recordFailure(d, "edit_file", editKey(in), out)
113+ }
114+ s.ToolRunning(ev.ID)
115+
116+ before, _ := os.ReadFile(path)
117+
118+ r, err := fileedit.Replace(path, in.Edits, in.DryRun)
119+ if err != nil {
120+ // A refused edit (text not found, ambiguous, overlapping) is the
121+ // NORMAL path of this tool: failed status for the client, text for the
122+ // model — which reads the rule and fixes its `old`.
123+ out := err.Error()
124+ s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: true})
125+ return recordFailure(d, "edit_file", editKey(in), out)
126+ }
127+ out := resultText(r) + diagnosticsAfter(r)
128+ res := ui.ToolResult{Output: out}
129+ if r.Changed && !in.DryRun {
130+ after, readErr := os.ReadFile(path)
131+ if readErr == nil {
132+ res.Diff = &ui.Diff{Path: absolute(path), OldText: string(before), NewText: string(after)}
133+ }
134+ }
135+ s.ToolEnd(ev.ID, res)
136+ return record(d, "edit_file", editKey(in), truncate(out))
137+}
138+
139+// resultText is what report() builds for the model, without the echo: the
140+// headline, then the numbered diff.
141+func resultText(r fileedit.Result) string {
142+ out := r.Headline
143+ if r.Diff != "" {
144+ out += "\n" + strings.TrimRight(r.Diff, "\n")
145+ }
146+ return out
147+}
148+
149+// report echoes a write/edit result to the user — headline then diff, dimmed
150+// and capped by previewLines like a command's output — and returns the same
151+// text to the model, capped by maxOutput. The user sees the change BEFORE the
152+// model comments on it: what the file became no longer depends on what the
153+// model chooses to say about it.
154+func report(d *detector.LoopDetector, tool, key string, r fileedit.Result) (string, error) {
155+ out := resultText(r) + diagnosticsAfter(r)
156+ spinner.Suspend(func() { echoOutput(out) })
157+ return record(d, tool, key, truncate(out))
158+}
modified internal/tools/plan.go +0 -353
@@ -4,10 +4,7 @@ import (
44 "context"
55 "encoding/json"
66 "fmt"
7- "sort"
87 "strings"
9- "sync"
10- "time"
118
129 "mm/internal/consent"
1310 "mm/internal/detector"
@@ -85,358 +82,8 @@ type PlanOutput struct {
8582 Total int `json:"total,omitempty"`
8683 }
8784
88-// PlanStore holds plans in memory, keyed by session ID and plan name.
89-// This is a package-level variable so plans persist across turns within
90-// a single session. Plans are cleared when a new session starts.
91-type PlanStore struct {
92- mu sync.RWMutex
93- plans map[string]map[string]*Plan // sessionID -> planName -> Plan
94- nextID map[string]int // sessionID -> next task ID
95- made int // plans created so far, for Plan.order
96-}
97-
98-var planStore = &PlanStore{
99- plans: make(map[string]map[string]*Plan),
100- nextID: make(map[string]int),
101-}
102-
103-// getSessionID is the conversation the plan call belongs to (ticket 108): the
104-// ACP session id, or "" in the line mode and the window, which hold one
105-// conversation at a time. It used to be a constant, so every thread an
106-// editor opened in one mm process saw — and could change — the others'
107-// plans.
108-func getSessionID() string {
109- return ui.ConversationID()
110-}
111-
112-// newPlanName generates a unique plan name if none is provided.
113-// Must be called with planStore.mu held.
114-func newPlanName(sessionID string, plans map[string]map[string]*Plan) string {
115- count := len(plans[sessionID])
116- return fmt.Sprintf("user-request-%d", count+1)
117-}
118-
11985 // PlanStore methods
12086
121-// CreatePlan creates a new plan with the given tasks.
122-func (s *PlanStore) CreatePlan(name string, tasks []PlanTaskInput) (*Plan, string, error) {
123- sessionID := getSessionID()
124- s.mu.Lock()
125- defer s.mu.Unlock()
126-
127- if name == "" {
128- name = newPlanName(sessionID, s.plans)
129- }
130-
131- // Check if plan already exists
132- if plans, ok := s.plans[sessionID]; ok {
133- if _, exists := plans[name]; exists {
134- return nil, "", fmt.Errorf("plan '%s' already exists", name)
135- }
136- }
137-
138- // Ensure we have a session entry
139- if _, ok := s.plans[sessionID]; !ok {
140- s.plans[sessionID] = make(map[string]*Plan)
141- }
142-
143- // Convert input tasks to PlanTasks
144- planTasks := make([]PlanTask, len(tasks))
145- for i, t := range tasks {
146- planTasks[i] = PlanTask{
147- ID: t.ID,
148- Description: t.Description,
149- Status: "open",
150- }
151- // Auto-assign IDs if not provided
152- if t.ID == 0 {
153- planTasks[i].ID = i + 1
154- }
155- }
156-
157- s.made++
158- plan := &Plan{
159- Name: name,
160- Tasks: planTasks,
161- Current: 0,
162- CreatedAt: time.Now().UTC().Format(time.RFC3339),
163- order: s.made,
164- }
165-
166- s.plans[sessionID][name] = plan
167-
168- return plan, fmt.Sprintf("Plan '%s' created with %d tasks. Current: Task %d", name, len(tasks), 1), nil
169-}
170-
171-// GetPlan retrieves a plan by name.
172-func (s *PlanStore) GetPlan(name string) (*Plan, string, error) {
173- sessionID := getSessionID()
174- s.mu.RLock()
175- defer s.mu.RUnlock()
176-
177- plans, ok := s.plans[sessionID]
178- if !ok {
179- return nil, "", fmt.Errorf("no plans found for this session")
180- }
181-
182- plan, exists := plans[name]
183- if !exists {
184- return nil, "", fmt.Errorf("no plan named '%s' found", name)
185- }
186-
187- return plan, fmt.Sprintf("Retrieved plan '%s' with %d tasks", name, len(plan.Tasks)), nil
188-}
189-
190-// ListPlans returns all plans for the current session.
191-func (s *PlanStore) ListPlans() ([]*Plan, string, error) {
192- sessionID := getSessionID()
193- s.mu.RLock()
194- defer s.mu.RUnlock()
195-
196- plans, ok := s.plans[sessionID]
197- if !ok || len(plans) == 0 {
198- return nil, "No active plans", nil
199- }
200-
201- // Sort plans by creation time (approximate via name for v1)
202- var planList []*Plan
203- for _, p := range plans {
204- planList = append(planList, p)
205- }
206- sort.Slice(planList, func(i, j int) bool {
207- return planList[i].CreatedAt < planList[j].CreatedAt
208- })
209-
210- return planList, fmt.Sprintf("Found %d plan(s)", len(planList)), nil
211-}
212-
213-// UpdateTask updates a task's status in a plan.
214-func (s *PlanStore) UpdateTask(name string, taskID int, status string, message string) (*Plan, string, error) {
215- sessionID := getSessionID()
216- s.mu.Lock()
217- defer s.mu.Unlock()
218-
219- plans, ok := s.plans[sessionID]
220- if !ok {
221- return nil, "", fmt.Errorf("no plans found for this session")
222- }
223-
224- plan, exists := plans[name]
225- if !exists {
226- return nil, "", fmt.Errorf("no plan named '%s' found", name)
227- }
228-
229- // Validate status
230- validStatuses := map[string]bool{"open": true, "in_progress": true, "done": true, "failed": true}
231- if !validStatuses[status] {
232- return nil, "", fmt.Errorf("invalid status '%s'. Must be one of: open, in_progress, done, failed", status)
233- }
234-
235- // Find task by ID (1-based)
236- taskIndex := -1
237- for i, t := range plan.Tasks {
238- if t.ID == taskID {
239- taskIndex = i
240- break
241- }
242- }
243-
244- if taskIndex == -1 {
245- return nil, "", fmt.Errorf("no task with id %d in plan '%s'", taskID, name)
246- }
247-
248- // Update task
249- task := &plan.Tasks[taskIndex]
250- task.Status = status
251- task.Notes = message
252- if status == "in_progress" {
253- plan.Current = taskIndex + 1 // so that a later `next` moves on from here
254- }
255-
256- // Set timestamps
257- now := time.Now().UTC().Format(time.RFC3339)
258- if status == "in_progress" && task.StartedAt == "" {
259- task.StartedAt = now
260- }
261- if status == "done" || status == "failed" {
262- task.CompletedAt = now
263- }
264-
265- return plan, fmt.Sprintf("Task %d in plan '%s' updated to '%s'", taskID, name, status), nil
266-}
267-
268-// NextTask advances to the next task in a plan, marking current as done.
269-func (s *PlanStore) NextTask(name string) (*Plan, *PlanTask, string, error) {
270- sessionID := getSessionID()
271- s.mu.Lock()
272- defer s.mu.Unlock()
273-
274- plans, ok := s.plans[sessionID]
275- if !ok {
276- return nil, nil, "", fmt.Errorf("no plans found for this session")
277- }
278-
279- plan, exists := plans[name]
280- if !exists {
281- return nil, nil, "", fmt.Errorf("no plan named '%s' found", name)
282- }
283-
284- // If plan is complete
285- if plan.Current > len(plan.Tasks) {
286- return plan, nil, fmt.Sprintf("Plan '%s' is complete! All %d tasks done.", name, len(plan.Tasks)), nil
287- }
288-
289- // Mark current task as done (if any)
290- if plan.Current > 0 && plan.Current <= len(plan.Tasks) {
291- plan.Tasks[plan.Current-1].Status = "done"
292- plan.Tasks[plan.Current-1].CompletedAt = time.Now().UTC().Format(time.RFC3339)
293- }
294-
295- // Move to the next task that still needs work: a task the model already
296- // marked done with `update` is skipped, never started again.
297- plan.Current++
298- for plan.Current <= len(plan.Tasks) && finished(plan.Tasks[plan.Current-1]) {
299- plan.Current++
300- }
301-
302- // Return next task
303- if plan.Current <= len(plan.Tasks) {
304- nextTask := &plan.Tasks[plan.Current-1]
305- // Auto-set to in_progress
306- nextTask.Status = "in_progress"
307- nextTask.StartedAt = time.Now().UTC().Format(time.RFC3339)
308- return plan, nextTask, fmt.Sprintf("Task %d done. Next: Task %d - %s", plan.Current-1, plan.Current, nextTask.Description), nil
309- }
310-
311- // Plan is now complete
312- return plan, nil, fmt.Sprintf("Plan '%s' is complete! All %d tasks done.", name, len(plan.Tasks)), nil
313-}
314-
315-// DeletePlan removes a plan.
316-func (s *PlanStore) DeletePlan(name string) (string, error) {
317- sessionID := getSessionID()
318- s.mu.Lock()
319- defer s.mu.Unlock()
320-
321- plans, ok := s.plans[sessionID]
322- if !ok {
323- return "", fmt.Errorf("no plans found for this session")
324- }
325-
326- if _, exists := plans[name]; !exists {
327- return "", fmt.Errorf("no plan named '%s' found", name)
328- }
329-
330- delete(plans, name)
331- return fmt.Sprintf("Plan '%s' deleted", name), nil
332-}
333-
334-// GetStatus returns a compact status line for a plan.
335-func (s *PlanStore) GetStatus(name string) (string, string, error) {
336- sessionID := getSessionID()
337- s.mu.RLock()
338- defer s.mu.RUnlock()
339-
340- plans, ok := s.plans[sessionID]
341- if !ok {
342- return "", "", fmt.Errorf("no plans found for this session")
343- }
344-
345- plan, exists := plans[name]
346- if !exists {
347- return "", "", fmt.Errorf("no plan named '%s' found", name)
348- }
349-
350- // Count statuses
351- doneCount := 0
352- for _, t := range plan.Tasks {
353- if t.Status == "done" {
354- doneCount++
355- }
356- }
357-
358- // The line shows the task being worked on — the first in progress, else
359- // the first still open — whatever the model used to get there: `update`
360- // does not move plan.Current, so following Current alone showed task 1
361- // for a plan whose task 1 was done and task 2 in progress (ticket 110).
362- summary := fmt.Sprintf("Plan '%s': %d/%d tasks complete", name, doneCount, len(plan.Tasks))
363- if i := workingTask(plan); i >= 0 {
364- task := plan.Tasks[i]
365- return fmt.Sprintf("[%d/%d] %s Task %d: %s (%s)", i+1, len(plan.Tasks), statusIcon(task.Status), i+1, task.Description, task.Status), summary, nil
366- }
367- if doneCount < len(plan.Tasks) {
368- failed := len(plan.Tasks) - doneCount
369- return fmt.Sprintf("[%d/%d] Plan finished: %d done, %d failed", len(plan.Tasks), len(plan.Tasks), doneCount, failed), summary, nil
370- }
371- return fmt.Sprintf("[%d/%d] All tasks complete!", len(plan.Tasks), len(plan.Tasks)),
372- fmt.Sprintf("Plan '%s': All %d tasks done ✅", name, len(plan.Tasks)), nil
373-}
374-
375-// workingTask is the index of the task a plan is at: the first in progress,
376-// else the first still open; -1 when every task is done or failed.
377-func workingTask(plan *Plan) int {
378- for i, t := range plan.Tasks {
379- if t.Status == "in_progress" {
380- return i
381- }
382- }
383- for i, t := range plan.Tasks {
384- if t.Status == "open" {
385- return i
386- }
387- }
388- return -1
389-}
390-
391-// finished reports whether a task needs no more work.
392-func finished(t PlanTask) bool { return t.Status == "done" || t.Status == "failed" }
393-
394-// statusIcon is the display mark for a task status.
395-func statusIcon(status string) string {
396- switch status {
397- case "done":
398- return "✅"
399- case "in_progress":
400- return "🔄"
401- case "failed":
402- return "❌"
403- default:
404- return "⏳"
405- }
406-}
407-
408-// LatestName is the name of the conversation's most recently created plan,
409-// "" when it has none. It is what an action without a name means: a small
410-// model does not keep the name `create` returned — measured on Qwen3.5 4B
411-// (demos/plans, 2026-10-21), every `update` came without one, failed with
412-// "no plan named ”", and the turn ended in runaway tool calls.
413-func (s *PlanStore) LatestName() string {
414- conversation := getSessionID()
415- s.mu.RLock()
416- defer s.mu.RUnlock()
417- latest, order := "", -1
418- for name, p := range s.plans[conversation] {
419- if p.order > order {
420- latest, order = name, p.order
421- }
422- }
423- return latest
424-}
425-
426-// ClearPlans removes the plans of one conversation.
427-func (s *PlanStore) ClearPlans(conversation string) {
428- s.mu.Lock()
429- defer s.mu.Unlock()
430- delete(s.plans, conversation)
431-}
432-
433-// ClearAllPlans removes all plans. Used for testing.
434-func (s *PlanStore) ClearAllPlans() {
435- s.mu.Lock()
436- defer s.mu.Unlock()
437- s.plans = make(map[string]map[string]*Plan)
438-}
439-
44087 // PlanTool declares the `plan` tool.
44188 func PlanTool(g *genkit.Genkit, d *detector.LoopDetector) ai.ToolRef {
44289 description := `Create and manage multi-step plans. When the user gives you a list of tasks to do (e.g., "Do: 1. X, 2. Y, 3. Z"), use this tool to create a plan and track progress.
@@ -4,10 +4,7 @@ import (
4 "context"4 "context"
5 "encoding/json"5 "encoding/json"
6 "fmt"6 "fmt"
7- "sort"
8 "strings"7 "strings"
9- "sync"
10- "time"
11 8
12 "mm/internal/consent"9 "mm/internal/consent"
13 "mm/internal/detector"10 "mm/internal/detector"
@@ -85,358 +82,8 @@ type PlanOutput struct {
85 Total int `json:"total,omitempty"`82 Total int `json:"total,omitempty"`
86 }83 }
87 84
88-// PlanStore holds plans in memory, keyed by session ID and plan name.
89-// This is a package-level variable so plans persist across turns within
90-// a single session. Plans are cleared when a new session starts.
91-type PlanStore struct {
92- mu sync.RWMutex
93- plans map[string]map[string]*Plan // sessionID -> planName -> Plan
94- nextID map[string]int // sessionID -> next task ID
95- made int // plans created so far, for Plan.order
96-}
97-
98-var planStore = &PlanStore{
99- plans: make(map[string]map[string]*Plan),
100- nextID: make(map[string]int),
101-}
102-
103-// getSessionID is the conversation the plan call belongs to (ticket 108): the
104-// ACP session id, or "" in the line mode and the window, which hold one
105-// conversation at a time. It used to be a constant, so every thread an
106-// editor opened in one mm process saw — and could change — the others'
107-// plans.
108-func getSessionID() string {
109- return ui.ConversationID()
110-}
111-
112-// newPlanName generates a unique plan name if none is provided.
113-// Must be called with planStore.mu held.
114-func newPlanName(sessionID string, plans map[string]map[string]*Plan) string {
115- count := len(plans[sessionID])
116- return fmt.Sprintf("user-request-%d", count+1)
117-}
118-
119 // PlanStore methods85 // PlanStore methods
120 86
121-// CreatePlan creates a new plan with the given tasks.
122-func (s *PlanStore) CreatePlan(name string, tasks []PlanTaskInput) (*Plan, string, error) {
123- sessionID := getSessionID()
124- s.mu.Lock()
125- defer s.mu.Unlock()
126-
127- if name == "" {
128- name = newPlanName(sessionID, s.plans)
129- }
130-
131- // Check if plan already exists
132- if plans, ok := s.plans[sessionID]; ok {
133- if _, exists := plans[name]; exists {
134- return nil, "", fmt.Errorf("plan '%s' already exists", name)
135- }
136- }
137-
138- // Ensure we have a session entry
139- if _, ok := s.plans[sessionID]; !ok {
140- s.plans[sessionID] = make(map[string]*Plan)
141- }
142-
143- // Convert input tasks to PlanTasks
144- planTasks := make([]PlanTask, len(tasks))
145- for i, t := range tasks {
146- planTasks[i] = PlanTask{
147- ID: t.ID,
148- Description: t.Description,
149- Status: "open",
150- }
151- // Auto-assign IDs if not provided
152- if t.ID == 0 {
153- planTasks[i].ID = i + 1
154- }
155- }
156-
157- s.made++
158- plan := &Plan{
159- Name: name,
160- Tasks: planTasks,
161- Current: 0,
162- CreatedAt: time.Now().UTC().Format(time.RFC3339),
163- order: s.made,
164- }
165-
166- s.plans[sessionID][name] = plan
167-
168- return plan, fmt.Sprintf("Plan '%s' created with %d tasks. Current: Task %d", name, len(tasks), 1), nil
169-}
170-
171-// GetPlan retrieves a plan by name.
172-func (s *PlanStore) GetPlan(name string) (*Plan, string, error) {
173- sessionID := getSessionID()
174- s.mu.RLock()
175- defer s.mu.RUnlock()
176-
177- plans, ok := s.plans[sessionID]
178- if !ok {
179- return nil, "", fmt.Errorf("no plans found for this session")
180- }
181-
182- plan, exists := plans[name]
183- if !exists {
184- return nil, "", fmt.Errorf("no plan named '%s' found", name)
185- }
186-
187- return plan, fmt.Sprintf("Retrieved plan '%s' with %d tasks", name, len(plan.Tasks)), nil
188-}
189-
190-// ListPlans returns all plans for the current session.
191-func (s *PlanStore) ListPlans() ([]*Plan, string, error) {
192- sessionID := getSessionID()
193- s.mu.RLock()
194- defer s.mu.RUnlock()
195-
196- plans, ok := s.plans[sessionID]
197- if !ok || len(plans) == 0 {
198- return nil, "No active plans", nil
199- }
200-
201- // Sort plans by creation time (approximate via name for v1)
202- var planList []*Plan
203- for _, p := range plans {
204- planList = append(planList, p)
205- }
206- sort.Slice(planList, func(i, j int) bool {
207- return planList[i].CreatedAt < planList[j].CreatedAt
208- })
209-
210- return planList, fmt.Sprintf("Found %d plan(s)", len(planList)), nil
211-}
212-
213-// UpdateTask updates a task's status in a plan.
214-func (s *PlanStore) UpdateTask(name string, taskID int, status string, message string) (*Plan, string, error) {
215- sessionID := getSessionID()
216- s.mu.Lock()
217- defer s.mu.Unlock()
218-
219- plans, ok := s.plans[sessionID]
220- if !ok {
221- return nil, "", fmt.Errorf("no plans found for this session")
222- }
223-
224- plan, exists := plans[name]
225- if !exists {
226- return nil, "", fmt.Errorf("no plan named '%s' found", name)
227- }
228-
229- // Validate status
230- validStatuses := map[string]bool{"open": true, "in_progress": true, "done": true, "failed": true}
231- if !validStatuses[status] {
232- return nil, "", fmt.Errorf("invalid status '%s'. Must be one of: open, in_progress, done, failed", status)
233- }
234-
235- // Find task by ID (1-based)
236- taskIndex := -1
237- for i, t := range plan.Tasks {
238- if t.ID == taskID {
239- taskIndex = i
240- break
241- }
242- }
243-
244- if taskIndex == -1 {
245- return nil, "", fmt.Errorf("no task with id %d in plan '%s'", taskID, name)
246- }
247-
248- // Update task
249- task := &plan.Tasks[taskIndex]
250- task.Status = status
251- task.Notes = message
252- if status == "in_progress" {
253- plan.Current = taskIndex + 1 // so that a later `next` moves on from here
254- }
255-
256- // Set timestamps
257- now := time.Now().UTC().Format(time.RFC3339)
258- if status == "in_progress" && task.StartedAt == "" {
259- task.StartedAt = now
260- }
261- if status == "done" || status == "failed" {
262- task.CompletedAt = now
263- }
264-
265- return plan, fmt.Sprintf("Task %d in plan '%s' updated to '%s'", taskID, name, status), nil
266-}
267-
268-// NextTask advances to the next task in a plan, marking current as done.
269-func (s *PlanStore) NextTask(name string) (*Plan, *PlanTask, string, error) {
270- sessionID := getSessionID()
271- s.mu.Lock()
272- defer s.mu.Unlock()
273-
274- plans, ok := s.plans[sessionID]
275- if !ok {
276- return nil, nil, "", fmt.Errorf("no plans found for this session")
277- }
278-
279- plan, exists := plans[name]
280- if !exists {
281- return nil, nil, "", fmt.Errorf("no plan named '%s' found", name)
282- }
283-
284- // If plan is complete
285- if plan.Current > len(plan.Tasks) {
286- return plan, nil, fmt.Sprintf("Plan '%s' is complete! All %d tasks done.", name, len(plan.Tasks)), nil
287- }
288-
289- // Mark current task as done (if any)
290- if plan.Current > 0 && plan.Current <= len(plan.Tasks) {
291- plan.Tasks[plan.Current-1].Status = "done"
292- plan.Tasks[plan.Current-1].CompletedAt = time.Now().UTC().Format(time.RFC3339)
293- }
294-
295- // Move to the next task that still needs work: a task the model already
296- // marked done with `update` is skipped, never started again.
297- plan.Current++
298- for plan.Current <= len(plan.Tasks) && finished(plan.Tasks[plan.Current-1]) {
299- plan.Current++
300- }
301-
302- // Return next task
303- if plan.Current <= len(plan.Tasks) {
304- nextTask := &plan.Tasks[plan.Current-1]
305- // Auto-set to in_progress
306- nextTask.Status = "in_progress"
307- nextTask.StartedAt = time.Now().UTC().Format(time.RFC3339)
308- return plan, nextTask, fmt.Sprintf("Task %d done. Next: Task %d - %s", plan.Current-1, plan.Current, nextTask.Description), nil
309- }
310-
311- // Plan is now complete
312- return plan, nil, fmt.Sprintf("Plan '%s' is complete! All %d tasks done.", name, len(plan.Tasks)), nil
313-}
314-
315-// DeletePlan removes a plan.
316-func (s *PlanStore) DeletePlan(name string) (string, error) {
317- sessionID := getSessionID()
318- s.mu.Lock()
319- defer s.mu.Unlock()
320-
321- plans, ok := s.plans[sessionID]
322- if !ok {
323- return "", fmt.Errorf("no plans found for this session")
324- }
325-
326- if _, exists := plans[name]; !exists {
327- return "", fmt.Errorf("no plan named '%s' found", name)
328- }
329-
330- delete(plans, name)
331- return fmt.Sprintf("Plan '%s' deleted", name), nil
332-}
333-
334-// GetStatus returns a compact status line for a plan.
335-func (s *PlanStore) GetStatus(name string) (string, string, error) {
336- sessionID := getSessionID()
337- s.mu.RLock()
338- defer s.mu.RUnlock()
339-
340- plans, ok := s.plans[sessionID]
341- if !ok {
342- return "", "", fmt.Errorf("no plans found for this session")
343- }
344-
345- plan, exists := plans[name]
346- if !exists {
347- return "", "", fmt.Errorf("no plan named '%s' found", name)
348- }
349-
350- // Count statuses
351- doneCount := 0
352- for _, t := range plan.Tasks {
353- if t.Status == "done" {
354- doneCount++
355- }
356- }
357-
358- // The line shows the task being worked on — the first in progress, else
359- // the first still open — whatever the model used to get there: `update`
360- // does not move plan.Current, so following Current alone showed task 1
361- // for a plan whose task 1 was done and task 2 in progress (ticket 110).
362- summary := fmt.Sprintf("Plan '%s': %d/%d tasks complete", name, doneCount, len(plan.Tasks))
363- if i := workingTask(plan); i >= 0 {
364- task := plan.Tasks[i]
365- return fmt.Sprintf("[%d/%d] %s Task %d: %s (%s)", i+1, len(plan.Tasks), statusIcon(task.Status), i+1, task.Description, task.Status), summary, nil
366- }
367- if doneCount < len(plan.Tasks) {
368- failed := len(plan.Tasks) - doneCount
369- return fmt.Sprintf("[%d/%d] Plan finished: %d done, %d failed", len(plan.Tasks), len(plan.Tasks), doneCount, failed), summary, nil
370- }
371- return fmt.Sprintf("[%d/%d] All tasks complete!", len(plan.Tasks), len(plan.Tasks)),
372- fmt.Sprintf("Plan '%s': All %d tasks done ✅", name, len(plan.Tasks)), nil
373-}
374-
375-// workingTask is the index of the task a plan is at: the first in progress,
376-// else the first still open; -1 when every task is done or failed.
377-func workingTask(plan *Plan) int {
378- for i, t := range plan.Tasks {
379- if t.Status == "in_progress" {
380- return i
381- }
382- }
383- for i, t := range plan.Tasks {
384- if t.Status == "open" {
385- return i
386- }
387- }
388- return -1
389-}
390-
391-// finished reports whether a task needs no more work.
392-func finished(t PlanTask) bool { return t.Status == "done" || t.Status == "failed" }
393-
394-// statusIcon is the display mark for a task status.
395-func statusIcon(status string) string {
396- switch status {
397- case "done":
398- return "✅"
399- case "in_progress":
400- return "🔄"
401- case "failed":
402- return "❌"
403- default:
404- return "⏳"
405- }
406-}
407-
408-// LatestName is the name of the conversation's most recently created plan,
409-// "" when it has none. It is what an action without a name means: a small
410-// model does not keep the name `create` returned — measured on Qwen3.5 4B
411-// (demos/plans, 2026-10-21), every `update` came without one, failed with
412-// "no plan named ”", and the turn ended in runaway tool calls.
413-func (s *PlanStore) LatestName() string {
414- conversation := getSessionID()
415- s.mu.RLock()
416- defer s.mu.RUnlock()
417- latest, order := "", -1
418- for name, p := range s.plans[conversation] {
419- if p.order > order {
420- latest, order = name, p.order
421- }
422- }
423- return latest
424-}
425-
426-// ClearPlans removes the plans of one conversation.
427-func (s *PlanStore) ClearPlans(conversation string) {
428- s.mu.Lock()
429- defer s.mu.Unlock()
430- delete(s.plans, conversation)
431-}
432-
433-// ClearAllPlans removes all plans. Used for testing.
434-func (s *PlanStore) ClearAllPlans() {
435- s.mu.Lock()
436- defer s.mu.Unlock()
437- s.plans = make(map[string]map[string]*Plan)
438-}
439-
440 // PlanTool declares the `plan` tool.87 // PlanTool declares the `plan` tool.
441 func PlanTool(g *genkit.Genkit, d *detector.LoopDetector) ai.ToolRef {88 func PlanTool(g *genkit.Genkit, d *detector.LoopDetector) ai.ToolRef {
442 description := `Create and manage multi-step plans. When the user gives you a list of tasks to do (e.g., "Do: 1. X, 2. Y, 3. Z"), use this tool to create a plan and track progress.89 description := `Create and manage multi-step plans. When the user gives you a list of tasks to do (e.g., "Do: 1. X, 2. Y, 3. Z"), use this tool to create a plan and track progress.
added internal/tools/plan_status.go +77 -0
new file mode 100644
@@ -0,0 +1,77 @@
1+package tools
2+
3+import "fmt"
4+
5+// GetStatus returns a compact status line for a plan.
6+func (s *PlanStore) GetStatus(name string) (string, string, error) {
7+ sessionID := getSessionID()
8+ s.mu.RLock()
9+ defer s.mu.RUnlock()
10+
11+ plans, ok := s.plans[sessionID]
12+ if !ok {
13+ return "", "", fmt.Errorf("no plans found for this session")
14+ }
15+
16+ plan, exists := plans[name]
17+ if !exists {
18+ return "", "", fmt.Errorf("no plan named '%s' found", name)
19+ }
20+
21+ // Count statuses
22+ doneCount := 0
23+ for _, t := range plan.Tasks {
24+ if t.Status == "done" {
25+ doneCount++
26+ }
27+ }
28+
29+ // The line shows the task being worked on — the first in progress, else
30+ // the first still open — whatever the model used to get there: `update`
31+ // does not move plan.Current, so following Current alone showed task 1
32+ // for a plan whose task 1 was done and task 2 in progress (ticket 110).
33+ summary := fmt.Sprintf("Plan '%s': %d/%d tasks complete", name, doneCount, len(plan.Tasks))
34+ if i := workingTask(plan); i >= 0 {
35+ task := plan.Tasks[i]
36+ return fmt.Sprintf("[%d/%d] %s Task %d: %s (%s)", i+1, len(plan.Tasks), statusIcon(task.Status), i+1, task.Description, task.Status), summary, nil
37+ }
38+ if doneCount < len(plan.Tasks) {
39+ failed := len(plan.Tasks) - doneCount
40+ return fmt.Sprintf("[%d/%d] Plan finished: %d done, %d failed", len(plan.Tasks), len(plan.Tasks), doneCount, failed), summary, nil
41+ }
42+ return fmt.Sprintf("[%d/%d] All tasks complete!", len(plan.Tasks), len(plan.Tasks)),
43+ fmt.Sprintf("Plan '%s': All %d tasks done ✅", name, len(plan.Tasks)), nil
44+}
45+
46+// workingTask is the index of the task a plan is at: the first in progress,
47+// else the first still open; -1 when every task is done or failed.
48+func workingTask(plan *Plan) int {
49+ for i, t := range plan.Tasks {
50+ if t.Status == "in_progress" {
51+ return i
52+ }
53+ }
54+ for i, t := range plan.Tasks {
55+ if t.Status == "open" {
56+ return i
57+ }
58+ }
59+ return -1
60+}
61+
62+// finished reports whether a task needs no more work.
63+func finished(t PlanTask) bool { return t.Status == "done" || t.Status == "failed" }
64+
65+// statusIcon is the display mark for a task status.
66+func statusIcon(status string) string {
67+ switch status {
68+ case "done":
69+ return "✅"
70+ case "in_progress":
71+ return "🔄"
72+ case "failed":
73+ return "❌"
74+ default:
75+ return "⏳"
76+ }
77+}
new file mode 100644
@@ -0,0 +1,77 @@
1+package tools
2+
3+import "fmt"
4+
5+// GetStatus returns a compact status line for a plan.
6+func (s *PlanStore) GetStatus(name string) (string, string, error) {
7+ sessionID := getSessionID()
8+ s.mu.RLock()
9+ defer s.mu.RUnlock()
10+
11+ plans, ok := s.plans[sessionID]
12+ if !ok {
13+ return "", "", fmt.Errorf("no plans found for this session")
14+ }
15+
16+ plan, exists := plans[name]
17+ if !exists {
18+ return "", "", fmt.Errorf("no plan named '%s' found", name)
19+ }
20+
21+ // Count statuses
22+ doneCount := 0
23+ for _, t := range plan.Tasks {
24+ if t.Status == "done" {
25+ doneCount++
26+ }
27+ }
28+
29+ // The line shows the task being worked on — the first in progress, else
30+ // the first still open — whatever the model used to get there: `update`
31+ // does not move plan.Current, so following Current alone showed task 1
32+ // for a plan whose task 1 was done and task 2 in progress (ticket 110).
33+ summary := fmt.Sprintf("Plan '%s': %d/%d tasks complete", name, doneCount, len(plan.Tasks))
34+ if i := workingTask(plan); i >= 0 {
35+ task := plan.Tasks[i]
36+ return fmt.Sprintf("[%d/%d] %s Task %d: %s (%s)", i+1, len(plan.Tasks), statusIcon(task.Status), i+1, task.Description, task.Status), summary, nil
37+ }
38+ if doneCount < len(plan.Tasks) {
39+ failed := len(plan.Tasks) - doneCount
40+ return fmt.Sprintf("[%d/%d] Plan finished: %d done, %d failed", len(plan.Tasks), len(plan.Tasks), doneCount, failed), summary, nil
41+ }
42+ return fmt.Sprintf("[%d/%d] All tasks complete!", len(plan.Tasks), len(plan.Tasks)),
43+ fmt.Sprintf("Plan '%s': All %d tasks done ✅", name, len(plan.Tasks)), nil
44+}
45+
46+// workingTask is the index of the task a plan is at: the first in progress,
47+// else the first still open; -1 when every task is done or failed.
48+func workingTask(plan *Plan) int {
49+ for i, t := range plan.Tasks {
50+ if t.Status == "in_progress" {
51+ return i
52+ }
53+ }
54+ for i, t := range plan.Tasks {
55+ if t.Status == "open" {
56+ return i
57+ }
58+ }
59+ return -1
60+}
61+
62+// finished reports whether a task needs no more work.
63+func finished(t PlanTask) bool { return t.Status == "done" || t.Status == "failed" }
64+
65+// statusIcon is the display mark for a task status.
66+func statusIcon(status string) string {
67+ switch status {
68+ case "done":
69+ return "✅"
70+ case "in_progress":
71+ return "🔄"
72+ case "failed":
73+ return "❌"
74+ default:
75+ return "⏳"
76+ }
77+}
added internal/tools/plan_store.go +286 -0
new file mode 100644
@@ -0,0 +1,286 @@
1+package tools
2+
3+import (
4+ "fmt"
5+ "sort"
6+ "sync"
7+ "time"
8+
9+ "mm/internal/ui"
10+)
11+
12+// PlanStore holds plans in memory, keyed by session ID and plan name.
13+// This is a package-level variable so plans persist across turns within
14+// a single session. Plans are cleared when a new session starts.
15+type PlanStore struct {
16+ mu sync.RWMutex
17+ plans map[string]map[string]*Plan // sessionID -> planName -> Plan
18+ nextID map[string]int // sessionID -> next task ID
19+ made int // plans created so far, for Plan.order
20+}
21+
22+var planStore = &PlanStore{
23+ plans: make(map[string]map[string]*Plan),
24+ nextID: make(map[string]int),
25+}
26+
27+// getSessionID is the conversation the plan call belongs to (ticket 108): the
28+// ACP session id, or "" in the line mode and the window, which hold one
29+// conversation at a time. It used to be a constant, so every thread an
30+// editor opened in one mm process saw — and could change — the others'
31+// plans.
32+func getSessionID() string {
33+ return ui.ConversationID()
34+}
35+
36+// newPlanName generates a unique plan name if none is provided.
37+// Must be called with planStore.mu held.
38+func newPlanName(sessionID string, plans map[string]map[string]*Plan) string {
39+ count := len(plans[sessionID])
40+ return fmt.Sprintf("user-request-%d", count+1)
41+}
42+
43+// CreatePlan creates a new plan with the given tasks.
44+func (s *PlanStore) CreatePlan(name string, tasks []PlanTaskInput) (*Plan, string, error) {
45+ sessionID := getSessionID()
46+ s.mu.Lock()
47+ defer s.mu.Unlock()
48+
49+ if name == "" {
50+ name = newPlanName(sessionID, s.plans)
51+ }
52+
53+ // Check if plan already exists
54+ if plans, ok := s.plans[sessionID]; ok {
55+ if _, exists := plans[name]; exists {
56+ return nil, "", fmt.Errorf("plan '%s' already exists", name)
57+ }
58+ }
59+
60+ // Ensure we have a session entry
61+ if _, ok := s.plans[sessionID]; !ok {
62+ s.plans[sessionID] = make(map[string]*Plan)
63+ }
64+
65+ // Convert input tasks to PlanTasks
66+ planTasks := make([]PlanTask, len(tasks))
67+ for i, t := range tasks {
68+ planTasks[i] = PlanTask{
69+ ID: t.ID,
70+ Description: t.Description,
71+ Status: "open",
72+ }
73+ // Auto-assign IDs if not provided
74+ if t.ID == 0 {
75+ planTasks[i].ID = i + 1
76+ }
77+ }
78+
79+ s.made++
80+ plan := &Plan{
81+ Name: name,
82+ Tasks: planTasks,
83+ Current: 0,
84+ CreatedAt: time.Now().UTC().Format(time.RFC3339),
85+ order: s.made,
86+ }
87+
88+ s.plans[sessionID][name] = plan
89+
90+ return plan, fmt.Sprintf("Plan '%s' created with %d tasks. Current: Task %d", name, len(tasks), 1), nil
91+}
92+
93+// GetPlan retrieves a plan by name.
94+func (s *PlanStore) GetPlan(name string) (*Plan, string, error) {
95+ sessionID := getSessionID()
96+ s.mu.RLock()
97+ defer s.mu.RUnlock()
98+
99+ plans, ok := s.plans[sessionID]
100+ if !ok {
101+ return nil, "", fmt.Errorf("no plans found for this session")
102+ }
103+
104+ plan, exists := plans[name]
105+ if !exists {
106+ return nil, "", fmt.Errorf("no plan named '%s' found", name)
107+ }
108+
109+ return plan, fmt.Sprintf("Retrieved plan '%s' with %d tasks", name, len(plan.Tasks)), nil
110+}
111+
112+// ListPlans returns all plans for the current session.
113+func (s *PlanStore) ListPlans() ([]*Plan, string, error) {
114+ sessionID := getSessionID()
115+ s.mu.RLock()
116+ defer s.mu.RUnlock()
117+
118+ plans, ok := s.plans[sessionID]
119+ if !ok || len(plans) == 0 {
120+ return nil, "No active plans", nil
121+ }
122+
123+ // Sort plans by creation time (approximate via name for v1)
124+ var planList []*Plan
125+ for _, p := range plans {
126+ planList = append(planList, p)
127+ }
128+ sort.Slice(planList, func(i, j int) bool {
129+ return planList[i].CreatedAt < planList[j].CreatedAt
130+ })
131+
132+ return planList, fmt.Sprintf("Found %d plan(s)", len(planList)), nil
133+}
134+
135+// UpdateTask updates a task's status in a plan.
136+func (s *PlanStore) UpdateTask(name string, taskID int, status string, message string) (*Plan, string, error) {
137+ sessionID := getSessionID()
138+ s.mu.Lock()
139+ defer s.mu.Unlock()
140+
141+ plans, ok := s.plans[sessionID]
142+ if !ok {
143+ return nil, "", fmt.Errorf("no plans found for this session")
144+ }
145+
146+ plan, exists := plans[name]
147+ if !exists {
148+ return nil, "", fmt.Errorf("no plan named '%s' found", name)
149+ }
150+
151+ // Validate status
152+ validStatuses := map[string]bool{"open": true, "in_progress": true, "done": true, "failed": true}
153+ if !validStatuses[status] {
154+ return nil, "", fmt.Errorf("invalid status '%s'. Must be one of: open, in_progress, done, failed", status)
155+ }
156+
157+ // Find task by ID (1-based)
158+ taskIndex := -1
159+ for i, t := range plan.Tasks {
160+ if t.ID == taskID {
161+ taskIndex = i
162+ break
163+ }
164+ }
165+
166+ if taskIndex == -1 {
167+ return nil, "", fmt.Errorf("no task with id %d in plan '%s'", taskID, name)
168+ }
169+
170+ // Update task
171+ task := &plan.Tasks[taskIndex]
172+ task.Status = status
173+ task.Notes = message
174+ if status == "in_progress" {
175+ plan.Current = taskIndex + 1 // so that a later `next` moves on from here
176+ }
177+
178+ // Set timestamps
179+ now := time.Now().UTC().Format(time.RFC3339)
180+ if status == "in_progress" && task.StartedAt == "" {
181+ task.StartedAt = now
182+ }
183+ if status == "done" || status == "failed" {
184+ task.CompletedAt = now
185+ }
186+
187+ return plan, fmt.Sprintf("Task %d in plan '%s' updated to '%s'", taskID, name, status), nil
188+}
189+
190+// NextTask advances to the next task in a plan, marking current as done.
191+func (s *PlanStore) NextTask(name string) (*Plan, *PlanTask, string, error) {
192+ sessionID := getSessionID()
193+ s.mu.Lock()
194+ defer s.mu.Unlock()
195+
196+ plans, ok := s.plans[sessionID]
197+ if !ok {
198+ return nil, nil, "", fmt.Errorf("no plans found for this session")
199+ }
200+
201+ plan, exists := plans[name]
202+ if !exists {
203+ return nil, nil, "", fmt.Errorf("no plan named '%s' found", name)
204+ }
205+
206+ // If plan is complete
207+ if plan.Current > len(plan.Tasks) {
208+ return plan, nil, fmt.Sprintf("Plan '%s' is complete! All %d tasks done.", name, len(plan.Tasks)), nil
209+ }
210+
211+ // Mark current task as done (if any)
212+ if plan.Current > 0 && plan.Current <= len(plan.Tasks) {
213+ plan.Tasks[plan.Current-1].Status = "done"
214+ plan.Tasks[plan.Current-1].CompletedAt = time.Now().UTC().Format(time.RFC3339)
215+ }
216+
217+ // Move to the next task that still needs work: a task the model already
218+ // marked done with `update` is skipped, never started again.
219+ plan.Current++
220+ for plan.Current <= len(plan.Tasks) && finished(plan.Tasks[plan.Current-1]) {
221+ plan.Current++
222+ }
223+
224+ // Return next task
225+ if plan.Current <= len(plan.Tasks) {
226+ nextTask := &plan.Tasks[plan.Current-1]
227+ // Auto-set to in_progress
228+ nextTask.Status = "in_progress"
229+ nextTask.StartedAt = time.Now().UTC().Format(time.RFC3339)
230+ return plan, nextTask, fmt.Sprintf("Task %d done. Next: Task %d - %s", plan.Current-1, plan.Current, nextTask.Description), nil
231+ }
232+
233+ // Plan is now complete
234+ return plan, nil, fmt.Sprintf("Plan '%s' is complete! All %d tasks done.", name, len(plan.Tasks)), nil
235+}
236+
237+// DeletePlan removes a plan.
238+func (s *PlanStore) DeletePlan(name string) (string, error) {
239+ sessionID := getSessionID()
240+ s.mu.Lock()
241+ defer s.mu.Unlock()
242+
243+ plans, ok := s.plans[sessionID]
244+ if !ok {
245+ return "", fmt.Errorf("no plans found for this session")
246+ }
247+
248+ if _, exists := plans[name]; !exists {
249+ return "", fmt.Errorf("no plan named '%s' found", name)
250+ }
251+
252+ delete(plans, name)
253+ return fmt.Sprintf("Plan '%s' deleted", name), nil
254+}
255+
256+// LatestName is the name of the conversation's most recently created plan,
257+// "" when it has none. It is what an action without a name means: a small
258+// model does not keep the name `create` returned — measured on Qwen3.5 4B
259+// (demos/plans, 2026-10-21), every `update` came without one, failed with
260+// "no plan named ”", and the turn ended in runaway tool calls.
261+func (s *PlanStore) LatestName() string {
262+ conversation := getSessionID()
263+ s.mu.RLock()
264+ defer s.mu.RUnlock()
265+ latest, order := "", -1
266+ for name, p := range s.plans[conversation] {
267+ if p.order > order {
268+ latest, order = name, p.order
269+ }
270+ }
271+ return latest
272+}
273+
274+// ClearPlans removes the plans of one conversation.
275+func (s *PlanStore) ClearPlans(conversation string) {
276+ s.mu.Lock()
277+ defer s.mu.Unlock()
278+ delete(s.plans, conversation)
279+}
280+
281+// ClearAllPlans removes all plans. Used for testing.
282+func (s *PlanStore) ClearAllPlans() {
283+ s.mu.Lock()
284+ defer s.mu.Unlock()
285+ s.plans = make(map[string]map[string]*Plan)
286+}
new file mode 100644
@@ -0,0 +1,286 @@
1+package tools
2+
3+import (
4+ "fmt"
5+ "sort"
6+ "sync"
7+ "time"
8+
9+ "mm/internal/ui"
10+)
11+
12+// PlanStore holds plans in memory, keyed by session ID and plan name.
13+// This is a package-level variable so plans persist across turns within
14+// a single session. Plans are cleared when a new session starts.
15+type PlanStore struct {
16+ mu sync.RWMutex
17+ plans map[string]map[string]*Plan // sessionID -> planName -> Plan
18+ nextID map[string]int // sessionID -> next task ID
19+ made int // plans created so far, for Plan.order
20+}
21+
22+var planStore = &PlanStore{
23+ plans: make(map[string]map[string]*Plan),
24+ nextID: make(map[string]int),
25+}
26+
27+// getSessionID is the conversation the plan call belongs to (ticket 108): the
28+// ACP session id, or "" in the line mode and the window, which hold one
29+// conversation at a time. It used to be a constant, so every thread an
30+// editor opened in one mm process saw — and could change — the others'
31+// plans.
32+func getSessionID() string {
33+ return ui.ConversationID()
34+}
35+
36+// newPlanName generates a unique plan name if none is provided.
37+// Must be called with planStore.mu held.
38+func newPlanName(sessionID string, plans map[string]map[string]*Plan) string {
39+ count := len(plans[sessionID])
40+ return fmt.Sprintf("user-request-%d", count+1)
41+}
42+
43+// CreatePlan creates a new plan with the given tasks.
44+func (s *PlanStore) CreatePlan(name string, tasks []PlanTaskInput) (*Plan, string, error) {
45+ sessionID := getSessionID()
46+ s.mu.Lock()
47+ defer s.mu.Unlock()
48+
49+ if name == "" {
50+ name = newPlanName(sessionID, s.plans)
51+ }
52+
53+ // Check if plan already exists
54+ if plans, ok := s.plans[sessionID]; ok {
55+ if _, exists := plans[name]; exists {
56+ return nil, "", fmt.Errorf("plan '%s' already exists", name)
57+ }
58+ }
59+
60+ // Ensure we have a session entry
61+ if _, ok := s.plans[sessionID]; !ok {
62+ s.plans[sessionID] = make(map[string]*Plan)
63+ }
64+
65+ // Convert input tasks to PlanTasks
66+ planTasks := make([]PlanTask, len(tasks))
67+ for i, t := range tasks {
68+ planTasks[i] = PlanTask{
69+ ID: t.ID,
70+ Description: t.Description,
71+ Status: "open",
72+ }
73+ // Auto-assign IDs if not provided
74+ if t.ID == 0 {
75+ planTasks[i].ID = i + 1
76+ }
77+ }
78+
79+ s.made++
80+ plan := &Plan{
81+ Name: name,
82+ Tasks: planTasks,
83+ Current: 0,
84+ CreatedAt: time.Now().UTC().Format(time.RFC3339),
85+ order: s.made,
86+ }
87+
88+ s.plans[sessionID][name] = plan
89+
90+ return plan, fmt.Sprintf("Plan '%s' created with %d tasks. Current: Task %d", name, len(tasks), 1), nil
91+}
92+
93+// GetPlan retrieves a plan by name.
94+func (s *PlanStore) GetPlan(name string) (*Plan, string, error) {
95+ sessionID := getSessionID()
96+ s.mu.RLock()
97+ defer s.mu.RUnlock()
98+
99+ plans, ok := s.plans[sessionID]
100+ if !ok {
101+ return nil, "", fmt.Errorf("no plans found for this session")
102+ }
103+
104+ plan, exists := plans[name]
105+ if !exists {
106+ return nil, "", fmt.Errorf("no plan named '%s' found", name)
107+ }
108+
109+ return plan, fmt.Sprintf("Retrieved plan '%s' with %d tasks", name, len(plan.Tasks)), nil
110+}
111+
112+// ListPlans returns all plans for the current session.
113+func (s *PlanStore) ListPlans() ([]*Plan, string, error) {
114+ sessionID := getSessionID()
115+ s.mu.RLock()
116+ defer s.mu.RUnlock()
117+
118+ plans, ok := s.plans[sessionID]
119+ if !ok || len(plans) == 0 {
120+ return nil, "No active plans", nil
121+ }
122+
123+ // Sort plans by creation time (approximate via name for v1)
124+ var planList []*Plan
125+ for _, p := range plans {
126+ planList = append(planList, p)
127+ }
128+ sort.Slice(planList, func(i, j int) bool {
129+ return planList[i].CreatedAt < planList[j].CreatedAt
130+ })
131+
132+ return planList, fmt.Sprintf("Found %d plan(s)", len(planList)), nil
133+}
134+
135+// UpdateTask updates a task's status in a plan.
136+func (s *PlanStore) UpdateTask(name string, taskID int, status string, message string) (*Plan, string, error) {
137+ sessionID := getSessionID()
138+ s.mu.Lock()
139+ defer s.mu.Unlock()
140+
141+ plans, ok := s.plans[sessionID]
142+ if !ok {
143+ return nil, "", fmt.Errorf("no plans found for this session")
144+ }
145+
146+ plan, exists := plans[name]
147+ if !exists {
148+ return nil, "", fmt.Errorf("no plan named '%s' found", name)
149+ }
150+
151+ // Validate status
152+ validStatuses := map[string]bool{"open": true, "in_progress": true, "done": true, "failed": true}
153+ if !validStatuses[status] {
154+ return nil, "", fmt.Errorf("invalid status '%s'. Must be one of: open, in_progress, done, failed", status)
155+ }
156+
157+ // Find task by ID (1-based)
158+ taskIndex := -1
159+ for i, t := range plan.Tasks {
160+ if t.ID == taskID {
161+ taskIndex = i
162+ break
163+ }
164+ }
165+
166+ if taskIndex == -1 {
167+ return nil, "", fmt.Errorf("no task with id %d in plan '%s'", taskID, name)
168+ }
169+
170+ // Update task
171+ task := &plan.Tasks[taskIndex]
172+ task.Status = status
173+ task.Notes = message
174+ if status == "in_progress" {
175+ plan.Current = taskIndex + 1 // so that a later `next` moves on from here
176+ }
177+
178+ // Set timestamps
179+ now := time.Now().UTC().Format(time.RFC3339)
180+ if status == "in_progress" && task.StartedAt == "" {
181+ task.StartedAt = now
182+ }
183+ if status == "done" || status == "failed" {
184+ task.CompletedAt = now
185+ }
186+
187+ return plan, fmt.Sprintf("Task %d in plan '%s' updated to '%s'", taskID, name, status), nil
188+}
189+
190+// NextTask advances to the next task in a plan, marking current as done.
191+func (s *PlanStore) NextTask(name string) (*Plan, *PlanTask, string, error) {
192+ sessionID := getSessionID()
193+ s.mu.Lock()
194+ defer s.mu.Unlock()
195+
196+ plans, ok := s.plans[sessionID]
197+ if !ok {
198+ return nil, nil, "", fmt.Errorf("no plans found for this session")
199+ }
200+
201+ plan, exists := plans[name]
202+ if !exists {
203+ return nil, nil, "", fmt.Errorf("no plan named '%s' found", name)
204+ }
205+
206+ // If plan is complete
207+ if plan.Current > len(plan.Tasks) {
208+ return plan, nil, fmt.Sprintf("Plan '%s' is complete! All %d tasks done.", name, len(plan.Tasks)), nil
209+ }
210+
211+ // Mark current task as done (if any)
212+ if plan.Current > 0 && plan.Current <= len(plan.Tasks) {
213+ plan.Tasks[plan.Current-1].Status = "done"
214+ plan.Tasks[plan.Current-1].CompletedAt = time.Now().UTC().Format(time.RFC3339)
215+ }
216+
217+ // Move to the next task that still needs work: a task the model already
218+ // marked done with `update` is skipped, never started again.
219+ plan.Current++
220+ for plan.Current <= len(plan.Tasks) && finished(plan.Tasks[plan.Current-1]) {
221+ plan.Current++
222+ }
223+
224+ // Return next task
225+ if plan.Current <= len(plan.Tasks) {
226+ nextTask := &plan.Tasks[plan.Current-1]
227+ // Auto-set to in_progress
228+ nextTask.Status = "in_progress"
229+ nextTask.StartedAt = time.Now().UTC().Format(time.RFC3339)
230+ return plan, nextTask, fmt.Sprintf("Task %d done. Next: Task %d - %s", plan.Current-1, plan.Current, nextTask.Description), nil
231+ }
232+
233+ // Plan is now complete
234+ return plan, nil, fmt.Sprintf("Plan '%s' is complete! All %d tasks done.", name, len(plan.Tasks)), nil
235+}
236+
237+// DeletePlan removes a plan.
238+func (s *PlanStore) DeletePlan(name string) (string, error) {
239+ sessionID := getSessionID()
240+ s.mu.Lock()
241+ defer s.mu.Unlock()
242+
243+ plans, ok := s.plans[sessionID]
244+ if !ok {
245+ return "", fmt.Errorf("no plans found for this session")
246+ }
247+
248+ if _, exists := plans[name]; !exists {
249+ return "", fmt.Errorf("no plan named '%s' found", name)
250+ }
251+
252+ delete(plans, name)
253+ return fmt.Sprintf("Plan '%s' deleted", name), nil
254+}
255+
256+// LatestName is the name of the conversation's most recently created plan,
257+// "" when it has none. It is what an action without a name means: a small
258+// model does not keep the name `create` returned — measured on Qwen3.5 4B
259+// (demos/plans, 2026-10-21), every `update` came without one, failed with
260+// "no plan named ”", and the turn ended in runaway tool calls.
261+func (s *PlanStore) LatestName() string {
262+ conversation := getSessionID()
263+ s.mu.RLock()
264+ defer s.mu.RUnlock()
265+ latest, order := "", -1
266+ for name, p := range s.plans[conversation] {
267+ if p.order > order {
268+ latest, order = name, p.order
269+ }
270+ }
271+ return latest
272+}
273+
274+// ClearPlans removes the plans of one conversation.
275+func (s *PlanStore) ClearPlans(conversation string) {
276+ s.mu.Lock()
277+ defer s.mu.Unlock()
278+ delete(s.plans, conversation)
279+}
280+
281+// ClearAllPlans removes all plans. Used for testing.
282+func (s *PlanStore) ClearAllPlans() {
283+ s.mu.Lock()
284+ defer s.mu.Unlock()
285+ s.plans = make(map[string]map[string]*Plan)
286+}
modified internal/tools/tools.go +13 -7
@@ -171,19 +171,25 @@ func runArgv(ctx context.Context, dir string, budget time.Duration, argv []strin
171171 startGrouped(cmd) // background.go: its own process group (ticket 228)
172172 err = cmd.Run()
173173 output = truncate(collected(sink)) + leftRunning(cmd)
174- if errors.Is(err, exec.ErrNotFound) || errors.Is(err, os.ErrNotExist) {
175- return output + fmt.Sprintf("[error: %s cannot be started: %v]", argv[0], err), true
176- }
174+ outcome, failed := runOutcome(ctx, err, argv[0], budget)
175+ return output + outcome, failed
176+}
177177
178+// runOutcome is what follows the output of a run that ended with err: why
179+// the program could not start, its timeout, a cancelled turn, its exit
180+// code — or nothing for a success.
181+func runOutcome(ctx context.Context, err error, program string, budget time.Duration) (string, bool) {
178182 switch {
183+ case errors.Is(err, exec.ErrNotFound) || errors.Is(err, os.ErrNotExist):
184+ return fmt.Sprintf("[error: %s cannot be started: %v]", program, err), true
179185 case errors.Is(ctx.Err(), context.DeadlineExceeded):
180- return output + fmt.Sprintf("\n[error: %s timeout exceeded]", budget), true
186+ return fmt.Sprintf("\n[error: %s timeout exceeded]", budget), true
181187 case errors.Is(ctx.Err(), context.Canceled):
182- return output + "\n[error: cancelled]", true
188+ return "\n[error: cancelled]", true
183189 case err != nil:
184- return output + fmt.Sprintf("\n[exit code: %v]", err), true
190+ return fmt.Sprintf("\n[exit code: %v]", err), true
185191 }
186- return output, false
192+ return "", false
187193 }
188194
189195 // collected reads back what the command wrote, keeping both ends of a very
@@ -171,19 +171,25 @@ func runArgv(ctx context.Context, dir string, budget time.Duration, argv []strin
171 startGrouped(cmd) // background.go: its own process group (ticket 228)171 startGrouped(cmd) // background.go: its own process group (ticket 228)
172 err = cmd.Run()172 err = cmd.Run()
173 output = truncate(collected(sink)) + leftRunning(cmd)173 output = truncate(collected(sink)) + leftRunning(cmd)
174- if errors.Is(err, exec.ErrNotFound) || errors.Is(err, os.ErrNotExist) {174+ outcome, failed := runOutcome(ctx, err, argv[0], budget)
175- return output + fmt.Sprintf("[error: %s cannot be started: %v]", argv[0], err), true175+ return output + outcome, failed
176- }176+}
177 177
178+// runOutcome is what follows the output of a run that ended with err: why
179+// the program could not start, its timeout, a cancelled turn, its exit
180+// code — or nothing for a success.
181+func runOutcome(ctx context.Context, err error, program string, budget time.Duration) (string, bool) {
178 switch {182 switch {
183+ case errors.Is(err, exec.ErrNotFound) || errors.Is(err, os.ErrNotExist):
184+ return fmt.Sprintf("[error: %s cannot be started: %v]", program, err), true
179 case errors.Is(ctx.Err(), context.DeadlineExceeded):185 case errors.Is(ctx.Err(), context.DeadlineExceeded):
180- return output + fmt.Sprintf("\n[error: %s timeout exceeded]", budget), true186+ return fmt.Sprintf("\n[error: %s timeout exceeded]", budget), true
181 case errors.Is(ctx.Err(), context.Canceled):187 case errors.Is(ctx.Err(), context.Canceled):
182- return output + "\n[error: cancelled]", true188+ return "\n[error: cancelled]", true
183 case err != nil:189 case err != nil:
184- return output + fmt.Sprintf("\n[exit code: %v]", err), true190+ return fmt.Sprintf("\n[exit code: %v]", err), true
185 }191 }
186- return output, false192+ return "", false
187 }193 }
188 194
189 // collected reads back what the command wrote, keeping both ends of a very195 // collected reads back what the command wrote, keeping both ends of a very