Skip to content

Commit 4bac092

Browse files
committed
Make chat agent selection explicit and preserve separate conversations
1 parent 29379a4 commit 4bac092

13 files changed

Lines changed: 343 additions & 65 deletions

File tree

‎cmd/micro/README.md‎

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ key skips setup when it identifies one provider; `--provider NAME` selects expli
2727
Use `/login` to replace a bad key. Keys entered here are saved for this project;
2828
environment variables and `--api_key` take precedence on restart.
2929

30-
With no registered agents, the local agent works with project files, shell
30+
Plain `micro chat` starts the built-in agent, which works with project files, shell
3131
commands, skills, web pages, and registered service tools. It loads `AGENTS.md`
3232
and includes directory-specific instructions when reading files. Mutating tools
3333
and network requests use `/approve` or `/deny`; `--yes` allows unattended actions.
@@ -49,7 +49,8 @@ live text and command output, input editing, completion, and these controls:
4949
| `/new`, `/sessions`, `/resume ID` | Create, list, or reopen conversations |
5050
| `/history`, `/search TEXT`, `/compact` | Inspect, search, or compact the conversation |
5151
| `/search --all TEXT` | Search recent conversations in the local project |
52-
| `/agents` | Show connected agents and their models |
52+
| `/agents` | List available agents |
53+
| `/agent NAME` | Switch agent; `/agent micro` returns to the built-in agent |
5354
| `/approve`, `/deny` | Decide a pending local tool action |
5455
| `/exit` | Exit and stop foreground work |
5556

@@ -115,18 +116,16 @@ To review a design before generating and running the project:
115116
micro run --prompt "a notes service with saving, listing, and search" --provider openai
116117
```
117118

118-
If agents are already registered, `micro chat` routes requests to them.
119-
`micro chat <name>` optionally selects a named agent. Create named
120-
agents with `micro.NewAgent` and assign service tools with `micro.AgentServices`;
121-
see the [Getting Started guide](../../internal/website/content/en/docs/getting-started/index.md).
119+
Use `micro chat NAME` to connect to a registered agent using its model and
120+
credentials, without a local provider key. Create agents with `micro.NewAgent`
121+
and assign service tools with `micro.AgentServices`; see
122+
[Getting Started](../../internal/website/content/en/docs/getting-started/index.md).
122123

124+
Inside chat, `/agents` lists available agents, `/agent NAME` connects to one,
125+
and `/agent micro` returns to the built-in agent. Each keeps its own conversation.
123126

124-
OpenAI is the default provider. For another provider, use
125-
`micro chat --provider anthropic` with its API key. When exactly one agent is
126-
registered, `micro chat` connects directly using that agent’s model and credentials.
127-
With multiple agents, the CLI needs a provider key to route requests;
128-
`micro chat <name>` connects directly to one without a local key. Put flags before
129-
the optional agent name.
127+
OpenAI is the default local provider. For another provider, use
128+
`micro chat --provider anthropic` with its API key. Put flags before the agent name.
130129

131130
## Create a service
132131

‎cmd/micro/chat/agents.go‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
package chat
2+
3+
import (
4+
"fmt"
5+
"sort"
6+
7+
"github.com/google/uuid"
8+
"go-micro.dev/v6/store"
9+
)
10+
11+
func (s *session) agentName() string {
12+
for name := range s.agents {
13+
return name
14+
}
15+
return "micro"
16+
}
17+
18+
// Discovery does not change the current conversation or its destination.
19+
func (s *session) availableAgents() map[string]agentInfo {
20+
discovery := &session{reg: s.reg}
21+
discovery.discoverAgents()
22+
return discovery.agents
23+
}
24+
25+
func (s *session) selectAgent(name string) error {
26+
if name == "micro" {
27+
s.agents = nil
28+
return nil
29+
}
30+
info, ok := s.availableAgents()[name]
31+
if !ok {
32+
return fmt.Errorf("agent %q is not registered; use /agents to list available agents", name)
33+
}
34+
if !info.Sessions {
35+
return fmt.Errorf("agent %q does not support isolated conversations; rebuild it with the current Go Micro version", name)
36+
}
37+
s.agents = map[string]agentInfo{name: info}
38+
return nil
39+
}
40+
41+
func (s *session) listAgents() {
42+
fmt.Fprintln(s.writer(), "micro built-in development agent")
43+
available := s.availableAgents()
44+
names := make([]string, 0, len(available))
45+
for name := range available {
46+
names = append(names, name)
47+
}
48+
sort.Strings(names)
49+
for _, name := range names {
50+
info := available[name]
51+
fmt.Fprintf(s.writer(), "%s %s / %s\n", terminalText(name), terminalText(info.Provider), terminalText(info.Model))
52+
}
53+
fmt.Fprintf(s.writer(), "Current: %s. Use /agent NAME to switch.\n", terminalText(s.agentName()))
54+
}
55+
56+
func (s *session) switchAgent(name string) error {
57+
if name == s.agentName() {
58+
return nil
59+
}
60+
previous := s.agents
61+
if err := s.selectAgent(name); err != nil {
62+
return err
63+
}
64+
rollback := func(err error) error { s.agents = previous; return err }
65+
if name == "micro" && s.configureLocal != nil {
66+
if err := s.configureLocal(); err != nil {
67+
return rollback(err)
68+
}
69+
}
70+
records, err := s.conversations().Read("current")
71+
if err != nil && err != store.ErrNotFound {
72+
return rollback(err)
73+
}
74+
id := uuid.NewString()
75+
if len(records) > 0 {
76+
id = string(records[0].Value)
77+
}
78+
if err := s.selectSession(id); err != nil {
79+
return rollback(err)
80+
}
81+
s.refreshTools()
82+
return nil
83+
}

‎cmd/micro/chat/agents_test.go‎

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
package chat
2+
3+
import (
4+
"bytes"
5+
"flag"
6+
"strings"
7+
"testing"
8+
9+
"github.com/urfave/cli/v2"
10+
"go-micro.dev/v6/cmd"
11+
"go-micro.dev/v6/registry"
12+
"go-micro.dev/v6/store"
13+
)
14+
15+
func registeredSupport(t *testing.T) registry.Registry {
16+
t.Helper()
17+
reg := registry.NewMemoryRegistry()
18+
if err := reg.Register(&registry.Service{Name: "support", Metadata: map[string]string{"agent": "v1"}, Nodes: []*registry.Node{{Id: "support-1", Address: "127.0.0.1:1234", Metadata: map[string]string{"sessions": "v1"}}}}); err != nil {
19+
t.Fatal(err)
20+
}
21+
return reg
22+
}
23+
24+
func TestDefaultChatDoesNotSelectRegisteredAgent(t *testing.T) {
25+
oldDir := store.DefaultDir
26+
store.DefaultDir = t.TempDir()
27+
defer func() { store.DefaultDir = oldDir }()
28+
options := cmd.DefaultOptions()
29+
oldReg, oldClient := *options.Registry, *options.Client
30+
remote := &remoteClient{Client: oldClient}
31+
*options.Registry, *options.Client = registeredSupport(t), remote
32+
defer func() { *options.Registry, *options.Client = oldReg, oldClient }()
33+
flags := flag.NewFlagSet("chat", flag.ContinueOnError)
34+
flags.String("provider", "unconfigured", "")
35+
flags.String("prompt", "hello", "")
36+
// The local configuration error must not be bypassed by a registered agent.
37+
err := run(cli.NewContext(cli.NewApp(), flags, nil))
38+
if err == nil || !strings.Contains(err.Error(), "unknown provider") {
39+
t.Fatalf("expected local setup, got %v", err)
40+
}
41+
if remote.calls != 0 {
42+
t.Fatalf("silently called remote agent %d times", remote.calls)
43+
}
44+
}
45+
46+
func TestAgentSwitchKeepsConversationsSeparate(t *testing.T) {
47+
var out bytes.Buffer
48+
s := &session{reg: registeredSupport(t), state: store.NewMemoryStore(), project: t.TempDir(), output: &out}
49+
if err := s.selectSession("local-thread"); err != nil {
50+
t.Fatal(err)
51+
}
52+
if err := s.remember("local question"); err != nil {
53+
t.Fatal(err)
54+
}
55+
s.listAgents()
56+
if s.agentName() != "micro" || !strings.Contains(out.String(), "support") {
57+
t.Fatal("listing changed routing or omitted support")
58+
}
59+
if err := s.switchAgent("support"); err != nil {
60+
t.Fatal(err)
61+
}
62+
if s.id == "local-thread" {
63+
t.Fatal("remote reused local conversation")
64+
}
65+
remoteID := s.id
66+
if err := s.remember("support question"); err != nil {
67+
t.Fatal(err)
68+
}
69+
if err := s.switchAgent("missing"); err == nil {
70+
t.Fatal("unknown agent accepted")
71+
}
72+
if s.agentName() != "support" || s.id != remoteID {
73+
t.Fatal("failed switch changed conversation")
74+
}
75+
if err := s.switchAgent("micro"); err != nil {
76+
t.Fatal(err)
77+
}
78+
if s.id != "local-thread" {
79+
t.Fatalf("local conversation lost: %s", s.id)
80+
}
81+
records, err := s.conversations().Read("session/local-thread")
82+
if err != nil {
83+
t.Fatal(err)
84+
}
85+
var entry conversation
86+
if err := records[0].Decode(&entry); err != nil {
87+
t.Fatal(err)
88+
}
89+
if entry.Title != "local question" {
90+
t.Fatal("remote title leaked into local history")
91+
}
92+
if err := s.switchAgent("support"); err != nil {
93+
t.Fatal(err)
94+
}
95+
if s.id != remoteID {
96+
t.Fatal("remote conversation not restored")
97+
}
98+
}
99+
100+
func TestRemoteConversationIsScopedToProject(t *testing.T) {
101+
state := store.NewMemoryStore()
102+
first := &session{state: state, project: t.TempDir(), agents: map[string]agentInfo{"support": {}}}
103+
second := &session{state: state, project: t.TempDir(), agents: map[string]agentInfo{"support": {}}}
104+
if err := first.selectSession("first-project"); err != nil {
105+
t.Fatal(err)
106+
}
107+
if records, err := second.conversations().Read("current"); err == nil && len(records) != 0 {
108+
t.Fatal("remote conversation leaked between projects")
109+
}
110+
if records, err := store.Scope(state, "agent", "support").Read("current"); err == nil && len(records) != 0 {
111+
t.Fatal("CLI state leaked into agent's store")
112+
}
113+
}

‎cmd/micro/chat/chat.go‎

Lines changed: 33 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -74,9 +74,9 @@ func init() {
7474
Usage: "Work on your project with an interactive agent",
7575
Description: `Start an interactive chat session that uses an LLM to call your services.
7676
77-
With one registered agent, micro chat connects directly without a local API key.
78-
Use micro chat NAME to select a particular agent when several are running.
79-
With no registered agents, chat uses a local development agent.
77+
micro chat always starts the local development agent.
78+
Use micro chat NAME to connect to a registered agent without a local API key.
79+
Use /agents to list agents and /agent NAME to switch during a conversation.
8080
8181
micro chat discovers every service in the registry, exposes each endpoint as a
8282
tool alongside workspace and web tools. Describe the work you need done.
@@ -124,18 +124,20 @@ type agentInfo struct {
124124
}
125125

126126
type session struct {
127-
display *chatDisplay
128-
workspace *workspace.Workspace
129-
instructions string
130-
approvals chan approvalRequest
131-
approvalMu sync.Mutex
132-
yes bool
133-
interactiveUI bool
134-
hosting bool
135-
id string
136-
state store.Store
137-
output io.Writer
138-
project string
127+
configureLocal func() error
128+
localReady bool
129+
display *chatDisplay
130+
workspace *workspace.Workspace
131+
instructions string
132+
approvals chan approvalRequest
133+
approvalMu sync.Mutex
134+
yes bool
135+
interactiveUI bool
136+
hosting bool
137+
id string
138+
state store.Store
139+
output io.Writer
140+
project string
139141

140142
provider string
141143
apiKey string
@@ -469,33 +471,25 @@ func run(c *cli.Context) error {
469471
cl: cl,
470472
stream: streamOutput,
471473
}
472-
hasAgents := s.discoverAgents()
473474
if c.String("host") != "" {
474-
s.agents = nil
475-
hasAgents = false
476475
targetAgent = ""
477476
}
478477
if targetAgent != "" {
479-
if _, ok := s.agents[targetAgent]; !ok {
480-
return fmt.Errorf("agent %q is not registered; run `micro agent list` to see available agents", targetAgent)
478+
if err := s.selectAgent(targetAgent); err != nil {
479+
return err
481480
}
482-
s.agents = map[string]agentInfo{targetAgent: s.agents[targetAgent]}
483-
hasAgents = true
484481
}
485482
if err := s.openSession(c.String("session"), c.Bool("new")); err != nil {
486483
return err
487484
}
488485
defer func() { _ = s.state.Close() }()
489-
// Remote agents own their model configuration.
490-
if len(s.agents) != 1 {
486+
s.configureLocal = func() error {
487+
if s.localReady {
488+
return nil
489+
}
491490
if err := s.configure(c); err != nil {
492-
if errors.Is(err, io.EOF) || errors.Is(err, readline.ErrInterrupt) {
493-
return nil
494-
}
495491
return err
496492
}
497-
}
498-
if !hasAgents {
499493
var err error
500494
skillsHome, err := os.UserHomeDir()
501495
if err != nil {
@@ -512,6 +506,16 @@ func run(c *cli.Context) error {
512506
if instructions != "" {
513507
s.instructions = "\n\nProject instructions (AGENTS.md):\n" + instructions
514508
}
509+
s.localReady = true
510+
return nil
511+
}
512+
if len(s.agents) == 0 {
513+
if err := s.configureLocal(); err != nil {
514+
if errors.Is(err, io.EOF) || errors.Is(err, readline.ErrInterrupt) {
515+
return nil
516+
}
517+
return err
518+
}
515519
}
516520
s.yes = c.Bool("yes")
517521
s.approvals = make(chan approvalRequest)

‎cmd/micro/chat/chat_test.go‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@ func TestRouterUsesConfiguredHarness(t *testing.T) {
217217
}
218218
}
219219

220-
func TestChatDiscoversSingleAgentWithoutLocalModel(t *testing.T) {
220+
func TestChatExplicitAgentWithoutLocalModel(t *testing.T) {
221221
oldDir := store.DefaultDir
222222
store.DefaultDir = t.TempDir()
223223
defer func() { store.DefaultDir = oldDir }()
@@ -253,6 +253,9 @@ func TestChatDiscoversSingleAgentWithoutLocalModel(t *testing.T) {
253253
prompt = ""
254254
}
255255
flags.String("prompt", prompt, "")
256+
if err := flags.Parse([]string{"assistant"}); err != nil {
257+
t.Fatal(err)
258+
}
256259
ctx := cli.NewContext(cli.NewApp(), flags, nil)
257260
if err := run(ctx); err != nil {
258261
t.Fatal(err)

0 commit comments

Comments
 (0)