added
.tickets/issues/0243-a2a-mode-discussion-what-should-mm-do-with-the-a.yaml +160 -0 | new file mode 100644 | ||
| @@ -0,0 +1,160 @@ | ||
| 1 | +# Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | |
| 2 | +id: 243 | |
| 3 | +title: "A2A mode: discussion — what should mm do with the Agent2Agent protocol?" | |
| 4 | +state: closed | |
| 5 | +author: | |
| 6 | + name: k33g | |
| 7 | + email: ph.charriere@gmail.com | |
| 8 | +createdAt: 2026-11-20T14:27:47.000Z | |
| 9 | +updatedAt: 2026-11-25T05:27:08.000Z | |
| 10 | +labels: | |
| 11 | + - question | |
| 12 | + - kind::feature | |
| 13 | +milestone: v2.0.1 | |
| 14 | +epic: A2A | |
| 15 | +related: | |
| 16 | + - 260 | |
| 17 | +body: | | |
| 18 | + ## Purpose | |
| 19 | + | |
| 20 | + A ticket to discuss an A2A (Agent2Agent protocol) mode for mm before any | |
| 21 | + code is written. mm already has front ends for people and editors | |
| 22 | + (terminal, `mm tui`, `mm -p`, `mm acp` for the Agent Client Protocol); | |
| 23 | + A2A would be a front end — or a client — for **other agents**. | |
| 24 | + | |
| 25 | + ## Questions to settle | |
| 26 | + | |
| 27 | + 1. **Direction** | |
| 28 | + - *Server*: `mm a2a` exposes one agent (its `agent.yaml`) as an A2A | |
| 29 | + agent: an Agent Card (`/.well-known/agent-card.json`) built from the | |
| 30 | + agent's name, description, tools and skills, and tasks/messages mapped | |
| 31 | + onto mm's generation loop. | |
| 32 | + - *Client*: mm calls remote A2A agents, e.g. as a tool (`a2a_send`) | |
| 33 | + declared in `agent.yaml`, the way MCP servers are declared. | |
| 34 | + - Both? Which one first? | |
| 35 | + 2. **Mapping onto mm's loop**: an A2A task ↔ an mm session (`.mm/sessions`)? | |
| 36 | + Streaming (SSE) ↔ mm's streamed text and tool events? `input-required` | |
| 37 | + ↔ `ask_user` / confirmations (no human at the other end: what happens | |
| 38 | + to `yolo: false`)? | |
| 39 | + 3. **Transport and security**: JSON-RPC over HTTP(S) only, or also gRPC? | |
| 40 | + Authentication (none on localhost, bearer token otherwise)? Which | |
| 41 | + working directory and which guardrails (`workspace.confine`, | |
| 42 | + `bashBackground`) apply to a task sent by a remote agent? | |
| 43 | + 4. **Implementation**: an existing Go SDK (a2a-go) or a hand-written | |
| 44 | + subset, as for ACP? Does Genkit offer anything here? | |
| 45 | + 5. **Use cases** to validate it: an mm coder called by an orchestrator | |
| 46 | + agent; several mm agents (each tuned to its small model) delegating to | |
| 47 | + each other — compare with what `demos/dev.team` does today. | |
| 48 | + | |
| 49 | + ## Outcome expected | |
| 50 | + | |
| 51 | + A decision recorded in this ticket (direction, scope of a first version, | |
| 52 | + milestone), then implementation tickets in the A2A epic. | |
| 53 | +tasks: | |
| 54 | + - id: 1 | |
| 55 | + title: "Decide direction, mapping, transport, implementation (comment 1)" | |
| 56 | + state: closed | |
| 57 | + priority: high | |
| 58 | + author: | |
| 59 | + name: k33g | |
| 60 | + email: ph.charriere@gmail.com | |
| 61 | + createdAt: 2026-11-25T05:10:10.000Z | |
| 62 | + updatedAt: 2026-11-25T05:10:10.000Z | |
| 63 | + closedAt: 2026-11-25T05:10:10.000Z | |
| 64 | + - id: 2 | |
| 65 | + title: "Server: mm a2a — Agent Card, SendMessage/GetTask (1.0) and message/send/tasks/get (0.3), one conversation per contextId" | |
| 66 | + state: closed | |
| 67 | + priority: high | |
| 68 | + author: | |
| 69 | + name: k33g | |
| 70 | + email: ph.charriere@gmail.com | |
| 71 | + createdAt: 2026-11-25T05:10:10.000Z | |
| 72 | + updatedAt: 2026-11-25T05:10:10.000Z | |
| 73 | + closedAt: 2026-11-25T05:10:10.000Z | |
| 74 | + - id: 3 | |
| 75 | + title: "Client: the ask_a2a_agent tool (a2a.agents) and mm a2a-send for scripts" | |
| 76 | + state: closed | |
| 77 | + priority: high | |
| 78 | + author: | |
| 79 | + name: k33g | |
| 80 | + email: ph.charriere@gmail.com | |
| 81 | + createdAt: 2026-11-25T05:10:10.000Z | |
| 82 | + updatedAt: 2026-11-25T05:10:10.000Z | |
| 83 | + closedAt: 2026-11-25T05:10:10.000Z | |
| 84 | + - id: 4 | |
| 85 | + title: "Interop: the official Python a2a-sdk 1.3.1 client against mm a2a" | |
| 86 | + state: closed | |
| 87 | + priority: medium | |
| 88 | + author: | |
| 89 | + name: k33g | |
| 90 | + email: ph.charriere@gmail.com | |
| 91 | + createdAt: 2026-11-25T05:10:10.000Z | |
| 92 | + updatedAt: 2026-11-25T05:10:10.000Z | |
| 93 | + closedAt: 2026-11-25T05:10:10.000Z | |
| 94 | + - id: 5 | |
| 95 | + title: "Demo demos/a2a-discussion (LFM3 1.7B, llamacpp, 3 agents) with its launch procedure" | |
| 96 | + state: closed | |
| 97 | + priority: medium | |
| 98 | + author: | |
| 99 | + name: k33g | |
| 100 | + email: ph.charriere@gmail.com | |
| 101 | + createdAt: 2026-11-25T05:10:10.000Z | |
| 102 | + updatedAt: 2026-11-25T05:10:10.000Z | |
| 103 | + closedAt: 2026-11-25T05:10:10.000Z | |
| 104 | + - id: 6 | |
| 105 | + title: "Tests and docs EN+FR (cli, configuration, tools)" | |
| 106 | + state: closed | |
| 107 | + priority: none | |
| 108 | + author: | |
| 109 | + name: k33g | |
| 110 | + email: ph.charriere@gmail.com | |
| 111 | + createdAt: 2026-11-25T05:10:10.000Z | |
| 112 | + updatedAt: 2026-11-25T05:10:10.000Z | |
| 113 | + closedAt: 2026-11-25T05:10:10.000Z | |
| 114 | +comments: | |
| 115 | + - id: 1 | |
| 116 | + author: | |
| 117 | + name: k33g | |
| 118 | + email: ph.charriere@gmail.com | |
| 119 | + createdAt: 2026-11-25T05:10:10.000Z | |
| 120 | + body: | | |
| 121 | + Decisions taken to implement the first version (user's request, | |
| 122 | + 2026-11-25: a simple demo, llamacpp, LFM3 1.7B, 2 or 3 agents talking): | |
| 123 | + 1. **Direction: both.** Server `mm a2a [file]` (also `-a2a`, | |
| 124 | + `--a2a-port`) and client: the `ask_a2a_agent` tool, declared by | |
| 125 | + `a2a.agents` (like `mmConfigs` for `ask_agent`), and `mm a2a-send` | |
| 126 | + for scripts. | |
| 127 | + 2. **Mapping:** one A2A `contextId` = one conversation, in memory for | |
| 128 | + the life of the process (not saved to `sessions`), compressed like a | |
| 129 | + terminal session; send is blocking (the finished task), one | |
| 130 | + generation at a time; no streaming, no `input-required` — with | |
| 131 | + `yolo: false` a tool needing consent is refused, as under `-p`; | |
| 132 | + `ask_user` should be off. | |
| 133 | + 3. **Transport/security:** JSON-RPC 2.0 over HTTP, text parts only; | |
| 134 | + listens on 127.0.0.1 (default port 9100); optional bearer token | |
| 135 | + (`a2a.tokenEnv` / `agents.<n>.tokenEnv`); the process's cwd and its | |
| 136 | + guardrails apply. | |
| 137 | + 4. **Implementation:** a hand-written subset (`internal/a2a`), no SDK. | |
| 138 | + Measured that the current protocol is **1.0** (`SendMessage`, | |
| 139 | + `GetTask`, `ROLE_USER`, `{"task": …}`, `supportedInterfaces`) and | |
| 140 | + 0.3 is the previous one: the server answers both; the client speaks | |
| 141 | + 1.0 and falls back to 0.3. Checked with the official Python | |
| 142 | + `a2a-sdk` 1.3.1 client (card, `TASK_STATE_COMPLETED`, `contextId`). | |
| 143 | + Whether to use the Go SDK instead: | |
| 144 | + [#260](.tickets/issues/0260-a2a-study-the-official-go-sdk-a2aproject-a2a-go.yaml). | |
| 145 | + 5. **Use case:** `demos/a2a-discussion` — Alice (for), Bob (against), | |
| 146 | + a moderator; one LFM3 1.7B on one llama-server shared by the three | |
| 147 | + (`unloadOnExit: false`). Measured: `discussion.sh` 2 rounds in 37 s; | |
| 148 | + moderator-led debates 4 and 8 calls, concluded (72 s, 130 s). | |
| 149 | + Found and fixed on the way: `ask_a2a_agent` now beats the generation's | |
| 150 | + watchdog while it waits (the first moderator-led debate stalled at its | |
| 151 | + 6th call). | |
| 152 | + Implemented on branch `feature/a2a` (not committed). | |
| 153 | + - id: 2 | |
| 154 | + author: | |
| 155 | + name: k33g | |
| 156 | + email: ph.charriere@gmail.com | |
| 157 | + createdAt: 2026-11-25T05:27:08.000Z | |
| 158 | + body: | | |
| 159 | + Validated by the user; merged into `main`. The Go SDK study goes on in | |
| 160 | + #260 (moved to v2.0.2). | |
| new file mode 100644 | |||
| @@ -0,0 +1,160 @@ | |||
| 1 | +# Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | ||
| 2 | +id: 243 | ||
| 3 | +title: "A2A mode: discussion — what should mm do with the Agent2Agent protocol?" | ||
| 4 | +state: closed | ||
| 5 | +author: | ||
| 6 | + name: k33g | ||
| 7 | + email: ph.charriere@gmail.com | ||
| 8 | +createdAt: 2026-11-20T14:27:47.000Z | ||
| 9 | +updatedAt: 2026-11-25T05:27:08.000Z | ||
| 10 | +labels: | ||
| 11 | + - question | ||
| 12 | + - kind::feature | ||
| 13 | +milestone: v2.0.1 | ||
| 14 | +epic: A2A | ||
| 15 | +related: | ||
| 16 | + - 260 | ||
| 17 | +body: | | ||
| 18 | + ## Purpose | ||
| 19 | + | ||
| 20 | + A ticket to discuss an A2A (Agent2Agent protocol) mode for mm before any | ||
| 21 | + code is written. mm already has front ends for people and editors | ||
| 22 | + (terminal, `mm tui`, `mm -p`, `mm acp` for the Agent Client Protocol); | ||
| 23 | + A2A would be a front end — or a client — for **other agents**. | ||
| 24 | + | ||
| 25 | + ## Questions to settle | ||
| 26 | + | ||
| 27 | + 1. **Direction** | ||
| 28 | + - *Server*: `mm a2a` exposes one agent (its `agent.yaml`) as an A2A | ||
| 29 | + agent: an Agent Card (`/.well-known/agent-card.json`) built from the | ||
| 30 | + agent's name, description, tools and skills, and tasks/messages mapped | ||
| 31 | + onto mm's generation loop. | ||
| 32 | + - *Client*: mm calls remote A2A agents, e.g. as a tool (`a2a_send`) | ||
| 33 | + declared in `agent.yaml`, the way MCP servers are declared. | ||
| 34 | + - Both? Which one first? | ||
| 35 | + 2. **Mapping onto mm's loop**: an A2A task ↔ an mm session (`.mm/sessions`)? | ||
| 36 | + Streaming (SSE) ↔ mm's streamed text and tool events? `input-required` | ||
| 37 | + ↔ `ask_user` / confirmations (no human at the other end: what happens | ||
| 38 | + to `yolo: false`)? | ||
| 39 | + 3. **Transport and security**: JSON-RPC over HTTP(S) only, or also gRPC? | ||
| 40 | + Authentication (none on localhost, bearer token otherwise)? Which | ||
| 41 | + working directory and which guardrails (`workspace.confine`, | ||
| 42 | + `bashBackground`) apply to a task sent by a remote agent? | ||
| 43 | + 4. **Implementation**: an existing Go SDK (a2a-go) or a hand-written | ||
| 44 | + subset, as for ACP? Does Genkit offer anything here? | ||
| 45 | + 5. **Use cases** to validate it: an mm coder called by an orchestrator | ||
| 46 | + agent; several mm agents (each tuned to its small model) delegating to | ||
| 47 | + each other — compare with what `demos/dev.team` does today. | ||
| 48 | + | ||
| 49 | + ## Outcome expected | ||
| 50 | + | ||
| 51 | + A decision recorded in this ticket (direction, scope of a first version, | ||
| 52 | + milestone), then implementation tickets in the A2A epic. | ||
| 53 | +tasks: | ||
| 54 | + - id: 1 | ||
| 55 | + title: "Decide direction, mapping, transport, implementation (comment 1)" | ||
| 56 | + state: closed | ||
| 57 | + priority: high | ||
| 58 | + author: | ||
| 59 | + name: k33g | ||
| 60 | + email: ph.charriere@gmail.com | ||
| 61 | + createdAt: 2026-11-25T05:10:10.000Z | ||
| 62 | + updatedAt: 2026-11-25T05:10:10.000Z | ||
| 63 | + closedAt: 2026-11-25T05:10:10.000Z | ||
| 64 | + - id: 2 | ||
| 65 | + title: "Server: mm a2a — Agent Card, SendMessage/GetTask (1.0) and message/send/tasks/get (0.3), one conversation per contextId" | ||
| 66 | + state: closed | ||
| 67 | + priority: high | ||
| 68 | + author: | ||
| 69 | + name: k33g | ||
| 70 | + email: ph.charriere@gmail.com | ||
| 71 | + createdAt: 2026-11-25T05:10:10.000Z | ||
| 72 | + updatedAt: 2026-11-25T05:10:10.000Z | ||
| 73 | + closedAt: 2026-11-25T05:10:10.000Z | ||
| 74 | + - id: 3 | ||
| 75 | + title: "Client: the ask_a2a_agent tool (a2a.agents) and mm a2a-send for scripts" | ||
| 76 | + state: closed | ||
| 77 | + priority: high | ||
| 78 | + author: | ||
| 79 | + name: k33g | ||
| 80 | + email: ph.charriere@gmail.com | ||
| 81 | + createdAt: 2026-11-25T05:10:10.000Z | ||
| 82 | + updatedAt: 2026-11-25T05:10:10.000Z | ||
| 83 | + closedAt: 2026-11-25T05:10:10.000Z | ||
| 84 | + - id: 4 | ||
| 85 | + title: "Interop: the official Python a2a-sdk 1.3.1 client against mm a2a" | ||
| 86 | + state: closed | ||
| 87 | + priority: medium | ||
| 88 | + author: | ||
| 89 | + name: k33g | ||
| 90 | + email: ph.charriere@gmail.com | ||
| 91 | + createdAt: 2026-11-25T05:10:10.000Z | ||
| 92 | + updatedAt: 2026-11-25T05:10:10.000Z | ||
| 93 | + closedAt: 2026-11-25T05:10:10.000Z | ||
| 94 | + - id: 5 | ||
| 95 | + title: "Demo demos/a2a-discussion (LFM3 1.7B, llamacpp, 3 agents) with its launch procedure" | ||
| 96 | + state: closed | ||
| 97 | + priority: medium | ||
| 98 | + author: | ||
| 99 | + name: k33g | ||
| 100 | + email: ph.charriere@gmail.com | ||
| 101 | + createdAt: 2026-11-25T05:10:10.000Z | ||
| 102 | + updatedAt: 2026-11-25T05:10:10.000Z | ||
| 103 | + closedAt: 2026-11-25T05:10:10.000Z | ||
| 104 | + - id: 6 | ||
| 105 | + title: "Tests and docs EN+FR (cli, configuration, tools)" | ||
| 106 | + state: closed | ||
| 107 | + priority: none | ||
| 108 | + author: | ||
| 109 | + name: k33g | ||
| 110 | + email: ph.charriere@gmail.com | ||
| 111 | + createdAt: 2026-11-25T05:10:10.000Z | ||
| 112 | + updatedAt: 2026-11-25T05:10:10.000Z | ||
| 113 | + closedAt: 2026-11-25T05:10:10.000Z | ||
| 114 | +comments: | ||
| 115 | + - id: 1 | ||
| 116 | + author: | ||
| 117 | + name: k33g | ||
| 118 | + email: ph.charriere@gmail.com | ||
| 119 | + createdAt: 2026-11-25T05:10:10.000Z | ||
| 120 | + body: | | ||
| 121 | + Decisions taken to implement the first version (user's request, | ||
| 122 | + 2026-11-25: a simple demo, llamacpp, LFM3 1.7B, 2 or 3 agents talking): | ||
| 123 | + 1. **Direction: both.** Server `mm a2a [file]` (also `-a2a`, | ||
| 124 | + `--a2a-port`) and client: the `ask_a2a_agent` tool, declared by | ||
| 125 | + `a2a.agents` (like `mmConfigs` for `ask_agent`), and `mm a2a-send` | ||
| 126 | + for scripts. | ||
| 127 | + 2. **Mapping:** one A2A `contextId` = one conversation, in memory for | ||
| 128 | + the life of the process (not saved to `sessions`), compressed like a | ||
| 129 | + terminal session; send is blocking (the finished task), one | ||
| 130 | + generation at a time; no streaming, no `input-required` — with | ||
| 131 | + `yolo: false` a tool needing consent is refused, as under `-p`; | ||
| 132 | + `ask_user` should be off. | ||
| 133 | + 3. **Transport/security:** JSON-RPC 2.0 over HTTP, text parts only; | ||
| 134 | + listens on 127.0.0.1 (default port 9100); optional bearer token | ||
| 135 | + (`a2a.tokenEnv` / `agents.<n>.tokenEnv`); the process's cwd and its | ||
| 136 | + guardrails apply. | ||
| 137 | + 4. **Implementation:** a hand-written subset (`internal/a2a`), no SDK. | ||
| 138 | + Measured that the current protocol is **1.0** (`SendMessage`, | ||
| 139 | + `GetTask`, `ROLE_USER`, `{"task": …}`, `supportedInterfaces`) and | ||
| 140 | + 0.3 is the previous one: the server answers both; the client speaks | ||
| 141 | + 1.0 and falls back to 0.3. Checked with the official Python | ||
| 142 | + `a2a-sdk` 1.3.1 client (card, `TASK_STATE_COMPLETED`, `contextId`). | ||
| 143 | + Whether to use the Go SDK instead: | ||
| 144 | + [#260](.tickets/issues/0260-a2a-study-the-official-go-sdk-a2aproject-a2a-go.yaml). | ||
| 145 | + 5. **Use case:** `demos/a2a-discussion` — Alice (for), Bob (against), | ||
| 146 | + a moderator; one LFM3 1.7B on one llama-server shared by the three | ||
| 147 | + (`unloadOnExit: false`). Measured: `discussion.sh` 2 rounds in 37 s; | ||
| 148 | + moderator-led debates 4 and 8 calls, concluded (72 s, 130 s). | ||
| 149 | + Found and fixed on the way: `ask_a2a_agent` now beats the generation's | ||
| 150 | + watchdog while it waits (the first moderator-led debate stalled at its | ||
| 151 | + 6th call). | ||
| 152 | + Implemented on branch `feature/a2a` (not committed). | ||
| 153 | + - id: 2 | ||
| 154 | + author: | ||
| 155 | + name: k33g | ||
| 156 | + email: ph.charriere@gmail.com | ||
| 157 | + createdAt: 2026-11-25T05:27:08.000Z | ||
| 158 | + body: | | ||
| 159 | + Validated by the user; merged into `main`. The Go SDK study goes on in | ||
| 160 | + #260 (moved to v2.0.2). | ||
deleted
.tickets/issues/0243-a2a-mode-discussion.yaml +0 -50 | deleted file mode 100644 | ||
| @@ -1,50 +0,0 @@ | ||
| 1 | -# Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | |
| 2 | -id: 243 | |
| 3 | -title: "A2A mode: discussion — what should mm do with the Agent2Agent protocol?" | |
| 4 | -state: open | |
| 5 | -author: | |
| 6 | - name: k33g | |
| 7 | - email: ph.charriere@gmail.com | |
| 8 | -createdAt: 2026-11-20T14:27:47.000Z | |
| 9 | -updatedAt: 2026-11-20T14:27:47.000Z | |
| 10 | -labels: | |
| 11 | - - question | |
| 12 | -epic: A2A | |
| 13 | -body: | | |
| 14 | - ## Purpose | |
| 15 | - | |
| 16 | - A ticket to discuss an A2A (Agent2Agent protocol) mode for mm before any | |
| 17 | - code is written. mm already has front ends for people and editors | |
| 18 | - (terminal, `mm tui`, `mm -p`, `mm acp` for the Agent Client Protocol); | |
| 19 | - A2A would be a front end — or a client — for **other agents**. | |
| 20 | - | |
| 21 | - ## Questions to settle | |
| 22 | - | |
| 23 | - 1. **Direction** | |
| 24 | - - *Server*: `mm a2a` exposes one agent (its `agent.yaml`) as an A2A | |
| 25 | - agent: an Agent Card (`/.well-known/agent-card.json`) built from the | |
| 26 | - agent's name, description, tools and skills, and tasks/messages mapped | |
| 27 | - onto mm's generation loop. | |
| 28 | - - *Client*: mm calls remote A2A agents, e.g. as a tool (`a2a_send`) | |
| 29 | - declared in `agent.yaml`, the way MCP servers are declared. | |
| 30 | - - Both? Which one first? | |
| 31 | - 2. **Mapping onto mm's loop**: an A2A task ↔ an mm session (`.mm/sessions`)? | |
| 32 | - Streaming (SSE) ↔ mm's streamed text and tool events? `input-required` | |
| 33 | - ↔ `ask_user` / confirmations (no human at the other end: what happens | |
| 34 | - to `yolo: false`)? | |
| 35 | - 3. **Transport and security**: JSON-RPC over HTTP(S) only, or also gRPC? | |
| 36 | - Authentication (none on localhost, bearer token otherwise)? Which | |
| 37 | - working directory and which guardrails (`workspace.confine`, | |
| 38 | - `bashBackground`) apply to a task sent by a remote agent? | |
| 39 | - 4. **Implementation**: an existing Go SDK (a2a-go) or a hand-written | |
| 40 | - subset, as for ACP? Does Genkit offer anything here? | |
| 41 | - 5. **Use cases** to validate it: an mm coder called by an orchestrator | |
| 42 | - agent; several mm agents (each tuned to its small model) delegating to | |
| 43 | - each other — compare with what `demos/dev.team` does today. | |
| 44 | - | |
| 45 | - ## Outcome expected | |
| 46 | - | |
| 47 | - A decision recorded in this ticket (direction, scope of a first version, | |
| 48 | - milestone), then implementation tickets in the A2A epic. | |
| 49 | -tasks: [] | |
| 50 | -comments: [] | |
| deleted file mode 100644 | |||
| @@ -1,50 +0,0 @@ | |||
| 1 | -# Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | ||
| 2 | -id: 243 | ||
| 3 | -title: "A2A mode: discussion — what should mm do with the Agent2Agent protocol?" | ||
| 4 | -state: open | ||
| 5 | -author: | ||
| 6 | - name: k33g | ||
| 7 | - email: ph.charriere@gmail.com | ||
| 8 | -createdAt: 2026-11-20T14:27:47.000Z | ||
| 9 | -updatedAt: 2026-11-20T14:27:47.000Z | ||
| 10 | -labels: | ||
| 11 | - - question | ||
| 12 | -epic: A2A | ||
| 13 | -body: | | ||
| 14 | - ## Purpose | ||
| 15 | - | ||
| 16 | - A ticket to discuss an A2A (Agent2Agent protocol) mode for mm before any | ||
| 17 | - code is written. mm already has front ends for people and editors | ||
| 18 | - (terminal, `mm tui`, `mm -p`, `mm acp` for the Agent Client Protocol); | ||
| 19 | - A2A would be a front end — or a client — for **other agents**. | ||
| 20 | - | ||
| 21 | - ## Questions to settle | ||
| 22 | - | ||
| 23 | - 1. **Direction** | ||
| 24 | - - *Server*: `mm a2a` exposes one agent (its `agent.yaml`) as an A2A | ||
| 25 | - agent: an Agent Card (`/.well-known/agent-card.json`) built from the | ||
| 26 | - agent's name, description, tools and skills, and tasks/messages mapped | ||
| 27 | - onto mm's generation loop. | ||
| 28 | - - *Client*: mm calls remote A2A agents, e.g. as a tool (`a2a_send`) | ||
| 29 | - declared in `agent.yaml`, the way MCP servers are declared. | ||
| 30 | - - Both? Which one first? | ||
| 31 | - 2. **Mapping onto mm's loop**: an A2A task ↔ an mm session (`.mm/sessions`)? | ||
| 32 | - Streaming (SSE) ↔ mm's streamed text and tool events? `input-required` | ||
| 33 | - ↔ `ask_user` / confirmations (no human at the other end: what happens | ||
| 34 | - to `yolo: false`)? | ||
| 35 | - 3. **Transport and security**: JSON-RPC over HTTP(S) only, or also gRPC? | ||
| 36 | - Authentication (none on localhost, bearer token otherwise)? Which | ||
| 37 | - working directory and which guardrails (`workspace.confine`, | ||
| 38 | - `bashBackground`) apply to a task sent by a remote agent? | ||
| 39 | - 4. **Implementation**: an existing Go SDK (a2a-go) or a hand-written | ||
| 40 | - subset, as for ACP? Does Genkit offer anything here? | ||
| 41 | - 5. **Use cases** to validate it: an mm coder called by an orchestrator | ||
| 42 | - agent; several mm agents (each tuned to its small model) delegating to | ||
| 43 | - each other — compare with what `demos/dev.team` does today. | ||
| 44 | - | ||
| 45 | - ## Outcome expected | ||
| 46 | - | ||
| 47 | - A decision recorded in this ticket (direction, scope of a first version, | ||
| 48 | - milestone), then implementation tickets in the A2A epic. | ||
| 49 | -tasks: [] | ||
| 50 | -comments: [] | ||
added
.tickets/issues/0260-a2a-study-the-official-go-sdk-a2aproject-a2a-go.yaml +89 -0 | new file mode 100644 | ||
| @@ -0,0 +1,89 @@ | ||
| 1 | +# Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | |
| 2 | +id: 260 | |
| 3 | +title: "A2A: study the official Go SDK (a2aproject/a2a-go) instead of mm's hand-written subset" | |
| 4 | +state: open | |
| 5 | +author: | |
| 6 | + name: k33g | |
| 7 | + email: ph.charriere@gmail.com | |
| 8 | +createdAt: 2026-11-25T05:04:41.000Z | |
| 9 | +updatedAt: 2026-11-25T05:27:08.000Z | |
| 10 | +labels: | |
| 11 | + - question | |
| 12 | + - kind::chore | |
| 13 | +milestone: v2.0.2 | |
| 14 | +epic: A2A | |
| 15 | +related: | |
| 16 | + - 243 | |
| 17 | +body: | | |
| 18 | + Follow-up of [#243 — A2A mode](.tickets/issues/0243-a2a-mode-discussion-what-should-mm-do-with-the-a.yaml). | |
| 19 | + Asked by the user (2026-11-25): study https://github.com/a2aproject/a2a-go. | |
| 20 | + | |
| 21 | + ## Today (branch `feature/a2a`) | |
| 22 | + `internal/a2a` is a hand-written subset (~600 lines): JSON-RPC over HTTP, | |
| 23 | + text parts only, no streaming, blocking send; it speaks **both** A2A 1.0 | |
| 24 | + (`SendMessage`, `GetTask`, `ROLE_USER`, `{"task": …}`, | |
| 25 | + `supportedInterfaces`) and 0.3 (`message/send`, `tasks/get`); the client | |
| 26 | + tries 1.0 and falls back to 0.3. Checked against the official **Python** | |
| 27 | + `a2a-sdk` 1.3.1 client: card read, `TASK_STATE_COMPLETED`, the | |
| 28 | + conversation continued by `contextId`. | |
| 29 | + | |
| 30 | + ## The SDK (proxy.golang.org, 2026-11-25) | |
| 31 | + - latest stable `v0.3.15` (2026-04-15) — the **0.3** protocol; | |
| 32 | + - `v1.0.0-alpha`, `-alpha.2`, `-alpha.3` — the **1.0** protocol, not | |
| 33 | + stable yet. | |
| 34 | + | |
| 35 | + ## Questions | |
| 36 | + - Which version: 0.3.15 (stable, old protocol) or a 1.0 alpha (current | |
| 37 | + protocol, API may change)? Can one dependency serve both versions, as | |
| 38 | + `internal/a2a` does today, or does it take two? | |
| 39 | + - What it brings that mm lacks: streaming (`SendStreamingMessage` / SSE — | |
| 40 | + mm streams text already), `input-required` (an `ask_user` question | |
| 41 | + sent back to the caller, a consent asked of the calling agent), task | |
| 42 | + cancel, push notifications, gRPC and HTTP+JSON bindings, card signatures, | |
| 43 | + auth helpers. | |
| 44 | + - Cost: dependency size (gRPC, protobuf?), build time and binary size — | |
| 45 | + mm ships one static binary for macOS, Linux and Windows; licence. | |
| 46 | + - Fit with mm's loop: its server's executor interface vs `runA2A`'s | |
| 47 | + handler (one conversation per contextId, one generation at a time); its | |
| 48 | + client inside the `ask_a2a_agent` tool and `mm a2a-send`. | |
| 49 | + - Interop: re-run the Python `a2a-sdk` check and | |
| 50 | + `demos/a2a-discussion` against an SDK-based build. | |
| 51 | + | |
| 52 | + ## Outcome expected | |
| 53 | + A decision recorded here — keep the hand-written subset, switch to the | |
| 54 | + SDK (which version), or both (the SDK for what the subset lacks) — and | |
| 55 | + implementation tickets if switching. | |
| 56 | +tasks: | |
| 57 | + - id: 1 | |
| 58 | + title: Read the SDK (v0.3.15 and v1.0.0-alpha.3) - API, dependencies, licence, binary size | |
| 59 | + state: open | |
| 60 | + priority: high | |
| 61 | + author: | |
| 62 | + name: k33g | |
| 63 | + email: ph.charriere@gmail.com | |
| 64 | + createdAt: 2026-11-25T05:04:41.000Z | |
| 65 | + - id: 2 | |
| 66 | + title: Prototype mm a2a and the client on the SDK, behind the same handler | |
| 67 | + state: open | |
| 68 | + priority: medium | |
| 69 | + author: | |
| 70 | + name: k33g | |
| 71 | + email: ph.charriere@gmail.com | |
| 72 | + createdAt: 2026-11-25T05:04:41.000Z | |
| 73 | + - id: 3 | |
| 74 | + title: Interop - Python a2a-sdk client and demos/a2a-discussion against the prototype | |
| 75 | + state: open | |
| 76 | + priority: medium | |
| 77 | + author: | |
| 78 | + name: k33g | |
| 79 | + email: ph.charriere@gmail.com | |
| 80 | + createdAt: 2026-11-25T05:04:41.000Z | |
| 81 | + - id: 4 | |
| 82 | + title: Decide and record (keep, switch, or both) | |
| 83 | + state: open | |
| 84 | + priority: high | |
| 85 | + author: | |
| 86 | + name: k33g | |
| 87 | + email: ph.charriere@gmail.com | |
| 88 | + createdAt: 2026-11-25T05:04:41.000Z | |
| 89 | +comments: [] | |
| new file mode 100644 | |||
| @@ -0,0 +1,89 @@ | |||
| 1 | +# Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | ||
| 2 | +id: 260 | ||
| 3 | +title: "A2A: study the official Go SDK (a2aproject/a2a-go) instead of mm's hand-written subset" | ||
| 4 | +state: open | ||
| 5 | +author: | ||
| 6 | + name: k33g | ||
| 7 | + email: ph.charriere@gmail.com | ||
| 8 | +createdAt: 2026-11-25T05:04:41.000Z | ||
| 9 | +updatedAt: 2026-11-25T05:27:08.000Z | ||
| 10 | +labels: | ||
| 11 | + - question | ||
| 12 | + - kind::chore | ||
| 13 | +milestone: v2.0.2 | ||
| 14 | +epic: A2A | ||
| 15 | +related: | ||
| 16 | + - 243 | ||
| 17 | +body: | | ||
| 18 | + Follow-up of [#243 — A2A mode](.tickets/issues/0243-a2a-mode-discussion-what-should-mm-do-with-the-a.yaml). | ||
| 19 | + Asked by the user (2026-11-25): study https://github.com/a2aproject/a2a-go. | ||
| 20 | + | ||
| 21 | + ## Today (branch `feature/a2a`) | ||
| 22 | + `internal/a2a` is a hand-written subset (~600 lines): JSON-RPC over HTTP, | ||
| 23 | + text parts only, no streaming, blocking send; it speaks **both** A2A 1.0 | ||
| 24 | + (`SendMessage`, `GetTask`, `ROLE_USER`, `{"task": …}`, | ||
| 25 | + `supportedInterfaces`) and 0.3 (`message/send`, `tasks/get`); the client | ||
| 26 | + tries 1.0 and falls back to 0.3. Checked against the official **Python** | ||
| 27 | + `a2a-sdk` 1.3.1 client: card read, `TASK_STATE_COMPLETED`, the | ||
| 28 | + conversation continued by `contextId`. | ||
| 29 | + | ||
| 30 | + ## The SDK (proxy.golang.org, 2026-11-25) | ||
| 31 | + - latest stable `v0.3.15` (2026-04-15) — the **0.3** protocol; | ||
| 32 | + - `v1.0.0-alpha`, `-alpha.2`, `-alpha.3` — the **1.0** protocol, not | ||
| 33 | + stable yet. | ||
| 34 | + | ||
| 35 | + ## Questions | ||
| 36 | + - Which version: 0.3.15 (stable, old protocol) or a 1.0 alpha (current | ||
| 37 | + protocol, API may change)? Can one dependency serve both versions, as | ||
| 38 | + `internal/a2a` does today, or does it take two? | ||
| 39 | + - What it brings that mm lacks: streaming (`SendStreamingMessage` / SSE — | ||
| 40 | + mm streams text already), `input-required` (an `ask_user` question | ||
| 41 | + sent back to the caller, a consent asked of the calling agent), task | ||
| 42 | + cancel, push notifications, gRPC and HTTP+JSON bindings, card signatures, | ||
| 43 | + auth helpers. | ||
| 44 | + - Cost: dependency size (gRPC, protobuf?), build time and binary size — | ||
| 45 | + mm ships one static binary for macOS, Linux and Windows; licence. | ||
| 46 | + - Fit with mm's loop: its server's executor interface vs `runA2A`'s | ||
| 47 | + handler (one conversation per contextId, one generation at a time); its | ||
| 48 | + client inside the `ask_a2a_agent` tool and `mm a2a-send`. | ||
| 49 | + - Interop: re-run the Python `a2a-sdk` check and | ||
| 50 | + `demos/a2a-discussion` against an SDK-based build. | ||
| 51 | + | ||
| 52 | + ## Outcome expected | ||
| 53 | + A decision recorded here — keep the hand-written subset, switch to the | ||
| 54 | + SDK (which version), or both (the SDK for what the subset lacks) — and | ||
| 55 | + implementation tickets if switching. | ||
| 56 | +tasks: | ||
| 57 | + - id: 1 | ||
| 58 | + title: Read the SDK (v0.3.15 and v1.0.0-alpha.3) - API, dependencies, licence, binary size | ||
| 59 | + state: open | ||
| 60 | + priority: high | ||
| 61 | + author: | ||
| 62 | + name: k33g | ||
| 63 | + email: ph.charriere@gmail.com | ||
| 64 | + createdAt: 2026-11-25T05:04:41.000Z | ||
| 65 | + - id: 2 | ||
| 66 | + title: Prototype mm a2a and the client on the SDK, behind the same handler | ||
| 67 | + state: open | ||
| 68 | + priority: medium | ||
| 69 | + author: | ||
| 70 | + name: k33g | ||
| 71 | + email: ph.charriere@gmail.com | ||
| 72 | + createdAt: 2026-11-25T05:04:41.000Z | ||
| 73 | + - id: 3 | ||
| 74 | + title: Interop - Python a2a-sdk client and demos/a2a-discussion against the prototype | ||
| 75 | + state: open | ||
| 76 | + priority: medium | ||
| 77 | + author: | ||
| 78 | + name: k33g | ||
| 79 | + email: ph.charriere@gmail.com | ||
| 80 | + createdAt: 2026-11-25T05:04:41.000Z | ||
| 81 | + - id: 4 | ||
| 82 | + title: Decide and record (keep, switch, or both) | ||
| 83 | + state: open | ||
| 84 | + priority: high | ||
| 85 | + author: | ||
| 86 | + name: k33g | ||
| 87 | + email: ph.charriere@gmail.com | ||
| 88 | + createdAt: 2026-11-25T05:04:41.000Z | ||
| 89 | +comments: [] | ||
added
.tickets/issues/0261-dynamic-system-instructions-inject-the-relevant-r.yaml +110 -0 | new file mode 100644 | ||
| @@ -0,0 +1,110 @@ | ||
| 1 | +# Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | |
| 2 | +id: 261 | |
| 3 | +title: "Dynamic system instructions: inject the relevant rules at each turn (study pk's directives)" | |
| 4 | +state: open | |
| 5 | +author: | |
| 6 | + name: k33g | |
| 7 | + email: ph.charriere@gmail.com | |
| 8 | +createdAt: 2026-11-25T05:15:39.000Z | |
| 9 | +updatedAt: 2026-11-25T05:15:39.000Z | |
| 10 | +labels: | |
| 11 | + - question | |
| 12 | + - enhancement | |
| 13 | +epic: Prompts | |
| 14 | +related: | |
| 15 | + - 253 | |
| 16 | + - 230 | |
| 17 | + - 262 | |
| 18 | +body: | | |
| 19 | + Asked by the user (2026-11-25): study dynamic system instructions, as | |
| 20 | + in pk (https://codeberg.org/ai-apocalypse-survival-kit/pk, its | |
| 21 | + `docs/directives-en.md`). | |
| 22 | + | |
| 23 | + ## What pk does ("directives") | |
| 24 | + - A corpus of short Markdown rules, one theme per file | |
| 25 | + (`.pk/directives/*.md`, 100–300 tokens each). | |
| 26 | + - At every user turn: the question is **embedded**, a top-K cosine | |
| 27 | + search runs over the indexed directives (`threshold_directives`, | |
| 28 | + default 0.8, stricter than its RAG's), and the hits (typically 1–3) | |
| 29 | + are formatted as a "# Active directives" block **concatenated to the | |
| 30 | + system prompt** — same system message, never a second one (some Qwen3 | |
| 31 | + templates refuse two). | |
| 32 | + - Index in `.pk/embeddings/directives.json`, built at start-up, | |
| 33 | + re-embedded incrementally (mtime) on an `update_period` tick; needs an | |
| 34 | + embedding model (`ai/embeddinggemma`). | |
| 35 | + - `/dyn-directives` shows which rules were injected at the last turn, | |
| 36 | + with their scores; a status line on every turn. | |
| 37 | + - AGENTS.md can be split at its `##` headings into directives | |
| 38 | + (`[agents] as_directive = true`). | |
| 39 | + - Their claim: a static prompt of 150–250 lines drops to 40–60, the | |
| 40 | + injection adds 200–800 tokens when a rule applies, often 0; small | |
| 41 | + models (Gemma-3 4B, Qwen3 4B, Phi-4-mini) "behave noticeably better". | |
| 42 | + | |
| 43 | + ## What mm has today | |
| 44 | + - A static `system:` with variables (#253), AGENTS.md appended whole. | |
| 45 | + - `turnReminder` (#230): a fixed text next to EVERY question — measured | |
| 46 | + in demos/lfm-coder: a rule followed 0/5 from the system prompt, 3/3 | |
| 47 | + next to the question. | |
| 48 | + - Skills and `skillRouting` (a decider picks the skill to load), | |
| 49 | + `docSearch` (BM25 over docs, no embeddings), `/docs`. | |
| 50 | + | |
| 51 | + ## Questions | |
| 52 | + - **Where to inject.** pk changes the SYSTEM prompt every turn: the | |
| 53 | + server's prompt cache (llama.cpp's KV cache) holds only up to the | |
| 54 | + first token that changed, so every turn re-reads the whole history. | |
| 55 | + mm's `turnReminder` measure says next to the QUESTION works better | |
| 56 | + for small models anyway, and keeps the cache. Measure both. | |
| 57 | + - **How to select.** Embeddings (a second model to serve and keep | |
| 58 | + loaded) vs BM25 (already in mm, `internal/docsearch`) vs a decider | |
| 59 | + (as `skillRouting`) vs keywords in each rule's front matter (like | |
| 60 | + skill keywords). Small corpora: is BM25 enough? | |
| 61 | + - **Kept in the history or not.** Injected once per turn and kept (like | |
| 62 | + `turnReminder`), or only in the request (no growth, but the model | |
| 63 | + loses why it did something). | |
| 64 | + - **Format of a rule.** One file per rule in `.mm/rules/` with a | |
| 65 | + `name`, `keywords`, and the text; an "always" flag for the hard rules. | |
| 66 | + - **Observability.** A `/rules` command (as `/dyn-directives`) and a | |
| 67 | + dim line per turn listing the injected rules. | |
| 68 | + - **AGENTS.md** split by `##` as rules — optional. | |
| 69 | + - Interaction with `skillRouting` (a skill is a procedure, a rule is a | |
| 70 | + constraint) and with the in-turn compression (#251). | |
| 71 | + | |
| 72 | + ## Outcome expected | |
| 73 | + A measured comparison on a demo agent with a long rule set (e.g. a | |
| 74 | + coder for one language, 15–20 rules), static prompt vs dynamic rules | |
| 75 | + (in the system prompt vs next to the question), with one or two small | |
| 76 | + models — then a decision and implementation tickets. | |
| 77 | +tasks: | |
| 78 | + - id: 1 | |
| 79 | + title: Read pk's implementation (pkg/directives, internal/agent/directives.go) and its dynamic-golo demo | |
| 80 | + state: open | |
| 81 | + priority: high | |
| 82 | + author: | |
| 83 | + name: k33g | |
| 84 | + email: ph.charriere@gmail.com | |
| 85 | + createdAt: 2026-11-25T05:15:39.000Z | |
| 86 | + - id: 2 | |
| 87 | + title: Choose a selection method (BM25, embeddings, decider, keywords) and the injection point (system vs next to the question) | |
| 88 | + state: open | |
| 89 | + priority: high | |
| 90 | + author: | |
| 91 | + name: k33g | |
| 92 | + email: ph.charriere@gmail.com | |
| 93 | + createdAt: 2026-11-25T05:15:39.000Z | |
| 94 | + - id: 3 | |
| 95 | + title: Measure on a demo agent with many rules - static vs dynamic, prompt cache cost | |
| 96 | + state: open | |
| 97 | + priority: medium | |
| 98 | + author: | |
| 99 | + name: k33g | |
| 100 | + email: ph.charriere@gmail.com | |
| 101 | + createdAt: 2026-11-25T05:15:39.000Z | |
| 102 | + - id: 4 | |
| 103 | + title: Decide and write implementation tickets | |
| 104 | + state: open | |
| 105 | + priority: medium | |
| 106 | + author: | |
| 107 | + name: k33g | |
| 108 | + email: ph.charriere@gmail.com | |
| 109 | + createdAt: 2026-11-25T05:15:39.000Z | |
| 110 | +comments: [] | |
| new file mode 100644 | |||
| @@ -0,0 +1,110 @@ | |||
| 1 | +# Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | ||
| 2 | +id: 261 | ||
| 3 | +title: "Dynamic system instructions: inject the relevant rules at each turn (study pk's directives)" | ||
| 4 | +state: open | ||
| 5 | +author: | ||
| 6 | + name: k33g | ||
| 7 | + email: ph.charriere@gmail.com | ||
| 8 | +createdAt: 2026-11-25T05:15:39.000Z | ||
| 9 | +updatedAt: 2026-11-25T05:15:39.000Z | ||
| 10 | +labels: | ||
| 11 | + - question | ||
| 12 | + - enhancement | ||
| 13 | +epic: Prompts | ||
| 14 | +related: | ||
| 15 | + - 253 | ||
| 16 | + - 230 | ||
| 17 | + - 262 | ||
| 18 | +body: | | ||
| 19 | + Asked by the user (2026-11-25): study dynamic system instructions, as | ||
| 20 | + in pk (https://codeberg.org/ai-apocalypse-survival-kit/pk, its | ||
| 21 | + `docs/directives-en.md`). | ||
| 22 | + | ||
| 23 | + ## What pk does ("directives") | ||
| 24 | + - A corpus of short Markdown rules, one theme per file | ||
| 25 | + (`.pk/directives/*.md`, 100–300 tokens each). | ||
| 26 | + - At every user turn: the question is **embedded**, a top-K cosine | ||
| 27 | + search runs over the indexed directives (`threshold_directives`, | ||
| 28 | + default 0.8, stricter than its RAG's), and the hits (typically 1–3) | ||
| 29 | + are formatted as a "# Active directives" block **concatenated to the | ||
| 30 | + system prompt** — same system message, never a second one (some Qwen3 | ||
| 31 | + templates refuse two). | ||
| 32 | + - Index in `.pk/embeddings/directives.json`, built at start-up, | ||
| 33 | + re-embedded incrementally (mtime) on an `update_period` tick; needs an | ||
| 34 | + embedding model (`ai/embeddinggemma`). | ||
| 35 | + - `/dyn-directives` shows which rules were injected at the last turn, | ||
| 36 | + with their scores; a status line on every turn. | ||
| 37 | + - AGENTS.md can be split at its `##` headings into directives | ||
| 38 | + (`[agents] as_directive = true`). | ||
| 39 | + - Their claim: a static prompt of 150–250 lines drops to 40–60, the | ||
| 40 | + injection adds 200–800 tokens when a rule applies, often 0; small | ||
| 41 | + models (Gemma-3 4B, Qwen3 4B, Phi-4-mini) "behave noticeably better". | ||
| 42 | + | ||
| 43 | + ## What mm has today | ||
| 44 | + - A static `system:` with variables (#253), AGENTS.md appended whole. | ||
| 45 | + - `turnReminder` (#230): a fixed text next to EVERY question — measured | ||
| 46 | + in demos/lfm-coder: a rule followed 0/5 from the system prompt, 3/3 | ||
| 47 | + next to the question. | ||
| 48 | + - Skills and `skillRouting` (a decider picks the skill to load), | ||
| 49 | + `docSearch` (BM25 over docs, no embeddings), `/docs`. | ||
| 50 | + | ||
| 51 | + ## Questions | ||
| 52 | + - **Where to inject.** pk changes the SYSTEM prompt every turn: the | ||
| 53 | + server's prompt cache (llama.cpp's KV cache) holds only up to the | ||
| 54 | + first token that changed, so every turn re-reads the whole history. | ||
| 55 | + mm's `turnReminder` measure says next to the QUESTION works better | ||
| 56 | + for small models anyway, and keeps the cache. Measure both. | ||
| 57 | + - **How to select.** Embeddings (a second model to serve and keep | ||
| 58 | + loaded) vs BM25 (already in mm, `internal/docsearch`) vs a decider | ||
| 59 | + (as `skillRouting`) vs keywords in each rule's front matter (like | ||
| 60 | + skill keywords). Small corpora: is BM25 enough? | ||
| 61 | + - **Kept in the history or not.** Injected once per turn and kept (like | ||
| 62 | + `turnReminder`), or only in the request (no growth, but the model | ||
| 63 | + loses why it did something). | ||
| 64 | + - **Format of a rule.** One file per rule in `.mm/rules/` with a | ||
| 65 | + `name`, `keywords`, and the text; an "always" flag for the hard rules. | ||
| 66 | + - **Observability.** A `/rules` command (as `/dyn-directives`) and a | ||
| 67 | + dim line per turn listing the injected rules. | ||
| 68 | + - **AGENTS.md** split by `##` as rules — optional. | ||
| 69 | + - Interaction with `skillRouting` (a skill is a procedure, a rule is a | ||
| 70 | + constraint) and with the in-turn compression (#251). | ||
| 71 | + | ||
| 72 | + ## Outcome expected | ||
| 73 | + A measured comparison on a demo agent with a long rule set (e.g. a | ||
| 74 | + coder for one language, 15–20 rules), static prompt vs dynamic rules | ||
| 75 | + (in the system prompt vs next to the question), with one or two small | ||
| 76 | + models — then a decision and implementation tickets. | ||
| 77 | +tasks: | ||
| 78 | + - id: 1 | ||
| 79 | + title: Read pk's implementation (pkg/directives, internal/agent/directives.go) and its dynamic-golo demo | ||
| 80 | + state: open | ||
| 81 | + priority: high | ||
| 82 | + author: | ||
| 83 | + name: k33g | ||
| 84 | + email: ph.charriere@gmail.com | ||
| 85 | + createdAt: 2026-11-25T05:15:39.000Z | ||
| 86 | + - id: 2 | ||
| 87 | + title: Choose a selection method (BM25, embeddings, decider, keywords) and the injection point (system vs next to the question) | ||
| 88 | + state: open | ||
| 89 | + priority: high | ||
| 90 | + author: | ||
| 91 | + name: k33g | ||
| 92 | + email: ph.charriere@gmail.com | ||
| 93 | + createdAt: 2026-11-25T05:15:39.000Z | ||
| 94 | + - id: 3 | ||
| 95 | + title: Measure on a demo agent with many rules - static vs dynamic, prompt cache cost | ||
| 96 | + state: open | ||
| 97 | + priority: medium | ||
| 98 | + author: | ||
| 99 | + name: k33g | ||
| 100 | + email: ph.charriere@gmail.com | ||
| 101 | + createdAt: 2026-11-25T05:15:39.000Z | ||
| 102 | + - id: 4 | ||
| 103 | + title: Decide and write implementation tickets | ||
| 104 | + state: open | ||
| 105 | + priority: medium | ||
| 106 | + author: | ||
| 107 | + name: k33g | ||
| 108 | + email: ph.charriere@gmail.com | ||
| 109 | + createdAt: 2026-11-25T05:15:39.000Z | ||
| 110 | +comments: [] | ||
added
.tickets/issues/0262-pk-which-of-its-features-would-be-useful-in-mini-m.yaml +86 -0 | new file mode 100644 | ||
| @@ -0,0 +1,86 @@ | ||
| 1 | +# Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | |
| 2 | +id: 262 | |
| 3 | +title: "pk: which of its features would be useful in mini-me?" | |
| 4 | +state: open | |
| 5 | +author: | |
| 6 | + name: k33g | |
| 7 | + email: ph.charriere@gmail.com | |
| 8 | +createdAt: 2026-11-25T05:15:39.000Z | |
| 9 | +updatedAt: 2026-11-25T05:15:39.000Z | |
| 10 | +labels: | |
| 11 | + - question | |
| 12 | +epic: Ideas | |
| 13 | +related: | |
| 14 | + - 261 | |
| 15 | +body: | | |
| 16 | + Asked by the user (2026-11-25): review pk | |
| 17 | + (https://codeberg.org/ai-apocalypse-survival-kit/pk), a Go TUI agent for | |
| 18 | + local models close to mm in spirit, and list what mm could take from it. | |
| 19 | + Dynamic system instructions have their own ticket: | |
| 20 | + [#261](.tickets/issues/0261-dynamic-system-instructions-inject-the-relevant-r.yaml). | |
| 21 | + | |
| 22 | + ## pk features mm does NOT have (as read on 2026-11-25, to check) | |
| 23 | + - **Skills as tools** (`exposed_as_tools`): a skill declared to the | |
| 24 | + model as a tool `skill__<name>`, instead of `read_skill`. | |
| 25 | + - **Skill `context: fork`**: a skill run in an isolated context, its | |
| 26 | + result only coming back to the conversation. | |
| 27 | + - **Skill templating and bash blocks**: `$ARGUMENTS[N]`, | |
| 28 | + `$ARGUMENTS_REST`, `$ARGUMENTS_COUNT`; bash blocks of a skill run | |
| 29 | + first, their output becomes the skill's content. | |
| 30 | + - **`/btw`**: notes queued and given to the model with the next turn. | |
| 31 | + - **`/meta`**: a bracketed prefix (`[Brief]`…) inserted in the input — | |
| 32 | + an inline style switch. | |
| 33 | + - **`/run`**: a command's output queued as a turn (mm has `/shell`: to | |
| 34 | + compare). | |
| 35 | + - **`/last`**, **`/history`**, **`/tools`**, **`/mcp-tools`** popups. | |
| 36 | + - **RAG with embeddings** (`.pk/docs/`, `rag:` prefix, `/rag-context`), | |
| 37 | + periodic incremental re-index — mm's `docSearch` is BM25. | |
| 38 | + - **`pack_context` / `clear_context` tools**: the model can compact or | |
| 39 | + clear its own context; **compression presets** (`system_instruction`: | |
| 40 | + Minimalist / Expert / Effective, `compression_prompt`: Minimalist / | |
| 41 | + Structured / UltraShort / ContinuityFocus); `max_history_exchanges`. | |
| 42 | + - **`thinking_tool_bridge`**: after a thinking turn with no tool call, | |
| 43 | + the model is prompted again to act. | |
| 44 | + - **Workspace ignore**: gitignore-style patterns enforced for the file | |
| 45 | + tools, best effort for bash (mm has `workspace.confine`). | |
| 46 | + - **REST API** (`/info`, `/prompt`, `/cancel`, `/logs/history`, | |
| 47 | + `/logs/trace`, bearer token) and a headless mode — mm has `-p`, ACP, | |
| 48 | + and now A2A (#243). | |
| 49 | + - **`tools_format` adapters** for phi-4 and Qwen3 (mm has | |
| 50 | + `toolFormat: xml_tools`). | |
| 51 | + - **`[environment]` / `env_file`**: variables given to the tools. | |
| 52 | + | |
| 53 | + ## Already in mm (no action, or compare only) | |
| 54 | + `$skill`, `@file`, MCP over HTTP, the loop guard, LSP, background jobs, | |
| 55 | + context compression (`/compact`), thinking display, tool confirmation | |
| 56 | + (`yolo`), AGENTS.md, `mm init` (vs `pk create`), `/copy`, `/save`. | |
| 57 | + | |
| 58 | + ## Outcome expected | |
| 59 | + For each feature: worth it for mm or not, and why (measured where it | |
| 60 | + matters); then one ticket per feature kept. | |
| 61 | +tasks: | |
| 62 | + - id: 1 | |
| 63 | + title: Read pk's docs and code for each feature above; confirm what mm lacks | |
| 64 | + state: open | |
| 65 | + priority: high | |
| 66 | + author: | |
| 67 | + name: k33g | |
| 68 | + email: ph.charriere@gmail.com | |
| 69 | + createdAt: 2026-11-25T05:15:39.000Z | |
| 70 | + - id: 2 | |
| 71 | + title: Rank them for mm (value for small models vs cost) and record the verdicts here | |
| 72 | + state: open | |
| 73 | + priority: medium | |
| 74 | + author: | |
| 75 | + name: k33g | |
| 76 | + email: ph.charriere@gmail.com | |
| 77 | + createdAt: 2026-11-25T05:15:39.000Z | |
| 78 | + - id: 3 | |
| 79 | + title: One ticket per feature kept | |
| 80 | + state: open | |
| 81 | + priority: none | |
| 82 | + author: | |
| 83 | + name: k33g | |
| 84 | + email: ph.charriere@gmail.com | |
| 85 | + createdAt: 2026-11-25T05:15:39.000Z | |
| 86 | +comments: [] | |
| new file mode 100644 | |||
| @@ -0,0 +1,86 @@ | |||
| 1 | +# Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | ||
| 2 | +id: 262 | ||
| 3 | +title: "pk: which of its features would be useful in mini-me?" | ||
| 4 | +state: open | ||
| 5 | +author: | ||
| 6 | + name: k33g | ||
| 7 | + email: ph.charriere@gmail.com | ||
| 8 | +createdAt: 2026-11-25T05:15:39.000Z | ||
| 9 | +updatedAt: 2026-11-25T05:15:39.000Z | ||
| 10 | +labels: | ||
| 11 | + - question | ||
| 12 | +epic: Ideas | ||
| 13 | +related: | ||
| 14 | + - 261 | ||
| 15 | +body: | | ||
| 16 | + Asked by the user (2026-11-25): review pk | ||
| 17 | + (https://codeberg.org/ai-apocalypse-survival-kit/pk), a Go TUI agent for | ||
| 18 | + local models close to mm in spirit, and list what mm could take from it. | ||
| 19 | + Dynamic system instructions have their own ticket: | ||
| 20 | + [#261](.tickets/issues/0261-dynamic-system-instructions-inject-the-relevant-r.yaml). | ||
| 21 | + | ||
| 22 | + ## pk features mm does NOT have (as read on 2026-11-25, to check) | ||
| 23 | + - **Skills as tools** (`exposed_as_tools`): a skill declared to the | ||
| 24 | + model as a tool `skill__<name>`, instead of `read_skill`. | ||
| 25 | + - **Skill `context: fork`**: a skill run in an isolated context, its | ||
| 26 | + result only coming back to the conversation. | ||
| 27 | + - **Skill templating and bash blocks**: `$ARGUMENTS[N]`, | ||
| 28 | + `$ARGUMENTS_REST`, `$ARGUMENTS_COUNT`; bash blocks of a skill run | ||
| 29 | + first, their output becomes the skill's content. | ||
| 30 | + - **`/btw`**: notes queued and given to the model with the next turn. | ||
| 31 | + - **`/meta`**: a bracketed prefix (`[Brief]`…) inserted in the input — | ||
| 32 | + an inline style switch. | ||
| 33 | + - **`/run`**: a command's output queued as a turn (mm has `/shell`: to | ||
| 34 | + compare). | ||
| 35 | + - **`/last`**, **`/history`**, **`/tools`**, **`/mcp-tools`** popups. | ||
| 36 | + - **RAG with embeddings** (`.pk/docs/`, `rag:` prefix, `/rag-context`), | ||
| 37 | + periodic incremental re-index — mm's `docSearch` is BM25. | ||
| 38 | + - **`pack_context` / `clear_context` tools**: the model can compact or | ||
| 39 | + clear its own context; **compression presets** (`system_instruction`: | ||
| 40 | + Minimalist / Expert / Effective, `compression_prompt`: Minimalist / | ||
| 41 | + Structured / UltraShort / ContinuityFocus); `max_history_exchanges`. | ||
| 42 | + - **`thinking_tool_bridge`**: after a thinking turn with no tool call, | ||
| 43 | + the model is prompted again to act. | ||
| 44 | + - **Workspace ignore**: gitignore-style patterns enforced for the file | ||
| 45 | + tools, best effort for bash (mm has `workspace.confine`). | ||
| 46 | + - **REST API** (`/info`, `/prompt`, `/cancel`, `/logs/history`, | ||
| 47 | + `/logs/trace`, bearer token) and a headless mode — mm has `-p`, ACP, | ||
| 48 | + and now A2A (#243). | ||
| 49 | + - **`tools_format` adapters** for phi-4 and Qwen3 (mm has | ||
| 50 | + `toolFormat: xml_tools`). | ||
| 51 | + - **`[environment]` / `env_file`**: variables given to the tools. | ||
| 52 | + | ||
| 53 | + ## Already in mm (no action, or compare only) | ||
| 54 | + `$skill`, `@file`, MCP over HTTP, the loop guard, LSP, background jobs, | ||
| 55 | + context compression (`/compact`), thinking display, tool confirmation | ||
| 56 | + (`yolo`), AGENTS.md, `mm init` (vs `pk create`), `/copy`, `/save`. | ||
| 57 | + | ||
| 58 | + ## Outcome expected | ||
| 59 | + For each feature: worth it for mm or not, and why (measured where it | ||
| 60 | + matters); then one ticket per feature kept. | ||
| 61 | +tasks: | ||
| 62 | + - id: 1 | ||
| 63 | + title: Read pk's docs and code for each feature above; confirm what mm lacks | ||
| 64 | + state: open | ||
| 65 | + priority: high | ||
| 66 | + author: | ||
| 67 | + name: k33g | ||
| 68 | + email: ph.charriere@gmail.com | ||
| 69 | + createdAt: 2026-11-25T05:15:39.000Z | ||
| 70 | + - id: 2 | ||
| 71 | + title: Rank them for mm (value for small models vs cost) and record the verdicts here | ||
| 72 | + state: open | ||
| 73 | + priority: medium | ||
| 74 | + author: | ||
| 75 | + name: k33g | ||
| 76 | + email: ph.charriere@gmail.com | ||
| 77 | + createdAt: 2026-11-25T05:15:39.000Z | ||
| 78 | + - id: 3 | ||
| 79 | + title: One ticket per feature kept | ||
| 80 | + state: open | ||
| 81 | + priority: none | ||
| 82 | + author: | ||
| 83 | + name: k33g | ||
| 84 | + email: ph.charriere@gmail.com | ||
| 85 | + createdAt: 2026-11-25T05:15:39.000Z | ||
| 86 | +comments: [] | ||
modified
README.md +1 -0 | @@ -177,6 +177,7 @@ The `demos/` directory holds ready-made set-ups (most with a README explaining h | ||
| 177 | 177 | | `demos/news-roundup/` | a press-review agent: DuckDuckGo News through a small MCP server (Python standard library), Qwen3.5 9B on llmman, ready-made citations so no article is invented, measured results | |
| 178 | 178 | | `demos/qwen-search/` | the same kind of agent with **skills** instead of an MCP server: web search and a press review through DuckDuckGo Lite and `fetch_content`, plus a skill with a catalogue of trusted pages (WebAssembly); Qwen3.5 2B and 4B measured | |
| 179 | 179 | | `demos/prompt-variables/` | the variables of the system prompt — `{{date}}`, `{{cwd}}`, `{{env.USER}}` and a `variables:` section used as `{{config.NAME}}` — with Qwen3.5 4B (and 2B) on llamacpp: what a small model repeats correctly, and what it cannot compute from them (measured) | |
| 180 | +| `demos/a2a-discussion/` | three mm agents (for, against, moderator) debating over the Agent2Agent protocol (`mm a2a`, `mm a2a-send`, the `ask_a2a_agent` tool), one LFM3 1.7B shared on one llama-server; a script-relayed debate and a moderator-led one, measured | | |
| 180 | 181 | | `demos/project-wizard/` | the interactive prompts (`ask_user`) in a small agent: a four-question form (text, two choices, several choices), then a yes/no confirmation carrying the plan before any file is written; Qwen3.5 9B on llmman, measured results | |
| 181 | 182 | | `demos/hooks/` | hooks in Node.js around a small shell assistant (Gemma 4 E4B on llmman): a question holding a secret never reaches the model, today's date and the file list are added to every question, `rm -r` / `sudo` / `curl \| sh` are denied, every tool call and turn is logged to `.mm/hooks-audit.jsonl` | |
| 182 | 183 | | `demos/hooks-ask/` | `preAsk` and `postAsk` hooks in Node.js around a help desk that hands technical questions to an expert agent (both Gemma 4 E4B on llmman): secrets masked before they leave, at most 2 `ask_agent` calls per question, standing rules added for the expert, a failed hand-off turned into an instruction, every hand-off logged to `.mm/ask-audit.jsonl` | |
| @@ -177,6 +177,7 @@ The `demos/` directory holds ready-made set-ups (most with a README explaining h | |||
| 177 | | `demos/news-roundup/` | a press-review agent: DuckDuckGo News through a small MCP server (Python standard library), Qwen3.5 9B on llmman, ready-made citations so no article is invented, measured results | | 177 | | `demos/news-roundup/` | a press-review agent: DuckDuckGo News through a small MCP server (Python standard library), Qwen3.5 9B on llmman, ready-made citations so no article is invented, measured results | |
| 178 | | `demos/qwen-search/` | the same kind of agent with **skills** instead of an MCP server: web search and a press review through DuckDuckGo Lite and `fetch_content`, plus a skill with a catalogue of trusted pages (WebAssembly); Qwen3.5 2B and 4B measured | | 178 | | `demos/qwen-search/` | the same kind of agent with **skills** instead of an MCP server: web search and a press review through DuckDuckGo Lite and `fetch_content`, plus a skill with a catalogue of trusted pages (WebAssembly); Qwen3.5 2B and 4B measured | |
| 179 | | `demos/prompt-variables/` | the variables of the system prompt — `{{date}}`, `{{cwd}}`, `{{env.USER}}` and a `variables:` section used as `{{config.NAME}}` — with Qwen3.5 4B (and 2B) on llamacpp: what a small model repeats correctly, and what it cannot compute from them (measured) | | 179 | | `demos/prompt-variables/` | the variables of the system prompt — `{{date}}`, `{{cwd}}`, `{{env.USER}}` and a `variables:` section used as `{{config.NAME}}` — with Qwen3.5 4B (and 2B) on llamacpp: what a small model repeats correctly, and what it cannot compute from them (measured) | |
| 180 | +| `demos/a2a-discussion/` | three mm agents (for, against, moderator) debating over the Agent2Agent protocol (`mm a2a`, `mm a2a-send`, the `ask_a2a_agent` tool), one LFM3 1.7B shared on one llama-server; a script-relayed debate and a moderator-led one, measured | | ||
| 180 | | `demos/project-wizard/` | the interactive prompts (`ask_user`) in a small agent: a four-question form (text, two choices, several choices), then a yes/no confirmation carrying the plan before any file is written; Qwen3.5 9B on llmman, measured results | | 181 | | `demos/project-wizard/` | the interactive prompts (`ask_user`) in a small agent: a four-question form (text, two choices, several choices), then a yes/no confirmation carrying the plan before any file is written; Qwen3.5 9B on llmman, measured results | |
| 181 | | `demos/hooks/` | hooks in Node.js around a small shell assistant (Gemma 4 E4B on llmman): a question holding a secret never reaches the model, today's date and the file list are added to every question, `rm -r` / `sudo` / `curl \| sh` are denied, every tool call and turn is logged to `.mm/hooks-audit.jsonl` | | 182 | | `demos/hooks/` | hooks in Node.js around a small shell assistant (Gemma 4 E4B on llmman): a question holding a secret never reaches the model, today's date and the file list are added to every question, `rm -r` / `sudo` / `curl \| sh` are denied, every tool call and turn is logged to `.mm/hooks-audit.jsonl` | |
| 182 | | `demos/hooks-ask/` | `preAsk` and `postAsk` hooks in Node.js around a help desk that hands technical questions to an expert agent (both Gemma 4 E4B on llmman): secrets masked before they leave, at most 2 `ask_agent` calls per question, standing rules added for the expert, a failed hand-off turned into an instruction, every hand-off logged to `.mm/ask-audit.jsonl` | | 183 | | `demos/hooks-ask/` | `preAsk` and `postAsk` hooks in Node.js around a help desk that hands technical questions to an expert agent (both Gemma 4 E4B on llmman): secrets masked before they leave, at most 2 `ask_agent` calls per question, standing rules added for the expert, a failed hand-off turned into an instruction, every hand-off logged to `.mm/ask-audit.jsonl` | |
added
a2a_wiring.go +210 -0 | new file mode 100644 | ||
| @@ -0,0 +1,210 @@ | ||
| 1 | +package main | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "context" | |
| 5 | + "errors" | |
| 6 | + "flag" | |
| 7 | + "fmt" | |
| 8 | + "io" | |
| 9 | + "net" | |
| 10 | + "net/http" | |
| 11 | + "os" | |
| 12 | + "os/signal" | |
| 13 | + "strconv" | |
| 14 | + "strings" | |
| 15 | + "sync" | |
| 16 | + "syscall" | |
| 17 | + "time" | |
| 18 | + | |
| 19 | + "mm/internal/a2a" | |
| 20 | + "mm/internal/agentsmd" | |
| 21 | + "mm/internal/compact" | |
| 22 | + "mm/internal/config" | |
| 23 | + "mm/internal/engine" | |
| 24 | + "mm/internal/session" | |
| 25 | + "mm/internal/skills" | |
| 26 | + "mm/internal/version" | |
| 27 | + | |
| 28 | + "github.com/firebase/genkit/go/ai" | |
| 29 | +) | |
| 30 | + | |
| 31 | +// The Agent2Agent protocol (ticket 243): `mm a2a` serves this agent to other | |
| 32 | +// agents, `mm a2a-send` talks to one from a script. The ask_a2a_agent tool | |
| 33 | +// (internal/tools/a2a.go) is the model's way to talk to them. | |
| 34 | + | |
| 35 | +// runA2A serves the agent until Ctrl-C, SIGTERM or SIGHUP: its card, and | |
| 36 | +// message/send answered by the same loop as the other front ends — one | |
| 37 | +// conversation per A2A contextId, kept in memory, compressed like a terminal | |
| 38 | +// session when it grows past context.threshold. Nobody can be asked for | |
| 39 | +// consent: with yolo false, a tool that needs it is refused, as under -p. | |
| 40 | +func runA2A(ctx context.Context, e *engine.Engine, system string, tools []ai.ToolRef, portFlag int) error { | |
| 41 | + cfg := config.Cfg.A2A | |
| 42 | + host, port := cfg.Host, cfg.Port | |
| 43 | + if host == "" { | |
| 44 | + host = config.DefaultA2AHost | |
| 45 | + } | |
| 46 | + if portFlag > 0 { | |
| 47 | + port = portFlag | |
| 48 | + } | |
| 49 | + if port == 0 { | |
| 50 | + port = config.DefaultA2APort | |
| 51 | + } | |
| 52 | + token := "" | |
| 53 | + if cfg.TokenEnv != "" { | |
| 54 | + if token = os.Getenv(cfg.TokenEnv); token == "" { | |
| 55 | + return fmt.Errorf("a2a.tokenEnv: %s is not set — export the token callers must send, or remove the key", cfg.TokenEnv) | |
| 56 | + } | |
| 57 | + } | |
| 58 | + addr := net.JoinHostPort(host, strconv.Itoa(port)) | |
| 59 | + url := "http://" + addr | |
| 60 | + | |
| 61 | + cwd, _ := os.Getwd() | |
| 62 | + var mu sync.Mutex | |
| 63 | + conversations := map[string][]*ai.Message{} | |
| 64 | + handle := func(ctx context.Context, contextID, text string) (string, error) { | |
| 65 | + mu.Lock() | |
| 66 | + msgs, ok := conversations[contextID] | |
| 67 | + mu.Unlock() | |
| 68 | + if !ok { | |
| 69 | + msgs = session.Fresh(agentsmd.System(system, cwd)) | |
| 70 | + } | |
| 71 | + if dec := compact.Decide(msgs, e.LastInputTokens(), e.ContextWindow, config.Cfg.Context); dec.Compact { | |
| 72 | + c := config.Cfg.Context | |
| 73 | + msgs, _, _ = compact.Apply(ctx, msgs, c, func(ctx context.Context, request []*ai.Message) (string, error) { | |
| 74 | + return e.Summarize(ctx, request, c.SummaryMaxTokens) | |
| 75 | + }, e.Explain) | |
| 76 | + } | |
| 77 | + fmt.Fprintf(os.Stderr, "\n📨 %s · %s\n", shortID(contextID), oneLine(text, 120)) | |
| 78 | + resp, full, err := e.Generate(ctx, append(msgs, ai.NewUserTextMessage(text)), tools) | |
| 79 | + fmt.Println() | |
| 80 | + if err != nil { | |
| 81 | + return "", err | |
| 82 | + } | |
| 83 | + mu.Lock() | |
| 84 | + conversations[contextID] = full | |
| 85 | + mu.Unlock() | |
| 86 | + return resp.Text(), nil | |
| 87 | + } | |
| 88 | + | |
| 89 | + srv := &http.Server{Addr: addr, Handler: a2a.NewServer(a2aCard(url), handle, token), ReadHeaderTimeout: 10 * time.Second} | |
| 90 | + ln, err := net.Listen("tcp", addr) | |
| 91 | + if err != nil { | |
| 92 | + return fmt.Errorf("a2a: cannot listen on %s: %w (another agent on this port? set a2a.port or --a2a-port)", addr, err) | |
| 93 | + } | |
| 94 | + fmt.Fprintf(os.Stderr, "🤝 A2A agent %q on %s — card: %s%s\n", a2aName(), url, url, a2a.CardPath) | |
| 95 | + if token != "" { | |
| 96 | + fmt.Fprintf(os.Stderr, " callers must send Authorization: Bearer $%s\n", cfg.TokenEnv) | |
| 97 | + } | |
| 98 | + | |
| 99 | + ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP) | |
| 100 | + defer stop() | |
| 101 | + go func() { | |
| 102 | + <-ctx.Done() | |
| 103 | + shut, cancel := context.WithTimeout(context.Background(), 5*time.Second) | |
| 104 | + defer cancel() | |
| 105 | + _ = srv.Shutdown(shut) | |
| 106 | + }() | |
| 107 | + if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) { | |
| 108 | + return err | |
| 109 | + } | |
| 110 | + fmt.Fprintln(os.Stderr, "\n🤝 A2A agent stopped") | |
| 111 | + return nil | |
| 112 | +} | |
| 113 | + | |
| 114 | +// a2aCard describes this agent: its name, what it is for, and its skills. | |
| 115 | +func a2aCard(url string) a2a.AgentCard { | |
| 116 | + desc := strings.TrimSpace(config.Cfg.A2A.Description) | |
| 117 | + if desc == "" { | |
| 118 | + desc = config.Cfg.ACP.Title | |
| 119 | + } | |
| 120 | + card := a2a.AgentCard{Name: a2aName(), Description: desc, URL: url, Version: version.Short()} | |
| 121 | + for _, s := range skills.Declared() { | |
| 122 | + card.Skills = append(card.Skills, a2a.Skill{ID: s.Name, Name: s.Name, Description: s.Description, Tags: s.Keywords}) | |
| 123 | + } | |
| 124 | + return card | |
| 125 | +} | |
| 126 | + | |
| 127 | +// a2aName is the agent's name for other agents: acp.name, else the title. | |
| 128 | +func a2aName() string { | |
| 129 | + if n := strings.TrimSpace(config.Cfg.ACP.Name); n != "" { | |
| 130 | + return n | |
| 131 | + } | |
| 132 | + return config.Cfg.ACP.Title | |
| 133 | +} | |
| 134 | + | |
| 135 | +// a2aSendMain is `mm a2a-send <url> [message]`: one message to an A2A | |
| 136 | +// agent, its answer on stdout, the conversation's contextId on stderr — | |
| 137 | +// `--context <id>` continues it. The message is read from stdin when not | |
| 138 | +// given. Exit codes: 0 answered, 1 the agent or the network failed, 2 usage. | |
| 139 | +// | |
| 140 | +// ctx=$(mm a2a-send http://127.0.0.1:9101 "Hello" 2>&1 >/dev/tty | sed -n 's/^context: //p') | |
| 141 | +func a2aSendMain(args []string, stdin io.Reader, stdout, stderr io.Writer) int { | |
| 142 | + fs := flag.NewFlagSet("mm a2a-send", flag.ContinueOnError) | |
| 143 | + fs.SetOutput(stderr) | |
| 144 | + contextID := fs.String("context", "", "continue the conversation with this contextId (printed by an earlier call)") | |
| 145 | + tokenEnv := fs.String("token-env", "", "environment variable holding the agent's bearer token") | |
| 146 | + timeout := fs.Duration("timeout", 10*time.Minute, "how long to wait for the answer") | |
| 147 | + fs.Usage = func() { | |
| 148 | + fmt.Fprintln(stderr, "usage: mm a2a-send [--context ID] [--token-env VAR] [--timeout D] <agent url> [message]") | |
| 149 | + fs.PrintDefaults() | |
| 150 | + } | |
| 151 | + // Flags may come before or after the URL and the message. | |
| 152 | + var positional []string | |
| 153 | + rest := args | |
| 154 | + for len(rest) > 0 { | |
| 155 | + if err := fs.Parse(rest); err != nil { | |
| 156 | + return 2 | |
| 157 | + } | |
| 158 | + rest = fs.Args() | |
| 159 | + if len(rest) > 0 { | |
| 160 | + positional = append(positional, rest[0]) | |
| 161 | + rest = rest[1:] | |
| 162 | + } | |
| 163 | + } | |
| 164 | + if len(positional) < 1 || len(positional) > 2 { | |
| 165 | + fs.Usage() | |
| 166 | + return 2 | |
| 167 | + } | |
| 168 | + text := "" | |
| 169 | + if len(positional) == 2 { | |
| 170 | + text = positional[1] | |
| 171 | + } else { | |
| 172 | + b, _ := io.ReadAll(stdin) | |
| 173 | + text = string(b) | |
| 174 | + } | |
| 175 | + if strings.TrimSpace(text) == "" { | |
| 176 | + fmt.Fprintln(stderr, "mm a2a-send: empty message") | |
| 177 | + return 2 | |
| 178 | + } | |
| 179 | + token := "" | |
| 180 | + if *tokenEnv != "" { | |
| 181 | + token = os.Getenv(*tokenEnv) | |
| 182 | + } | |
| 183 | + ctx, cancel := context.WithTimeout(context.Background(), *timeout) | |
| 184 | + defer cancel() | |
| 185 | + answer, ctxID, err := a2a.Client{}.Send(ctx, positional[0], token, *contextID, text) | |
| 186 | + if ctxID != "" { | |
| 187 | + fmt.Fprintf(stderr, "context: %s\n", ctxID) | |
| 188 | + } | |
| 189 | + if err != nil { | |
| 190 | + fmt.Fprintf(stderr, "mm a2a-send: %v\n", err) | |
| 191 | + return 1 | |
| 192 | + } | |
| 193 | + fmt.Fprintln(stdout, strings.TrimSpace(answer)) | |
| 194 | + return 0 | |
| 195 | +} | |
| 196 | + | |
| 197 | +func shortID(id string) string { | |
| 198 | + if len(id) > 8 { | |
| 199 | + return id[:8] | |
| 200 | + } | |
| 201 | + return id | |
| 202 | +} | |
| 203 | + | |
| 204 | +func oneLine(s string, n int) string { | |
| 205 | + s = strings.Join(strings.Fields(s), " ") | |
| 206 | + if len([]rune(s)) > n { | |
| 207 | + return string([]rune(s)[:n]) + "…" | |
| 208 | + } | |
| 209 | + return s | |
| 210 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,210 @@ | |||
| 1 | +package main | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "context" | ||
| 5 | + "errors" | ||
| 6 | + "flag" | ||
| 7 | + "fmt" | ||
| 8 | + "io" | ||
| 9 | + "net" | ||
| 10 | + "net/http" | ||
| 11 | + "os" | ||
| 12 | + "os/signal" | ||
| 13 | + "strconv" | ||
| 14 | + "strings" | ||
| 15 | + "sync" | ||
| 16 | + "syscall" | ||
| 17 | + "time" | ||
| 18 | + | ||
| 19 | + "mm/internal/a2a" | ||
| 20 | + "mm/internal/agentsmd" | ||
| 21 | + "mm/internal/compact" | ||
| 22 | + "mm/internal/config" | ||
| 23 | + "mm/internal/engine" | ||
| 24 | + "mm/internal/session" | ||
| 25 | + "mm/internal/skills" | ||
| 26 | + "mm/internal/version" | ||
| 27 | + | ||
| 28 | + "github.com/firebase/genkit/go/ai" | ||
| 29 | +) | ||
| 30 | + | ||
| 31 | +// The Agent2Agent protocol (ticket 243): `mm a2a` serves this agent to other | ||
| 32 | +// agents, `mm a2a-send` talks to one from a script. The ask_a2a_agent tool | ||
| 33 | +// (internal/tools/a2a.go) is the model's way to talk to them. | ||
| 34 | + | ||
| 35 | +// runA2A serves the agent until Ctrl-C, SIGTERM or SIGHUP: its card, and | ||
| 36 | +// message/send answered by the same loop as the other front ends — one | ||
| 37 | +// conversation per A2A contextId, kept in memory, compressed like a terminal | ||
| 38 | +// session when it grows past context.threshold. Nobody can be asked for | ||
| 39 | +// consent: with yolo false, a tool that needs it is refused, as under -p. | ||
| 40 | +func runA2A(ctx context.Context, e *engine.Engine, system string, tools []ai.ToolRef, portFlag int) error { | ||
| 41 | + cfg := config.Cfg.A2A | ||
| 42 | + host, port := cfg.Host, cfg.Port | ||
| 43 | + if host == "" { | ||
| 44 | + host = config.DefaultA2AHost | ||
| 45 | + } | ||
| 46 | + if portFlag > 0 { | ||
| 47 | + port = portFlag | ||
| 48 | + } | ||
| 49 | + if port == 0 { | ||
| 50 | + port = config.DefaultA2APort | ||
| 51 | + } | ||
| 52 | + token := "" | ||
| 53 | + if cfg.TokenEnv != "" { | ||
| 54 | + if token = os.Getenv(cfg.TokenEnv); token == "" { | ||
| 55 | + return fmt.Errorf("a2a.tokenEnv: %s is not set — export the token callers must send, or remove the key", cfg.TokenEnv) | ||
| 56 | + } | ||
| 57 | + } | ||
| 58 | + addr := net.JoinHostPort(host, strconv.Itoa(port)) | ||
| 59 | + url := "http://" + addr | ||
| 60 | + | ||
| 61 | + cwd, _ := os.Getwd() | ||
| 62 | + var mu sync.Mutex | ||
| 63 | + conversations := map[string][]*ai.Message{} | ||
| 64 | + handle := func(ctx context.Context, contextID, text string) (string, error) { | ||
| 65 | + mu.Lock() | ||
| 66 | + msgs, ok := conversations[contextID] | ||
| 67 | + mu.Unlock() | ||
| 68 | + if !ok { | ||
| 69 | + msgs = session.Fresh(agentsmd.System(system, cwd)) | ||
| 70 | + } | ||
| 71 | + if dec := compact.Decide(msgs, e.LastInputTokens(), e.ContextWindow, config.Cfg.Context); dec.Compact { | ||
| 72 | + c := config.Cfg.Context | ||
| 73 | + msgs, _, _ = compact.Apply(ctx, msgs, c, func(ctx context.Context, request []*ai.Message) (string, error) { | ||
| 74 | + return e.Summarize(ctx, request, c.SummaryMaxTokens) | ||
| 75 | + }, e.Explain) | ||
| 76 | + } | ||
| 77 | + fmt.Fprintf(os.Stderr, "\n📨 %s · %s\n", shortID(contextID), oneLine(text, 120)) | ||
| 78 | + resp, full, err := e.Generate(ctx, append(msgs, ai.NewUserTextMessage(text)), tools) | ||
| 79 | + fmt.Println() | ||
| 80 | + if err != nil { | ||
| 81 | + return "", err | ||
| 82 | + } | ||
| 83 | + mu.Lock() | ||
| 84 | + conversations[contextID] = full | ||
| 85 | + mu.Unlock() | ||
| 86 | + return resp.Text(), nil | ||
| 87 | + } | ||
| 88 | + | ||
| 89 | + srv := &http.Server{Addr: addr, Handler: a2a.NewServer(a2aCard(url), handle, token), ReadHeaderTimeout: 10 * time.Second} | ||
| 90 | + ln, err := net.Listen("tcp", addr) | ||
| 91 | + if err != nil { | ||
| 92 | + return fmt.Errorf("a2a: cannot listen on %s: %w (another agent on this port? set a2a.port or --a2a-port)", addr, err) | ||
| 93 | + } | ||
| 94 | + fmt.Fprintf(os.Stderr, "🤝 A2A agent %q on %s — card: %s%s\n", a2aName(), url, url, a2a.CardPath) | ||
| 95 | + if token != "" { | ||
| 96 | + fmt.Fprintf(os.Stderr, " callers must send Authorization: Bearer $%s\n", cfg.TokenEnv) | ||
| 97 | + } | ||
| 98 | + | ||
| 99 | + ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP) | ||
| 100 | + defer stop() | ||
| 101 | + go func() { | ||
| 102 | + <-ctx.Done() | ||
| 103 | + shut, cancel := context.WithTimeout(context.Background(), 5*time.Second) | ||
| 104 | + defer cancel() | ||
| 105 | + _ = srv.Shutdown(shut) | ||
| 106 | + }() | ||
| 107 | + if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) { | ||
| 108 | + return err | ||
| 109 | + } | ||
| 110 | + fmt.Fprintln(os.Stderr, "\n🤝 A2A agent stopped") | ||
| 111 | + return nil | ||
| 112 | +} | ||
| 113 | + | ||
| 114 | +// a2aCard describes this agent: its name, what it is for, and its skills. | ||
| 115 | +func a2aCard(url string) a2a.AgentCard { | ||
| 116 | + desc := strings.TrimSpace(config.Cfg.A2A.Description) | ||
| 117 | + if desc == "" { | ||
| 118 | + desc = config.Cfg.ACP.Title | ||
| 119 | + } | ||
| 120 | + card := a2a.AgentCard{Name: a2aName(), Description: desc, URL: url, Version: version.Short()} | ||
| 121 | + for _, s := range skills.Declared() { | ||
| 122 | + card.Skills = append(card.Skills, a2a.Skill{ID: s.Name, Name: s.Name, Description: s.Description, Tags: s.Keywords}) | ||
| 123 | + } | ||
| 124 | + return card | ||
| 125 | +} | ||
| 126 | + | ||
| 127 | +// a2aName is the agent's name for other agents: acp.name, else the title. | ||
| 128 | +func a2aName() string { | ||
| 129 | + if n := strings.TrimSpace(config.Cfg.ACP.Name); n != "" { | ||
| 130 | + return n | ||
| 131 | + } | ||
| 132 | + return config.Cfg.ACP.Title | ||
| 133 | +} | ||
| 134 | + | ||
| 135 | +// a2aSendMain is `mm a2a-send <url> [message]`: one message to an A2A | ||
| 136 | +// agent, its answer on stdout, the conversation's contextId on stderr — | ||
| 137 | +// `--context <id>` continues it. The message is read from stdin when not | ||
| 138 | +// given. Exit codes: 0 answered, 1 the agent or the network failed, 2 usage. | ||
| 139 | +// | ||
| 140 | +// ctx=$(mm a2a-send http://127.0.0.1:9101 "Hello" 2>&1 >/dev/tty | sed -n 's/^context: //p') | ||
| 141 | +func a2aSendMain(args []string, stdin io.Reader, stdout, stderr io.Writer) int { | ||
| 142 | + fs := flag.NewFlagSet("mm a2a-send", flag.ContinueOnError) | ||
| 143 | + fs.SetOutput(stderr) | ||
| 144 | + contextID := fs.String("context", "", "continue the conversation with this contextId (printed by an earlier call)") | ||
| 145 | + tokenEnv := fs.String("token-env", "", "environment variable holding the agent's bearer token") | ||
| 146 | + timeout := fs.Duration("timeout", 10*time.Minute, "how long to wait for the answer") | ||
| 147 | + fs.Usage = func() { | ||
| 148 | + fmt.Fprintln(stderr, "usage: mm a2a-send [--context ID] [--token-env VAR] [--timeout D] <agent url> [message]") | ||
| 149 | + fs.PrintDefaults() | ||
| 150 | + } | ||
| 151 | + // Flags may come before or after the URL and the message. | ||
| 152 | + var positional []string | ||
| 153 | + rest := args | ||
| 154 | + for len(rest) > 0 { | ||
| 155 | + if err := fs.Parse(rest); err != nil { | ||
| 156 | + return 2 | ||
| 157 | + } | ||
| 158 | + rest = fs.Args() | ||
| 159 | + if len(rest) > 0 { | ||
| 160 | + positional = append(positional, rest[0]) | ||
| 161 | + rest = rest[1:] | ||
| 162 | + } | ||
| 163 | + } | ||
| 164 | + if len(positional) < 1 || len(positional) > 2 { | ||
| 165 | + fs.Usage() | ||
| 166 | + return 2 | ||
| 167 | + } | ||
| 168 | + text := "" | ||
| 169 | + if len(positional) == 2 { | ||
| 170 | + text = positional[1] | ||
| 171 | + } else { | ||
| 172 | + b, _ := io.ReadAll(stdin) | ||
| 173 | + text = string(b) | ||
| 174 | + } | ||
| 175 | + if strings.TrimSpace(text) == "" { | ||
| 176 | + fmt.Fprintln(stderr, "mm a2a-send: empty message") | ||
| 177 | + return 2 | ||
| 178 | + } | ||
| 179 | + token := "" | ||
| 180 | + if *tokenEnv != "" { | ||
| 181 | + token = os.Getenv(*tokenEnv) | ||
| 182 | + } | ||
| 183 | + ctx, cancel := context.WithTimeout(context.Background(), *timeout) | ||
| 184 | + defer cancel() | ||
| 185 | + answer, ctxID, err := a2a.Client{}.Send(ctx, positional[0], token, *contextID, text) | ||
| 186 | + if ctxID != "" { | ||
| 187 | + fmt.Fprintf(stderr, "context: %s\n", ctxID) | ||
| 188 | + } | ||
| 189 | + if err != nil { | ||
| 190 | + fmt.Fprintf(stderr, "mm a2a-send: %v\n", err) | ||
| 191 | + return 1 | ||
| 192 | + } | ||
| 193 | + fmt.Fprintln(stdout, strings.TrimSpace(answer)) | ||
| 194 | + return 0 | ||
| 195 | +} | ||
| 196 | + | ||
| 197 | +func shortID(id string) string { | ||
| 198 | + if len(id) > 8 { | ||
| 199 | + return id[:8] | ||
| 200 | + } | ||
| 201 | + return id | ||
| 202 | +} | ||
| 203 | + | ||
| 204 | +func oneLine(s string, n int) string { | ||
| 205 | + s = strings.Join(strings.Fields(s), " ") | ||
| 206 | + if len([]rune(s)) > n { | ||
| 207 | + return string([]rune(s)[:n]) + "…" | ||
| 208 | + } | ||
| 209 | + return s | ||
| 210 | +} | ||
added
demos/a2a-discussion/.gitignore +2 -0 | new file mode 100644 | ||
| @@ -0,0 +1,2 @@ | ||
| 1 | +*.log | |
| 2 | +*.pid | |
| new file mode 100644 | |||
| @@ -0,0 +1,2 @@ | |||
| 1 | +*.log | ||
| 2 | +*.pid | ||
added
demos/a2a-discussion/README.en.md +93 -0 | new file mode 100644 | ||
| @@ -0,0 +1,93 @@ | ||
| 1 | +# a2a-discussion — three mm agents debating over A2A | |
| 2 | + | |
| 3 | +*[French version](README.fr.md)* | |
| 4 | + | |
| 5 | +Three agents, each served by `mm a2a` on its own port, talk to each other over the Agent2Agent protocol (A2A, ticket 243): | |
| 6 | + | |
| 7 | +| Agent | File | Address | Role | | |
| 8 | +|---|---|---|---| | |
| 9 | +| Alice | `alice.yaml` | `http://127.0.0.1:9101` | argues **for** the idea | | |
| 10 | +| Bob | `bob.yaml` | `http://127.0.0.1:9102` | argues **against** | | |
| 11 | +| Moderator | `moderator.yaml` | `http://127.0.0.1:9103` | runs the debate (`ask_a2a_agent`) or concludes a transcript | | |
| 12 | + | |
| 13 | +All three use the same small model, `LiquidAI/LFM3-1.7B-GGUF:Q4_K_M`, on **one** llama-server that mm starts (`llamacpp.autoStart`): the model is in memory once, about 1.2 GB — a 32 GB machine has room to spare. The last agent to stop stops the server. | |
| 14 | + | |
| 15 | +## Prerequisites | |
| 16 | + | |
| 17 | +- `mm` built at the repository root (`go build -o mm .`). | |
| 18 | +- llama.cpp: `llama-server` (or `llama`) on the `PATH` — `brew install llama.cpp` on macOS. Nothing to start: mm starts it, and downloads the model the first time (~1.2 GB). | |
| 19 | +- `curl` (used by `start.sh` to wait for the agents). | |
| 20 | +- If a llama-server already answers on 9931 (the Llama app, or your own), the agents use it instead, and mm never stops it. | |
| 21 | + | |
| 22 | +## Run | |
| 23 | + | |
| 24 | +```bash | |
| 25 | +cd demos/a2a-discussion | |
| 26 | +./start.sh # the three agents, in the background (logs: alice.log, bob.log, moderator.log) | |
| 27 | +``` | |
| 28 | + | |
| 29 | +```text | |
| 30 | +started alice (pid 12345, log alice.log) | |
| 31 | +started bob (pid 12346, log bob.log) | |
| 32 | +started moderator (pid 12347, log moderator.log) | |
| 33 | +waiting for alice on http://127.0.0.1:9101 .................. ready | |
| 34 | +waiting for bob on http://127.0.0.1:9102 ready | |
| 35 | +waiting for moderator on http://127.0.0.1:9103 ready | |
| 36 | +``` | |
| 37 | + | |
| 38 | +**1. A debate relayed by a script.** `discussion.sh` sends the topic to Alice, her answer to Bob, his answer back to Alice… for N rounds, then the transcript to the moderator: | |
| 39 | + | |
| 40 | +```bash | |
| 41 | +./discussion.sh "Remote work should be the default for software teams" 2 | |
| 42 | +``` | |
| 43 | + | |
| 44 | +Each call is one `mm a2a-send` (see below); each agent keeps its side of the conversation through the A2A `contextId`. | |
| 45 | + | |
| 46 | +**2. A debate run by the moderator itself.** The moderator's file declares Alice and Bob under `a2a.agents`: its model calls them with the `ask_a2a_agent` tool, one at a time, then concludes. | |
| 47 | + | |
| 48 | +```bash | |
| 49 | +../../mm moderator.yaml -p "Run a debate on: Should cities ban cars from their centre?" | |
| 50 | +``` | |
| 51 | + | |
| 52 | +**3. Talk to one agent yourself.** | |
| 53 | + | |
| 54 | +```bash | |
| 55 | +../../mm a2a-send http://127.0.0.1:9101 "Why should we plant more trees in cities?" | |
| 56 | +# context: 5a24d958… ← on stderr: pass it back to continue | |
| 57 | +../../mm a2a-send --context 5a24d958… http://127.0.0.1:9101 "And the cost?" | |
| 58 | +curl -s http://127.0.0.1:9101/.well-known/agent-card.json # Alice's Agent Card | |
| 59 | +``` | |
| 60 | + | |
| 61 | +**Stop.** | |
| 62 | + | |
| 63 | +```bash | |
| 64 | +./stop.sh | |
| 65 | +``` | |
| 66 | + | |
| 67 | +To watch an agent think, start it in its own terminal instead of `start.sh`: `../../mm -a2a alice.yaml` prints each message received (`📨 …`) and streams its answers. | |
| 68 | + | |
| 69 | +## How it is built — and why | |
| 70 | + | |
| 71 | +- **One model, shared.** Each agent is its own mm process with its own prompt, but `llamacpp.autoStart` makes them share one llama-server; `unloadOnExit: false`, so the first agent to quit does not unload the model under the two others. | |
| 72 | +- **Short turns.** `max_tokens: 400` and "at most 3 sentences" in the prompts keep a round readable. | |
| 73 | +- **No `ask_user`.** Nobody answers questions on an A2A server. | |
| 74 | +- **Two ways to run a debate.** The script needs nothing from the model but to answer; the moderator-led debate needs a model that calls tools — LFM3 1.7B does. | |
| 75 | + | |
| 76 | +## Measured results | |
| 77 | + | |
| 78 | +Measured on 2026-11-25 in a Docker sandbox (Linux arm64, CPU), llama.cpp build 12359, the model on a local llama-server. | |
| 79 | + | |
| 80 | +| Case | Result | Time | | |
| 81 | +|---|---|---| | |
| 82 | +| `start.sh` (model already downloaded) | three agents ready, **one** llama-server, three leases | 18 s | | |
| 83 | +| `discussion.sh` "Remote work…" 2 rounds | Alice and Bob answer each other twice, the moderator summarises each side and names the strongest argument | 37 s | | |
| 84 | +| Moderator-led debate, run 1 | 4 calls (alice, bob, alice, bob), conclusion | 72 s | | |
| 85 | +| Moderator-led debate, run 2 | 8 calls alternating alice/bob, conclusion | 130 s | | |
| 86 | +| `stop.sh` | Alice and Bob leave the server to the others, the moderator — last — stops it | — | | |
| 87 | +| Python `a2a-sdk` 1.3.1 client → Alice | card read (A2A 1.0 and 0.3 interfaces), `TASK_STATE_COMPLETED`, conversation continued by `contextId` | — | | |
| 88 | + | |
| 89 | +What a 1.7B model does in a debate: | |
| 90 | + | |
| 91 | +- **It invents its evidence**: "GitHub's 2023 report shows a 30% increase", Spotify, Netflix, Portland, Bogotá — figures and cases nobody checked. A demo of agents talking, not a source of facts. | |
| 92 | +- **It does not always keep to 3 sentences**, and in its first turn Alice once answered "Bob's point" before Bob had spoken. | |
| 93 | +- Before a fix found by this demo, the moderator's first debate stopped at its sixth call: the generation's watchdog counted the wait for Bob's answer as a silence. `ask_a2a_agent` now keeps it informed while it waits. | |
| new file mode 100644 | |||
| @@ -0,0 +1,93 @@ | |||
| 1 | +# a2a-discussion — three mm agents debating over A2A | ||
| 2 | + | ||
| 3 | +*[French version](README.fr.md)* | ||
| 4 | + | ||
| 5 | +Three agents, each served by `mm a2a` on its own port, talk to each other over the Agent2Agent protocol (A2A, ticket 243): | ||
| 6 | + | ||
| 7 | +| Agent | File | Address | Role | | ||
| 8 | +|---|---|---|---| | ||
| 9 | +| Alice | `alice.yaml` | `http://127.0.0.1:9101` | argues **for** the idea | | ||
| 10 | +| Bob | `bob.yaml` | `http://127.0.0.1:9102` | argues **against** | | ||
| 11 | +| Moderator | `moderator.yaml` | `http://127.0.0.1:9103` | runs the debate (`ask_a2a_agent`) or concludes a transcript | | ||
| 12 | + | ||
| 13 | +All three use the same small model, `LiquidAI/LFM3-1.7B-GGUF:Q4_K_M`, on **one** llama-server that mm starts (`llamacpp.autoStart`): the model is in memory once, about 1.2 GB — a 32 GB machine has room to spare. The last agent to stop stops the server. | ||
| 14 | + | ||
| 15 | +## Prerequisites | ||
| 16 | + | ||
| 17 | +- `mm` built at the repository root (`go build -o mm .`). | ||
| 18 | +- llama.cpp: `llama-server` (or `llama`) on the `PATH` — `brew install llama.cpp` on macOS. Nothing to start: mm starts it, and downloads the model the first time (~1.2 GB). | ||
| 19 | +- `curl` (used by `start.sh` to wait for the agents). | ||
| 20 | +- If a llama-server already answers on 9931 (the Llama app, or your own), the agents use it instead, and mm never stops it. | ||
| 21 | + | ||
| 22 | +## Run | ||
| 23 | + | ||
| 24 | +```bash | ||
| 25 | +cd demos/a2a-discussion | ||
| 26 | +./start.sh # the three agents, in the background (logs: alice.log, bob.log, moderator.log) | ||
| 27 | +``` | ||
| 28 | + | ||
| 29 | +```text | ||
| 30 | +started alice (pid 12345, log alice.log) | ||
| 31 | +started bob (pid 12346, log bob.log) | ||
| 32 | +started moderator (pid 12347, log moderator.log) | ||
| 33 | +waiting for alice on http://127.0.0.1:9101 .................. ready | ||
| 34 | +waiting for bob on http://127.0.0.1:9102 ready | ||
| 35 | +waiting for moderator on http://127.0.0.1:9103 ready | ||
| 36 | +``` | ||
| 37 | + | ||
| 38 | +**1. A debate relayed by a script.** `discussion.sh` sends the topic to Alice, her answer to Bob, his answer back to Alice… for N rounds, then the transcript to the moderator: | ||
| 39 | + | ||
| 40 | +```bash | ||
| 41 | +./discussion.sh "Remote work should be the default for software teams" 2 | ||
| 42 | +``` | ||
| 43 | + | ||
| 44 | +Each call is one `mm a2a-send` (see below); each agent keeps its side of the conversation through the A2A `contextId`. | ||
| 45 | + | ||
| 46 | +**2. A debate run by the moderator itself.** The moderator's file declares Alice and Bob under `a2a.agents`: its model calls them with the `ask_a2a_agent` tool, one at a time, then concludes. | ||
| 47 | + | ||
| 48 | +```bash | ||
| 49 | +../../mm moderator.yaml -p "Run a debate on: Should cities ban cars from their centre?" | ||
| 50 | +``` | ||
| 51 | + | ||
| 52 | +**3. Talk to one agent yourself.** | ||
| 53 | + | ||
| 54 | +```bash | ||
| 55 | +../../mm a2a-send http://127.0.0.1:9101 "Why should we plant more trees in cities?" | ||
| 56 | +# context: 5a24d958… ← on stderr: pass it back to continue | ||
| 57 | +../../mm a2a-send --context 5a24d958… http://127.0.0.1:9101 "And the cost?" | ||
| 58 | +curl -s http://127.0.0.1:9101/.well-known/agent-card.json # Alice's Agent Card | ||
| 59 | +``` | ||
| 60 | + | ||
| 61 | +**Stop.** | ||
| 62 | + | ||
| 63 | +```bash | ||
| 64 | +./stop.sh | ||
| 65 | +``` | ||
| 66 | + | ||
| 67 | +To watch an agent think, start it in its own terminal instead of `start.sh`: `../../mm -a2a alice.yaml` prints each message received (`📨 …`) and streams its answers. | ||
| 68 | + | ||
| 69 | +## How it is built — and why | ||
| 70 | + | ||
| 71 | +- **One model, shared.** Each agent is its own mm process with its own prompt, but `llamacpp.autoStart` makes them share one llama-server; `unloadOnExit: false`, so the first agent to quit does not unload the model under the two others. | ||
| 72 | +- **Short turns.** `max_tokens: 400` and "at most 3 sentences" in the prompts keep a round readable. | ||
| 73 | +- **No `ask_user`.** Nobody answers questions on an A2A server. | ||
| 74 | +- **Two ways to run a debate.** The script needs nothing from the model but to answer; the moderator-led debate needs a model that calls tools — LFM3 1.7B does. | ||
| 75 | + | ||
| 76 | +## Measured results | ||
| 77 | + | ||
| 78 | +Measured on 2026-11-25 in a Docker sandbox (Linux arm64, CPU), llama.cpp build 12359, the model on a local llama-server. | ||
| 79 | + | ||
| 80 | +| Case | Result | Time | | ||
| 81 | +|---|---|---| | ||
| 82 | +| `start.sh` (model already downloaded) | three agents ready, **one** llama-server, three leases | 18 s | | ||
| 83 | +| `discussion.sh` "Remote work…" 2 rounds | Alice and Bob answer each other twice, the moderator summarises each side and names the strongest argument | 37 s | | ||
| 84 | +| Moderator-led debate, run 1 | 4 calls (alice, bob, alice, bob), conclusion | 72 s | | ||
| 85 | +| Moderator-led debate, run 2 | 8 calls alternating alice/bob, conclusion | 130 s | | ||
| 86 | +| `stop.sh` | Alice and Bob leave the server to the others, the moderator — last — stops it | — | | ||
| 87 | +| Python `a2a-sdk` 1.3.1 client → Alice | card read (A2A 1.0 and 0.3 interfaces), `TASK_STATE_COMPLETED`, conversation continued by `contextId` | — | | ||
| 88 | + | ||
| 89 | +What a 1.7B model does in a debate: | ||
| 90 | + | ||
| 91 | +- **It invents its evidence**: "GitHub's 2023 report shows a 30% increase", Spotify, Netflix, Portland, Bogotá — figures and cases nobody checked. A demo of agents talking, not a source of facts. | ||
| 92 | +- **It does not always keep to 3 sentences**, and in its first turn Alice once answered "Bob's point" before Bob had spoken. | ||
| 93 | +- Before a fix found by this demo, the moderator's first debate stopped at its sixth call: the generation's watchdog counted the wait for Bob's answer as a silence. `ask_a2a_agent` now keeps it informed while it waits. | ||
added
demos/a2a-discussion/README.fr.md +93 -0 | new file mode 100644 | ||
| @@ -0,0 +1,93 @@ | ||
| 1 | +# a2a-discussion — trois agents mm qui débattent par A2A | |
| 2 | + | |
| 3 | +*[English version](README.en.md)* | |
| 4 | + | |
| 5 | +Trois agents, chacun servi par `mm a2a` sur son propre port, se parlent par le protocole Agent2Agent (A2A, ticket 243) : | |
| 6 | + | |
| 7 | +| Agent | Fichier | Adresse | Rôle | | |
| 8 | +|---|---|---|---| | |
| 9 | +| Alice | `alice.yaml` | `http://127.0.0.1:9101` | défend l'idée (**pour**) | | |
| 10 | +| Bob | `bob.yaml` | `http://127.0.0.1:9102` | s'y oppose (**contre**) | | |
| 11 | +| Modérateur | `moderator.yaml` | `http://127.0.0.1:9103` | mène le débat (`ask_a2a_agent`) ou conclut une transcription | | |
| 12 | + | |
| 13 | +Les trois utilisent le même petit modèle, `LiquidAI/LFM3-1.7B-GGUF:Q4_K_M`, sur **un seul** llama-server que mm démarre (`llamacpp.autoStart`) : le modèle est une seule fois en mémoire, environ 1,2 Go — une machine de 32 Go a de la marge. Le dernier agent arrêté arrête le serveur. | |
| 14 | + | |
| 15 | +## Prérequis | |
| 16 | + | |
| 17 | +- `mm` compilé à la racine du dépôt (`go build -o mm .`). | |
| 18 | +- llama.cpp : `llama-server` (ou `llama`) dans le `PATH` — `brew install llama.cpp` sous macOS. Rien à lancer : mm le démarre, et télécharge le modèle la première fois (~1,2 Go). | |
| 19 | +- `curl` (utilisé par `start.sh` pour attendre les agents). | |
| 20 | +- Si un llama-server répond déjà sur 9931 (l'application Llama, ou le vôtre), les agents l'utilisent, et mm ne l'arrête jamais. | |
| 21 | + | |
| 22 | +## Lancer | |
| 23 | + | |
| 24 | +```bash | |
| 25 | +cd demos/a2a-discussion | |
| 26 | +./start.sh # les trois agents, en arrière-plan (logs : alice.log, bob.log, moderator.log) | |
| 27 | +``` | |
| 28 | + | |
| 29 | +```text | |
| 30 | +started alice (pid 12345, log alice.log) | |
| 31 | +started bob (pid 12346, log bob.log) | |
| 32 | +started moderator (pid 12347, log moderator.log) | |
| 33 | +waiting for alice on http://127.0.0.1:9101 .................. ready | |
| 34 | +waiting for bob on http://127.0.0.1:9102 ready | |
| 35 | +waiting for moderator on http://127.0.0.1:9103 ready | |
| 36 | +``` | |
| 37 | + | |
| 38 | +**1. Un débat relayé par un script.** `discussion.sh` envoie le sujet à Alice, sa réponse à Bob, la réponse de Bob à Alice… pendant N tours, puis la transcription au modérateur : | |
| 39 | + | |
| 40 | +```bash | |
| 41 | +./discussion.sh "Remote work should be the default for software teams" 2 | |
| 42 | +``` | |
| 43 | + | |
| 44 | +Chaque appel est un `mm a2a-send` (voir plus bas) ; chaque agent garde sa part de la conversation grâce au `contextId` A2A. | |
| 45 | + | |
| 46 | +**2. Un débat mené par le modérateur lui-même.** Le fichier du modérateur déclare Alice et Bob sous `a2a.agents` : son modèle les appelle avec l'outil `ask_a2a_agent`, l'un après l'autre, puis conclut. | |
| 47 | + | |
| 48 | +```bash | |
| 49 | +../../mm moderator.yaml -p "Run a debate on: Should cities ban cars from their centre?" | |
| 50 | +``` | |
| 51 | + | |
| 52 | +**3. Parler vous-même à un agent.** | |
| 53 | + | |
| 54 | +```bash | |
| 55 | +../../mm a2a-send http://127.0.0.1:9101 "Why should we plant more trees in cities?" | |
| 56 | +# context: 5a24d958… ← sur stderr : à repasser pour continuer | |
| 57 | +../../mm a2a-send --context 5a24d958… http://127.0.0.1:9101 "And the cost?" | |
| 58 | +curl -s http://127.0.0.1:9101/.well-known/agent-card.json # l'Agent Card d'Alice | |
| 59 | +``` | |
| 60 | + | |
| 61 | +**Arrêter.** | |
| 62 | + | |
| 63 | +```bash | |
| 64 | +./stop.sh | |
| 65 | +``` | |
| 66 | + | |
| 67 | +Pour voir un agent travailler, lancez-le dans son propre terminal plutôt qu'avec `start.sh` : `../../mm -a2a alice.yaml` affiche chaque message reçu (`📨 …`) et ses réponses au fil de leur génération. | |
| 68 | + | |
| 69 | +## Comment c'est construit — et pourquoi | |
| 70 | + | |
| 71 | +- **Un modèle, partagé.** Chaque agent est un processus mm avec son propre prompt, mais `llamacpp.autoStart` leur fait partager un seul llama-server ; `unloadOnExit: false`, pour que le premier agent qui quitte ne décharge pas le modèle sous les deux autres. | |
| 72 | +- **Des tours courts.** `max_tokens: 400` et « at most 3 sentences » dans les prompts gardent un tour lisible. | |
| 73 | +- **Pas d'`ask_user`.** Personne ne répond aux questions sur un serveur A2A. | |
| 74 | +- **Deux façons de mener un débat.** Le script ne demande au modèle que de répondre ; le débat mené par le modérateur demande un modèle qui appelle des outils — LFM3 1.7B le fait. | |
| 75 | + | |
| 76 | +## Résultats mesurés | |
| 77 | + | |
| 78 | +Mesurés le 25/11/2026 dans un Docker Sandbox (Linux arm64, CPU), llama.cpp build 12359, le modèle sur un llama-server local. | |
| 79 | + | |
| 80 | +| Cas | Résultat | Durée | | |
| 81 | +|---|---|---| | |
| 82 | +| `start.sh` (modèle déjà téléchargé) | trois agents prêts, **un** llama-server, trois baux | 18 s | | |
| 83 | +| `discussion.sh` « Remote work… » 2 tours | Alice et Bob se répondent deux fois, le modérateur résume chaque camp et désigne l'argument le plus fort | 37 s | | |
| 84 | +| Débat mené par le modérateur, essai 1 | 4 appels (alice, bob, alice, bob), conclusion | 72 s | | |
| 85 | +| Débat mené par le modérateur, essai 2 | 8 appels en alternance alice/bob, conclusion | 130 s | | |
| 86 | +| `stop.sh` | Alice et Bob laissent le serveur aux autres, le modérateur — dernier — l'arrête | — | | |
| 87 | +| Client Python `a2a-sdk` 1.3.1 → Alice | carte lue (interfaces A2A 1.0 et 0.3), `TASK_STATE_COMPLETED`, conversation continuée par `contextId` | — | | |
| 88 | + | |
| 89 | +Ce que fait un modèle de 1,7B dans un débat : | |
| 90 | + | |
| 91 | +- **Il invente ses preuves** : « GitHub's 2023 report shows a 30% increase », Spotify, Netflix, Portland, Bogotá — des chiffres et des cas que personne n'a vérifiés. Une démo d'agents qui se parlent, pas une source de faits. | |
| 92 | +- **Il ne s'en tient pas toujours à 3 phrases**, et à son premier tour Alice a une fois répondu au « point de Bob » avant que Bob ait parlé. | |
| 93 | +- Avant un correctif trouvé grâce à cette démo, le premier débat du modérateur s'arrêtait à son sixième appel : le watchdog de la génération comptait l'attente de la réponse de Bob comme un silence. `ask_a2a_agent` le tient désormais informé pendant qu'il attend. | |
| new file mode 100644 | |||
| @@ -0,0 +1,93 @@ | |||
| 1 | +# a2a-discussion — trois agents mm qui débattent par A2A | ||
| 2 | + | ||
| 3 | +*[English version](README.en.md)* | ||
| 4 | + | ||
| 5 | +Trois agents, chacun servi par `mm a2a` sur son propre port, se parlent par le protocole Agent2Agent (A2A, ticket 243) : | ||
| 6 | + | ||
| 7 | +| Agent | Fichier | Adresse | Rôle | | ||
| 8 | +|---|---|---|---| | ||
| 9 | +| Alice | `alice.yaml` | `http://127.0.0.1:9101` | défend l'idée (**pour**) | | ||
| 10 | +| Bob | `bob.yaml` | `http://127.0.0.1:9102` | s'y oppose (**contre**) | | ||
| 11 | +| Modérateur | `moderator.yaml` | `http://127.0.0.1:9103` | mène le débat (`ask_a2a_agent`) ou conclut une transcription | | ||
| 12 | + | ||
| 13 | +Les trois utilisent le même petit modèle, `LiquidAI/LFM3-1.7B-GGUF:Q4_K_M`, sur **un seul** llama-server que mm démarre (`llamacpp.autoStart`) : le modèle est une seule fois en mémoire, environ 1,2 Go — une machine de 32 Go a de la marge. Le dernier agent arrêté arrête le serveur. | ||
| 14 | + | ||
| 15 | +## Prérequis | ||
| 16 | + | ||
| 17 | +- `mm` compilé à la racine du dépôt (`go build -o mm .`). | ||
| 18 | +- llama.cpp : `llama-server` (ou `llama`) dans le `PATH` — `brew install llama.cpp` sous macOS. Rien à lancer : mm le démarre, et télécharge le modèle la première fois (~1,2 Go). | ||
| 19 | +- `curl` (utilisé par `start.sh` pour attendre les agents). | ||
| 20 | +- Si un llama-server répond déjà sur 9931 (l'application Llama, ou le vôtre), les agents l'utilisent, et mm ne l'arrête jamais. | ||
| 21 | + | ||
| 22 | +## Lancer | ||
| 23 | + | ||
| 24 | +```bash | ||
| 25 | +cd demos/a2a-discussion | ||
| 26 | +./start.sh # les trois agents, en arrière-plan (logs : alice.log, bob.log, moderator.log) | ||
| 27 | +``` | ||
| 28 | + | ||
| 29 | +```text | ||
| 30 | +started alice (pid 12345, log alice.log) | ||
| 31 | +started bob (pid 12346, log bob.log) | ||
| 32 | +started moderator (pid 12347, log moderator.log) | ||
| 33 | +waiting for alice on http://127.0.0.1:9101 .................. ready | ||
| 34 | +waiting for bob on http://127.0.0.1:9102 ready | ||
| 35 | +waiting for moderator on http://127.0.0.1:9103 ready | ||
| 36 | +``` | ||
| 37 | + | ||
| 38 | +**1. Un débat relayé par un script.** `discussion.sh` envoie le sujet à Alice, sa réponse à Bob, la réponse de Bob à Alice… pendant N tours, puis la transcription au modérateur : | ||
| 39 | + | ||
| 40 | +```bash | ||
| 41 | +./discussion.sh "Remote work should be the default for software teams" 2 | ||
| 42 | +``` | ||
| 43 | + | ||
| 44 | +Chaque appel est un `mm a2a-send` (voir plus bas) ; chaque agent garde sa part de la conversation grâce au `contextId` A2A. | ||
| 45 | + | ||
| 46 | +**2. Un débat mené par le modérateur lui-même.** Le fichier du modérateur déclare Alice et Bob sous `a2a.agents` : son modèle les appelle avec l'outil `ask_a2a_agent`, l'un après l'autre, puis conclut. | ||
| 47 | + | ||
| 48 | +```bash | ||
| 49 | +../../mm moderator.yaml -p "Run a debate on: Should cities ban cars from their centre?" | ||
| 50 | +``` | ||
| 51 | + | ||
| 52 | +**3. Parler vous-même à un agent.** | ||
| 53 | + | ||
| 54 | +```bash | ||
| 55 | +../../mm a2a-send http://127.0.0.1:9101 "Why should we plant more trees in cities?" | ||
| 56 | +# context: 5a24d958… ← sur stderr : à repasser pour continuer | ||
| 57 | +../../mm a2a-send --context 5a24d958… http://127.0.0.1:9101 "And the cost?" | ||
| 58 | +curl -s http://127.0.0.1:9101/.well-known/agent-card.json # l'Agent Card d'Alice | ||
| 59 | +``` | ||
| 60 | + | ||
| 61 | +**Arrêter.** | ||
| 62 | + | ||
| 63 | +```bash | ||
| 64 | +./stop.sh | ||
| 65 | +``` | ||
| 66 | + | ||
| 67 | +Pour voir un agent travailler, lancez-le dans son propre terminal plutôt qu'avec `start.sh` : `../../mm -a2a alice.yaml` affiche chaque message reçu (`📨 …`) et ses réponses au fil de leur génération. | ||
| 68 | + | ||
| 69 | +## Comment c'est construit — et pourquoi | ||
| 70 | + | ||
| 71 | +- **Un modèle, partagé.** Chaque agent est un processus mm avec son propre prompt, mais `llamacpp.autoStart` leur fait partager un seul llama-server ; `unloadOnExit: false`, pour que le premier agent qui quitte ne décharge pas le modèle sous les deux autres. | ||
| 72 | +- **Des tours courts.** `max_tokens: 400` et « at most 3 sentences » dans les prompts gardent un tour lisible. | ||
| 73 | +- **Pas d'`ask_user`.** Personne ne répond aux questions sur un serveur A2A. | ||
| 74 | +- **Deux façons de mener un débat.** Le script ne demande au modèle que de répondre ; le débat mené par le modérateur demande un modèle qui appelle des outils — LFM3 1.7B le fait. | ||
| 75 | + | ||
| 76 | +## Résultats mesurés | ||
| 77 | + | ||
| 78 | +Mesurés le 25/11/2026 dans un Docker Sandbox (Linux arm64, CPU), llama.cpp build 12359, le modèle sur un llama-server local. | ||
| 79 | + | ||
| 80 | +| Cas | Résultat | Durée | | ||
| 81 | +|---|---|---| | ||
| 82 | +| `start.sh` (modèle déjà téléchargé) | trois agents prêts, **un** llama-server, trois baux | 18 s | | ||
| 83 | +| `discussion.sh` « Remote work… » 2 tours | Alice et Bob se répondent deux fois, le modérateur résume chaque camp et désigne l'argument le plus fort | 37 s | | ||
| 84 | +| Débat mené par le modérateur, essai 1 | 4 appels (alice, bob, alice, bob), conclusion | 72 s | | ||
| 85 | +| Débat mené par le modérateur, essai 2 | 8 appels en alternance alice/bob, conclusion | 130 s | | ||
| 86 | +| `stop.sh` | Alice et Bob laissent le serveur aux autres, le modérateur — dernier — l'arrête | — | | ||
| 87 | +| Client Python `a2a-sdk` 1.3.1 → Alice | carte lue (interfaces A2A 1.0 et 0.3), `TASK_STATE_COMPLETED`, conversation continuée par `contextId` | — | | ||
| 88 | + | ||
| 89 | +Ce que fait un modèle de 1,7B dans un débat : | ||
| 90 | + | ||
| 91 | +- **Il invente ses preuves** : « GitHub's 2023 report shows a 30% increase », Spotify, Netflix, Portland, Bogotá — des chiffres et des cas que personne n'a vérifiés. Une démo d'agents qui se parlent, pas une source de faits. | ||
| 92 | +- **Il ne s'en tient pas toujours à 3 phrases**, et à son premier tour Alice a une fois répondu au « point de Bob » avant que Bob ait parlé. | ||
| 93 | +- Avant un correctif trouvé grâce à cette démo, le premier débat du modérateur s'arrêtait à son sixième appel : le watchdog de la génération comptait l'attente de la réponse de Bob comme un silence. `ask_a2a_agent` le tient désormais informé pendant qu'il attend. | ||
added
demos/a2a-discussion/alice.yaml +89 -0 | new file mode 100644 | ||
| @@ -0,0 +1,89 @@ | ||
| 1 | +# Alice — argues for — one of the three agents of demos/a2a-discussion (ticket 243). | |
| 2 | +# | |
| 3 | +# Written by `mm init --provider llamacpp --model LiquidAI/LFM3-1.7B-GGUF:Q4_K_M` | |
| 4 | +# (usage assistant), then tuned for a debate between agents over A2A: see | |
| 5 | +# README.en.md. Served to the other agents with: | |
| 6 | +# | |
| 7 | +# ../../mm -a2a alice.yaml # http://127.0.0.1:9101 | |
| 8 | +# | |
| 9 | +# The three agents use the same model: mm starts ONE llama-server and they | |
| 10 | +# share it (the model is in memory once, ~1.2 GB). | |
| 11 | + | |
| 12 | +provider: llamacpp | |
| 13 | +# The model. Chosen for it (family other): sampling (temperature, top_p, | |
| 14 | +# max_tokens) and sampling.chat_template_kwargs (enable_thinking). Change the | |
| 15 | +# model and redo them together — running mm init again is the quick way. | |
| 16 | +model: "LiquidAI/LFM3-1.7B-GGUF:Q4_K_M" | |
| 17 | +# No baseUrl: llamacpp's defaults apply. For the record: | |
| 18 | +# baseUrl: "http://127.0.0.1:9931/v1" | |
| 19 | +# (llamacpp also tries http://127.0.0.1:8080/v1 on this machine when baseUrl does not answer) | |
| 20 | +# fallback: "http://host.docker.internal:9931/v1" # tried when baseUrl does not answer | |
| 21 | +# Nothing answers at this address: mm starts llama-server (router mode, this | |
| 22 | +# model, downloaded on first use) and stops it with the last mm session using | |
| 23 | +# it. A server you started yourself is never stopped. false: start it yourself. | |
| 24 | +llamacpp: | |
| 25 | + autoStart: true | |
| 26 | + | |
| 27 | +# 0 = mm asks the server for the window it serves (the model's native window | |
| 28 | +# is 4096 tokens; the server may serve less) | |
| 29 | +contextWindow: 0 | |
| 30 | +# usage assistant's default: tools run without asking | |
| 31 | +yolo: true | |
| 32 | +# usage assistant | |
| 33 | +bashTool: false | |
| 34 | +editTools: false | |
| 35 | +planTool: false | |
| 36 | +# off: nobody answers questions on an A2A server | |
| 37 | +askUserTool: false | |
| 38 | +# false: the three agents share ONE model on ONE llama-server; the first to | |
| 39 | +# quit must not unload it under the two others. The server stops (and frees | |
| 40 | +# the memory) with the last of them. | |
| 41 | +unloadOnExit: false | |
| 42 | +skillsDir: no-skills | |
| 43 | +# usage assistant | |
| 44 | +maxTurns: 5 | |
| 45 | +# [guide] settings guide, row "Small model (≤ 8B), short tasks" | |
| 46 | +maxOutput: 8000 | |
| 47 | +firstTokenTimeout: 3m | |
| 48 | +watchdogTimeout: 20s | |
| 49 | + | |
| 50 | +sampling: | |
| 51 | + # [rule] family other: skills/create-agent rule when nothing is published: | |
| 52 | + # 0.7 / 0.9, 0.2 for a code agent without reasoning | |
| 53 | + temperature: 0.7 | |
| 54 | + top_p: 0.9 | |
| 55 | + # a turn of a debate: a few sentences | |
| 56 | + max_tokens: 400 | |
| 57 | + # one tool call per reply: small models run a check before the change it | |
| 58 | + # checks has landed otherwise | |
| 59 | + parallel_tool_calls: false | |
| 60 | + chat_template_kwargs: | |
| 61 | + # reasoning off: short, direct answers (read from the chat template) | |
| 62 | + enable_thinking: false | |
| 63 | + | |
| 64 | +context: | |
| 65 | + # compress the history before the window is full (settings guide, every row) | |
| 66 | + enabled: true | |
| 67 | + # mm's default: 75 % of the window the server serves, a quarter left for the | |
| 68 | + # next question and its tool outputs | |
| 69 | + threshold: 75 | |
| 70 | + | |
| 71 | +agentsMd: | |
| 72 | + enabled: false | |
| 73 | + | |
| 74 | +acp: | |
| 75 | + name: alice | |
| 76 | + title: "Alice — argues for" | |
| 77 | + | |
| 78 | +# The A2A agent this file is when served with `mm a2a`: where it listens, | |
| 79 | +# and what the other agents read about it (its Agent Card). | |
| 80 | +a2a: | |
| 81 | + port: 9101 | |
| 82 | + description: "Alice, an optimist: she argues FOR the idea under discussion." | |
| 83 | + | |
| 84 | +system: | | |
| 85 | + Your name is Alice. You take part in a debate with Bob, who argues | |
| 86 | + against. You argue FOR the idea under discussion: its benefits, its | |
| 87 | + chances, what it makes possible. Answer what Bob just said, with one | |
| 88 | + concrete example. At most 3 sentences, in the language of the message. | |
| 89 | + Never pretend to be Bob or the moderator. | |
| new file mode 100644 | |||
| @@ -0,0 +1,89 @@ | |||
| 1 | +# Alice — argues for — one of the three agents of demos/a2a-discussion (ticket 243). | ||
| 2 | +# | ||
| 3 | +# Written by `mm init --provider llamacpp --model LiquidAI/LFM3-1.7B-GGUF:Q4_K_M` | ||
| 4 | +# (usage assistant), then tuned for a debate between agents over A2A: see | ||
| 5 | +# README.en.md. Served to the other agents with: | ||
| 6 | +# | ||
| 7 | +# ../../mm -a2a alice.yaml # http://127.0.0.1:9101 | ||
| 8 | +# | ||
| 9 | +# The three agents use the same model: mm starts ONE llama-server and they | ||
| 10 | +# share it (the model is in memory once, ~1.2 GB). | ||
| 11 | + | ||
| 12 | +provider: llamacpp | ||
| 13 | +# The model. Chosen for it (family other): sampling (temperature, top_p, | ||
| 14 | +# max_tokens) and sampling.chat_template_kwargs (enable_thinking). Change the | ||
| 15 | +# model and redo them together — running mm init again is the quick way. | ||
| 16 | +model: "LiquidAI/LFM3-1.7B-GGUF:Q4_K_M" | ||
| 17 | +# No baseUrl: llamacpp's defaults apply. For the record: | ||
| 18 | +# baseUrl: "http://127.0.0.1:9931/v1" | ||
| 19 | +# (llamacpp also tries http://127.0.0.1:8080/v1 on this machine when baseUrl does not answer) | ||
| 20 | +# fallback: "http://host.docker.internal:9931/v1" # tried when baseUrl does not answer | ||
| 21 | +# Nothing answers at this address: mm starts llama-server (router mode, this | ||
| 22 | +# model, downloaded on first use) and stops it with the last mm session using | ||
| 23 | +# it. A server you started yourself is never stopped. false: start it yourself. | ||
| 24 | +llamacpp: | ||
| 25 | + autoStart: true | ||
| 26 | + | ||
| 27 | +# 0 = mm asks the server for the window it serves (the model's native window | ||
| 28 | +# is 4096 tokens; the server may serve less) | ||
| 29 | +contextWindow: 0 | ||
| 30 | +# usage assistant's default: tools run without asking | ||
| 31 | +yolo: true | ||
| 32 | +# usage assistant | ||
| 33 | +bashTool: false | ||
| 34 | +editTools: false | ||
| 35 | +planTool: false | ||
| 36 | +# off: nobody answers questions on an A2A server | ||
| 37 | +askUserTool: false | ||
| 38 | +# false: the three agents share ONE model on ONE llama-server; the first to | ||
| 39 | +# quit must not unload it under the two others. The server stops (and frees | ||
| 40 | +# the memory) with the last of them. | ||
| 41 | +unloadOnExit: false | ||
| 42 | +skillsDir: no-skills | ||
| 43 | +# usage assistant | ||
| 44 | +maxTurns: 5 | ||
| 45 | +# [guide] settings guide, row "Small model (≤ 8B), short tasks" | ||
| 46 | +maxOutput: 8000 | ||
| 47 | +firstTokenTimeout: 3m | ||
| 48 | +watchdogTimeout: 20s | ||
| 49 | + | ||
| 50 | +sampling: | ||
| 51 | + # [rule] family other: skills/create-agent rule when nothing is published: | ||
| 52 | + # 0.7 / 0.9, 0.2 for a code agent without reasoning | ||
| 53 | + temperature: 0.7 | ||
| 54 | + top_p: 0.9 | ||
| 55 | + # a turn of a debate: a few sentences | ||
| 56 | + max_tokens: 400 | ||
| 57 | + # one tool call per reply: small models run a check before the change it | ||
| 58 | + # checks has landed otherwise | ||
| 59 | + parallel_tool_calls: false | ||
| 60 | + chat_template_kwargs: | ||
| 61 | + # reasoning off: short, direct answers (read from the chat template) | ||
| 62 | + enable_thinking: false | ||
| 63 | + | ||
| 64 | +context: | ||
| 65 | + # compress the history before the window is full (settings guide, every row) | ||
| 66 | + enabled: true | ||
| 67 | + # mm's default: 75 % of the window the server serves, a quarter left for the | ||
| 68 | + # next question and its tool outputs | ||
| 69 | + threshold: 75 | ||
| 70 | + | ||
| 71 | +agentsMd: | ||
| 72 | + enabled: false | ||
| 73 | + | ||
| 74 | +acp: | ||
| 75 | + name: alice | ||
| 76 | + title: "Alice — argues for" | ||
| 77 | + | ||
| 78 | +# The A2A agent this file is when served with `mm a2a`: where it listens, | ||
| 79 | +# and what the other agents read about it (its Agent Card). | ||
| 80 | +a2a: | ||
| 81 | + port: 9101 | ||
| 82 | + description: "Alice, an optimist: she argues FOR the idea under discussion." | ||
| 83 | + | ||
| 84 | +system: | | ||
| 85 | + Your name is Alice. You take part in a debate with Bob, who argues | ||
| 86 | + against. You argue FOR the idea under discussion: its benefits, its | ||
| 87 | + chances, what it makes possible. Answer what Bob just said, with one | ||
| 88 | + concrete example. At most 3 sentences, in the language of the message. | ||
| 89 | + Never pretend to be Bob or the moderator. | ||
added
demos/a2a-discussion/bob.yaml +89 -0 | new file mode 100644 | ||
| @@ -0,0 +1,89 @@ | ||
| 1 | +# Bob — argues against — one of the three agents of demos/a2a-discussion (ticket 243). | |
| 2 | +# | |
| 3 | +# Written by `mm init --provider llamacpp --model LiquidAI/LFM3-1.7B-GGUF:Q4_K_M` | |
| 4 | +# (usage assistant), then tuned for a debate between agents over A2A: see | |
| 5 | +# README.en.md. Served to the other agents with: | |
| 6 | +# | |
| 7 | +# ../../mm -a2a bob.yaml # http://127.0.0.1:9102 | |
| 8 | +# | |
| 9 | +# The three agents use the same model: mm starts ONE llama-server and they | |
| 10 | +# share it (the model is in memory once, ~1.2 GB). | |
| 11 | + | |
| 12 | +provider: llamacpp | |
| 13 | +# The model. Chosen for it (family other): sampling (temperature, top_p, | |
| 14 | +# max_tokens) and sampling.chat_template_kwargs (enable_thinking). Change the | |
| 15 | +# model and redo them together — running mm init again is the quick way. | |
| 16 | +model: "LiquidAI/LFM3-1.7B-GGUF:Q4_K_M" | |
| 17 | +# No baseUrl: llamacpp's defaults apply. For the record: | |
| 18 | +# baseUrl: "http://127.0.0.1:9931/v1" | |
| 19 | +# (llamacpp also tries http://127.0.0.1:8080/v1 on this machine when baseUrl does not answer) | |
| 20 | +# fallback: "http://host.docker.internal:9931/v1" # tried when baseUrl does not answer | |
| 21 | +# Nothing answers at this address: mm starts llama-server (router mode, this | |
| 22 | +# model, downloaded on first use) and stops it with the last mm session using | |
| 23 | +# it. A server you started yourself is never stopped. false: start it yourself. | |
| 24 | +llamacpp: | |
| 25 | + autoStart: true | |
| 26 | + | |
| 27 | +# 0 = mm asks the server for the window it serves (the model's native window | |
| 28 | +# is 4096 tokens; the server may serve less) | |
| 29 | +contextWindow: 0 | |
| 30 | +# usage assistant's default: tools run without asking | |
| 31 | +yolo: true | |
| 32 | +# usage assistant | |
| 33 | +bashTool: false | |
| 34 | +editTools: false | |
| 35 | +planTool: false | |
| 36 | +# off: nobody answers questions on an A2A server | |
| 37 | +askUserTool: false | |
| 38 | +# false: the three agents share ONE model on ONE llama-server; the first to | |
| 39 | +# quit must not unload it under the two others. The server stops (and frees | |
| 40 | +# the memory) with the last of them. | |
| 41 | +unloadOnExit: false | |
| 42 | +skillsDir: no-skills | |
| 43 | +# usage assistant | |
| 44 | +maxTurns: 5 | |
| 45 | +# [guide] settings guide, row "Small model (≤ 8B), short tasks" | |
| 46 | +maxOutput: 8000 | |
| 47 | +firstTokenTimeout: 3m | |
| 48 | +watchdogTimeout: 20s | |
| 49 | + | |
| 50 | +sampling: | |
| 51 | + # [rule] family other: skills/create-agent rule when nothing is published: | |
| 52 | + # 0.7 / 0.9, 0.2 for a code agent without reasoning | |
| 53 | + temperature: 0.7 | |
| 54 | + top_p: 0.9 | |
| 55 | + # a turn of a debate: a few sentences | |
| 56 | + max_tokens: 400 | |
| 57 | + # one tool call per reply: small models run a check before the change it | |
| 58 | + # checks has landed otherwise | |
| 59 | + parallel_tool_calls: false | |
| 60 | + chat_template_kwargs: | |
| 61 | + # reasoning off: short, direct answers (read from the chat template) | |
| 62 | + enable_thinking: false | |
| 63 | + | |
| 64 | +context: | |
| 65 | + # compress the history before the window is full (settings guide, every row) | |
| 66 | + enabled: true | |
| 67 | + # mm's default: 75 % of the window the server serves, a quarter left for the | |
| 68 | + # next question and its tool outputs | |
| 69 | + threshold: 75 | |
| 70 | + | |
| 71 | +agentsMd: | |
| 72 | + enabled: false | |
| 73 | + | |
| 74 | +acp: | |
| 75 | + name: bob | |
| 76 | + title: "Bob — argues against" | |
| 77 | + | |
| 78 | +# The A2A agent this file is when served with `mm a2a`: where it listens, | |
| 79 | +# and what the other agents read about it (its Agent Card). | |
| 80 | +a2a: | |
| 81 | + port: 9102 | |
| 82 | + description: "Bob, a sceptic: he argues AGAINST the idea under discussion." | |
| 83 | + | |
| 84 | +system: | | |
| 85 | + Your name is Bob. You take part in a debate with Alice, who argues for. | |
| 86 | + You argue AGAINST the idea under discussion: its costs, its risks, what | |
| 87 | + could go wrong. Answer what Alice just said, with one concrete example. At | |
| 88 | + most 3 sentences, in the language of the message. Never pretend to be | |
| 89 | + Alice or the moderator. | |
| new file mode 100644 | |||
| @@ -0,0 +1,89 @@ | |||
| 1 | +# Bob — argues against — one of the three agents of demos/a2a-discussion (ticket 243). | ||
| 2 | +# | ||
| 3 | +# Written by `mm init --provider llamacpp --model LiquidAI/LFM3-1.7B-GGUF:Q4_K_M` | ||
| 4 | +# (usage assistant), then tuned for a debate between agents over A2A: see | ||
| 5 | +# README.en.md. Served to the other agents with: | ||
| 6 | +# | ||
| 7 | +# ../../mm -a2a bob.yaml # http://127.0.0.1:9102 | ||
| 8 | +# | ||
| 9 | +# The three agents use the same model: mm starts ONE llama-server and they | ||
| 10 | +# share it (the model is in memory once, ~1.2 GB). | ||
| 11 | + | ||
| 12 | +provider: llamacpp | ||
| 13 | +# The model. Chosen for it (family other): sampling (temperature, top_p, | ||
| 14 | +# max_tokens) and sampling.chat_template_kwargs (enable_thinking). Change the | ||
| 15 | +# model and redo them together — running mm init again is the quick way. | ||
| 16 | +model: "LiquidAI/LFM3-1.7B-GGUF:Q4_K_M" | ||
| 17 | +# No baseUrl: llamacpp's defaults apply. For the record: | ||
| 18 | +# baseUrl: "http://127.0.0.1:9931/v1" | ||
| 19 | +# (llamacpp also tries http://127.0.0.1:8080/v1 on this machine when baseUrl does not answer) | ||
| 20 | +# fallback: "http://host.docker.internal:9931/v1" # tried when baseUrl does not answer | ||
| 21 | +# Nothing answers at this address: mm starts llama-server (router mode, this | ||
| 22 | +# model, downloaded on first use) and stops it with the last mm session using | ||
| 23 | +# it. A server you started yourself is never stopped. false: start it yourself. | ||
| 24 | +llamacpp: | ||
| 25 | + autoStart: true | ||
| 26 | + | ||
| 27 | +# 0 = mm asks the server for the window it serves (the model's native window | ||
| 28 | +# is 4096 tokens; the server may serve less) | ||
| 29 | +contextWindow: 0 | ||
| 30 | +# usage assistant's default: tools run without asking | ||
| 31 | +yolo: true | ||
| 32 | +# usage assistant | ||
| 33 | +bashTool: false | ||
| 34 | +editTools: false | ||
| 35 | +planTool: false | ||
| 36 | +# off: nobody answers questions on an A2A server | ||
| 37 | +askUserTool: false | ||
| 38 | +# false: the three agents share ONE model on ONE llama-server; the first to | ||
| 39 | +# quit must not unload it under the two others. The server stops (and frees | ||
| 40 | +# the memory) with the last of them. | ||
| 41 | +unloadOnExit: false | ||
| 42 | +skillsDir: no-skills | ||
| 43 | +# usage assistant | ||
| 44 | +maxTurns: 5 | ||
| 45 | +# [guide] settings guide, row "Small model (≤ 8B), short tasks" | ||
| 46 | +maxOutput: 8000 | ||
| 47 | +firstTokenTimeout: 3m | ||
| 48 | +watchdogTimeout: 20s | ||
| 49 | + | ||
| 50 | +sampling: | ||
| 51 | + # [rule] family other: skills/create-agent rule when nothing is published: | ||
| 52 | + # 0.7 / 0.9, 0.2 for a code agent without reasoning | ||
| 53 | + temperature: 0.7 | ||
| 54 | + top_p: 0.9 | ||
| 55 | + # a turn of a debate: a few sentences | ||
| 56 | + max_tokens: 400 | ||
| 57 | + # one tool call per reply: small models run a check before the change it | ||
| 58 | + # checks has landed otherwise | ||
| 59 | + parallel_tool_calls: false | ||
| 60 | + chat_template_kwargs: | ||
| 61 | + # reasoning off: short, direct answers (read from the chat template) | ||
| 62 | + enable_thinking: false | ||
| 63 | + | ||
| 64 | +context: | ||
| 65 | + # compress the history before the window is full (settings guide, every row) | ||
| 66 | + enabled: true | ||
| 67 | + # mm's default: 75 % of the window the server serves, a quarter left for the | ||
| 68 | + # next question and its tool outputs | ||
| 69 | + threshold: 75 | ||
| 70 | + | ||
| 71 | +agentsMd: | ||
| 72 | + enabled: false | ||
| 73 | + | ||
| 74 | +acp: | ||
| 75 | + name: bob | ||
| 76 | + title: "Bob — argues against" | ||
| 77 | + | ||
| 78 | +# The A2A agent this file is when served with `mm a2a`: where it listens, | ||
| 79 | +# and what the other agents read about it (its Agent Card). | ||
| 80 | +a2a: | ||
| 81 | + port: 9102 | ||
| 82 | + description: "Bob, a sceptic: he argues AGAINST the idea under discussion." | ||
| 83 | + | ||
| 84 | +system: | | ||
| 85 | + Your name is Bob. You take part in a debate with Alice, who argues for. | ||
| 86 | + You argue AGAINST the idea under discussion: its costs, its risks, what | ||
| 87 | + could go wrong. Answer what Alice just said, with one concrete example. At | ||
| 88 | + most 3 sentences, in the language of the message. Never pretend to be | ||
| 89 | + Alice or the moderator. | ||
added
demos/a2a-discussion/discussion.sh +39 -0 | new file mode 100755 | ||
| @@ -0,0 +1,39 @@ | ||
| 1 | +#!/usr/bin/env bash | |
| 2 | +# A debate between Alice and Bob, relayed by this script over A2A, then the | |
| 3 | +# moderator's conclusion. The agents must be running (./start.sh). | |
| 4 | +# | |
| 5 | +# ./discussion.sh "Remote work should be the default" 2 | |
| 6 | +set -euo pipefail | |
| 7 | +cd "$(dirname "$0")" | |
| 8 | +MM=${MM:-../../mm} | |
| 9 | +TOPIC=${1:?usage: ./discussion.sh "topic" [rounds]} | |
| 10 | +ROUNDS=${2:-2} | |
| 11 | +ALICE=http://127.0.0.1:9101 BOB=http://127.0.0.1:9102 MODERATOR=http://127.0.0.1:9103 | |
| 12 | + | |
| 13 | +# send URL CONTEXT MESSAGE — sets ANSWER and CONTEXT (the conversation's id). | |
| 14 | +send() { | |
| 15 | + local err; err=$(mktemp) | |
| 16 | + if ! ANSWER=$("$MM" a2a-send ${2:+--context "$2"} "$1" "$3" 2>"$err"); then | |
| 17 | + cat "$err" >&2; rm -f "$err"; exit 1 | |
| 18 | + fi | |
| 19 | + CONTEXT=$(sed -n 's/^context: //p' "$err"); rm -f "$err" | |
| 20 | +} | |
| 21 | + | |
| 22 | +say() { printf '\n\033[1m%s\033[0m\n%s\n' "$1" "$2"; TRANSCRIPT+="$1: $2"$'\n'; } | |
| 23 | +TRANSCRIPT="" | |
| 24 | + | |
| 25 | +send "$ALICE" "" "The topic of the debate: $TOPIC. Give your opening argument." | |
| 26 | +A_CTX=$CONTEXT; say "Alice" "$ANSWER" | |
| 27 | +send "$BOB" "" "The topic of the debate: $TOPIC. Alice argued: \"$ANSWER\" Answer her." | |
| 28 | +B_CTX=$CONTEXT; say "Bob" "$ANSWER" | |
| 29 | +for ((round = 2; round <= ROUNDS; round++)); do | |
| 30 | + send "$ALICE" "$A_CTX" "Bob answered: \"$ANSWER\" Answer him." | |
| 31 | + say "Alice" "$ANSWER" | |
| 32 | + send "$BOB" "$B_CTX" "Alice answered: \"$ANSWER\" Answer her." | |
| 33 | + say "Bob" "$ANSWER" | |
| 34 | +done | |
| 35 | +send "$MODERATOR" "" "Here is the transcript of a debate on: $TOPIC. | |
| 36 | + | |
| 37 | +$TRANSCRIPT | |
| 38 | +Conclude it." | |
| 39 | +printf '\n\033[1mModerator\033[0m\n%s\n' "$ANSWER" | |
| new file mode 100755 | |||
| @@ -0,0 +1,39 @@ | |||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# A debate between Alice and Bob, relayed by this script over A2A, then the | ||
| 3 | +# moderator's conclusion. The agents must be running (./start.sh). | ||
| 4 | +# | ||
| 5 | +# ./discussion.sh "Remote work should be the default" 2 | ||
| 6 | +set -euo pipefail | ||
| 7 | +cd "$(dirname "$0")" | ||
| 8 | +MM=${MM:-../../mm} | ||
| 9 | +TOPIC=${1:?usage: ./discussion.sh "topic" [rounds]} | ||
| 10 | +ROUNDS=${2:-2} | ||
| 11 | +ALICE=http://127.0.0.1:9101 BOB=http://127.0.0.1:9102 MODERATOR=http://127.0.0.1:9103 | ||
| 12 | + | ||
| 13 | +# send URL CONTEXT MESSAGE — sets ANSWER and CONTEXT (the conversation's id). | ||
| 14 | +send() { | ||
| 15 | + local err; err=$(mktemp) | ||
| 16 | + if ! ANSWER=$("$MM" a2a-send ${2:+--context "$2"} "$1" "$3" 2>"$err"); then | ||
| 17 | + cat "$err" >&2; rm -f "$err"; exit 1 | ||
| 18 | + fi | ||
| 19 | + CONTEXT=$(sed -n 's/^context: //p' "$err"); rm -f "$err" | ||
| 20 | +} | ||
| 21 | + | ||
| 22 | +say() { printf '\n\033[1m%s\033[0m\n%s\n' "$1" "$2"; TRANSCRIPT+="$1: $2"$'\n'; } | ||
| 23 | +TRANSCRIPT="" | ||
| 24 | + | ||
| 25 | +send "$ALICE" "" "The topic of the debate: $TOPIC. Give your opening argument." | ||
| 26 | +A_CTX=$CONTEXT; say "Alice" "$ANSWER" | ||
| 27 | +send "$BOB" "" "The topic of the debate: $TOPIC. Alice argued: \"$ANSWER\" Answer her." | ||
| 28 | +B_CTX=$CONTEXT; say "Bob" "$ANSWER" | ||
| 29 | +for ((round = 2; round <= ROUNDS; round++)); do | ||
| 30 | + send "$ALICE" "$A_CTX" "Bob answered: \"$ANSWER\" Answer him." | ||
| 31 | + say "Alice" "$ANSWER" | ||
| 32 | + send "$BOB" "$B_CTX" "Alice answered: \"$ANSWER\" Answer her." | ||
| 33 | + say "Bob" "$ANSWER" | ||
| 34 | +done | ||
| 35 | +send "$MODERATOR" "" "Here is the transcript of a debate on: $TOPIC. | ||
| 36 | + | ||
| 37 | +$TRANSCRIPT | ||
| 38 | +Conclude it." | ||
| 39 | +printf '\n\033[1mModerator\033[0m\n%s\n' "$ANSWER" | ||
added
demos/a2a-discussion/moderator.yaml +103 -0 | new file mode 100644 | ||
| @@ -0,0 +1,103 @@ | ||
| 1 | +# Moderator — one of the three agents of demos/a2a-discussion (ticket 243). | |
| 2 | +# | |
| 3 | +# Written by `mm init --provider llamacpp --model LiquidAI/LFM3-1.7B-GGUF:Q4_K_M` | |
| 4 | +# (usage assistant), then tuned for a debate between agents over A2A: see | |
| 5 | +# README.en.md. Served to the other agents with: | |
| 6 | +# | |
| 7 | +# ../../mm -a2a moderator.yaml # http://127.0.0.1:9103 | |
| 8 | +# | |
| 9 | +# The three agents use the same model: mm starts ONE llama-server and they | |
| 10 | +# share it (the model is in memory once, ~1.2 GB). | |
| 11 | + | |
| 12 | +provider: llamacpp | |
| 13 | +# The model. Chosen for it (family other): sampling (temperature, top_p, | |
| 14 | +# max_tokens) and sampling.chat_template_kwargs (enable_thinking). Change the | |
| 15 | +# model and redo them together — running mm init again is the quick way. | |
| 16 | +model: "LiquidAI/LFM3-1.7B-GGUF:Q4_K_M" | |
| 17 | +# No baseUrl: llamacpp's defaults apply. For the record: | |
| 18 | +# baseUrl: "http://127.0.0.1:9931/v1" | |
| 19 | +# (llamacpp also tries http://127.0.0.1:8080/v1 on this machine when baseUrl does not answer) | |
| 20 | +# fallback: "http://host.docker.internal:9931/v1" # tried when baseUrl does not answer | |
| 21 | +# Nothing answers at this address: mm starts llama-server (router mode, this | |
| 22 | +# model, downloaded on first use) and stops it with the last mm session using | |
| 23 | +# it. A server you started yourself is never stopped. false: start it yourself. | |
| 24 | +llamacpp: | |
| 25 | + autoStart: true | |
| 26 | + | |
| 27 | +# 0 = mm asks the server for the window it serves (the model's native window | |
| 28 | +# is 4096 tokens; the server may serve less) | |
| 29 | +contextWindow: 0 | |
| 30 | +# usage assistant's default: tools run without asking | |
| 31 | +yolo: true | |
| 32 | +# usage assistant | |
| 33 | +bashTool: false | |
| 34 | +editTools: false | |
| 35 | +planTool: false | |
| 36 | +# off: nobody answers questions on an A2A server | |
| 37 | +askUserTool: false | |
| 38 | +# false: the three agents share ONE model on ONE llama-server; the first to | |
| 39 | +# quit must not unload it under the two others. The server stops (and frees | |
| 40 | +# the memory) with the last of them. | |
| 41 | +unloadOnExit: false | |
| 42 | +skillsDir: no-skills | |
| 43 | +# usage assistant | |
| 44 | +maxTurns: 12 | |
| 45 | +# [guide] settings guide, row "Small model (≤ 8B), short tasks" | |
| 46 | +maxOutput: 8000 | |
| 47 | +firstTokenTimeout: 3m | |
| 48 | +watchdogTimeout: 20s | |
| 49 | + | |
| 50 | +sampling: | |
| 51 | + # [rule] family other: skills/create-agent rule when nothing is published: | |
| 52 | + # 0.7 / 0.9, 0.2 for a code agent without reasoning | |
| 53 | + temperature: 0.7 | |
| 54 | + top_p: 0.9 | |
| 55 | + # a conclusion, or one tool call at a time | |
| 56 | + max_tokens: 600 | |
| 57 | + # one tool call per reply: small models run a check before the change it | |
| 58 | + # checks has landed otherwise | |
| 59 | + parallel_tool_calls: false | |
| 60 | + chat_template_kwargs: | |
| 61 | + # reasoning off: short, direct answers (read from the chat template) | |
| 62 | + enable_thinking: false | |
| 63 | + | |
| 64 | +context: | |
| 65 | + # compress the history before the window is full (settings guide, every row) | |
| 66 | + enabled: true | |
| 67 | + # mm's default: 75 % of the window the server serves, a quarter left for the | |
| 68 | + # next question and its tool outputs | |
| 69 | + threshold: 75 | |
| 70 | + | |
| 71 | +agentsMd: | |
| 72 | + enabled: false | |
| 73 | + | |
| 74 | +acp: | |
| 75 | + name: moderator | |
| 76 | + title: "Moderator" | |
| 77 | + | |
| 78 | +# The A2A agent this file is when served with `mm a2a`: where it listens, | |
| 79 | +# and what the other agents read about it (its Agent Card). | |
| 80 | +a2a: | |
| 81 | + port: 9103 | |
| 82 | + description: "The moderator: runs a debate between Alice and Bob, then concludes." | |
| 83 | + agents: | |
| 84 | + alice: | |
| 85 | + url: http://127.0.0.1:9101 | |
| 86 | + description: "Alice, an optimist who argues FOR the idea." | |
| 87 | + bob: | |
| 88 | + url: http://127.0.0.1:9102 | |
| 89 | + description: "Bob, a sceptic who argues AGAINST the idea." | |
| 90 | + | |
| 91 | +system: | | |
| 92 | + You are the moderator of a debate between Alice (for) and Bob (against). | |
| 93 | + When you are given a transcript, summarise each side in one sentence, | |
| 94 | + then say which argument was the strongest and why — 4 sentences in all. | |
| 95 | + | |
| 96 | + When you are asked to RUN a debate on a topic, use the ask_a2a_agent | |
| 97 | + tool, one call at a time: | |
| 98 | + 1. ask alice for her opening argument on the topic; | |
| 99 | + 2. send bob what Alice said, and ask him to answer her; | |
| 100 | + 3. send alice what Bob said, and ask her to answer him; | |
| 101 | + 4. send bob what Alice said, and ask for his last word. | |
| 102 | + Then write the conclusion as above. Never write Alice's or Bob's words | |
| 103 | + yourself: only what the tool returned. | |
| new file mode 100644 | |||
| @@ -0,0 +1,103 @@ | |||
| 1 | +# Moderator — one of the three agents of demos/a2a-discussion (ticket 243). | ||
| 2 | +# | ||
| 3 | +# Written by `mm init --provider llamacpp --model LiquidAI/LFM3-1.7B-GGUF:Q4_K_M` | ||
| 4 | +# (usage assistant), then tuned for a debate between agents over A2A: see | ||
| 5 | +# README.en.md. Served to the other agents with: | ||
| 6 | +# | ||
| 7 | +# ../../mm -a2a moderator.yaml # http://127.0.0.1:9103 | ||
| 8 | +# | ||
| 9 | +# The three agents use the same model: mm starts ONE llama-server and they | ||
| 10 | +# share it (the model is in memory once, ~1.2 GB). | ||
| 11 | + | ||
| 12 | +provider: llamacpp | ||
| 13 | +# The model. Chosen for it (family other): sampling (temperature, top_p, | ||
| 14 | +# max_tokens) and sampling.chat_template_kwargs (enable_thinking). Change the | ||
| 15 | +# model and redo them together — running mm init again is the quick way. | ||
| 16 | +model: "LiquidAI/LFM3-1.7B-GGUF:Q4_K_M" | ||
| 17 | +# No baseUrl: llamacpp's defaults apply. For the record: | ||
| 18 | +# baseUrl: "http://127.0.0.1:9931/v1" | ||
| 19 | +# (llamacpp also tries http://127.0.0.1:8080/v1 on this machine when baseUrl does not answer) | ||
| 20 | +# fallback: "http://host.docker.internal:9931/v1" # tried when baseUrl does not answer | ||
| 21 | +# Nothing answers at this address: mm starts llama-server (router mode, this | ||
| 22 | +# model, downloaded on first use) and stops it with the last mm session using | ||
| 23 | +# it. A server you started yourself is never stopped. false: start it yourself. | ||
| 24 | +llamacpp: | ||
| 25 | + autoStart: true | ||
| 26 | + | ||
| 27 | +# 0 = mm asks the server for the window it serves (the model's native window | ||
| 28 | +# is 4096 tokens; the server may serve less) | ||
| 29 | +contextWindow: 0 | ||
| 30 | +# usage assistant's default: tools run without asking | ||
| 31 | +yolo: true | ||
| 32 | +# usage assistant | ||
| 33 | +bashTool: false | ||
| 34 | +editTools: false | ||
| 35 | +planTool: false | ||
| 36 | +# off: nobody answers questions on an A2A server | ||
| 37 | +askUserTool: false | ||
| 38 | +# false: the three agents share ONE model on ONE llama-server; the first to | ||
| 39 | +# quit must not unload it under the two others. The server stops (and frees | ||
| 40 | +# the memory) with the last of them. | ||
| 41 | +unloadOnExit: false | ||
| 42 | +skillsDir: no-skills | ||
| 43 | +# usage assistant | ||
| 44 | +maxTurns: 12 | ||
| 45 | +# [guide] settings guide, row "Small model (≤ 8B), short tasks" | ||
| 46 | +maxOutput: 8000 | ||
| 47 | +firstTokenTimeout: 3m | ||
| 48 | +watchdogTimeout: 20s | ||
| 49 | + | ||
| 50 | +sampling: | ||
| 51 | + # [rule] family other: skills/create-agent rule when nothing is published: | ||
| 52 | + # 0.7 / 0.9, 0.2 for a code agent without reasoning | ||
| 53 | + temperature: 0.7 | ||
| 54 | + top_p: 0.9 | ||
| 55 | + # a conclusion, or one tool call at a time | ||
| 56 | + max_tokens: 600 | ||
| 57 | + # one tool call per reply: small models run a check before the change it | ||
| 58 | + # checks has landed otherwise | ||
| 59 | + parallel_tool_calls: false | ||
| 60 | + chat_template_kwargs: | ||
| 61 | + # reasoning off: short, direct answers (read from the chat template) | ||
| 62 | + enable_thinking: false | ||
| 63 | + | ||
| 64 | +context: | ||
| 65 | + # compress the history before the window is full (settings guide, every row) | ||
| 66 | + enabled: true | ||
| 67 | + # mm's default: 75 % of the window the server serves, a quarter left for the | ||
| 68 | + # next question and its tool outputs | ||
| 69 | + threshold: 75 | ||
| 70 | + | ||
| 71 | +agentsMd: | ||
| 72 | + enabled: false | ||
| 73 | + | ||
| 74 | +acp: | ||
| 75 | + name: moderator | ||
| 76 | + title: "Moderator" | ||
| 77 | + | ||
| 78 | +# The A2A agent this file is when served with `mm a2a`: where it listens, | ||
| 79 | +# and what the other agents read about it (its Agent Card). | ||
| 80 | +a2a: | ||
| 81 | + port: 9103 | ||
| 82 | + description: "The moderator: runs a debate between Alice and Bob, then concludes." | ||
| 83 | + agents: | ||
| 84 | + alice: | ||
| 85 | + url: http://127.0.0.1:9101 | ||
| 86 | + description: "Alice, an optimist who argues FOR the idea." | ||
| 87 | + bob: | ||
| 88 | + url: http://127.0.0.1:9102 | ||
| 89 | + description: "Bob, a sceptic who argues AGAINST the idea." | ||
| 90 | + | ||
| 91 | +system: | | ||
| 92 | + You are the moderator of a debate between Alice (for) and Bob (against). | ||
| 93 | + When you are given a transcript, summarise each side in one sentence, | ||
| 94 | + then say which argument was the strongest and why — 4 sentences in all. | ||
| 95 | + | ||
| 96 | + When you are asked to RUN a debate on a topic, use the ask_a2a_agent | ||
| 97 | + tool, one call at a time: | ||
| 98 | + 1. ask alice for her opening argument on the topic; | ||
| 99 | + 2. send bob what Alice said, and ask him to answer her; | ||
| 100 | + 3. send alice what Bob said, and ask her to answer him; | ||
| 101 | + 4. send bob what Alice said, and ask for his last word. | ||
| 102 | + Then write the conclusion as above. Never write Alice's or Bob's words | ||
| 103 | + yourself: only what the tool returned. | ||
added
demos/a2a-discussion/start.sh +26 -0 | new file mode 100755 | ||
| @@ -0,0 +1,26 @@ | ||
| 1 | +#!/usr/bin/env bash | |
| 2 | +# Start the three agents as A2A servers, in the background, one log each. | |
| 3 | +# mm starts llama-server for the first one (and downloads the model the first | |
| 4 | +# time); the two others share it. Stop them with ./stop.sh. | |
| 5 | +set -euo pipefail | |
| 6 | +cd "$(dirname "$0")" | |
| 7 | +MM=${MM:-../../mm} | |
| 8 | +for agent in alice bob moderator; do | |
| 9 | + "$MM" -a2a "$agent.yaml" > "$agent.log" 2>&1 & | |
| 10 | + echo $! > "$agent.pid" | |
| 11 | + echo "started $agent (pid $!, log $agent.log)" | |
| 12 | +done | |
| 13 | +# The first start downloads the model (~1.2 GB): up to 15 minutes. | |
| 14 | +for agent in alice:9101 bob:9102 moderator:9103; do | |
| 15 | + name=${agent%:*} port=${agent#*:} | |
| 16 | + printf "waiting for %s on http://127.0.0.1:%s " "$name" "$port" | |
| 17 | + for _ in $(seq 1 900); do | |
| 18 | + curl -sf "http://127.0.0.1:$port/.well-known/agent-card.json" > /dev/null && break | |
| 19 | + if ! kill -0 "$(cat "$name.pid")" 2>/dev/null; then | |
| 20 | + echo " stopped:"; tail -5 "$name.log"; exit 1 | |
| 21 | + fi | |
| 22 | + printf "."; sleep 1 | |
| 23 | + done | |
| 24 | + curl -sf "http://127.0.0.1:$port/.well-known/agent-card.json" > /dev/null || { echo " no answer — see $name.log"; exit 1; } | |
| 25 | + echo " ready" | |
| 26 | +done | |
| new file mode 100755 | |||
| @@ -0,0 +1,26 @@ | |||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# Start the three agents as A2A servers, in the background, one log each. | ||
| 3 | +# mm starts llama-server for the first one (and downloads the model the first | ||
| 4 | +# time); the two others share it. Stop them with ./stop.sh. | ||
| 5 | +set -euo pipefail | ||
| 6 | +cd "$(dirname "$0")" | ||
| 7 | +MM=${MM:-../../mm} | ||
| 8 | +for agent in alice bob moderator; do | ||
| 9 | + "$MM" -a2a "$agent.yaml" > "$agent.log" 2>&1 & | ||
| 10 | + echo $! > "$agent.pid" | ||
| 11 | + echo "started $agent (pid $!, log $agent.log)" | ||
| 12 | +done | ||
| 13 | +# The first start downloads the model (~1.2 GB): up to 15 minutes. | ||
| 14 | +for agent in alice:9101 bob:9102 moderator:9103; do | ||
| 15 | + name=${agent%:*} port=${agent#*:} | ||
| 16 | + printf "waiting for %s on http://127.0.0.1:%s " "$name" "$port" | ||
| 17 | + for _ in $(seq 1 900); do | ||
| 18 | + curl -sf "http://127.0.0.1:$port/.well-known/agent-card.json" > /dev/null && break | ||
| 19 | + if ! kill -0 "$(cat "$name.pid")" 2>/dev/null; then | ||
| 20 | + echo " stopped:"; tail -5 "$name.log"; exit 1 | ||
| 21 | + fi | ||
| 22 | + printf "."; sleep 1 | ||
| 23 | + done | ||
| 24 | + curl -sf "http://127.0.0.1:$port/.well-known/agent-card.json" > /dev/null || { echo " no answer — see $name.log"; exit 1; } | ||
| 25 | + echo " ready" | ||
| 26 | +done | ||
added
demos/a2a-discussion/stop.sh +7 -0 | new file mode 100755 | ||
| @@ -0,0 +1,7 @@ | ||
| 1 | +#!/usr/bin/env bash | |
| 2 | +# Stop the three agents. The last one to quit stops llama-server. | |
| 3 | +cd "$(dirname "$0")" | |
| 4 | +for agent in alice bob moderator; do | |
| 5 | + [ -f "$agent.pid" ] && kill "$(cat "$agent.pid")" 2>/dev/null && echo "stopped $agent" | |
| 6 | + rm -f "$agent.pid" | |
| 7 | +done | |
| new file mode 100755 | |||
| @@ -0,0 +1,7 @@ | |||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# Stop the three agents. The last one to quit stops llama-server. | ||
| 3 | +cd "$(dirname "$0")" | ||
| 4 | +for agent in alice bob moderator; do | ||
| 5 | + [ -f "$agent.pid" ] && kill "$(cat "$agent.pid")" 2>/dev/null && echo "stopped $agent" | ||
| 6 | + rm -f "$agent.pid" | ||
| 7 | +done | ||
modified
docs/en/reference/cli.md +26 -0 | @@ -22,6 +22,8 @@ mm acp [<path>] [flags] (same as mm -acp) | ||
| 22 | 22 | | `-config <path>` | string | `""` | Path of the YAML configuration file. | |
| 23 | 23 | | `<path>` | positional | none | Same as `-config`, when `-config` is not given. A second positional argument is an error. A first argument `init`, `tui` or `acp` is a mode word, not a path: a configuration file with one of these names is given as `./tui` or with `-config`. | |
| 24 | 24 | | `-acp` | bool | `false` | Serve the Agent Client Protocol on stdin/stdout instead of the terminal REPL. Also written `--acp`, or `acp` as the first argument (`mm acp agent.yaml`). | |
| 25 | +| `-a2a` | bool | `false` | Serve the agent over the Agent2Agent protocol (A2A, JSON-RPC over HTTP) on `a2a.host:a2a.port` (`127.0.0.1:9100` by default) instead of the terminal REPL. Also written `--a2a`, or `a2a` as the first argument (`mm a2a agent.yaml`). See [A2A mode specifics](#a2a-mode-specifics). | | |
| 26 | +| `-a2a-port` | int | `0` | With `-a2a`: the port to listen on, instead of `a2a.port`. | | |
| 25 | 27 | | `-tui` | bool | `false` | Open the single-window mode (conversation above, input box below). Same effect as `tui: true` in the YAML; ignored with `-acp`. Falls back to the line mode when stdin or stdout is not a terminal. Also written `--tui`, or `tui` as the first argument (`mm tui agent.yaml`). | |
| 26 | 28 | | `-prompt <text>` / `-p <text>` | string | `""` | Run a single prompt and exit. The prompt text is required. Works with the config file before or after: `mm -p "hello" config.yaml` and `mm config.yaml -p "hello"` are both valid. No banner, no session persistence, no TUI/ACP. | |
| 27 | 29 | | `--version` | bool | `false` | Print the version and exit, before the configuration is read. `-version` is the same flag. | |
| @@ -120,6 +122,22 @@ mm v0.1.7 | config: agent.llamacpp.yaml | provider: llamacpp | model: jetbrains/ | ||
| 120 | 122 | | Relative `skillsDir` | Resolved from the [base directory](#base-directory-of-relative-paths) of the configuration file, when a file was found (the project root for a `.mm/agent.yaml`); otherwise from the working directory, as in terminal mode. | |
| 121 | 123 | | Permissions | `yolo: true`: no `session/request_permission` is sent for the built-in tools. `yolo: false`: one per call, with four options — `allow` (allow once), `allow_always` (this tool for the session), `reject` (reject once), `never` (`reject_always`: this tool, for the session). MCP tools marked `ask` always send one. | |
| 122 | 124 | |
| 125 | +## A2A mode specifics | |
| 126 | + | |
| 127 | +`mm a2a` serves the agent to other agents over the [Agent2Agent protocol](https://a2a-protocol.org) (ticket 243) — a subset written in mm, checked against the official Python `a2a-sdk` 1.3.1 client. | |
| 128 | + | |
| 129 | +| Aspect | Behaviour | | |
| 130 | +|--------|-----------| | |
| 131 | +| Address | `http://<a2a.host>:<a2a.port>`, `127.0.0.1:9100` by default — loopback: an A2A agent runs tools for whoever calls it. | | |
| 132 | +| Agent Card | `GET /.well-known/agent-card.json` (also `/.well-known/agent.json`): `name` = `acp.name`, `description` = `a2a.description` (else `acp.title`), the skills of `skillsDir`, `capabilities.streaming: false`, and the endpoint for both protocol versions (`supportedInterfaces`: 1.0 and 0.3 over JSONRPC; `url`, `protocolVersion` for 0.3). | | |
| 133 | +| Methods | `POST /`, JSON-RPC 2.0. A2A 1.0: `SendMessage`, `GetTask`; A2A 0.3: `message/send`, `tasks/get` — each answered in its version's shape. Any other method: error `-32601`. Text parts only. | | |
| 134 | +| Sending | Blocking: the answer is the finished task (`TASK_STATE_COMPLETED` / `completed`, the answer as an artifact and as the status message), or a failed one with the reason. One generation at a time, in arrival order. | | |
| 135 | +| Conversations | One per A2A `contextId`, in memory, for the life of the process: a message with a known `contextId` continues it, one without starts a new one. Compressed like a terminal session past `context.threshold`. Not saved to `sessions`. | | |
| 136 | +| Consent | Nobody can be asked: with `yolo: false` a tool that needs consent is refused, as under `-p`. `ask_user`: no one to answer — turn it off (`askUserTool: false`). | | |
| 137 | +| Authentication | `a2a.tokenEnv` set: every JSON-RPC call needs `Authorization: Bearer <token>`, else `401`; the card stays public and lists the scheme. | | |
| 138 | +| Output | stderr: the banner, `🤝 A2A agent "<name>" on <url>`, one `📨 <context> · <message>` line per message received; stdout: the answers as they stream. | | |
| 139 | +| Stop | `Ctrl-C`, SIGTERM or SIGHUP: the server stops, then the usual exit (unload, llama-server lease). | | |
| 140 | + | |
| 123 | 141 | ## Line mode specifics |
| 124 | 142 | |
| 125 | 143 | | Aspect | Behaviour | |
| @@ -296,6 +314,14 @@ An agent file outside the workspace only gives a warning: see [when the agent fi | ||
| 296 | 314 | | After writing | The messages of `mm init` (`✅ wrote <file>`, `✅ mm loads it`), then `mm acp <absolute path>`, a pointer to `/zedconfig`, and one to `/dockerinit` and `/sbxinit`; for a client whose `clientInfo.name` contains `zed`, an `agent_servers` snippet too. Later prompts answer that the file is written. | |
| 297 | 315 | | Exit codes | 0 the client closed the connection, or `-h`; 1 a refused flag value or presets that do not load; 2 a bad flag. | |
| 298 | 316 | |
| 317 | +## `mm a2a-send` — one message to an A2A agent | |
| 318 | + | |
| 319 | +```text | |
| 320 | +mm a2a-send [--context ID] [--token-env VAR] [--timeout D] <agent url> [message] | |
| 321 | +``` | |
| 322 | + | |
| 323 | +Sends one message to an A2A agent (another `mm a2a`, or any agent speaking A2A over JSON-RPC) and prints its answer on stdout; the conversation's `contextId` goes to stderr as `context: <id>`. `--context <id>` continues that conversation. The message is read from stdin when not given. A2A 1.0 first, then 0.3 if the agent does not know `SendMessage`. No configuration file and no model are read. Exit codes: `0` answered, `1` the agent or the network failed, `2` usage. Also written `--a2a-send`. See `demos/a2a-discussion/discussion.sh`. | |
| 324 | + | |
| 299 | 325 | ## `mm skillcreate` — the skill wizard |
| 300 | 326 | |
| 301 | 327 | `mm skillcreate` (also `--skillcreate`, `-skillcreate`) asks for a skill and writes it as `<skillsDir>/<name>/SKILL.md`. It is answered before any agent starts. Each question below has a flag; a question whose flag is given is not asked. See [How to add a skill](../how-to/add-a-skill.md). |
| @@ -22,6 +22,8 @@ mm acp [<path>] [flags] (same as mm -acp) | |||
| 22 | | `-config <path>` | string | `""` | Path of the YAML configuration file. | | 22 | | `-config <path>` | string | `""` | Path of the YAML configuration file. | |
| 23 | | `<path>` | positional | none | Same as `-config`, when `-config` is not given. A second positional argument is an error. A first argument `init`, `tui` or `acp` is a mode word, not a path: a configuration file with one of these names is given as `./tui` or with `-config`. | | 23 | | `<path>` | positional | none | Same as `-config`, when `-config` is not given. A second positional argument is an error. A first argument `init`, `tui` or `acp` is a mode word, not a path: a configuration file with one of these names is given as `./tui` or with `-config`. | |
| 24 | | `-acp` | bool | `false` | Serve the Agent Client Protocol on stdin/stdout instead of the terminal REPL. Also written `--acp`, or `acp` as the first argument (`mm acp agent.yaml`). | | 24 | | `-acp` | bool | `false` | Serve the Agent Client Protocol on stdin/stdout instead of the terminal REPL. Also written `--acp`, or `acp` as the first argument (`mm acp agent.yaml`). | |
| 25 | +| `-a2a` | bool | `false` | Serve the agent over the Agent2Agent protocol (A2A, JSON-RPC over HTTP) on `a2a.host:a2a.port` (`127.0.0.1:9100` by default) instead of the terminal REPL. Also written `--a2a`, or `a2a` as the first argument (`mm a2a agent.yaml`). See [A2A mode specifics](#a2a-mode-specifics). | | ||
| 26 | +| `-a2a-port` | int | `0` | With `-a2a`: the port to listen on, instead of `a2a.port`. | | ||
| 25 | | `-tui` | bool | `false` | Open the single-window mode (conversation above, input box below). Same effect as `tui: true` in the YAML; ignored with `-acp`. Falls back to the line mode when stdin or stdout is not a terminal. Also written `--tui`, or `tui` as the first argument (`mm tui agent.yaml`). | | 27 | | `-tui` | bool | `false` | Open the single-window mode (conversation above, input box below). Same effect as `tui: true` in the YAML; ignored with `-acp`. Falls back to the line mode when stdin or stdout is not a terminal. Also written `--tui`, or `tui` as the first argument (`mm tui agent.yaml`). | |
| 26 | | `-prompt <text>` / `-p <text>` | string | `""` | Run a single prompt and exit. The prompt text is required. Works with the config file before or after: `mm -p "hello" config.yaml` and `mm config.yaml -p "hello"` are both valid. No banner, no session persistence, no TUI/ACP. | | 28 | | `-prompt <text>` / `-p <text>` | string | `""` | Run a single prompt and exit. The prompt text is required. Works with the config file before or after: `mm -p "hello" config.yaml` and `mm config.yaml -p "hello"` are both valid. No banner, no session persistence, no TUI/ACP. | |
| 27 | | `--version` | bool | `false` | Print the version and exit, before the configuration is read. `-version` is the same flag. | | 29 | | `--version` | bool | `false` | Print the version and exit, before the configuration is read. `-version` is the same flag. | |
| @@ -120,6 +122,22 @@ mm v0.1.7 | config: agent.llamacpp.yaml | provider: llamacpp | model: jetbrains/ | |||
| 120 | | Relative `skillsDir` | Resolved from the [base directory](#base-directory-of-relative-paths) of the configuration file, when a file was found (the project root for a `.mm/agent.yaml`); otherwise from the working directory, as in terminal mode. | | 122 | | Relative `skillsDir` | Resolved from the [base directory](#base-directory-of-relative-paths) of the configuration file, when a file was found (the project root for a `.mm/agent.yaml`); otherwise from the working directory, as in terminal mode. | |
| 121 | | Permissions | `yolo: true`: no `session/request_permission` is sent for the built-in tools. `yolo: false`: one per call, with four options — `allow` (allow once), `allow_always` (this tool for the session), `reject` (reject once), `never` (`reject_always`: this tool, for the session). MCP tools marked `ask` always send one. | | 123 | | Permissions | `yolo: true`: no `session/request_permission` is sent for the built-in tools. `yolo: false`: one per call, with four options — `allow` (allow once), `allow_always` (this tool for the session), `reject` (reject once), `never` (`reject_always`: this tool, for the session). MCP tools marked `ask` always send one. | |
| 122 | 124 | ||
| 125 | +## A2A mode specifics | ||
| 126 | + | ||
| 127 | +`mm a2a` serves the agent to other agents over the [Agent2Agent protocol](https://a2a-protocol.org) (ticket 243) — a subset written in mm, checked against the official Python `a2a-sdk` 1.3.1 client. | ||
| 128 | + | ||
| 129 | +| Aspect | Behaviour | | ||
| 130 | +|--------|-----------| | ||
| 131 | +| Address | `http://<a2a.host>:<a2a.port>`, `127.0.0.1:9100` by default — loopback: an A2A agent runs tools for whoever calls it. | | ||
| 132 | +| Agent Card | `GET /.well-known/agent-card.json` (also `/.well-known/agent.json`): `name` = `acp.name`, `description` = `a2a.description` (else `acp.title`), the skills of `skillsDir`, `capabilities.streaming: false`, and the endpoint for both protocol versions (`supportedInterfaces`: 1.0 and 0.3 over JSONRPC; `url`, `protocolVersion` for 0.3). | | ||
| 133 | +| Methods | `POST /`, JSON-RPC 2.0. A2A 1.0: `SendMessage`, `GetTask`; A2A 0.3: `message/send`, `tasks/get` — each answered in its version's shape. Any other method: error `-32601`. Text parts only. | | ||
| 134 | +| Sending | Blocking: the answer is the finished task (`TASK_STATE_COMPLETED` / `completed`, the answer as an artifact and as the status message), or a failed one with the reason. One generation at a time, in arrival order. | | ||
| 135 | +| Conversations | One per A2A `contextId`, in memory, for the life of the process: a message with a known `contextId` continues it, one without starts a new one. Compressed like a terminal session past `context.threshold`. Not saved to `sessions`. | | ||
| 136 | +| Consent | Nobody can be asked: with `yolo: false` a tool that needs consent is refused, as under `-p`. `ask_user`: no one to answer — turn it off (`askUserTool: false`). | | ||
| 137 | +| Authentication | `a2a.tokenEnv` set: every JSON-RPC call needs `Authorization: Bearer <token>`, else `401`; the card stays public and lists the scheme. | | ||
| 138 | +| Output | stderr: the banner, `🤝 A2A agent "<name>" on <url>`, one `📨 <context> · <message>` line per message received; stdout: the answers as they stream. | | ||
| 139 | +| Stop | `Ctrl-C`, SIGTERM or SIGHUP: the server stops, then the usual exit (unload, llama-server lease). | | ||
| 140 | + | ||
| 123 | ## Line mode specifics | 141 | ## Line mode specifics |
| 124 | 142 | ||
| 125 | | Aspect | Behaviour | | 143 | | Aspect | Behaviour | |
| @@ -296,6 +314,14 @@ An agent file outside the workspace only gives a warning: see [when the agent fi | |||
| 296 | | After writing | The messages of `mm init` (`✅ wrote <file>`, `✅ mm loads it`), then `mm acp <absolute path>`, a pointer to `/zedconfig`, and one to `/dockerinit` and `/sbxinit`; for a client whose `clientInfo.name` contains `zed`, an `agent_servers` snippet too. Later prompts answer that the file is written. | | 314 | | After writing | The messages of `mm init` (`✅ wrote <file>`, `✅ mm loads it`), then `mm acp <absolute path>`, a pointer to `/zedconfig`, and one to `/dockerinit` and `/sbxinit`; for a client whose `clientInfo.name` contains `zed`, an `agent_servers` snippet too. Later prompts answer that the file is written. | |
| 297 | | Exit codes | 0 the client closed the connection, or `-h`; 1 a refused flag value or presets that do not load; 2 a bad flag. | | 315 | | Exit codes | 0 the client closed the connection, or `-h`; 1 a refused flag value or presets that do not load; 2 a bad flag. | |
| 298 | 316 | ||
| 317 | +## `mm a2a-send` — one message to an A2A agent | ||
| 318 | + | ||
| 319 | +```text | ||
| 320 | +mm a2a-send [--context ID] [--token-env VAR] [--timeout D] <agent url> [message] | ||
| 321 | +``` | ||
| 322 | + | ||
| 323 | +Sends one message to an A2A agent (another `mm a2a`, or any agent speaking A2A over JSON-RPC) and prints its answer on stdout; the conversation's `contextId` goes to stderr as `context: <id>`. `--context <id>` continues that conversation. The message is read from stdin when not given. A2A 1.0 first, then 0.3 if the agent does not know `SendMessage`. No configuration file and no model are read. Exit codes: `0` answered, `1` the agent or the network failed, `2` usage. Also written `--a2a-send`. See `demos/a2a-discussion/discussion.sh`. | ||
| 324 | + | ||
| 299 | ## `mm skillcreate` — the skill wizard | 325 | ## `mm skillcreate` — the skill wizard |
| 300 | 326 | ||
| 301 | `mm skillcreate` (also `--skillcreate`, `-skillcreate`) asks for a skill and writes it as `<skillsDir>/<name>/SKILL.md`. It is answered before any agent starts. Each question below has a flag; a question whose flag is given is not asked. See [How to add a skill](../how-to/add-a-skill.md). | 327 | `mm skillcreate` (also `--skillcreate`, `-skillcreate`) asks for a skill and writes it as `<skillsDir>/<name>/SKILL.md`. It is answered before any agent starts. Each question below has a flag; a question whose flag is given is not asked. See [How to add a skill](../how-to/add-a-skill.md). |
modified
docs/en/reference/configuration.md +21 -0 | @@ -60,6 +60,7 @@ Where `mm` looks for this file: [Configuration file resolution](cli.md#configura | ||
| 60 | 60 | | `yolo` | bool | `true` | `true`: the tools run without asking. `false`: every call that changes something — `bash`, `write_file`, `edit_file`, `fetch_content` with `output`, `lsp` `rename`, `plan` `create`/`update`/`next`/`delete` — waits for the user's answer in every front end (line mode, window, editor), and so does every MCP tool, whatever `mcp.permissions` says. Answers: allow once, allow this tool for the session, reject this call, never (this tool, for the session). `read_file`, `read_skill`, `fetch_content` without `output` and the `lsp` navigation actions never ask. In `-p` and `mm --ask`, nobody can answer: those calls are rejected. An agent started by `/ask`, `ask_agent` or `mm --ask` runs with `AGENT_YOLO=false` and submits its calls to the asking agent: the `yolo` of its `mmConfigs` entry decides when set, else the asking agent's `yolo`. Overridden by `AGENT_YOLO`. `bashTool`, `editTools`, `fetchContentTool` still decide which tools exist. See [How to confirm tool calls](../how-to/confirm-tool-calls.md). | |
| 61 | 61 | | `permissions` | string | absent | Deprecated, replaced by `yolo`. `ask` = `yolo: false` (and wins over `yolo: true`); `auto` changes nothing. Either value adds a start-up warning. Must be `auto` or `ask`. | |
| 62 | 62 | | `mmConfigs` | map name → path, or name → `{path, description, yolo, askUser, unloadModels}` | none | Other mm agents this one can ask. Each name generates `/ask-<name>` and `/ask-with-context-<name>` (see [slash commands](slash-commands.md#asking-another-agent)), and the list declares the [`ask_agent`](tools.md#ask_agent) tool, through which the model calls them itself. The long form adds `description` (when to call that agent; shown in `ask_agent`'s description, falling back to the agent file's `acp.title`) and `yolo` (decides that agent's tool calls when it is asked, by `/ask`, `ask_agent` or `mm --ask`, instead of this agent's `yolo`: `true` they run, `false` each one is asked; absent, this agent's `yolo` decides) and `askUser` (whether that agent may ask the user questions when it is asked: `true` its `ask_user` questions come up to this agent's user, `false` its `ask_user` tool is not declared; absent, that agent's own `askUserTool` decides) and `unloadModels` (default `false`; `true`: every hand-off to that agent — `ask_agent`, `/ask…`, `mm --ask` — unloads this agent's model right before that agent starts, and that agent's model once it has answered, before this agent reads the answer, so the two models are never loaded together; each unload is a `🧹` notice, a failed one does not stop the hand-off; this agent's model is unloaded on its own server, that agent's on the server its file names; `mm --ask` only unloads that agent's model; not the top-level `unloadModels`, which declares `/unload` and `unload_model`). `path` must not be empty. A relative path is relative to the directory of the file that declares it. Names: lowercase letters, digits and `-`, starting with a letter or a digit, not starting with `with-context`. A path whose file does not exist is a start-up warning, not an error. | |
| 63 | +| `a2a` | `{host, port, description, tokenEnv, agents}` | `127.0.0.1:9100`, no agents | The Agent2Agent protocol (ticket 243): how `mm a2a` serves this agent, and the remote A2A agents its model talks to through [`ask_a2a_agent`](tools.md#ask_a2a_agent). See [`a2a` keys](#a2a-keys). | | |
| 63 | 64 | |
| 64 | 65 | ## `context` keys |
| 65 | 66 | |
| @@ -138,6 +139,26 @@ Not read: a missing file, a file of blanks only, a file above `maxChars`, any fi | ||
| 138 | 139 | |
| 139 | 140 | The version is not configurable: `agentInfo.version` is always the binary's, as printed by `mm --version`. |
| 140 | 141 | |
| 142 | +## `a2a` keys | |
| 143 | + | |
| 144 | +```yaml | |
| 145 | +a2a: | |
| 146 | + port: 9101 | |
| 147 | + description: "Alice, an optimist: she argues FOR the idea." | |
| 148 | + agents: | |
| 149 | + bob: | |
| 150 | + url: http://127.0.0.1:9102 | |
| 151 | + description: "Bob, a sceptic who argues against." | |
| 152 | +``` | |
| 153 | + | |
| 154 | +| Key | Type | Default | Description | | |
| 155 | +|-----|------|---------|-------------| | |
| 156 | +| `host` | string | `127.0.0.1` | Where `mm a2a` listens. Keep the loopback unless other machines must call it: an A2A agent runs tools for whoever calls it. | | |
| 157 | +| `port` | int | `9100` | Its port; `--a2a-port` overrides it. Between 0 and 65535. | | |
| 158 | +| `description` | string | `acp.title` | The Agent Card's description: what the agents that call this one read about it. | | |
| 159 | +| `tokenEnv` | string | `""` | The variable holding the token every caller must send (`Authorization: Bearer …`); unset at start-up, `mm a2a` stops. Empty: no authentication. | | |
| 160 | +| `agents` | map name → `{url, description, tokenEnv}` | none | The remote A2A agents the model can talk to: their presence declares [`ask_a2a_agent`](tools.md#ask_a2a_agent). `url`: the agent's address (`http`/`https`). `description`: when to call it, shown in the tool's description. `tokenEnv`: the variable holding its token, if it wants one. Names: lowercase letters, digits and `-`. | | |
| 161 | + | |
| 141 | 162 | ## `lsp` keys |
| 142 | 163 | |
| 143 | 164 | | Key | Type | Default | Description | |
| @@ -60,6 +60,7 @@ Where `mm` looks for this file: [Configuration file resolution](cli.md#configura | |||
| 60 | | `yolo` | bool | `true` | `true`: the tools run without asking. `false`: every call that changes something — `bash`, `write_file`, `edit_file`, `fetch_content` with `output`, `lsp` `rename`, `plan` `create`/`update`/`next`/`delete` — waits for the user's answer in every front end (line mode, window, editor), and so does every MCP tool, whatever `mcp.permissions` says. Answers: allow once, allow this tool for the session, reject this call, never (this tool, for the session). `read_file`, `read_skill`, `fetch_content` without `output` and the `lsp` navigation actions never ask. In `-p` and `mm --ask`, nobody can answer: those calls are rejected. An agent started by `/ask`, `ask_agent` or `mm --ask` runs with `AGENT_YOLO=false` and submits its calls to the asking agent: the `yolo` of its `mmConfigs` entry decides when set, else the asking agent's `yolo`. Overridden by `AGENT_YOLO`. `bashTool`, `editTools`, `fetchContentTool` still decide which tools exist. See [How to confirm tool calls](../how-to/confirm-tool-calls.md). | | 60 | | `yolo` | bool | `true` | `true`: the tools run without asking. `false`: every call that changes something — `bash`, `write_file`, `edit_file`, `fetch_content` with `output`, `lsp` `rename`, `plan` `create`/`update`/`next`/`delete` — waits for the user's answer in every front end (line mode, window, editor), and so does every MCP tool, whatever `mcp.permissions` says. Answers: allow once, allow this tool for the session, reject this call, never (this tool, for the session). `read_file`, `read_skill`, `fetch_content` without `output` and the `lsp` navigation actions never ask. In `-p` and `mm --ask`, nobody can answer: those calls are rejected. An agent started by `/ask`, `ask_agent` or `mm --ask` runs with `AGENT_YOLO=false` and submits its calls to the asking agent: the `yolo` of its `mmConfigs` entry decides when set, else the asking agent's `yolo`. Overridden by `AGENT_YOLO`. `bashTool`, `editTools`, `fetchContentTool` still decide which tools exist. See [How to confirm tool calls](../how-to/confirm-tool-calls.md). | |
| 61 | | `permissions` | string | absent | Deprecated, replaced by `yolo`. `ask` = `yolo: false` (and wins over `yolo: true`); `auto` changes nothing. Either value adds a start-up warning. Must be `auto` or `ask`. | | 61 | | `permissions` | string | absent | Deprecated, replaced by `yolo`. `ask` = `yolo: false` (and wins over `yolo: true`); `auto` changes nothing. Either value adds a start-up warning. Must be `auto` or `ask`. | |
| 62 | | `mmConfigs` | map name → path, or name → `{path, description, yolo, askUser, unloadModels}` | none | Other mm agents this one can ask. Each name generates `/ask-<name>` and `/ask-with-context-<name>` (see [slash commands](slash-commands.md#asking-another-agent)), and the list declares the [`ask_agent`](tools.md#ask_agent) tool, through which the model calls them itself. The long form adds `description` (when to call that agent; shown in `ask_agent`'s description, falling back to the agent file's `acp.title`) and `yolo` (decides that agent's tool calls when it is asked, by `/ask`, `ask_agent` or `mm --ask`, instead of this agent's `yolo`: `true` they run, `false` each one is asked; absent, this agent's `yolo` decides) and `askUser` (whether that agent may ask the user questions when it is asked: `true` its `ask_user` questions come up to this agent's user, `false` its `ask_user` tool is not declared; absent, that agent's own `askUserTool` decides) and `unloadModels` (default `false`; `true`: every hand-off to that agent — `ask_agent`, `/ask…`, `mm --ask` — unloads this agent's model right before that agent starts, and that agent's model once it has answered, before this agent reads the answer, so the two models are never loaded together; each unload is a `🧹` notice, a failed one does not stop the hand-off; this agent's model is unloaded on its own server, that agent's on the server its file names; `mm --ask` only unloads that agent's model; not the top-level `unloadModels`, which declares `/unload` and `unload_model`). `path` must not be empty. A relative path is relative to the directory of the file that declares it. Names: lowercase letters, digits and `-`, starting with a letter or a digit, not starting with `with-context`. A path whose file does not exist is a start-up warning, not an error. | | 62 | | `mmConfigs` | map name → path, or name → `{path, description, yolo, askUser, unloadModels}` | none | Other mm agents this one can ask. Each name generates `/ask-<name>` and `/ask-with-context-<name>` (see [slash commands](slash-commands.md#asking-another-agent)), and the list declares the [`ask_agent`](tools.md#ask_agent) tool, through which the model calls them itself. The long form adds `description` (when to call that agent; shown in `ask_agent`'s description, falling back to the agent file's `acp.title`) and `yolo` (decides that agent's tool calls when it is asked, by `/ask`, `ask_agent` or `mm --ask`, instead of this agent's `yolo`: `true` they run, `false` each one is asked; absent, this agent's `yolo` decides) and `askUser` (whether that agent may ask the user questions when it is asked: `true` its `ask_user` questions come up to this agent's user, `false` its `ask_user` tool is not declared; absent, that agent's own `askUserTool` decides) and `unloadModels` (default `false`; `true`: every hand-off to that agent — `ask_agent`, `/ask…`, `mm --ask` — unloads this agent's model right before that agent starts, and that agent's model once it has answered, before this agent reads the answer, so the two models are never loaded together; each unload is a `🧹` notice, a failed one does not stop the hand-off; this agent's model is unloaded on its own server, that agent's on the server its file names; `mm --ask` only unloads that agent's model; not the top-level `unloadModels`, which declares `/unload` and `unload_model`). `path` must not be empty. A relative path is relative to the directory of the file that declares it. Names: lowercase letters, digits and `-`, starting with a letter or a digit, not starting with `with-context`. A path whose file does not exist is a start-up warning, not an error. | |
| 63 | +| `a2a` | `{host, port, description, tokenEnv, agents}` | `127.0.0.1:9100`, no agents | The Agent2Agent protocol (ticket 243): how `mm a2a` serves this agent, and the remote A2A agents its model talks to through [`ask_a2a_agent`](tools.md#ask_a2a_agent). See [`a2a` keys](#a2a-keys). | | ||
| 63 | 64 | ||
| 64 | ## `context` keys | 65 | ## `context` keys |
| 65 | 66 | ||
| @@ -138,6 +139,26 @@ Not read: a missing file, a file of blanks only, a file above `maxChars`, any fi | |||
| 138 | 139 | ||
| 139 | The version is not configurable: `agentInfo.version` is always the binary's, as printed by `mm --version`. | 140 | The version is not configurable: `agentInfo.version` is always the binary's, as printed by `mm --version`. |
| 140 | 141 | ||
| 142 | +## `a2a` keys | ||
| 143 | + | ||
| 144 | +```yaml | ||
| 145 | +a2a: | ||
| 146 | + port: 9101 | ||
| 147 | + description: "Alice, an optimist: she argues FOR the idea." | ||
| 148 | + agents: | ||
| 149 | + bob: | ||
| 150 | + url: http://127.0.0.1:9102 | ||
| 151 | + description: "Bob, a sceptic who argues against." | ||
| 152 | +``` | ||
| 153 | + | ||
| 154 | +| Key | Type | Default | Description | | ||
| 155 | +|-----|------|---------|-------------| | ||
| 156 | +| `host` | string | `127.0.0.1` | Where `mm a2a` listens. Keep the loopback unless other machines must call it: an A2A agent runs tools for whoever calls it. | | ||
| 157 | +| `port` | int | `9100` | Its port; `--a2a-port` overrides it. Between 0 and 65535. | | ||
| 158 | +| `description` | string | `acp.title` | The Agent Card's description: what the agents that call this one read about it. | | ||
| 159 | +| `tokenEnv` | string | `""` | The variable holding the token every caller must send (`Authorization: Bearer …`); unset at start-up, `mm a2a` stops. Empty: no authentication. | | ||
| 160 | +| `agents` | map name → `{url, description, tokenEnv}` | none | The remote A2A agents the model can talk to: their presence declares [`ask_a2a_agent`](tools.md#ask_a2a_agent). `url`: the agent's address (`http`/`https`). `description`: when to call it, shown in the tool's description. `tokenEnv`: the variable holding its token, if it wants one. Names: lowercase letters, digits and `-`. | | ||
| 161 | + | ||
| 141 | ## `lsp` keys | 162 | ## `lsp` keys |
| 142 | 163 | ||
| 143 | | Key | Type | Default | Description | | 164 | | Key | Type | Default | Description | |
modified
docs/en/reference/tools.md +18 -0 | @@ -261,6 +261,24 @@ Declared when `mmConfigs` names at least one agent. Hands a task to one of them | ||
| 261 | 261 | | Errors | `[ask_agent: unknown agent "x" — agents: a, b]`; `[ask_agent: the prompt is empty — say what <agent> must do]`; `[ask_agent: <agent> failed: <reason>]`; `[ask_agent: <agent> gave no answer]`; a cancelled or broken run returns what was answered, then `[ask_agent: <agent> stopped before finishing: <reason>]`. | |
| 262 | 262 | | Depth | An asked agent may itself have `mmConfigs` and call `ask_agent`, up to two levels (`MM_ASK_DEPTH`); beyond, the call fails with the depth message. | |
| 263 | 263 | |
| 264 | +## `ask_a2a_agent` | |
| 265 | + | |
| 266 | +Declared when `a2a.agents` names at least one agent. Sends a message to a remote A2A agent and returns its answer (ticket 243). | |
| 267 | + | |
| 268 | +| Field | Type | Default | Description | | |
| 269 | +|-------|------|---------|-------------| | |
| 270 | +| `agent` | string | — | The agent's name, a key of `a2a.agents`. | | |
| 271 | +| `message` | string | — | What to say to it. It sees only what it is sent, and its own earlier answers to this agent. | | |
| 272 | +| `new_conversation` | bool | `false` | `true`: start a new conversation with that agent. | | |
| 273 | + | |
| 274 | +| Aspect | Behaviour | | |
| 275 | +|--------|-----------| | |
| 276 | +| Conversation | Goes on from one call to the next: the A2A `contextId` is kept per agent, for the life of the process. | | |
| 277 | +| Protocol | A2A 1.0 (`SendMessage`), then 0.3 (`message/send`) if the agent does not know it. Blocking: waits for the finished task, up to 10 minutes; the generation's watchdog does not count that wait. | | |
| 278 | +| Result | The agent's answer; `[ask_a2a_agent: <agent> did not answer — <reason>]` on a failure, `[ask_a2a_agent: no agent "<name>" — use one of: …]` for an unknown name. | | |
| 279 | +| Terminal display | `🤝 ask_a2a_agent: <agent>`, spinner `Waiting for <agent>`, then the answer echoed. | | |
| 280 | +| Consent | None asked: talking to an agent changes nothing here (the remote agent applies its own `yolo`). | | |
| 281 | + | |
| 264 | 282 | ## `ask_user` |
| 265 | 283 | |
| 266 | 284 | Declared unless `askUserTool: false` (on by default), and never beside a `structuredOutput`. Puts one to four questions to the user and returns the answers. Not gated by `yolo`: asking changes nothing. |
| @@ -261,6 +261,24 @@ Declared when `mmConfigs` names at least one agent. Hands a task to one of them | |||
| 261 | | Errors | `[ask_agent: unknown agent "x" — agents: a, b]`; `[ask_agent: the prompt is empty — say what <agent> must do]`; `[ask_agent: <agent> failed: <reason>]`; `[ask_agent: <agent> gave no answer]`; a cancelled or broken run returns what was answered, then `[ask_agent: <agent> stopped before finishing: <reason>]`. | | 261 | | Errors | `[ask_agent: unknown agent "x" — agents: a, b]`; `[ask_agent: the prompt is empty — say what <agent> must do]`; `[ask_agent: <agent> failed: <reason>]`; `[ask_agent: <agent> gave no answer]`; a cancelled or broken run returns what was answered, then `[ask_agent: <agent> stopped before finishing: <reason>]`. | |
| 262 | | Depth | An asked agent may itself have `mmConfigs` and call `ask_agent`, up to two levels (`MM_ASK_DEPTH`); beyond, the call fails with the depth message. | | 262 | | Depth | An asked agent may itself have `mmConfigs` and call `ask_agent`, up to two levels (`MM_ASK_DEPTH`); beyond, the call fails with the depth message. | |
| 263 | 263 | ||
| 264 | +## `ask_a2a_agent` | ||
| 265 | + | ||
| 266 | +Declared when `a2a.agents` names at least one agent. Sends a message to a remote A2A agent and returns its answer (ticket 243). | ||
| 267 | + | ||
| 268 | +| Field | Type | Default | Description | | ||
| 269 | +|-------|------|---------|-------------| | ||
| 270 | +| `agent` | string | — | The agent's name, a key of `a2a.agents`. | | ||
| 271 | +| `message` | string | — | What to say to it. It sees only what it is sent, and its own earlier answers to this agent. | | ||
| 272 | +| `new_conversation` | bool | `false` | `true`: start a new conversation with that agent. | | ||
| 273 | + | ||
| 274 | +| Aspect | Behaviour | | ||
| 275 | +|--------|-----------| | ||
| 276 | +| Conversation | Goes on from one call to the next: the A2A `contextId` is kept per agent, for the life of the process. | | ||
| 277 | +| Protocol | A2A 1.0 (`SendMessage`), then 0.3 (`message/send`) if the agent does not know it. Blocking: waits for the finished task, up to 10 minutes; the generation's watchdog does not count that wait. | | ||
| 278 | +| Result | The agent's answer; `[ask_a2a_agent: <agent> did not answer — <reason>]` on a failure, `[ask_a2a_agent: no agent "<name>" — use one of: …]` for an unknown name. | | ||
| 279 | +| Terminal display | `🤝 ask_a2a_agent: <agent>`, spinner `Waiting for <agent>`, then the answer echoed. | | ||
| 280 | +| Consent | None asked: talking to an agent changes nothing here (the remote agent applies its own `yolo`). | | ||
| 281 | + | ||
| 264 | ## `ask_user` | 282 | ## `ask_user` |
| 265 | 283 | ||
| 266 | Declared unless `askUserTool: false` (on by default), and never beside a `structuredOutput`. Puts one to four questions to the user and returns the answers. Not gated by `yolo`: asking changes nothing. | 284 | Declared unless `askUserTool: false` (on by default), and never beside a `structuredOutput`. Puts one to four questions to the user and returns the answers. Not gated by `yolo`: asking changes nothing. |
modified
docs/fr/reference/cli.md +26 -0 | @@ -22,6 +22,8 @@ mm acp [<chemin>] [options] (identique à m | ||
| 22 | 22 | | `-config <chemin>` | chaîne | `""` | Chemin du fichier de configuration YAML. | |
| 23 | 23 | | `<chemin>` | positionnel | aucun | Équivalent de `-config` quand `-config` n'est pas donné. Un second argument positionnel est une erreur. Un premier argument `init`, `tui` ou `acp` est un mot de mode, pas un chemin : un fichier de configuration portant l'un de ces noms se donne en `./tui` ou avec `-config`. | |
| 24 | 24 | | `-acp` | booléen | `false` | Sert l'Agent Client Protocol sur stdin/stdout au lieu du REPL du terminal. S'écrit aussi `--acp`, ou `acp` en premier argument (`mm acp agent.yaml`). | |
| 25 | +| `-a2a` | booléen | `false` | Sert l'agent par le protocole Agent2Agent (A2A, JSON-RPC sur HTTP) sur `a2a.host:a2a.port` (`127.0.0.1:9100` par défaut) au lieu de la boucle du terminal. S'écrit aussi `--a2a`, ou `a2a` en premier argument (`mm a2a agent.yaml`). Voir [Spécificités du mode A2A](#spécificités-du-mode-a2a). | | |
| 26 | +| `-a2a-port` | entier | `0` | Avec `-a2a` : le port d'écoute, à la place d'`a2a.port`. | | |
| 25 | 27 | | `-tui` | booléen | `false` | Ouvre le mode fenêtre unique (conversation en haut, zone de saisie en bas). Même effet que `tui: true` dans le YAML ; ignoré avec `-acp`. Retombe sur le mode ligne quand stdin ou stdout n'est pas un terminal. S'écrit aussi `--tui`, ou `tui` en premier argument (`mm tui agent.yaml`). | |
| 26 | 28 | | `-prompt <texte>` / `-p <texte>` | chaîne | `""` | Exécute une seule invite et quitte. Le texte de l'invite est obligatoire. Fonctionne avec le fichier de config avant ou après : `mm -p "bonjour" config.yaml` et `mm config.yaml -p "bonjour"` sont tous deux valides. Pas de bannière, pas de persistance de session, pas de TUI/ACP. | |
| 27 | 29 | | `--version` | bool | `false` | Affiche la version et quitte, avant la lecture de la configuration. `-version` est la même option. | |
| @@ -120,6 +122,22 @@ mm v0.1.7 | config: agent.llamacpp.yaml | provider: llamacpp | model: jetbrains/ | ||
| 120 | 122 | | `skillsDir` relatif | Résolu depuis le [répertoire de base](#répertoire-de-base-des-chemins-relatifs) du fichier de configuration, quand un fichier a été trouvé (la racine du projet pour un `.mm/agent.yaml`) ; sinon depuis le répertoire de travail, comme en mode terminal. | |
| 121 | 123 | | Permissions | `yolo: true` : aucune `session/request_permission` n'est envoyée pour les outils intégrés. `yolo: false` : une par appel, avec quatre options — `allow` (autoriser une fois), `allow_always` (cet outil pour la session), `reject` (refuser une fois), `never` (`reject_always` : cet outil, pour la session). Les outils MCP marqués `ask` en envoient toujours une. | |
| 122 | 124 | |
| 125 | +## Spécificités du mode A2A | |
| 126 | + | |
| 127 | +`mm a2a` sert l'agent à d'autres agents par le [protocole Agent2Agent](https://a2a-protocol.org) (ticket 243) — un sous-ensemble écrit dans mm, vérifié avec le client officiel Python `a2a-sdk` 1.3.1. | |
| 128 | + | |
| 129 | +| Aspect | Comportement | | |
| 130 | +|--------|--------------| | |
| 131 | +| Adresse | `http://<a2a.host>:<a2a.port>`, `127.0.0.1:9100` par défaut — boucle locale : un agent A2A exécute des outils pour quiconque l'appelle. | | |
| 132 | +| Agent Card | `GET /.well-known/agent-card.json` (aussi `/.well-known/agent.json`) : `name` = `acp.name`, `description` = `a2a.description` (sinon `acp.title`), les skills de `skillsDir`, `capabilities.streaming: false`, et le point d'accès pour les deux versions du protocole (`supportedInterfaces` : 1.0 et 0.3 en JSONRPC ; `url`, `protocolVersion` pour la 0.3). | | |
| 133 | +| Méthodes | `POST /`, JSON-RPC 2.0. A2A 1.0 : `SendMessage`, `GetTask` ; A2A 0.3 : `message/send`, `tasks/get` — chacune répond dans la forme de sa version. Toute autre méthode : erreur `-32601`. Parties texte seulement. | | |
| 134 | +| Envoi | Bloquant : la réponse est la tâche terminée (`TASK_STATE_COMPLETED` / `completed`, la réponse en artefact et en message de statut), ou une tâche en échec avec la raison. Une génération à la fois, dans l'ordre d'arrivée. | | |
| 135 | +| Conversations | Une par `contextId` A2A, en mémoire, pour la durée du processus : un message avec un `contextId` connu la continue, un message sans en commence une. Compressées comme une session de terminal au-delà de `context.threshold`. Pas enregistrées dans `sessions`. | | |
| 136 | +| Consentement | Personne à qui demander : avec `yolo: false`, un outil qui demande un consentement est refusé, comme avec `-p`. `ask_user` : personne pour répondre — désactivez-le (`askUserTool: false`). | | |
| 137 | +| Authentification | `a2a.tokenEnv` renseigné : chaque appel JSON-RPC demande `Authorization: Bearer <jeton>`, sinon `401` ; la carte reste publique et indique le schéma. | | |
| 138 | +| Sortie | stderr : la bannière, `🤝 A2A agent "<nom>" on <url>`, une ligne `📨 <contexte> · <message>` par message reçu ; stdout : les réponses au fil de leur génération. | | |
| 139 | +| Arrêt | `Ctrl-C`, SIGTERM ou SIGHUP : le serveur s'arrête, puis la sortie habituelle (déchargement, bail llama-server). | | |
| 140 | + | |
| 123 | 141 | ## Spécificités du mode ligne |
| 124 | 142 | |
| 125 | 143 | | Aspect | Comportement | |
| @@ -296,6 +314,14 @@ Un fichier d'agent hors du workspace ne donne qu'un avertissement : voir [quand | ||
| 296 | 314 | | Après l'écriture | Les messages de `mm init` (`✅ wrote <fichier>`, `✅ mm loads it`), puis `mm acp <chemin absolu>`, un renvoi vers `/zedconfig`, et un vers `/dockerinit` et `/sbxinit` ; pour un client dont `clientInfo.name` contient `zed`, une entrée `agent_servers` en plus. Les prompts suivants répondent que le fichier est écrit. | |
| 297 | 315 | | Codes de sortie | 0 le client a fermé la connexion, ou `-h` ; 1 une valeur d'option refusée ou des presets illisibles ; 2 une option inconnue. | |
| 298 | 316 | |
| 317 | +## `mm a2a-send` — un message à un agent A2A | |
| 318 | + | |
| 319 | +```text | |
| 320 | +mm a2a-send [--context ID] [--token-env VAR] [--timeout D] <url de l'agent> [message] | |
| 321 | +``` | |
| 322 | + | |
| 323 | +Envoie un message à un agent A2A (un autre `mm a2a`, ou tout agent qui parle A2A en JSON-RPC) et affiche sa réponse sur stdout ; le `contextId` de la conversation va sur stderr sous la forme `context: <id>`. `--context <id>` continue cette conversation. Le message est lu sur stdin quand il n'est pas donné. A2A 1.0 d'abord, puis 0.3 si l'agent ne connaît pas `SendMessage`. Aucun fichier de configuration ni modèle n'est lu. Codes de sortie : `0` réponse reçue, `1` l'agent ou le réseau a échoué, `2` usage. S'écrit aussi `--a2a-send`. Voir `demos/a2a-discussion/discussion.sh`. | |
| 324 | + | |
| 299 | 325 | ## `mm skillcreate` — l'assistant de skill |
| 300 | 326 | |
| 301 | 327 | `mm skillcreate` (aussi `--skillcreate`, `-skillcreate`) demande un skill et l'écrit dans `<skillsDir>/<nom>/SKILL.md`. Il répond avant qu'aucun agent ne démarre. Chaque question ci-dessous a une option ; une question dont l'option est donnée n'est pas posée. Voir [Comment ajouter un skill](../how-to/add-a-skill.md). |
| @@ -22,6 +22,8 @@ mm acp [<chemin>] [options] (identique à m | |||
| 22 | | `-config <chemin>` | chaîne | `""` | Chemin du fichier de configuration YAML. | | 22 | | `-config <chemin>` | chaîne | `""` | Chemin du fichier de configuration YAML. | |
| 23 | | `<chemin>` | positionnel | aucun | Équivalent de `-config` quand `-config` n'est pas donné. Un second argument positionnel est une erreur. Un premier argument `init`, `tui` ou `acp` est un mot de mode, pas un chemin : un fichier de configuration portant l'un de ces noms se donne en `./tui` ou avec `-config`. | | 23 | | `<chemin>` | positionnel | aucun | Équivalent de `-config` quand `-config` n'est pas donné. Un second argument positionnel est une erreur. Un premier argument `init`, `tui` ou `acp` est un mot de mode, pas un chemin : un fichier de configuration portant l'un de ces noms se donne en `./tui` ou avec `-config`. | |
| 24 | | `-acp` | booléen | `false` | Sert l'Agent Client Protocol sur stdin/stdout au lieu du REPL du terminal. S'écrit aussi `--acp`, ou `acp` en premier argument (`mm acp agent.yaml`). | | 24 | | `-acp` | booléen | `false` | Sert l'Agent Client Protocol sur stdin/stdout au lieu du REPL du terminal. S'écrit aussi `--acp`, ou `acp` en premier argument (`mm acp agent.yaml`). | |
| 25 | +| `-a2a` | booléen | `false` | Sert l'agent par le protocole Agent2Agent (A2A, JSON-RPC sur HTTP) sur `a2a.host:a2a.port` (`127.0.0.1:9100` par défaut) au lieu de la boucle du terminal. S'écrit aussi `--a2a`, ou `a2a` en premier argument (`mm a2a agent.yaml`). Voir [Spécificités du mode A2A](#spécificités-du-mode-a2a). | | ||
| 26 | +| `-a2a-port` | entier | `0` | Avec `-a2a` : le port d'écoute, à la place d'`a2a.port`. | | ||
| 25 | | `-tui` | booléen | `false` | Ouvre le mode fenêtre unique (conversation en haut, zone de saisie en bas). Même effet que `tui: true` dans le YAML ; ignoré avec `-acp`. Retombe sur le mode ligne quand stdin ou stdout n'est pas un terminal. S'écrit aussi `--tui`, ou `tui` en premier argument (`mm tui agent.yaml`). | | 27 | | `-tui` | booléen | `false` | Ouvre le mode fenêtre unique (conversation en haut, zone de saisie en bas). Même effet que `tui: true` dans le YAML ; ignoré avec `-acp`. Retombe sur le mode ligne quand stdin ou stdout n'est pas un terminal. S'écrit aussi `--tui`, ou `tui` en premier argument (`mm tui agent.yaml`). | |
| 26 | | `-prompt <texte>` / `-p <texte>` | chaîne | `""` | Exécute une seule invite et quitte. Le texte de l'invite est obligatoire. Fonctionne avec le fichier de config avant ou après : `mm -p "bonjour" config.yaml` et `mm config.yaml -p "bonjour"` sont tous deux valides. Pas de bannière, pas de persistance de session, pas de TUI/ACP. | | 28 | | `-prompt <texte>` / `-p <texte>` | chaîne | `""` | Exécute une seule invite et quitte. Le texte de l'invite est obligatoire. Fonctionne avec le fichier de config avant ou après : `mm -p "bonjour" config.yaml` et `mm config.yaml -p "bonjour"` sont tous deux valides. Pas de bannière, pas de persistance de session, pas de TUI/ACP. | |
| 27 | | `--version` | bool | `false` | Affiche la version et quitte, avant la lecture de la configuration. `-version` est la même option. | | 29 | | `--version` | bool | `false` | Affiche la version et quitte, avant la lecture de la configuration. `-version` est la même option. | |
| @@ -120,6 +122,22 @@ mm v0.1.7 | config: agent.llamacpp.yaml | provider: llamacpp | model: jetbrains/ | |||
| 120 | | `skillsDir` relatif | Résolu depuis le [répertoire de base](#répertoire-de-base-des-chemins-relatifs) du fichier de configuration, quand un fichier a été trouvé (la racine du projet pour un `.mm/agent.yaml`) ; sinon depuis le répertoire de travail, comme en mode terminal. | | 122 | | `skillsDir` relatif | Résolu depuis le [répertoire de base](#répertoire-de-base-des-chemins-relatifs) du fichier de configuration, quand un fichier a été trouvé (la racine du projet pour un `.mm/agent.yaml`) ; sinon depuis le répertoire de travail, comme en mode terminal. | |
| 121 | | Permissions | `yolo: true` : aucune `session/request_permission` n'est envoyée pour les outils intégrés. `yolo: false` : une par appel, avec quatre options — `allow` (autoriser une fois), `allow_always` (cet outil pour la session), `reject` (refuser une fois), `never` (`reject_always` : cet outil, pour la session). Les outils MCP marqués `ask` en envoient toujours une. | | 123 | | Permissions | `yolo: true` : aucune `session/request_permission` n'est envoyée pour les outils intégrés. `yolo: false` : une par appel, avec quatre options — `allow` (autoriser une fois), `allow_always` (cet outil pour la session), `reject` (refuser une fois), `never` (`reject_always` : cet outil, pour la session). Les outils MCP marqués `ask` en envoient toujours une. | |
| 122 | 124 | ||
| 125 | +## Spécificités du mode A2A | ||
| 126 | + | ||
| 127 | +`mm a2a` sert l'agent à d'autres agents par le [protocole Agent2Agent](https://a2a-protocol.org) (ticket 243) — un sous-ensemble écrit dans mm, vérifié avec le client officiel Python `a2a-sdk` 1.3.1. | ||
| 128 | + | ||
| 129 | +| Aspect | Comportement | | ||
| 130 | +|--------|--------------| | ||
| 131 | +| Adresse | `http://<a2a.host>:<a2a.port>`, `127.0.0.1:9100` par défaut — boucle locale : un agent A2A exécute des outils pour quiconque l'appelle. | | ||
| 132 | +| Agent Card | `GET /.well-known/agent-card.json` (aussi `/.well-known/agent.json`) : `name` = `acp.name`, `description` = `a2a.description` (sinon `acp.title`), les skills de `skillsDir`, `capabilities.streaming: false`, et le point d'accès pour les deux versions du protocole (`supportedInterfaces` : 1.0 et 0.3 en JSONRPC ; `url`, `protocolVersion` pour la 0.3). | | ||
| 133 | +| Méthodes | `POST /`, JSON-RPC 2.0. A2A 1.0 : `SendMessage`, `GetTask` ; A2A 0.3 : `message/send`, `tasks/get` — chacune répond dans la forme de sa version. Toute autre méthode : erreur `-32601`. Parties texte seulement. | | ||
| 134 | +| Envoi | Bloquant : la réponse est la tâche terminée (`TASK_STATE_COMPLETED` / `completed`, la réponse en artefact et en message de statut), ou une tâche en échec avec la raison. Une génération à la fois, dans l'ordre d'arrivée. | | ||
| 135 | +| Conversations | Une par `contextId` A2A, en mémoire, pour la durée du processus : un message avec un `contextId` connu la continue, un message sans en commence une. Compressées comme une session de terminal au-delà de `context.threshold`. Pas enregistrées dans `sessions`. | | ||
| 136 | +| Consentement | Personne à qui demander : avec `yolo: false`, un outil qui demande un consentement est refusé, comme avec `-p`. `ask_user` : personne pour répondre — désactivez-le (`askUserTool: false`). | | ||
| 137 | +| Authentification | `a2a.tokenEnv` renseigné : chaque appel JSON-RPC demande `Authorization: Bearer <jeton>`, sinon `401` ; la carte reste publique et indique le schéma. | | ||
| 138 | +| Sortie | stderr : la bannière, `🤝 A2A agent "<nom>" on <url>`, une ligne `📨 <contexte> · <message>` par message reçu ; stdout : les réponses au fil de leur génération. | | ||
| 139 | +| Arrêt | `Ctrl-C`, SIGTERM ou SIGHUP : le serveur s'arrête, puis la sortie habituelle (déchargement, bail llama-server). | | ||
| 140 | + | ||
| 123 | ## Spécificités du mode ligne | 141 | ## Spécificités du mode ligne |
| 124 | 142 | ||
| 125 | | Aspect | Comportement | | 143 | | Aspect | Comportement | |
| @@ -296,6 +314,14 @@ Un fichier d'agent hors du workspace ne donne qu'un avertissement : voir [quand | |||
| 296 | | Après l'écriture | Les messages de `mm init` (`✅ wrote <fichier>`, `✅ mm loads it`), puis `mm acp <chemin absolu>`, un renvoi vers `/zedconfig`, et un vers `/dockerinit` et `/sbxinit` ; pour un client dont `clientInfo.name` contient `zed`, une entrée `agent_servers` en plus. Les prompts suivants répondent que le fichier est écrit. | | 314 | | Après l'écriture | Les messages de `mm init` (`✅ wrote <fichier>`, `✅ mm loads it`), puis `mm acp <chemin absolu>`, un renvoi vers `/zedconfig`, et un vers `/dockerinit` et `/sbxinit` ; pour un client dont `clientInfo.name` contient `zed`, une entrée `agent_servers` en plus. Les prompts suivants répondent que le fichier est écrit. | |
| 297 | | Codes de sortie | 0 le client a fermé la connexion, ou `-h` ; 1 une valeur d'option refusée ou des presets illisibles ; 2 une option inconnue. | | 315 | | Codes de sortie | 0 le client a fermé la connexion, ou `-h` ; 1 une valeur d'option refusée ou des presets illisibles ; 2 une option inconnue. | |
| 298 | 316 | ||
| 317 | +## `mm a2a-send` — un message à un agent A2A | ||
| 318 | + | ||
| 319 | +```text | ||
| 320 | +mm a2a-send [--context ID] [--token-env VAR] [--timeout D] <url de l'agent> [message] | ||
| 321 | +``` | ||
| 322 | + | ||
| 323 | +Envoie un message à un agent A2A (un autre `mm a2a`, ou tout agent qui parle A2A en JSON-RPC) et affiche sa réponse sur stdout ; le `contextId` de la conversation va sur stderr sous la forme `context: <id>`. `--context <id>` continue cette conversation. Le message est lu sur stdin quand il n'est pas donné. A2A 1.0 d'abord, puis 0.3 si l'agent ne connaît pas `SendMessage`. Aucun fichier de configuration ni modèle n'est lu. Codes de sortie : `0` réponse reçue, `1` l'agent ou le réseau a échoué, `2` usage. S'écrit aussi `--a2a-send`. Voir `demos/a2a-discussion/discussion.sh`. | ||
| 324 | + | ||
| 299 | ## `mm skillcreate` — l'assistant de skill | 325 | ## `mm skillcreate` — l'assistant de skill |
| 300 | 326 | ||
| 301 | `mm skillcreate` (aussi `--skillcreate`, `-skillcreate`) demande un skill et l'écrit dans `<skillsDir>/<nom>/SKILL.md`. Il répond avant qu'aucun agent ne démarre. Chaque question ci-dessous a une option ; une question dont l'option est donnée n'est pas posée. Voir [Comment ajouter un skill](../how-to/add-a-skill.md). | 327 | `mm skillcreate` (aussi `--skillcreate`, `-skillcreate`) demande un skill et l'écrit dans `<skillsDir>/<nom>/SKILL.md`. Il répond avant qu'aucun agent ne démarre. Chaque question ci-dessous a une option ; une question dont l'option est donnée n'est pas posée. Voir [Comment ajouter un skill](../how-to/add-a-skill.md). |
modified
docs/fr/reference/configuration.md +21 -0 | @@ -60,6 +60,7 @@ Où `mm` cherche ce fichier : [Résolution du fichier de configuration](cli.md#r | ||
| 60 | 60 | | `yolo` | booléen | `true` | `true` : les outils s'exécutent sans demander. `false` : chaque appel qui modifie quelque chose — `bash`, `write_file`, `edit_file`, `fetch_content` avec `output`, `rename` de `lsp`, `create`/`update`/`next`/`delete` de `plan` — attend la réponse de l'utilisateur dans toutes les façades (mode ligne, fenêtre, éditeur), de même que chaque outil MCP, quoi que dise `mcp.permissions`. Réponses : autoriser une fois, autoriser cet outil pour la session, refuser cet appel, jamais (cet outil, pour la session). `read_file`, `read_skill`, `fetch_content` sans `output` et les actions de navigation de `lsp` ne demandent jamais. Avec `-p` et `mm --ask`, personne ne peut répondre : ces appels sont refusés. Un agent lancé par `/ask`, `ask_agent` ou `mm --ask` tourne avec `AGENT_YOLO=false` et soumet ses appels à l'agent qui l'interroge : le `yolo` de son entrée `mmConfigs` décide s'il est fixé, sinon le `yolo` de l'agent qui interroge. Surchargée par `AGENT_YOLO`. `bashTool`, `editTools`, `fetchContentTool` décident toujours quels outils existent. Voir [Confirmer les appels d'outils](../how-to/confirm-tool-calls.md). | |
| 61 | 61 | | `permissions` | chaîne | absente | Obsolète, remplacée par `yolo`. `ask` = `yolo: false` (et l'emporte sur `yolo: true`) ; `auto` ne change rien. Les deux valeurs ajoutent un avertissement au démarrage. Doit valoir `auto` ou `ask`. | |
| 62 | 62 | | `mmConfigs` | dictionnaire nom → chemin, ou nom → `{path, description, yolo, askUser, unloadModels}` | aucun | Les autres agents mm que celui-ci peut interroger. Chaque nom génère `/ask-<nom>` et `/ask-with-context-<nom>` (voir les [commandes slash](slash-commands.md#interroger-un-autre-agent)), et la liste déclare l'outil [`ask_agent`](tools.md#ask_agent), par lequel le modèle les appelle lui-même. La forme longue ajoute `description` (quand appeler cet agent ; affichée dans la description d'`ask_agent`, à défaut l'`acp.title` du fichier de l'agent) et `yolo` (décide des appels d'outils de cet agent quand il est interrogé, par `/ask`, `ask_agent` ou `mm --ask`, à la place du `yolo` de cet agent-ci : `true` ils s'exécutent, `false` chacun est demandé ; absent, le `yolo` de cet agent-ci décide) et `askUser` (si cet agent peut poser des questions à l'utilisateur quand il est interrogé : `true` ses questions `ask_user` remontent à l'utilisateur de cet agent-ci, `false` son outil `ask_user` n'est pas déclaré ; absent, le `askUserTool` de cet agent décide) et `unloadModels` (`false` par défaut ; `true` : chaque passage de main à cet agent — `ask_agent`, `/ask…`, `mm --ask` — décharge le modèle de cet agent-ci juste avant que l'autre démarre, puis le modèle de l'autre une fois qu'il a répondu, avant que cet agent-ci lise la réponse : les deux modèles ne sont jamais chargés ensemble ; chaque déchargement est une notice `🧹`, un échec n'arrête pas le passage de main ; le modèle de cet agent-ci est déchargé sur son serveur, celui de l'autre sur le serveur que nomme son fichier ; `mm --ask` ne décharge que le modèle de l'autre ; à ne pas confondre avec la clé `unloadModels` de premier niveau, qui déclare `/unload` et `unload_model`). `path` ne doit pas être vide. Un chemin relatif l'est au dossier du fichier qui le déclare. Noms : lettres minuscules, chiffres et `-`, commençant par une lettre ou un chiffre, ne commençant pas par `with-context`. Un chemin dont le fichier n'existe pas donne un avertissement au démarrage, pas une erreur. | |
| 63 | +| `a2a` | `{host, port, description, tokenEnv, agents}` | `127.0.0.1:9100`, aucun agent | Le protocole Agent2Agent (ticket 243) : comment `mm a2a` sert cet agent, et les agents A2A distants auxquels son modèle parle par [`ask_a2a_agent`](tools.md#ask_a2a_agent). Voir [clés de `a2a`](#clés-de-a2a). | | |
| 63 | 64 | |
| 64 | 65 | ## Clés de `context` |
| 65 | 66 | |
| @@ -138,6 +139,26 @@ Non lu : un fichier absent, un fichier qui ne contient que des blancs, un fichie | ||
| 138 | 139 | |
| 139 | 140 | La version n'est pas paramétrable : `agentInfo.version` est toujours celle du binaire, telle qu'affichée par `mm --version`. |
| 140 | 141 | |
| 142 | +## Clés de `a2a` | |
| 143 | + | |
| 144 | +```yaml | |
| 145 | +a2a: | |
| 146 | + port: 9101 | |
| 147 | + description: "Alice, an optimist: she argues FOR the idea." | |
| 148 | + agents: | |
| 149 | + bob: | |
| 150 | + url: http://127.0.0.1:9102 | |
| 151 | + description: "Bob, a sceptic who argues against." | |
| 152 | +``` | |
| 153 | + | |
| 154 | +| Clé | Type | Défaut | Description | | |
| 155 | +|-----|------|--------|-------------| | |
| 156 | +| `host` | chaîne | `127.0.0.1` | L'adresse où `mm a2a` écoute. Gardez la boucle locale sauf si d'autres machines doivent l'appeler : un agent A2A exécute des outils pour quiconque l'appelle. | | |
| 157 | +| `port` | entier | `9100` | Son port ; `--a2a-port` le remplace. Entre 0 et 65535. | | |
| 158 | +| `description` | chaîne | `acp.title` | La description de l'Agent Card : ce que lisent de lui les agents qui l'appellent. | | |
| 159 | +| `tokenEnv` | chaîne | `""` | La variable qui contient le jeton que chaque appelant doit envoyer (`Authorization: Bearer …`) ; non définie au démarrage, `mm a2a` s'arrête. Vide : pas d'authentification. | | |
| 160 | +| `agents` | dictionnaire nom → `{url, description, tokenEnv}` | aucun | Les agents A2A distants auxquels le modèle peut parler : leur présence déclare [`ask_a2a_agent`](tools.md#ask_a2a_agent). `url` : l'adresse de l'agent (`http`/`https`). `description` : quand l'appeler, affichée dans la description de l'outil. `tokenEnv` : la variable qui contient son jeton, s'il en demande un. Noms : lettres minuscules, chiffres et `-`. | | |
| 161 | + | |
| 141 | 162 | ## Clés de `lsp` |
| 142 | 163 | |
| 143 | 164 | | Clé | Type | Défaut | Description | |
| @@ -60,6 +60,7 @@ Où `mm` cherche ce fichier : [Résolution du fichier de configuration](cli.md#r | |||
| 60 | | `yolo` | booléen | `true` | `true` : les outils s'exécutent sans demander. `false` : chaque appel qui modifie quelque chose — `bash`, `write_file`, `edit_file`, `fetch_content` avec `output`, `rename` de `lsp`, `create`/`update`/`next`/`delete` de `plan` — attend la réponse de l'utilisateur dans toutes les façades (mode ligne, fenêtre, éditeur), de même que chaque outil MCP, quoi que dise `mcp.permissions`. Réponses : autoriser une fois, autoriser cet outil pour la session, refuser cet appel, jamais (cet outil, pour la session). `read_file`, `read_skill`, `fetch_content` sans `output` et les actions de navigation de `lsp` ne demandent jamais. Avec `-p` et `mm --ask`, personne ne peut répondre : ces appels sont refusés. Un agent lancé par `/ask`, `ask_agent` ou `mm --ask` tourne avec `AGENT_YOLO=false` et soumet ses appels à l'agent qui l'interroge : le `yolo` de son entrée `mmConfigs` décide s'il est fixé, sinon le `yolo` de l'agent qui interroge. Surchargée par `AGENT_YOLO`. `bashTool`, `editTools`, `fetchContentTool` décident toujours quels outils existent. Voir [Confirmer les appels d'outils](../how-to/confirm-tool-calls.md). | | 60 | | `yolo` | booléen | `true` | `true` : les outils s'exécutent sans demander. `false` : chaque appel qui modifie quelque chose — `bash`, `write_file`, `edit_file`, `fetch_content` avec `output`, `rename` de `lsp`, `create`/`update`/`next`/`delete` de `plan` — attend la réponse de l'utilisateur dans toutes les façades (mode ligne, fenêtre, éditeur), de même que chaque outil MCP, quoi que dise `mcp.permissions`. Réponses : autoriser une fois, autoriser cet outil pour la session, refuser cet appel, jamais (cet outil, pour la session). `read_file`, `read_skill`, `fetch_content` sans `output` et les actions de navigation de `lsp` ne demandent jamais. Avec `-p` et `mm --ask`, personne ne peut répondre : ces appels sont refusés. Un agent lancé par `/ask`, `ask_agent` ou `mm --ask` tourne avec `AGENT_YOLO=false` et soumet ses appels à l'agent qui l'interroge : le `yolo` de son entrée `mmConfigs` décide s'il est fixé, sinon le `yolo` de l'agent qui interroge. Surchargée par `AGENT_YOLO`. `bashTool`, `editTools`, `fetchContentTool` décident toujours quels outils existent. Voir [Confirmer les appels d'outils](../how-to/confirm-tool-calls.md). | |
| 61 | | `permissions` | chaîne | absente | Obsolète, remplacée par `yolo`. `ask` = `yolo: false` (et l'emporte sur `yolo: true`) ; `auto` ne change rien. Les deux valeurs ajoutent un avertissement au démarrage. Doit valoir `auto` ou `ask`. | | 61 | | `permissions` | chaîne | absente | Obsolète, remplacée par `yolo`. `ask` = `yolo: false` (et l'emporte sur `yolo: true`) ; `auto` ne change rien. Les deux valeurs ajoutent un avertissement au démarrage. Doit valoir `auto` ou `ask`. | |
| 62 | | `mmConfigs` | dictionnaire nom → chemin, ou nom → `{path, description, yolo, askUser, unloadModels}` | aucun | Les autres agents mm que celui-ci peut interroger. Chaque nom génère `/ask-<nom>` et `/ask-with-context-<nom>` (voir les [commandes slash](slash-commands.md#interroger-un-autre-agent)), et la liste déclare l'outil [`ask_agent`](tools.md#ask_agent), par lequel le modèle les appelle lui-même. La forme longue ajoute `description` (quand appeler cet agent ; affichée dans la description d'`ask_agent`, à défaut l'`acp.title` du fichier de l'agent) et `yolo` (décide des appels d'outils de cet agent quand il est interrogé, par `/ask`, `ask_agent` ou `mm --ask`, à la place du `yolo` de cet agent-ci : `true` ils s'exécutent, `false` chacun est demandé ; absent, le `yolo` de cet agent-ci décide) et `askUser` (si cet agent peut poser des questions à l'utilisateur quand il est interrogé : `true` ses questions `ask_user` remontent à l'utilisateur de cet agent-ci, `false` son outil `ask_user` n'est pas déclaré ; absent, le `askUserTool` de cet agent décide) et `unloadModels` (`false` par défaut ; `true` : chaque passage de main à cet agent — `ask_agent`, `/ask…`, `mm --ask` — décharge le modèle de cet agent-ci juste avant que l'autre démarre, puis le modèle de l'autre une fois qu'il a répondu, avant que cet agent-ci lise la réponse : les deux modèles ne sont jamais chargés ensemble ; chaque déchargement est une notice `🧹`, un échec n'arrête pas le passage de main ; le modèle de cet agent-ci est déchargé sur son serveur, celui de l'autre sur le serveur que nomme son fichier ; `mm --ask` ne décharge que le modèle de l'autre ; à ne pas confondre avec la clé `unloadModels` de premier niveau, qui déclare `/unload` et `unload_model`). `path` ne doit pas être vide. Un chemin relatif l'est au dossier du fichier qui le déclare. Noms : lettres minuscules, chiffres et `-`, commençant par une lettre ou un chiffre, ne commençant pas par `with-context`. Un chemin dont le fichier n'existe pas donne un avertissement au démarrage, pas une erreur. | | 62 | | `mmConfigs` | dictionnaire nom → chemin, ou nom → `{path, description, yolo, askUser, unloadModels}` | aucun | Les autres agents mm que celui-ci peut interroger. Chaque nom génère `/ask-<nom>` et `/ask-with-context-<nom>` (voir les [commandes slash](slash-commands.md#interroger-un-autre-agent)), et la liste déclare l'outil [`ask_agent`](tools.md#ask_agent), par lequel le modèle les appelle lui-même. La forme longue ajoute `description` (quand appeler cet agent ; affichée dans la description d'`ask_agent`, à défaut l'`acp.title` du fichier de l'agent) et `yolo` (décide des appels d'outils de cet agent quand il est interrogé, par `/ask`, `ask_agent` ou `mm --ask`, à la place du `yolo` de cet agent-ci : `true` ils s'exécutent, `false` chacun est demandé ; absent, le `yolo` de cet agent-ci décide) et `askUser` (si cet agent peut poser des questions à l'utilisateur quand il est interrogé : `true` ses questions `ask_user` remontent à l'utilisateur de cet agent-ci, `false` son outil `ask_user` n'est pas déclaré ; absent, le `askUserTool` de cet agent décide) et `unloadModels` (`false` par défaut ; `true` : chaque passage de main à cet agent — `ask_agent`, `/ask…`, `mm --ask` — décharge le modèle de cet agent-ci juste avant que l'autre démarre, puis le modèle de l'autre une fois qu'il a répondu, avant que cet agent-ci lise la réponse : les deux modèles ne sont jamais chargés ensemble ; chaque déchargement est une notice `🧹`, un échec n'arrête pas le passage de main ; le modèle de cet agent-ci est déchargé sur son serveur, celui de l'autre sur le serveur que nomme son fichier ; `mm --ask` ne décharge que le modèle de l'autre ; à ne pas confondre avec la clé `unloadModels` de premier niveau, qui déclare `/unload` et `unload_model`). `path` ne doit pas être vide. Un chemin relatif l'est au dossier du fichier qui le déclare. Noms : lettres minuscules, chiffres et `-`, commençant par une lettre ou un chiffre, ne commençant pas par `with-context`. Un chemin dont le fichier n'existe pas donne un avertissement au démarrage, pas une erreur. | |
| 63 | +| `a2a` | `{host, port, description, tokenEnv, agents}` | `127.0.0.1:9100`, aucun agent | Le protocole Agent2Agent (ticket 243) : comment `mm a2a` sert cet agent, et les agents A2A distants auxquels son modèle parle par [`ask_a2a_agent`](tools.md#ask_a2a_agent). Voir [clés de `a2a`](#clés-de-a2a). | | ||
| 63 | 64 | ||
| 64 | ## Clés de `context` | 65 | ## Clés de `context` |
| 65 | 66 | ||
| @@ -138,6 +139,26 @@ Non lu : un fichier absent, un fichier qui ne contient que des blancs, un fichie | |||
| 138 | 139 | ||
| 139 | La version n'est pas paramétrable : `agentInfo.version` est toujours celle du binaire, telle qu'affichée par `mm --version`. | 140 | La version n'est pas paramétrable : `agentInfo.version` est toujours celle du binaire, telle qu'affichée par `mm --version`. |
| 140 | 141 | ||
| 142 | +## Clés de `a2a` | ||
| 143 | + | ||
| 144 | +```yaml | ||
| 145 | +a2a: | ||
| 146 | + port: 9101 | ||
| 147 | + description: "Alice, an optimist: she argues FOR the idea." | ||
| 148 | + agents: | ||
| 149 | + bob: | ||
| 150 | + url: http://127.0.0.1:9102 | ||
| 151 | + description: "Bob, a sceptic who argues against." | ||
| 152 | +``` | ||
| 153 | + | ||
| 154 | +| Clé | Type | Défaut | Description | | ||
| 155 | +|-----|------|--------|-------------| | ||
| 156 | +| `host` | chaîne | `127.0.0.1` | L'adresse où `mm a2a` écoute. Gardez la boucle locale sauf si d'autres machines doivent l'appeler : un agent A2A exécute des outils pour quiconque l'appelle. | | ||
| 157 | +| `port` | entier | `9100` | Son port ; `--a2a-port` le remplace. Entre 0 et 65535. | | ||
| 158 | +| `description` | chaîne | `acp.title` | La description de l'Agent Card : ce que lisent de lui les agents qui l'appellent. | | ||
| 159 | +| `tokenEnv` | chaîne | `""` | La variable qui contient le jeton que chaque appelant doit envoyer (`Authorization: Bearer …`) ; non définie au démarrage, `mm a2a` s'arrête. Vide : pas d'authentification. | | ||
| 160 | +| `agents` | dictionnaire nom → `{url, description, tokenEnv}` | aucun | Les agents A2A distants auxquels le modèle peut parler : leur présence déclare [`ask_a2a_agent`](tools.md#ask_a2a_agent). `url` : l'adresse de l'agent (`http`/`https`). `description` : quand l'appeler, affichée dans la description de l'outil. `tokenEnv` : la variable qui contient son jeton, s'il en demande un. Noms : lettres minuscules, chiffres et `-`. | | ||
| 161 | + | ||
| 141 | ## Clés de `lsp` | 162 | ## Clés de `lsp` |
| 142 | 163 | ||
| 143 | | Clé | Type | Défaut | Description | | 164 | | Clé | Type | Défaut | Description | |
modified
docs/fr/reference/tools.md +18 -0 | @@ -261,6 +261,24 @@ Déclaré quand `mmConfigs` nomme au moins un agent. Confie une tâche à l'un d | ||
| 261 | 261 | | Erreurs | `[ask_agent: unknown agent "x" — agents: a, b]` ; `[ask_agent: the prompt is empty — say what <agent> must do]` ; `[ask_agent: <agent> failed: <raison>]` ; `[ask_agent: <agent> gave no answer]` ; une exécution annulée ou interrompue renvoie ce qui a été répondu, puis `[ask_agent: <agent> stopped before finishing: <raison>]`. | |
| 262 | 262 | | Profondeur | Un agent interrogé peut lui-même avoir des `mmConfigs` et appeler `ask_agent`, jusqu'à deux niveaux (`MM_ASK_DEPTH`) ; au-delà, l'appel échoue avec le message de profondeur. | |
| 263 | 263 | |
| 264 | +## `ask_a2a_agent` | |
| 265 | + | |
| 266 | +Déclaré quand `a2a.agents` nomme au moins un agent. Envoie un message à un agent A2A distant et renvoie sa réponse (ticket 243). | |
| 267 | + | |
| 268 | +| Champ | Type | Défaut | Description | | |
| 269 | +|-------|------|--------|-------------| | |
| 270 | +| `agent` | chaîne | — | Le nom de l'agent, une clé de `a2a.agents`. | | |
| 271 | +| `message` | chaîne | — | Ce qu'on lui dit. Il ne voit que ce qu'on lui envoie, et ses propres réponses précédentes à cet agent. | | |
| 272 | +| `new_conversation` | booléen | `false` | `true` : commence une nouvelle conversation avec cet agent. | | |
| 273 | + | |
| 274 | +| Aspect | Comportement | | |
| 275 | +|--------|--------------| | |
| 276 | +| Conversation | Se poursuit d'un appel à l'autre : le `contextId` A2A est gardé par agent, pour la durée du processus. | | |
| 277 | +| Protocole | A2A 1.0 (`SendMessage`), puis 0.3 (`message/send`) si l'agent ne la connaît pas. Bloquant : attend la tâche terminée, jusqu'à 10 minutes ; le watchdog de la génération ne compte pas cette attente. | | |
| 278 | +| Résultat | La réponse de l'agent ; `[ask_a2a_agent: <agent> did not answer — <raison>]` en cas d'échec, `[ask_a2a_agent: no agent "<nom>" — use one of: …]` pour un nom inconnu. | | |
| 279 | +| Affichage terminal | `🤝 ask_a2a_agent: <agent>`, spinner `Waiting for <agent>`, puis la réponse affichée. | | |
| 280 | +| Consentement | Aucun : parler à un agent ne change rien ici (l'agent distant applique son propre `yolo`). | | |
| 281 | + | |
| 264 | 282 | ## `ask_user` |
| 265 | 283 | |
| 266 | 284 | Déclaré sauf avec `askUserTool: false` (actif par défaut), et jamais à côté d'un `structuredOutput`. Pose une à quatre questions à l'utilisateur et renvoie les réponses. Non soumis à `yolo` : poser une question ne modifie rien. |
| @@ -261,6 +261,24 @@ Déclaré quand `mmConfigs` nomme au moins un agent. Confie une tâche à l'un d | |||
| 261 | | Erreurs | `[ask_agent: unknown agent "x" — agents: a, b]` ; `[ask_agent: the prompt is empty — say what <agent> must do]` ; `[ask_agent: <agent> failed: <raison>]` ; `[ask_agent: <agent> gave no answer]` ; une exécution annulée ou interrompue renvoie ce qui a été répondu, puis `[ask_agent: <agent> stopped before finishing: <raison>]`. | | 261 | | Erreurs | `[ask_agent: unknown agent "x" — agents: a, b]` ; `[ask_agent: the prompt is empty — say what <agent> must do]` ; `[ask_agent: <agent> failed: <raison>]` ; `[ask_agent: <agent> gave no answer]` ; une exécution annulée ou interrompue renvoie ce qui a été répondu, puis `[ask_agent: <agent> stopped before finishing: <raison>]`. | |
| 262 | | Profondeur | Un agent interrogé peut lui-même avoir des `mmConfigs` et appeler `ask_agent`, jusqu'à deux niveaux (`MM_ASK_DEPTH`) ; au-delà, l'appel échoue avec le message de profondeur. | | 262 | | Profondeur | Un agent interrogé peut lui-même avoir des `mmConfigs` et appeler `ask_agent`, jusqu'à deux niveaux (`MM_ASK_DEPTH`) ; au-delà, l'appel échoue avec le message de profondeur. | |
| 263 | 263 | ||
| 264 | +## `ask_a2a_agent` | ||
| 265 | + | ||
| 266 | +Déclaré quand `a2a.agents` nomme au moins un agent. Envoie un message à un agent A2A distant et renvoie sa réponse (ticket 243). | ||
| 267 | + | ||
| 268 | +| Champ | Type | Défaut | Description | | ||
| 269 | +|-------|------|--------|-------------| | ||
| 270 | +| `agent` | chaîne | — | Le nom de l'agent, une clé de `a2a.agents`. | | ||
| 271 | +| `message` | chaîne | — | Ce qu'on lui dit. Il ne voit que ce qu'on lui envoie, et ses propres réponses précédentes à cet agent. | | ||
| 272 | +| `new_conversation` | booléen | `false` | `true` : commence une nouvelle conversation avec cet agent. | | ||
| 273 | + | ||
| 274 | +| Aspect | Comportement | | ||
| 275 | +|--------|--------------| | ||
| 276 | +| Conversation | Se poursuit d'un appel à l'autre : le `contextId` A2A est gardé par agent, pour la durée du processus. | | ||
| 277 | +| Protocole | A2A 1.0 (`SendMessage`), puis 0.3 (`message/send`) si l'agent ne la connaît pas. Bloquant : attend la tâche terminée, jusqu'à 10 minutes ; le watchdog de la génération ne compte pas cette attente. | | ||
| 278 | +| Résultat | La réponse de l'agent ; `[ask_a2a_agent: <agent> did not answer — <raison>]` en cas d'échec, `[ask_a2a_agent: no agent "<nom>" — use one of: …]` pour un nom inconnu. | | ||
| 279 | +| Affichage terminal | `🤝 ask_a2a_agent: <agent>`, spinner `Waiting for <agent>`, puis la réponse affichée. | | ||
| 280 | +| Consentement | Aucun : parler à un agent ne change rien ici (l'agent distant applique son propre `yolo`). | | ||
| 281 | + | ||
| 264 | ## `ask_user` | 282 | ## `ask_user` |
| 265 | 283 | ||
| 266 | Déclaré sauf avec `askUserTool: false` (actif par défaut), et jamais à côté d'un `structuredOutput`. Pose une à quatre questions à l'utilisateur et renvoie les réponses. Non soumis à `yolo` : poser une question ne modifie rien. | 284 | Déclaré sauf avec `askUserTool: false` (actif par défaut), et jamais à côté d'un `structuredOutput`. Pose une à quatre questions à l'utilisateur et renvoie les réponses. Non soumis à `yolo` : poser une question ne modifie rien. |
added
internal/a2a/a2a.go +275 -0 | new file mode 100644 | ||
| @@ -0,0 +1,275 @@ | ||
| 1 | +// Package a2a is the subset of the Agent2Agent protocol (A2A) mm speaks | |
| 2 | +// (ticket 243): JSON-RPC 2.0 over HTTP, text parts only, no streaming — in | |
| 3 | +// both versions in use, 1.0 (the current one) and 0.3: | |
| 4 | +// | |
| 5 | +// 1.0 0.3 | |
| 6 | +// send SendMessage message/send | |
| 7 | +// read a task GetTask tasks/get | |
| 8 | +// message role ROLE_USER, parts [{text}] kind, role user, parts [{kind:text,text}] | |
| 9 | +// answer {"task": {…TASK_STATE_COMPLETED}} the task, state completed | |
| 10 | +// | |
| 11 | +// (measured against the official Python a2a-sdk 1.3.1, 2026-11-25). | |
| 12 | +// | |
| 13 | +// - Server: an Agent Card at /.well-known/agent-card.json valid for both | |
| 14 | +// (supportedInterfaces for 1.0, url/protocolVersion for 0.3), and on | |
| 15 | +// POST / the four methods above, each answering in its version's shape. | |
| 16 | +// message/send is blocking: the answer is the finished task. A message's | |
| 17 | +// contextId names a conversation: the same contextId continues it, none | |
| 18 | +// starts one. Every other method is "method not found" (-32601). | |
| 19 | +// - Client: Send speaks 1.0 and falls back to 0.3 when the agent does not | |
| 20 | +// know SendMessage; it returns the agent's text and the conversation's | |
| 21 | +// contextId, to continue it with the next call. | |
| 22 | +// | |
| 23 | +// Hand-written, like the rest of mm's protocol edges: the subset is small, | |
| 24 | +// and a dependency for it would be larger than the code. | |
| 25 | +package a2a | |
| 26 | + | |
| 27 | +import ( | |
| 28 | + "crypto/rand" | |
| 29 | + "encoding/hex" | |
| 30 | + "encoding/json" | |
| 31 | + "strings" | |
| 32 | +) | |
| 33 | + | |
| 34 | +// ProtocolVersion is the version the card's 0.3 fields announce; | |
| 35 | +// ProtocolVersion1 the current one, in its supportedInterfaces. | |
| 36 | +const ( | |
| 37 | + ProtocolVersion = "0.3.0" | |
| 38 | + ProtocolVersion1 = "1.0" | |
| 39 | +) | |
| 40 | + | |
| 41 | +// CardPath is where an agent publishes its card; LegacyCardPath is the | |
| 42 | +// name older clients ask for. | |
| 43 | +const ( | |
| 44 | + CardPath = "/.well-known/agent-card.json" | |
| 45 | + LegacyCardPath = "/.well-known/agent.json" | |
| 46 | +) | |
| 47 | + | |
| 48 | +// Part is one piece of a message. Only text is produced; other kinds a | |
| 49 | +// client sends are ignored. | |
| 50 | +type Part struct { | |
| 51 | + Kind string `json:"kind"` | |
| 52 | + Text string `json:"text,omitempty"` | |
| 53 | +} | |
| 54 | + | |
| 55 | +// Message is a turn of a conversation: role "user" (the caller) or "agent". | |
| 56 | +type Message struct { | |
| 57 | + Kind string `json:"kind"` | |
| 58 | + Role string `json:"role"` | |
| 59 | + Parts []Part `json:"parts"` | |
| 60 | + MessageID string `json:"messageId"` | |
| 61 | + ContextID string `json:"contextId,omitempty"` | |
| 62 | + TaskID string `json:"taskId,omitempty"` | |
| 63 | +} | |
| 64 | + | |
| 65 | +// Text joins the message's text parts. | |
| 66 | +func (m Message) Text() string { return partsText(m.Parts) } | |
| 67 | + | |
| 68 | +func partsText(parts []Part) string { | |
| 69 | + var b strings.Builder | |
| 70 | + for _, p := range parts { | |
| 71 | + if p.Kind == "text" || (p.Kind == "" && p.Text != "") { | |
| 72 | + b.WriteString(p.Text) | |
| 73 | + } | |
| 74 | + } | |
| 75 | + return b.String() | |
| 76 | +} | |
| 77 | + | |
| 78 | +// The task states mm uses. | |
| 79 | +const ( | |
| 80 | + StateCompleted = "completed" | |
| 81 | + StateFailed = "failed" | |
| 82 | +) | |
| 83 | + | |
| 84 | +// TaskStatus is where a task stands; Message carries the agent's last word | |
| 85 | +// (the answer, or why it failed). | |
| 86 | +type TaskStatus struct { | |
| 87 | + State string `json:"state"` | |
| 88 | + Message *Message `json:"message,omitempty"` | |
| 89 | + Timestamp string `json:"timestamp,omitempty"` | |
| 90 | +} | |
| 91 | + | |
| 92 | +// Artifact is what a task produced: here, the answer. | |
| 93 | +type Artifact struct { | |
| 94 | + ArtifactID string `json:"artifactId"` | |
| 95 | + Name string `json:"name,omitempty"` | |
| 96 | + Parts []Part `json:"parts"` | |
| 97 | +} | |
| 98 | + | |
| 99 | +// Task is one message/send and its outcome. | |
| 100 | +type Task struct { | |
| 101 | + Kind string `json:"kind"` | |
| 102 | + ID string `json:"id"` | |
| 103 | + ContextID string `json:"contextId"` | |
| 104 | + Status TaskStatus `json:"status"` | |
| 105 | + Artifacts []Artifact `json:"artifacts,omitempty"` | |
| 106 | + History []Message `json:"history,omitempty"` | |
| 107 | +} | |
| 108 | + | |
| 109 | +// Answer is the agent's text: the artifacts', else the status message's. | |
| 110 | +func (t Task) Answer() string { | |
| 111 | + var b strings.Builder | |
| 112 | + for _, a := range t.Artifacts { | |
| 113 | + b.WriteString(partsText(a.Parts)) | |
| 114 | + } | |
| 115 | + if b.Len() == 0 && t.Status.Message != nil { | |
| 116 | + return t.Status.Message.Text() | |
| 117 | + } | |
| 118 | + return b.String() | |
| 119 | +} | |
| 120 | + | |
| 121 | +// Skill is one entry of an Agent Card's skills. | |
| 122 | +type Skill struct { | |
| 123 | + ID string `json:"id"` | |
| 124 | + Name string `json:"name"` | |
| 125 | + Description string `json:"description"` | |
| 126 | + Tags []string `json:"tags"` | |
| 127 | +} | |
| 128 | + | |
| 129 | +// Capabilities is what the agent supports beyond message/send. | |
| 130 | +type Capabilities struct { | |
| 131 | + Streaming bool `json:"streaming"` | |
| 132 | + PushNotifications bool `json:"pushNotifications"` | |
| 133 | +} | |
| 134 | + | |
| 135 | +// AgentCard describes an agent to its callers. | |
| 136 | +type AgentCard struct { | |
| 137 | + ProtocolVersion string `json:"protocolVersion"` | |
| 138 | + Name string `json:"name"` | |
| 139 | + Description string `json:"description"` | |
| 140 | + URL string `json:"url"` | |
| 141 | + PreferredTransport string `json:"preferredTransport"` | |
| 142 | + Version string `json:"version"` | |
| 143 | + Capabilities Capabilities `json:"capabilities"` | |
| 144 | + DefaultInputModes []string `json:"defaultInputModes"` | |
| 145 | + DefaultOutputModes []string `json:"defaultOutputModes"` | |
| 146 | + Skills []Skill `json:"skills"` | |
| 147 | + // SupportedInterfaces is the 1.0 card's list of endpoints. | |
| 148 | + SupportedInterfaces []AgentInterface `json:"supportedInterfaces,omitempty"` | |
| 149 | + SecuritySchemes map[string]any `json:"securitySchemes,omitempty"` | |
| 150 | + Security []map[string][]string `json:"security,omitempty"` | |
| 151 | +} | |
| 152 | + | |
| 153 | +// AgentInterface is one endpoint of a 1.0 card. | |
| 154 | +type AgentInterface struct { | |
| 155 | + URL string `json:"url"` | |
| 156 | + ProtocolBinding string `json:"protocolBinding"` | |
| 157 | + ProtocolVersion string `json:"protocolVersion"` | |
| 158 | +} | |
| 159 | + | |
| 160 | +// v1State maps mm's task states to 1.0's enum, and back. | |
| 161 | +var v1State = map[string]string{StateCompleted: "TASK_STATE_COMPLETED", StateFailed: "TASK_STATE_FAILED"} | |
| 162 | + | |
| 163 | +func fromV1State(s string) string { | |
| 164 | + for k, v := range v1State { | |
| 165 | + if v == s { | |
| 166 | + return k | |
| 167 | + } | |
| 168 | + } | |
| 169 | + return strings.ToLower(strings.TrimPrefix(s, "TASK_STATE_")) | |
| 170 | +} | |
| 171 | + | |
| 172 | +// v1Message is a message in 1.0's shape. | |
| 173 | +func v1Message(m *Message) map[string]any { | |
| 174 | + if m == nil { | |
| 175 | + return nil | |
| 176 | + } | |
| 177 | + role := "ROLE_AGENT" | |
| 178 | + if m.Role == "user" { | |
| 179 | + role = "ROLE_USER" | |
| 180 | + } | |
| 181 | + out := map[string]any{"messageId": m.MessageID, "role": role, "parts": v1Parts(m.Parts)} | |
| 182 | + if m.ContextID != "" { | |
| 183 | + out["contextId"] = m.ContextID | |
| 184 | + } | |
| 185 | + if m.TaskID != "" { | |
| 186 | + out["taskId"] = m.TaskID | |
| 187 | + } | |
| 188 | + return out | |
| 189 | +} | |
| 190 | + | |
| 191 | +func v1Parts(parts []Part) []map[string]any { | |
| 192 | + out := make([]map[string]any, 0, len(parts)) | |
| 193 | + for _, p := range parts { | |
| 194 | + out = append(out, map[string]any{"text": p.Text}) | |
| 195 | + } | |
| 196 | + return out | |
| 197 | +} | |
| 198 | + | |
| 199 | +// v1Task is a task in 1.0's shape. | |
| 200 | +func v1Task(t Task) map[string]any { | |
| 201 | + status := map[string]any{"state": v1State[t.Status.State]} | |
| 202 | + if t.Status.Message != nil { | |
| 203 | + status["message"] = v1Message(t.Status.Message) | |
| 204 | + } | |
| 205 | + if t.Status.Timestamp != "" { | |
| 206 | + status["timestamp"] = t.Status.Timestamp | |
| 207 | + } | |
| 208 | + out := map[string]any{"id": t.ID, "contextId": t.ContextID, "status": status} | |
| 209 | + var arts []map[string]any | |
| 210 | + for _, a := range t.Artifacts { | |
| 211 | + arts = append(arts, map[string]any{"artifactId": a.ArtifactID, "name": a.Name, "parts": v1Parts(a.Parts)}) | |
| 212 | + } | |
| 213 | + if arts != nil { | |
| 214 | + out["artifacts"] = arts | |
| 215 | + } | |
| 216 | + var hist []map[string]any | |
| 217 | + for i := range t.History { | |
| 218 | + hist = append(hist, v1Message(&t.History[i])) | |
| 219 | + } | |
| 220 | + if hist != nil { | |
| 221 | + out["history"] = hist | |
| 222 | + } | |
| 223 | + return out | |
| 224 | +} | |
| 225 | + | |
| 226 | +// rpcRequest and rpcResponse are JSON-RPC 2.0 envelopes. | |
| 227 | +type rpcRequest struct { | |
| 228 | + JSONRPC string `json:"jsonrpc"` | |
| 229 | + ID json.RawMessage `json:"id"` | |
| 230 | + Method string `json:"method"` | |
| 231 | + Params json.RawMessage `json:"params"` | |
| 232 | +} | |
| 233 | + | |
| 234 | +type rpcError struct { | |
| 235 | + Code int `json:"code"` | |
| 236 | + Message string `json:"message"` | |
| 237 | +} | |
| 238 | + | |
| 239 | +type rpcResponse struct { | |
| 240 | + JSONRPC string `json:"jsonrpc"` | |
| 241 | + ID json.RawMessage `json:"id"` | |
| 242 | + Result any `json:"result,omitempty"` | |
| 243 | + Error *rpcError `json:"error,omitempty"` | |
| 244 | +} | |
| 245 | + | |
| 246 | +// The JSON-RPC and A2A error codes mm returns. | |
| 247 | +const ( | |
| 248 | + codeParse = -32700 | |
| 249 | + codeInvalidRequest = -32600 | |
| 250 | + codeMethodNotFound = -32601 | |
| 251 | + codeInvalidParams = -32602 | |
| 252 | + codeTaskNotFound = -32001 | |
| 253 | +) | |
| 254 | + | |
| 255 | +// messageSendParams is message/send's params. | |
| 256 | +type messageSendParams struct { | |
| 257 | + Message Message `json:"message"` | |
| 258 | +} | |
| 259 | + | |
| 260 | +// taskQueryParams is tasks/get's params. | |
| 261 | +type taskQueryParams struct { | |
| 262 | + ID string `json:"id"` | |
| 263 | +} | |
| 264 | + | |
| 265 | +// NewID is a random identifier for messages, tasks and contexts. | |
| 266 | +func NewID() string { | |
| 267 | + var b [16]byte | |
| 268 | + _, _ = rand.Read(b[:]) | |
| 269 | + return hex.EncodeToString(b[:]) | |
| 270 | +} | |
| 271 | + | |
| 272 | +// TextMessage is a message of one text part. | |
| 273 | +func TextMessage(role, text, contextID string) Message { | |
| 274 | + return Message{Kind: "message", Role: role, Parts: []Part{{Kind: "text", Text: text}}, MessageID: NewID(), ContextID: contextID} | |
| 275 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,275 @@ | |||
| 1 | +// Package a2a is the subset of the Agent2Agent protocol (A2A) mm speaks | ||
| 2 | +// (ticket 243): JSON-RPC 2.0 over HTTP, text parts only, no streaming — in | ||
| 3 | +// both versions in use, 1.0 (the current one) and 0.3: | ||
| 4 | +// | ||
| 5 | +// 1.0 0.3 | ||
| 6 | +// send SendMessage message/send | ||
| 7 | +// read a task GetTask tasks/get | ||
| 8 | +// message role ROLE_USER, parts [{text}] kind, role user, parts [{kind:text,text}] | ||
| 9 | +// answer {"task": {…TASK_STATE_COMPLETED}} the task, state completed | ||
| 10 | +// | ||
| 11 | +// (measured against the official Python a2a-sdk 1.3.1, 2026-11-25). | ||
| 12 | +// | ||
| 13 | +// - Server: an Agent Card at /.well-known/agent-card.json valid for both | ||
| 14 | +// (supportedInterfaces for 1.0, url/protocolVersion for 0.3), and on | ||
| 15 | +// POST / the four methods above, each answering in its version's shape. | ||
| 16 | +// message/send is blocking: the answer is the finished task. A message's | ||
| 17 | +// contextId names a conversation: the same contextId continues it, none | ||
| 18 | +// starts one. Every other method is "method not found" (-32601). | ||
| 19 | +// - Client: Send speaks 1.0 and falls back to 0.3 when the agent does not | ||
| 20 | +// know SendMessage; it returns the agent's text and the conversation's | ||
| 21 | +// contextId, to continue it with the next call. | ||
| 22 | +// | ||
| 23 | +// Hand-written, like the rest of mm's protocol edges: the subset is small, | ||
| 24 | +// and a dependency for it would be larger than the code. | ||
| 25 | +package a2a | ||
| 26 | + | ||
| 27 | +import ( | ||
| 28 | + "crypto/rand" | ||
| 29 | + "encoding/hex" | ||
| 30 | + "encoding/json" | ||
| 31 | + "strings" | ||
| 32 | +) | ||
| 33 | + | ||
| 34 | +// ProtocolVersion is the version the card's 0.3 fields announce; | ||
| 35 | +// ProtocolVersion1 the current one, in its supportedInterfaces. | ||
| 36 | +const ( | ||
| 37 | + ProtocolVersion = "0.3.0" | ||
| 38 | + ProtocolVersion1 = "1.0" | ||
| 39 | +) | ||
| 40 | + | ||
| 41 | +// CardPath is where an agent publishes its card; LegacyCardPath is the | ||
| 42 | +// name older clients ask for. | ||
| 43 | +const ( | ||
| 44 | + CardPath = "/.well-known/agent-card.json" | ||
| 45 | + LegacyCardPath = "/.well-known/agent.json" | ||
| 46 | +) | ||
| 47 | + | ||
| 48 | +// Part is one piece of a message. Only text is produced; other kinds a | ||
| 49 | +// client sends are ignored. | ||
| 50 | +type Part struct { | ||
| 51 | + Kind string `json:"kind"` | ||
| 52 | + Text string `json:"text,omitempty"` | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +// Message is a turn of a conversation: role "user" (the caller) or "agent". | ||
| 56 | +type Message struct { | ||
| 57 | + Kind string `json:"kind"` | ||
| 58 | + Role string `json:"role"` | ||
| 59 | + Parts []Part `json:"parts"` | ||
| 60 | + MessageID string `json:"messageId"` | ||
| 61 | + ContextID string `json:"contextId,omitempty"` | ||
| 62 | + TaskID string `json:"taskId,omitempty"` | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +// Text joins the message's text parts. | ||
| 66 | +func (m Message) Text() string { return partsText(m.Parts) } | ||
| 67 | + | ||
| 68 | +func partsText(parts []Part) string { | ||
| 69 | + var b strings.Builder | ||
| 70 | + for _, p := range parts { | ||
| 71 | + if p.Kind == "text" || (p.Kind == "" && p.Text != "") { | ||
| 72 | + b.WriteString(p.Text) | ||
| 73 | + } | ||
| 74 | + } | ||
| 75 | + return b.String() | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +// The task states mm uses. | ||
| 79 | +const ( | ||
| 80 | + StateCompleted = "completed" | ||
| 81 | + StateFailed = "failed" | ||
| 82 | +) | ||
| 83 | + | ||
| 84 | +// TaskStatus is where a task stands; Message carries the agent's last word | ||
| 85 | +// (the answer, or why it failed). | ||
| 86 | +type TaskStatus struct { | ||
| 87 | + State string `json:"state"` | ||
| 88 | + Message *Message `json:"message,omitempty"` | ||
| 89 | + Timestamp string `json:"timestamp,omitempty"` | ||
| 90 | +} | ||
| 91 | + | ||
| 92 | +// Artifact is what a task produced: here, the answer. | ||
| 93 | +type Artifact struct { | ||
| 94 | + ArtifactID string `json:"artifactId"` | ||
| 95 | + Name string `json:"name,omitempty"` | ||
| 96 | + Parts []Part `json:"parts"` | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +// Task is one message/send and its outcome. | ||
| 100 | +type Task struct { | ||
| 101 | + Kind string `json:"kind"` | ||
| 102 | + ID string `json:"id"` | ||
| 103 | + ContextID string `json:"contextId"` | ||
| 104 | + Status TaskStatus `json:"status"` | ||
| 105 | + Artifacts []Artifact `json:"artifacts,omitempty"` | ||
| 106 | + History []Message `json:"history,omitempty"` | ||
| 107 | +} | ||
| 108 | + | ||
| 109 | +// Answer is the agent's text: the artifacts', else the status message's. | ||
| 110 | +func (t Task) Answer() string { | ||
| 111 | + var b strings.Builder | ||
| 112 | + for _, a := range t.Artifacts { | ||
| 113 | + b.WriteString(partsText(a.Parts)) | ||
| 114 | + } | ||
| 115 | + if b.Len() == 0 && t.Status.Message != nil { | ||
| 116 | + return t.Status.Message.Text() | ||
| 117 | + } | ||
| 118 | + return b.String() | ||
| 119 | +} | ||
| 120 | + | ||
| 121 | +// Skill is one entry of an Agent Card's skills. | ||
| 122 | +type Skill struct { | ||
| 123 | + ID string `json:"id"` | ||
| 124 | + Name string `json:"name"` | ||
| 125 | + Description string `json:"description"` | ||
| 126 | + Tags []string `json:"tags"` | ||
| 127 | +} | ||
| 128 | + | ||
| 129 | +// Capabilities is what the agent supports beyond message/send. | ||
| 130 | +type Capabilities struct { | ||
| 131 | + Streaming bool `json:"streaming"` | ||
| 132 | + PushNotifications bool `json:"pushNotifications"` | ||
| 133 | +} | ||
| 134 | + | ||
| 135 | +// AgentCard describes an agent to its callers. | ||
| 136 | +type AgentCard struct { | ||
| 137 | + ProtocolVersion string `json:"protocolVersion"` | ||
| 138 | + Name string `json:"name"` | ||
| 139 | + Description string `json:"description"` | ||
| 140 | + URL string `json:"url"` | ||
| 141 | + PreferredTransport string `json:"preferredTransport"` | ||
| 142 | + Version string `json:"version"` | ||
| 143 | + Capabilities Capabilities `json:"capabilities"` | ||
| 144 | + DefaultInputModes []string `json:"defaultInputModes"` | ||
| 145 | + DefaultOutputModes []string `json:"defaultOutputModes"` | ||
| 146 | + Skills []Skill `json:"skills"` | ||
| 147 | + // SupportedInterfaces is the 1.0 card's list of endpoints. | ||
| 148 | + SupportedInterfaces []AgentInterface `json:"supportedInterfaces,omitempty"` | ||
| 149 | + SecuritySchemes map[string]any `json:"securitySchemes,omitempty"` | ||
| 150 | + Security []map[string][]string `json:"security,omitempty"` | ||
| 151 | +} | ||
| 152 | + | ||
| 153 | +// AgentInterface is one endpoint of a 1.0 card. | ||
| 154 | +type AgentInterface struct { | ||
| 155 | + URL string `json:"url"` | ||
| 156 | + ProtocolBinding string `json:"protocolBinding"` | ||
| 157 | + ProtocolVersion string `json:"protocolVersion"` | ||
| 158 | +} | ||
| 159 | + | ||
| 160 | +// v1State maps mm's task states to 1.0's enum, and back. | ||
| 161 | +var v1State = map[string]string{StateCompleted: "TASK_STATE_COMPLETED", StateFailed: "TASK_STATE_FAILED"} | ||
| 162 | + | ||
| 163 | +func fromV1State(s string) string { | ||
| 164 | + for k, v := range v1State { | ||
| 165 | + if v == s { | ||
| 166 | + return k | ||
| 167 | + } | ||
| 168 | + } | ||
| 169 | + return strings.ToLower(strings.TrimPrefix(s, "TASK_STATE_")) | ||
| 170 | +} | ||
| 171 | + | ||
| 172 | +// v1Message is a message in 1.0's shape. | ||
| 173 | +func v1Message(m *Message) map[string]any { | ||
| 174 | + if m == nil { | ||
| 175 | + return nil | ||
| 176 | + } | ||
| 177 | + role := "ROLE_AGENT" | ||
| 178 | + if m.Role == "user" { | ||
| 179 | + role = "ROLE_USER" | ||
| 180 | + } | ||
| 181 | + out := map[string]any{"messageId": m.MessageID, "role": role, "parts": v1Parts(m.Parts)} | ||
| 182 | + if m.ContextID != "" { | ||
| 183 | + out["contextId"] = m.ContextID | ||
| 184 | + } | ||
| 185 | + if m.TaskID != "" { | ||
| 186 | + out["taskId"] = m.TaskID | ||
| 187 | + } | ||
| 188 | + return out | ||
| 189 | +} | ||
| 190 | + | ||
| 191 | +func v1Parts(parts []Part) []map[string]any { | ||
| 192 | + out := make([]map[string]any, 0, len(parts)) | ||
| 193 | + for _, p := range parts { | ||
| 194 | + out = append(out, map[string]any{"text": p.Text}) | ||
| 195 | + } | ||
| 196 | + return out | ||
| 197 | +} | ||
| 198 | + | ||
| 199 | +// v1Task is a task in 1.0's shape. | ||
| 200 | +func v1Task(t Task) map[string]any { | ||
| 201 | + status := map[string]any{"state": v1State[t.Status.State]} | ||
| 202 | + if t.Status.Message != nil { | ||
| 203 | + status["message"] = v1Message(t.Status.Message) | ||
| 204 | + } | ||
| 205 | + if t.Status.Timestamp != "" { | ||
| 206 | + status["timestamp"] = t.Status.Timestamp | ||
| 207 | + } | ||
| 208 | + out := map[string]any{"id": t.ID, "contextId": t.ContextID, "status": status} | ||
| 209 | + var arts []map[string]any | ||
| 210 | + for _, a := range t.Artifacts { | ||
| 211 | + arts = append(arts, map[string]any{"artifactId": a.ArtifactID, "name": a.Name, "parts": v1Parts(a.Parts)}) | ||
| 212 | + } | ||
| 213 | + if arts != nil { | ||
| 214 | + out["artifacts"] = arts | ||
| 215 | + } | ||
| 216 | + var hist []map[string]any | ||
| 217 | + for i := range t.History { | ||
| 218 | + hist = append(hist, v1Message(&t.History[i])) | ||
| 219 | + } | ||
| 220 | + if hist != nil { | ||
| 221 | + out["history"] = hist | ||
| 222 | + } | ||
| 223 | + return out | ||
| 224 | +} | ||
| 225 | + | ||
| 226 | +// rpcRequest and rpcResponse are JSON-RPC 2.0 envelopes. | ||
| 227 | +type rpcRequest struct { | ||
| 228 | + JSONRPC string `json:"jsonrpc"` | ||
| 229 | + ID json.RawMessage `json:"id"` | ||
| 230 | + Method string `json:"method"` | ||
| 231 | + Params json.RawMessage `json:"params"` | ||
| 232 | +} | ||
| 233 | + | ||
| 234 | +type rpcError struct { | ||
| 235 | + Code int `json:"code"` | ||
| 236 | + Message string `json:"message"` | ||
| 237 | +} | ||
| 238 | + | ||
| 239 | +type rpcResponse struct { | ||
| 240 | + JSONRPC string `json:"jsonrpc"` | ||
| 241 | + ID json.RawMessage `json:"id"` | ||
| 242 | + Result any `json:"result,omitempty"` | ||
| 243 | + Error *rpcError `json:"error,omitempty"` | ||
| 244 | +} | ||
| 245 | + | ||
| 246 | +// The JSON-RPC and A2A error codes mm returns. | ||
| 247 | +const ( | ||
| 248 | + codeParse = -32700 | ||
| 249 | + codeInvalidRequest = -32600 | ||
| 250 | + codeMethodNotFound = -32601 | ||
| 251 | + codeInvalidParams = -32602 | ||
| 252 | + codeTaskNotFound = -32001 | ||
| 253 | +) | ||
| 254 | + | ||
| 255 | +// messageSendParams is message/send's params. | ||
| 256 | +type messageSendParams struct { | ||
| 257 | + Message Message `json:"message"` | ||
| 258 | +} | ||
| 259 | + | ||
| 260 | +// taskQueryParams is tasks/get's params. | ||
| 261 | +type taskQueryParams struct { | ||
| 262 | + ID string `json:"id"` | ||
| 263 | +} | ||
| 264 | + | ||
| 265 | +// NewID is a random identifier for messages, tasks and contexts. | ||
| 266 | +func NewID() string { | ||
| 267 | + var b [16]byte | ||
| 268 | + _, _ = rand.Read(b[:]) | ||
| 269 | + return hex.EncodeToString(b[:]) | ||
| 270 | +} | ||
| 271 | + | ||
| 272 | +// TextMessage is a message of one text part. | ||
| 273 | +func TextMessage(role, text, contextID string) Message { | ||
| 274 | + return Message{Kind: "message", Role: role, Parts: []Part{{Kind: "text", Text: text}}, MessageID: NewID(), ContextID: contextID} | ||
| 275 | +} | ||
added
internal/a2a/a2a_test.go +162 -0 | new file mode 100644 | ||
| @@ -0,0 +1,162 @@ | ||
| 1 | +package a2a | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "bytes" | |
| 5 | + "context" | |
| 6 | + "encoding/json" | |
| 7 | + "errors" | |
| 8 | + "net/http" | |
| 9 | + "net/http/httptest" | |
| 10 | + "strings" | |
| 11 | + "testing" | |
| 12 | +) | |
| 13 | + | |
| 14 | +// echo is a handler that remembers each conversation's messages. | |
| 15 | +func echo() (Handler, map[string][]string) { | |
| 16 | + seen := map[string][]string{} | |
| 17 | + return func(_ context.Context, contextID, text string) (string, error) { | |
| 18 | + if text == "fail" { | |
| 19 | + return "", errors.New("the model is down") | |
| 20 | + } | |
| 21 | + seen[contextID] = append(seen[contextID], text) | |
| 22 | + return strings.Join(seen[contextID], " | "), nil | |
| 23 | + }, seen | |
| 24 | +} | |
| 25 | + | |
| 26 | +func serve(t *testing.T, token string) (*httptest.Server, map[string][]string) { | |
| 27 | + t.Helper() | |
| 28 | + h, seen := echo() | |
| 29 | + srv := httptest.NewServer(NewServer(AgentCard{Name: "alice", Description: "an optimist", Version: "1"}, h, token)) | |
| 30 | + t.Cleanup(srv.Close) | |
| 31 | + return srv, seen | |
| 32 | +} | |
| 33 | + | |
| 34 | +func TestCardIsPublished(t *testing.T) { | |
| 35 | + srv, _ := serve(t, "") | |
| 36 | + for _, path := range []string{CardPath, LegacyCardPath} { | |
| 37 | + card, err := Client{}.Card(context.Background(), srv.URL) | |
| 38 | + if err != nil || card.Name != "alice" || card.ProtocolVersion != ProtocolVersion || card.PreferredTransport != "JSONRPC" || card.Capabilities.Streaming { | |
| 39 | + t.Errorf("%s: %+v, %v", path, card, err) | |
| 40 | + } | |
| 41 | + } | |
| 42 | +} | |
| 43 | + | |
| 44 | +// The contextId the agent returns continues the same conversation; none | |
| 45 | +// starts a new one. | |
| 46 | +func TestSendContinuesAConversation(t *testing.T) { | |
| 47 | + srv, seen := serve(t, "") | |
| 48 | + c := Client{} | |
| 49 | + a1, ctxID, err := c.Send(context.Background(), srv.URL, "", "", "hello") | |
| 50 | + if err != nil || a1 != "hello" || ctxID == "" { | |
| 51 | + t.Fatalf("first: %q %q %v", a1, ctxID, err) | |
| 52 | + } | |
| 53 | + a2, ctxID2, err := c.Send(context.Background(), srv.URL, "", ctxID, "again") | |
| 54 | + if err != nil || a2 != "hello | again" || ctxID2 != ctxID { | |
| 55 | + t.Fatalf("second: %q %q %v", a2, ctxID2, err) | |
| 56 | + } | |
| 57 | + if _, other, _ := c.Send(context.Background(), srv.URL, "", "", "new"); other == ctxID || len(seen) != 2 { | |
| 58 | + t.Errorf("a new conversation reused %s (%d conversations)", other, len(seen)) | |
| 59 | + } | |
| 60 | +} | |
| 61 | + | |
| 62 | +func TestFailedTaskAndErrors(t *testing.T) { | |
| 63 | + srv, _ := serve(t, "") | |
| 64 | + if _, _, err := (Client{}).Send(context.Background(), srv.URL, "", "", "fail"); err == nil || !strings.Contains(err.Error(), "the model is down") { | |
| 65 | + t.Errorf("failed task: %v", err) | |
| 66 | + } | |
| 67 | + call := func(body string) map[string]any { | |
| 68 | + resp, err := http.Post(srv.URL+"/", "application/json", bytes.NewBufferString(body)) | |
| 69 | + if err != nil { | |
| 70 | + t.Fatal(err) | |
| 71 | + } | |
| 72 | + defer resp.Body.Close() | |
| 73 | + var out map[string]any | |
| 74 | + _ = json.NewDecoder(resp.Body).Decode(&out) | |
| 75 | + return out | |
| 76 | + } | |
| 77 | + if e := call(`{"jsonrpc":"2.0","id":1,"method":"message/stream","params":{}}`)["error"].(map[string]any); e["code"].(float64) != codeMethodNotFound { | |
| 78 | + t.Errorf("unknown method: %v", e) | |
| 79 | + } | |
| 80 | + if e := call(`not json`)["error"].(map[string]any); e["code"].(float64) != codeParse { | |
| 81 | + t.Errorf("parse error: %v", e) | |
| 82 | + } | |
| 83 | + if e := call(`{"jsonrpc":"2.0","id":2,"method":"tasks/get","params":{"id":"nope"}}`)["error"].(map[string]any); e["code"].(float64) != codeTaskNotFound { | |
| 84 | + t.Errorf("tasks/get: %v", e) | |
| 85 | + } | |
| 86 | + // A task once sent can be read back. | |
| 87 | + out := call(`{"jsonrpc":"2.0","id":3,"method":"message/send","params":{"message":{"kind":"message","role":"user","messageId":"m1","parts":[{"kind":"text","text":"hi"}]}}}`) | |
| 88 | + id := out["result"].(map[string]any)["id"].(string) | |
| 89 | + got := call(`{"jsonrpc":"2.0","id":4,"method":"tasks/get","params":{"id":"` + id + `"}}`)["result"].(map[string]any) | |
| 90 | + if got["status"].(map[string]any)["state"] != StateCompleted { | |
| 91 | + t.Errorf("tasks/get: %v", got) | |
| 92 | + } | |
| 93 | +} | |
| 94 | + | |
| 95 | +// With a token, JSON-RPC needs it; the card stays readable and says so. | |
| 96 | +func TestBearerToken(t *testing.T) { | |
| 97 | + srv, _ := serve(t, "s3cret") | |
| 98 | + if _, _, err := (Client{}).Send(context.Background(), srv.URL, "", "", "hi"); err == nil || !strings.Contains(err.Error(), "401") { | |
| 99 | + t.Errorf("no token: %v", err) | |
| 100 | + } | |
| 101 | + if a, _, err := (Client{}).Send(context.Background(), srv.URL, "s3cret", "", "hi"); err != nil || a != "hi" { | |
| 102 | + t.Errorf("token: %q %v", a, err) | |
| 103 | + } | |
| 104 | + card, err := Client{}.Card(context.Background(), srv.URL) | |
| 105 | + if err != nil || len(card.Security) != 1 { | |
| 106 | + t.Errorf("card: %+v %v", card, err) | |
| 107 | + } | |
| 108 | +} | |
| 109 | + | |
| 110 | +// An agent that only speaks 0.3: SendMessage is "method not found", the | |
| 111 | +// client falls back to message/send. | |
| 112 | +func TestClientFallsBackTo03(t *testing.T) { | |
| 113 | + var methods []string | |
| 114 | + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 115 | + var req struct { | |
| 116 | + ID json.RawMessage `json:"id"` | |
| 117 | + Method string `json:"method"` | |
| 118 | + } | |
| 119 | + _ = json.NewDecoder(r.Body).Decode(&req) | |
| 120 | + methods = append(methods, req.Method) | |
| 121 | + if req.Method == "SendMessage" { | |
| 122 | + _, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":` + string(req.ID) + `,"error":{"code":-32601,"message":"Method not found"}}`)) | |
| 123 | + return | |
| 124 | + } | |
| 125 | + _, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":` + string(req.ID) + `,"result":{"kind":"task","id":"t","contextId":"c9","status":{"state":"completed"},"artifacts":[{"artifactId":"a","parts":[{"kind":"text","text":"old agent"}]}]}}`)) | |
| 126 | + })) | |
| 127 | + t.Cleanup(srv.Close) | |
| 128 | + answer, ctxID, err := Client{}.Send(context.Background(), srv.URL, "", "", "hi") | |
| 129 | + if err != nil || answer != "old agent" || ctxID != "c9" || strings.Join(methods, ",") != "SendMessage,message/send" { | |
| 130 | + t.Errorf("%q %q %v, methods %v", answer, ctxID, err, methods) | |
| 131 | + } | |
| 132 | +} | |
| 133 | + | |
| 134 | +// mm's server answers 1.0's SendMessage in 1.0's shape. | |
| 135 | +func TestServerSpeaks10(t *testing.T) { | |
| 136 | + srv, _ := serve(t, "") | |
| 137 | + resp, err := http.Post(srv.URL+"/", "application/json", bytes.NewBufferString(`{"jsonrpc":"2.0","id":"1","method":"SendMessage","params":{"message":{"messageId":"m1","role":"ROLE_USER","parts":[{"text":"hi"}]}}}`)) | |
| 138 | + if err != nil { | |
| 139 | + t.Fatal(err) | |
| 140 | + } | |
| 141 | + defer resp.Body.Close() | |
| 142 | + var out struct { | |
| 143 | + Result struct { | |
| 144 | + Task struct { | |
| 145 | + ContextID string `json:"contextId"` | |
| 146 | + Status struct { | |
| 147 | + State string `json:"state"` | |
| 148 | + } `json:"status"` | |
| 149 | + Artifacts []struct { | |
| 150 | + Parts []struct { | |
| 151 | + Text string `json:"text"` | |
| 152 | + } `json:"parts"` | |
| 153 | + } `json:"artifacts"` | |
| 154 | + } `json:"task"` | |
| 155 | + } `json:"result"` | |
| 156 | + } | |
| 157 | + _ = json.NewDecoder(resp.Body).Decode(&out) | |
| 158 | + task := out.Result.Task | |
| 159 | + if task.Status.State != "TASK_STATE_COMPLETED" || task.ContextID == "" || len(task.Artifacts) != 1 || task.Artifacts[0].Parts[0].Text != "hi" { | |
| 160 | + t.Errorf("1.0 answer: %+v", task) | |
| 161 | + } | |
| 162 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,162 @@ | |||
| 1 | +package a2a | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "bytes" | ||
| 5 | + "context" | ||
| 6 | + "encoding/json" | ||
| 7 | + "errors" | ||
| 8 | + "net/http" | ||
| 9 | + "net/http/httptest" | ||
| 10 | + "strings" | ||
| 11 | + "testing" | ||
| 12 | +) | ||
| 13 | + | ||
| 14 | +// echo is a handler that remembers each conversation's messages. | ||
| 15 | +func echo() (Handler, map[string][]string) { | ||
| 16 | + seen := map[string][]string{} | ||
| 17 | + return func(_ context.Context, contextID, text string) (string, error) { | ||
| 18 | + if text == "fail" { | ||
| 19 | + return "", errors.New("the model is down") | ||
| 20 | + } | ||
| 21 | + seen[contextID] = append(seen[contextID], text) | ||
| 22 | + return strings.Join(seen[contextID], " | "), nil | ||
| 23 | + }, seen | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +func serve(t *testing.T, token string) (*httptest.Server, map[string][]string) { | ||
| 27 | + t.Helper() | ||
| 28 | + h, seen := echo() | ||
| 29 | + srv := httptest.NewServer(NewServer(AgentCard{Name: "alice", Description: "an optimist", Version: "1"}, h, token)) | ||
| 30 | + t.Cleanup(srv.Close) | ||
| 31 | + return srv, seen | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +func TestCardIsPublished(t *testing.T) { | ||
| 35 | + srv, _ := serve(t, "") | ||
| 36 | + for _, path := range []string{CardPath, LegacyCardPath} { | ||
| 37 | + card, err := Client{}.Card(context.Background(), srv.URL) | ||
| 38 | + if err != nil || card.Name != "alice" || card.ProtocolVersion != ProtocolVersion || card.PreferredTransport != "JSONRPC" || card.Capabilities.Streaming { | ||
| 39 | + t.Errorf("%s: %+v, %v", path, card, err) | ||
| 40 | + } | ||
| 41 | + } | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +// The contextId the agent returns continues the same conversation; none | ||
| 45 | +// starts a new one. | ||
| 46 | +func TestSendContinuesAConversation(t *testing.T) { | ||
| 47 | + srv, seen := serve(t, "") | ||
| 48 | + c := Client{} | ||
| 49 | + a1, ctxID, err := c.Send(context.Background(), srv.URL, "", "", "hello") | ||
| 50 | + if err != nil || a1 != "hello" || ctxID == "" { | ||
| 51 | + t.Fatalf("first: %q %q %v", a1, ctxID, err) | ||
| 52 | + } | ||
| 53 | + a2, ctxID2, err := c.Send(context.Background(), srv.URL, "", ctxID, "again") | ||
| 54 | + if err != nil || a2 != "hello | again" || ctxID2 != ctxID { | ||
| 55 | + t.Fatalf("second: %q %q %v", a2, ctxID2, err) | ||
| 56 | + } | ||
| 57 | + if _, other, _ := c.Send(context.Background(), srv.URL, "", "", "new"); other == ctxID || len(seen) != 2 { | ||
| 58 | + t.Errorf("a new conversation reused %s (%d conversations)", other, len(seen)) | ||
| 59 | + } | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +func TestFailedTaskAndErrors(t *testing.T) { | ||
| 63 | + srv, _ := serve(t, "") | ||
| 64 | + if _, _, err := (Client{}).Send(context.Background(), srv.URL, "", "", "fail"); err == nil || !strings.Contains(err.Error(), "the model is down") { | ||
| 65 | + t.Errorf("failed task: %v", err) | ||
| 66 | + } | ||
| 67 | + call := func(body string) map[string]any { | ||
| 68 | + resp, err := http.Post(srv.URL+"/", "application/json", bytes.NewBufferString(body)) | ||
| 69 | + if err != nil { | ||
| 70 | + t.Fatal(err) | ||
| 71 | + } | ||
| 72 | + defer resp.Body.Close() | ||
| 73 | + var out map[string]any | ||
| 74 | + _ = json.NewDecoder(resp.Body).Decode(&out) | ||
| 75 | + return out | ||
| 76 | + } | ||
| 77 | + if e := call(`{"jsonrpc":"2.0","id":1,"method":"message/stream","params":{}}`)["error"].(map[string]any); e["code"].(float64) != codeMethodNotFound { | ||
| 78 | + t.Errorf("unknown method: %v", e) | ||
| 79 | + } | ||
| 80 | + if e := call(`not json`)["error"].(map[string]any); e["code"].(float64) != codeParse { | ||
| 81 | + t.Errorf("parse error: %v", e) | ||
| 82 | + } | ||
| 83 | + if e := call(`{"jsonrpc":"2.0","id":2,"method":"tasks/get","params":{"id":"nope"}}`)["error"].(map[string]any); e["code"].(float64) != codeTaskNotFound { | ||
| 84 | + t.Errorf("tasks/get: %v", e) | ||
| 85 | + } | ||
| 86 | + // A task once sent can be read back. | ||
| 87 | + out := call(`{"jsonrpc":"2.0","id":3,"method":"message/send","params":{"message":{"kind":"message","role":"user","messageId":"m1","parts":[{"kind":"text","text":"hi"}]}}}`) | ||
| 88 | + id := out["result"].(map[string]any)["id"].(string) | ||
| 89 | + got := call(`{"jsonrpc":"2.0","id":4,"method":"tasks/get","params":{"id":"` + id + `"}}`)["result"].(map[string]any) | ||
| 90 | + if got["status"].(map[string]any)["state"] != StateCompleted { | ||
| 91 | + t.Errorf("tasks/get: %v", got) | ||
| 92 | + } | ||
| 93 | +} | ||
| 94 | + | ||
| 95 | +// With a token, JSON-RPC needs it; the card stays readable and says so. | ||
| 96 | +func TestBearerToken(t *testing.T) { | ||
| 97 | + srv, _ := serve(t, "s3cret") | ||
| 98 | + if _, _, err := (Client{}).Send(context.Background(), srv.URL, "", "", "hi"); err == nil || !strings.Contains(err.Error(), "401") { | ||
| 99 | + t.Errorf("no token: %v", err) | ||
| 100 | + } | ||
| 101 | + if a, _, err := (Client{}).Send(context.Background(), srv.URL, "s3cret", "", "hi"); err != nil || a != "hi" { | ||
| 102 | + t.Errorf("token: %q %v", a, err) | ||
| 103 | + } | ||
| 104 | + card, err := Client{}.Card(context.Background(), srv.URL) | ||
| 105 | + if err != nil || len(card.Security) != 1 { | ||
| 106 | + t.Errorf("card: %+v %v", card, err) | ||
| 107 | + } | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +// An agent that only speaks 0.3: SendMessage is "method not found", the | ||
| 111 | +// client falls back to message/send. | ||
| 112 | +func TestClientFallsBackTo03(t *testing.T) { | ||
| 113 | + var methods []string | ||
| 114 | + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| 115 | + var req struct { | ||
| 116 | + ID json.RawMessage `json:"id"` | ||
| 117 | + Method string `json:"method"` | ||
| 118 | + } | ||
| 119 | + _ = json.NewDecoder(r.Body).Decode(&req) | ||
| 120 | + methods = append(methods, req.Method) | ||
| 121 | + if req.Method == "SendMessage" { | ||
| 122 | + _, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":` + string(req.ID) + `,"error":{"code":-32601,"message":"Method not found"}}`)) | ||
| 123 | + return | ||
| 124 | + } | ||
| 125 | + _, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":` + string(req.ID) + `,"result":{"kind":"task","id":"t","contextId":"c9","status":{"state":"completed"},"artifacts":[{"artifactId":"a","parts":[{"kind":"text","text":"old agent"}]}]}}`)) | ||
| 126 | + })) | ||
| 127 | + t.Cleanup(srv.Close) | ||
| 128 | + answer, ctxID, err := Client{}.Send(context.Background(), srv.URL, "", "", "hi") | ||
| 129 | + if err != nil || answer != "old agent" || ctxID != "c9" || strings.Join(methods, ",") != "SendMessage,message/send" { | ||
| 130 | + t.Errorf("%q %q %v, methods %v", answer, ctxID, err, methods) | ||
| 131 | + } | ||
| 132 | +} | ||
| 133 | + | ||
| 134 | +// mm's server answers 1.0's SendMessage in 1.0's shape. | ||
| 135 | +func TestServerSpeaks10(t *testing.T) { | ||
| 136 | + srv, _ := serve(t, "") | ||
| 137 | + resp, err := http.Post(srv.URL+"/", "application/json", bytes.NewBufferString(`{"jsonrpc":"2.0","id":"1","method":"SendMessage","params":{"message":{"messageId":"m1","role":"ROLE_USER","parts":[{"text":"hi"}]}}}`)) | ||
| 138 | + if err != nil { | ||
| 139 | + t.Fatal(err) | ||
| 140 | + } | ||
| 141 | + defer resp.Body.Close() | ||
| 142 | + var out struct { | ||
| 143 | + Result struct { | ||
| 144 | + Task struct { | ||
| 145 | + ContextID string `json:"contextId"` | ||
| 146 | + Status struct { | ||
| 147 | + State string `json:"state"` | ||
| 148 | + } `json:"status"` | ||
| 149 | + Artifacts []struct { | ||
| 150 | + Parts []struct { | ||
| 151 | + Text string `json:"text"` | ||
| 152 | + } `json:"parts"` | ||
| 153 | + } `json:"artifacts"` | ||
| 154 | + } `json:"task"` | ||
| 155 | + } `json:"result"` | ||
| 156 | + } | ||
| 157 | + _ = json.NewDecoder(resp.Body).Decode(&out) | ||
| 158 | + task := out.Result.Task | ||
| 159 | + if task.Status.State != "TASK_STATE_COMPLETED" || task.ContextID == "" || len(task.Artifacts) != 1 || task.Artifacts[0].Parts[0].Text != "hi" { | ||
| 160 | + t.Errorf("1.0 answer: %+v", task) | ||
| 161 | + } | ||
| 162 | +} | ||
added
internal/a2a/client.go +227 -0 | new file mode 100644 | ||
| @@ -0,0 +1,227 @@ | ||
| 1 | +package a2a | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "bytes" | |
| 5 | + "context" | |
| 6 | + "encoding/json" | |
| 7 | + "errors" | |
| 8 | + "fmt" | |
| 9 | + "io" | |
| 10 | + "net/http" | |
| 11 | + "strings" | |
| 12 | + "time" | |
| 13 | +) | |
| 14 | + | |
| 15 | +// Client calls A2A agents. The zero value works, with no timeout of its own | |
| 16 | +// (the context bounds a call). | |
| 17 | +type Client struct { | |
| 18 | + HTTP *http.Client | |
| 19 | +} | |
| 20 | + | |
| 21 | +func (c Client) http() *http.Client { | |
| 22 | + if c.HTTP != nil { | |
| 23 | + return c.HTTP | |
| 24 | + } | |
| 25 | + return &http.Client{Timeout: 0} | |
| 26 | +} | |
| 27 | + | |
| 28 | +// Send sends text to the agent at url, in the conversation contextID ("" = | |
| 29 | +// a new one), and returns the agent's answer and the conversation's | |
| 30 | +// contextID — pass it to the next Send to continue. token "" = no | |
| 31 | +// Authorization header. | |
| 32 | +// | |
| 33 | +// answer, ctxID, err := a2a.Client{}.Send(ctx, "http://127.0.0.1:9101", "", "", "Hello") | |
| 34 | +func (c Client) Send(ctx context.Context, url, token, contextID, text string) (answer, newContextID string, err error) { | |
| 35 | + msg := TextMessage("user", text, contextID) | |
| 36 | + answer, newContextID, err = c.sendV1(ctx, url, token, msg) | |
| 37 | + var rpcErr *RPCError | |
| 38 | + if errors.As(err, &rpcErr) && rpcErr.Code == codeMethodNotFound { | |
| 39 | + return c.sendV03(ctx, url, token, msg) | |
| 40 | + } | |
| 41 | + return answer, newContextID, err | |
| 42 | +} | |
| 43 | + | |
| 44 | +// RPCError is an error the agent answered with. | |
| 45 | +type RPCError struct { | |
| 46 | + Code int | |
| 47 | + Message string | |
| 48 | +} | |
| 49 | + | |
| 50 | +func (e *RPCError) Error() string { | |
| 51 | + return fmt.Sprintf("the agent answered error %d: %s", e.Code, e.Message) | |
| 52 | +} | |
| 53 | + | |
| 54 | +// rpcCall posts one JSON-RPC call and returns its result. | |
| 55 | +func (c Client) rpcCall(ctx context.Context, url, token, method string, params any) (json.RawMessage, error) { | |
| 56 | + req := map[string]any{"jsonrpc": "2.0", "id": NewID(), "method": method, "params": params} | |
| 57 | + var resp struct { | |
| 58 | + Result json.RawMessage `json:"result"` | |
| 59 | + Error *rpcError `json:"error"` | |
| 60 | + } | |
| 61 | + if err := c.post(ctx, endpoint(url), token, req, &resp); err != nil { | |
| 62 | + return nil, err | |
| 63 | + } | |
| 64 | + if resp.Error != nil { | |
| 65 | + return nil, &RPCError{Code: resp.Error.Code, Message: resp.Error.Message} | |
| 66 | + } | |
| 67 | + return resp.Result, nil | |
| 68 | +} | |
| 69 | + | |
| 70 | +// sendV1 is SendMessage, A2A 1.0: the answer is {"task": …} or {"message": …}. | |
| 71 | +func (c Client) sendV1(ctx context.Context, url, token string, msg Message) (string, string, error) { | |
| 72 | + result, err := c.rpcCall(ctx, url, token, "SendMessage", map[string]any{"message": v1Message(&msg)}) | |
| 73 | + if err != nil { | |
| 74 | + return "", msg.ContextID, err | |
| 75 | + } | |
| 76 | + var r struct { | |
| 77 | + Task *v1TaskJSON `json:"task"` | |
| 78 | + Message *v1MessageJSON `json:"message"` | |
| 79 | + } | |
| 80 | + if err := json.Unmarshal(result, &r); err != nil { | |
| 81 | + return "", msg.ContextID, err | |
| 82 | + } | |
| 83 | + switch { | |
| 84 | + case r.Message != nil: | |
| 85 | + return partsText(r.Message.parts()), firstNonEmpty(r.Message.ContextID, msg.ContextID), nil | |
| 86 | + case r.Task != nil: | |
| 87 | + return taskOutcome(r.Task.task(), msg.ContextID) | |
| 88 | + } | |
| 89 | + return "", msg.ContextID, fmt.Errorf("the agent's answer holds neither a task nor a message") | |
| 90 | +} | |
| 91 | + | |
| 92 | +// v1MessageJSON and v1TaskJSON read 1.0's shapes. | |
| 93 | +type v1MessageJSON struct { | |
| 94 | + ContextID string `json:"contextId"` | |
| 95 | + Parts []struct { | |
| 96 | + Text string `json:"text"` | |
| 97 | + } `json:"parts"` | |
| 98 | +} | |
| 99 | + | |
| 100 | +func (m v1MessageJSON) parts() []Part { | |
| 101 | + out := make([]Part, 0, len(m.Parts)) | |
| 102 | + for _, p := range m.Parts { | |
| 103 | + out = append(out, Part{Kind: "text", Text: p.Text}) | |
| 104 | + } | |
| 105 | + return out | |
| 106 | +} | |
| 107 | + | |
| 108 | +type v1TaskJSON struct { | |
| 109 | + ID string `json:"id"` | |
| 110 | + ContextID string `json:"contextId"` | |
| 111 | + Status struct { | |
| 112 | + State string `json:"state"` | |
| 113 | + Message *v1MessageJSON `json:"message"` | |
| 114 | + } `json:"status"` | |
| 115 | + Artifacts []v1MessageJSON `json:"artifacts"` | |
| 116 | +} | |
| 117 | + | |
| 118 | +func (t v1TaskJSON) task() Task { | |
| 119 | + out := Task{ID: t.ID, ContextID: t.ContextID, Status: TaskStatus{State: fromV1State(t.Status.State)}} | |
| 120 | + if t.Status.Message != nil { | |
| 121 | + m := Message{Parts: t.Status.Message.parts()} | |
| 122 | + out.Status.Message = &m | |
| 123 | + } | |
| 124 | + for _, a := range t.Artifacts { | |
| 125 | + out.Artifacts = append(out.Artifacts, Artifact{Parts: a.parts()}) | |
| 126 | + } | |
| 127 | + return out | |
| 128 | +} | |
| 129 | + | |
| 130 | +// taskOutcome is a finished task's answer, or why it is not one. | |
| 131 | +func taskOutcome(t Task, contextID string) (string, string, error) { | |
| 132 | + ctxID := firstNonEmpty(t.ContextID, contextID) | |
| 133 | + if t.Status.State == StateFailed { | |
| 134 | + return "", ctxID, fmt.Errorf("the agent's task failed: %s", t.Answer()) | |
| 135 | + } | |
| 136 | + if t.Status.State != "" && t.Status.State != StateCompleted { | |
| 137 | + return t.Answer(), ctxID, fmt.Errorf("the agent's task is %q, not completed (mm waits for the send to finish; this agent does not)", t.Status.State) | |
| 138 | + } | |
| 139 | + return t.Answer(), ctxID, nil | |
| 140 | +} | |
| 141 | + | |
| 142 | +// sendV03 is message/send, A2A 0.3: the answer is a task or a message. | |
| 143 | +func (c Client) sendV03(ctx context.Context, url, token string, msg Message) (string, string, error) { | |
| 144 | + contextID := msg.ContextID | |
| 145 | + result, err := c.rpcCall(ctx, url, token, "message/send", map[string]any{"message": msg}) | |
| 146 | + if err != nil { | |
| 147 | + return "", contextID, err | |
| 148 | + } | |
| 149 | + var kind struct { | |
| 150 | + Kind string `json:"kind"` | |
| 151 | + } | |
| 152 | + _ = json.Unmarshal(result, &kind) | |
| 153 | + if kind.Kind == "message" { | |
| 154 | + var m Message | |
| 155 | + if err := json.Unmarshal(result, &m); err != nil { | |
| 156 | + return "", contextID, err | |
| 157 | + } | |
| 158 | + return m.Text(), firstNonEmpty(m.ContextID, contextID), nil | |
| 159 | + } | |
| 160 | + var t Task // "kind" may be absent on older agents | |
| 161 | + if err := json.Unmarshal(result, &t); err != nil { | |
| 162 | + return "", contextID, err | |
| 163 | + } | |
| 164 | + return taskOutcome(t, contextID) | |
| 165 | +} | |
| 166 | + | |
| 167 | +// Card reads the agent card published at url. | |
| 168 | +func (c Client) Card(ctx context.Context, url string) (AgentCard, error) { | |
| 169 | + var card AgentCard | |
| 170 | + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) | |
| 171 | + defer cancel() | |
| 172 | + req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimSuffix(url, "/")+CardPath, nil) | |
| 173 | + if err != nil { | |
| 174 | + return card, err | |
| 175 | + } | |
| 176 | + resp, err := c.http().Do(req) | |
| 177 | + if err != nil { | |
| 178 | + return card, err | |
| 179 | + } | |
| 180 | + defer func() { _ = resp.Body.Close() }() | |
| 181 | + if resp.StatusCode != http.StatusOK { | |
| 182 | + return card, fmt.Errorf("GET %s: %s", CardPath, resp.Status) | |
| 183 | + } | |
| 184 | + return card, json.NewDecoder(resp.Body).Decode(&card) | |
| 185 | +} | |
| 186 | + | |
| 187 | +func (c Client) post(ctx context.Context, url, token string, body, out any) error { | |
| 188 | + data, err := json.Marshal(body) | |
| 189 | + if err != nil { | |
| 190 | + return err | |
| 191 | + } | |
| 192 | + req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(data)) | |
| 193 | + if err != nil { | |
| 194 | + return err | |
| 195 | + } | |
| 196 | + req.Header.Set("Content-Type", "application/json") | |
| 197 | + req.Header.Set("Accept", "application/json") | |
| 198 | + req.Header.Set("A2A-Version", ProtocolVersion1) | |
| 199 | + if token != "" { | |
| 200 | + req.Header.Set("Authorization", "Bearer "+token) | |
| 201 | + } | |
| 202 | + resp, err := c.http().Do(req) | |
| 203 | + if err != nil { | |
| 204 | + return err | |
| 205 | + } | |
| 206 | + defer func() { _ = resp.Body.Close() }() | |
| 207 | + if resp.StatusCode != http.StatusOK { | |
| 208 | + b, _ := io.ReadAll(io.LimitReader(resp.Body, 300)) | |
| 209 | + return fmt.Errorf("%s answered %s: %s", url, resp.Status, strings.TrimSpace(string(b))) | |
| 210 | + } | |
| 211 | + return json.NewDecoder(resp.Body).Decode(out) | |
| 212 | +} | |
| 213 | + | |
| 214 | +// endpoint is the JSON-RPC address: the agent's URL itself. | |
| 215 | +func endpoint(url string) string { | |
| 216 | + if strings.HasSuffix(url, "/") { | |
| 217 | + return url | |
| 218 | + } | |
| 219 | + return url + "/" | |
| 220 | +} | |
| 221 | + | |
| 222 | +func firstNonEmpty(a, b string) string { | |
| 223 | + if a != "" { | |
| 224 | + return a | |
| 225 | + } | |
| 226 | + return b | |
| 227 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,227 @@ | |||
| 1 | +package a2a | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "bytes" | ||
| 5 | + "context" | ||
| 6 | + "encoding/json" | ||
| 7 | + "errors" | ||
| 8 | + "fmt" | ||
| 9 | + "io" | ||
| 10 | + "net/http" | ||
| 11 | + "strings" | ||
| 12 | + "time" | ||
| 13 | +) | ||
| 14 | + | ||
| 15 | +// Client calls A2A agents. The zero value works, with no timeout of its own | ||
| 16 | +// (the context bounds a call). | ||
| 17 | +type Client struct { | ||
| 18 | + HTTP *http.Client | ||
| 19 | +} | ||
| 20 | + | ||
| 21 | +func (c Client) http() *http.Client { | ||
| 22 | + if c.HTTP != nil { | ||
| 23 | + return c.HTTP | ||
| 24 | + } | ||
| 25 | + return &http.Client{Timeout: 0} | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | +// Send sends text to the agent at url, in the conversation contextID ("" = | ||
| 29 | +// a new one), and returns the agent's answer and the conversation's | ||
| 30 | +// contextID — pass it to the next Send to continue. token "" = no | ||
| 31 | +// Authorization header. | ||
| 32 | +// | ||
| 33 | +// answer, ctxID, err := a2a.Client{}.Send(ctx, "http://127.0.0.1:9101", "", "", "Hello") | ||
| 34 | +func (c Client) Send(ctx context.Context, url, token, contextID, text string) (answer, newContextID string, err error) { | ||
| 35 | + msg := TextMessage("user", text, contextID) | ||
| 36 | + answer, newContextID, err = c.sendV1(ctx, url, token, msg) | ||
| 37 | + var rpcErr *RPCError | ||
| 38 | + if errors.As(err, &rpcErr) && rpcErr.Code == codeMethodNotFound { | ||
| 39 | + return c.sendV03(ctx, url, token, msg) | ||
| 40 | + } | ||
| 41 | + return answer, newContextID, err | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +// RPCError is an error the agent answered with. | ||
| 45 | +type RPCError struct { | ||
| 46 | + Code int | ||
| 47 | + Message string | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +func (e *RPCError) Error() string { | ||
| 51 | + return fmt.Sprintf("the agent answered error %d: %s", e.Code, e.Message) | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +// rpcCall posts one JSON-RPC call and returns its result. | ||
| 55 | +func (c Client) rpcCall(ctx context.Context, url, token, method string, params any) (json.RawMessage, error) { | ||
| 56 | + req := map[string]any{"jsonrpc": "2.0", "id": NewID(), "method": method, "params": params} | ||
| 57 | + var resp struct { | ||
| 58 | + Result json.RawMessage `json:"result"` | ||
| 59 | + Error *rpcError `json:"error"` | ||
| 60 | + } | ||
| 61 | + if err := c.post(ctx, endpoint(url), token, req, &resp); err != nil { | ||
| 62 | + return nil, err | ||
| 63 | + } | ||
| 64 | + if resp.Error != nil { | ||
| 65 | + return nil, &RPCError{Code: resp.Error.Code, Message: resp.Error.Message} | ||
| 66 | + } | ||
| 67 | + return resp.Result, nil | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +// sendV1 is SendMessage, A2A 1.0: the answer is {"task": …} or {"message": …}. | ||
| 71 | +func (c Client) sendV1(ctx context.Context, url, token string, msg Message) (string, string, error) { | ||
| 72 | + result, err := c.rpcCall(ctx, url, token, "SendMessage", map[string]any{"message": v1Message(&msg)}) | ||
| 73 | + if err != nil { | ||
| 74 | + return "", msg.ContextID, err | ||
| 75 | + } | ||
| 76 | + var r struct { | ||
| 77 | + Task *v1TaskJSON `json:"task"` | ||
| 78 | + Message *v1MessageJSON `json:"message"` | ||
| 79 | + } | ||
| 80 | + if err := json.Unmarshal(result, &r); err != nil { | ||
| 81 | + return "", msg.ContextID, err | ||
| 82 | + } | ||
| 83 | + switch { | ||
| 84 | + case r.Message != nil: | ||
| 85 | + return partsText(r.Message.parts()), firstNonEmpty(r.Message.ContextID, msg.ContextID), nil | ||
| 86 | + case r.Task != nil: | ||
| 87 | + return taskOutcome(r.Task.task(), msg.ContextID) | ||
| 88 | + } | ||
| 89 | + return "", msg.ContextID, fmt.Errorf("the agent's answer holds neither a task nor a message") | ||
| 90 | +} | ||
| 91 | + | ||
| 92 | +// v1MessageJSON and v1TaskJSON read 1.0's shapes. | ||
| 93 | +type v1MessageJSON struct { | ||
| 94 | + ContextID string `json:"contextId"` | ||
| 95 | + Parts []struct { | ||
| 96 | + Text string `json:"text"` | ||
| 97 | + } `json:"parts"` | ||
| 98 | +} | ||
| 99 | + | ||
| 100 | +func (m v1MessageJSON) parts() []Part { | ||
| 101 | + out := make([]Part, 0, len(m.Parts)) | ||
| 102 | + for _, p := range m.Parts { | ||
| 103 | + out = append(out, Part{Kind: "text", Text: p.Text}) | ||
| 104 | + } | ||
| 105 | + return out | ||
| 106 | +} | ||
| 107 | + | ||
| 108 | +type v1TaskJSON struct { | ||
| 109 | + ID string `json:"id"` | ||
| 110 | + ContextID string `json:"contextId"` | ||
| 111 | + Status struct { | ||
| 112 | + State string `json:"state"` | ||
| 113 | + Message *v1MessageJSON `json:"message"` | ||
| 114 | + } `json:"status"` | ||
| 115 | + Artifacts []v1MessageJSON `json:"artifacts"` | ||
| 116 | +} | ||
| 117 | + | ||
| 118 | +func (t v1TaskJSON) task() Task { | ||
| 119 | + out := Task{ID: t.ID, ContextID: t.ContextID, Status: TaskStatus{State: fromV1State(t.Status.State)}} | ||
| 120 | + if t.Status.Message != nil { | ||
| 121 | + m := Message{Parts: t.Status.Message.parts()} | ||
| 122 | + out.Status.Message = &m | ||
| 123 | + } | ||
| 124 | + for _, a := range t.Artifacts { | ||
| 125 | + out.Artifacts = append(out.Artifacts, Artifact{Parts: a.parts()}) | ||
| 126 | + } | ||
| 127 | + return out | ||
| 128 | +} | ||
| 129 | + | ||
| 130 | +// taskOutcome is a finished task's answer, or why it is not one. | ||
| 131 | +func taskOutcome(t Task, contextID string) (string, string, error) { | ||
| 132 | + ctxID := firstNonEmpty(t.ContextID, contextID) | ||
| 133 | + if t.Status.State == StateFailed { | ||
| 134 | + return "", ctxID, fmt.Errorf("the agent's task failed: %s", t.Answer()) | ||
| 135 | + } | ||
| 136 | + if t.Status.State != "" && t.Status.State != StateCompleted { | ||
| 137 | + return t.Answer(), ctxID, fmt.Errorf("the agent's task is %q, not completed (mm waits for the send to finish; this agent does not)", t.Status.State) | ||
| 138 | + } | ||
| 139 | + return t.Answer(), ctxID, nil | ||
| 140 | +} | ||
| 141 | + | ||
| 142 | +// sendV03 is message/send, A2A 0.3: the answer is a task or a message. | ||
| 143 | +func (c Client) sendV03(ctx context.Context, url, token string, msg Message) (string, string, error) { | ||
| 144 | + contextID := msg.ContextID | ||
| 145 | + result, err := c.rpcCall(ctx, url, token, "message/send", map[string]any{"message": msg}) | ||
| 146 | + if err != nil { | ||
| 147 | + return "", contextID, err | ||
| 148 | + } | ||
| 149 | + var kind struct { | ||
| 150 | + Kind string `json:"kind"` | ||
| 151 | + } | ||
| 152 | + _ = json.Unmarshal(result, &kind) | ||
| 153 | + if kind.Kind == "message" { | ||
| 154 | + var m Message | ||
| 155 | + if err := json.Unmarshal(result, &m); err != nil { | ||
| 156 | + return "", contextID, err | ||
| 157 | + } | ||
| 158 | + return m.Text(), firstNonEmpty(m.ContextID, contextID), nil | ||
| 159 | + } | ||
| 160 | + var t Task // "kind" may be absent on older agents | ||
| 161 | + if err := json.Unmarshal(result, &t); err != nil { | ||
| 162 | + return "", contextID, err | ||
| 163 | + } | ||
| 164 | + return taskOutcome(t, contextID) | ||
| 165 | +} | ||
| 166 | + | ||
| 167 | +// Card reads the agent card published at url. | ||
| 168 | +func (c Client) Card(ctx context.Context, url string) (AgentCard, error) { | ||
| 169 | + var card AgentCard | ||
| 170 | + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) | ||
| 171 | + defer cancel() | ||
| 172 | + req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimSuffix(url, "/")+CardPath, nil) | ||
| 173 | + if err != nil { | ||
| 174 | + return card, err | ||
| 175 | + } | ||
| 176 | + resp, err := c.http().Do(req) | ||
| 177 | + if err != nil { | ||
| 178 | + return card, err | ||
| 179 | + } | ||
| 180 | + defer func() { _ = resp.Body.Close() }() | ||
| 181 | + if resp.StatusCode != http.StatusOK { | ||
| 182 | + return card, fmt.Errorf("GET %s: %s", CardPath, resp.Status) | ||
| 183 | + } | ||
| 184 | + return card, json.NewDecoder(resp.Body).Decode(&card) | ||
| 185 | +} | ||
| 186 | + | ||
| 187 | +func (c Client) post(ctx context.Context, url, token string, body, out any) error { | ||
| 188 | + data, err := json.Marshal(body) | ||
| 189 | + if err != nil { | ||
| 190 | + return err | ||
| 191 | + } | ||
| 192 | + req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(data)) | ||
| 193 | + if err != nil { | ||
| 194 | + return err | ||
| 195 | + } | ||
| 196 | + req.Header.Set("Content-Type", "application/json") | ||
| 197 | + req.Header.Set("Accept", "application/json") | ||
| 198 | + req.Header.Set("A2A-Version", ProtocolVersion1) | ||
| 199 | + if token != "" { | ||
| 200 | + req.Header.Set("Authorization", "Bearer "+token) | ||
| 201 | + } | ||
| 202 | + resp, err := c.http().Do(req) | ||
| 203 | + if err != nil { | ||
| 204 | + return err | ||
| 205 | + } | ||
| 206 | + defer func() { _ = resp.Body.Close() }() | ||
| 207 | + if resp.StatusCode != http.StatusOK { | ||
| 208 | + b, _ := io.ReadAll(io.LimitReader(resp.Body, 300)) | ||
| 209 | + return fmt.Errorf("%s answered %s: %s", url, resp.Status, strings.TrimSpace(string(b))) | ||
| 210 | + } | ||
| 211 | + return json.NewDecoder(resp.Body).Decode(out) | ||
| 212 | +} | ||
| 213 | + | ||
| 214 | +// endpoint is the JSON-RPC address: the agent's URL itself. | ||
| 215 | +func endpoint(url string) string { | ||
| 216 | + if strings.HasSuffix(url, "/") { | ||
| 217 | + return url | ||
| 218 | + } | ||
| 219 | + return url + "/" | ||
| 220 | +} | ||
| 221 | + | ||
| 222 | +func firstNonEmpty(a, b string) string { | ||
| 223 | + if a != "" { | ||
| 224 | + return a | ||
| 225 | + } | ||
| 226 | + return b | ||
| 227 | +} | ||
added
internal/a2a/server.go +184 -0 | new file mode 100644 | ||
| @@ -0,0 +1,184 @@ | ||
| 1 | +package a2a | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "context" | |
| 5 | + "crypto/subtle" | |
| 6 | + "encoding/json" | |
| 7 | + "fmt" | |
| 8 | + "io" | |
| 9 | + "net/http" | |
| 10 | + "strings" | |
| 11 | + "sync" | |
| 12 | + "time" | |
| 13 | +) | |
| 14 | + | |
| 15 | +// Handler answers one message of the conversation contextID; an error makes | |
| 16 | +// the task "failed", its text the reason. | |
| 17 | +type Handler func(ctx context.Context, contextID, text string) (string, error) | |
| 18 | + | |
| 19 | +// Server serves one agent: its card and message/send. Messages are answered | |
| 20 | +// one at a time — mm runs one generation at a time — in the order they | |
| 21 | +// arrive. | |
| 22 | +type Server struct { | |
| 23 | + card AgentCard | |
| 24 | + handle Handler | |
| 25 | + token string // "" = no authentication | |
| 26 | + mu sync.Mutex | |
| 27 | + tasks map[string]Task | |
| 28 | + turn sync.Mutex // one generation at a time | |
| 29 | + maxBody int64 | |
| 30 | +} | |
| 31 | + | |
| 32 | +// maxTasks bounds the tasks kept for tasks/get; the oldest are forgotten. | |
| 33 | +const maxTasks = 200 | |
| 34 | + | |
| 35 | +// NewServer serves card and answers with handle. A non-empty token makes | |
| 36 | +// every JSON-RPC call require "Authorization: Bearer <token>"; the card | |
| 37 | +// stays public, and says so. | |
| 38 | +func NewServer(card AgentCard, handle Handler, token string) *Server { | |
| 39 | + card.ProtocolVersion = ProtocolVersion | |
| 40 | + card.PreferredTransport = "JSONRPC" | |
| 41 | + if card.DefaultInputModes == nil { | |
| 42 | + card.DefaultInputModes = []string{"text/plain"} | |
| 43 | + } | |
| 44 | + if card.DefaultOutputModes == nil { | |
| 45 | + card.DefaultOutputModes = []string{"text/plain"} | |
| 46 | + } | |
| 47 | + if card.Skills == nil { | |
| 48 | + card.Skills = []Skill{} | |
| 49 | + } | |
| 50 | + if card.URL != "" && card.SupportedInterfaces == nil { | |
| 51 | + card.SupportedInterfaces = []AgentInterface{ | |
| 52 | + {URL: card.URL, ProtocolBinding: "JSONRPC", ProtocolVersion: ProtocolVersion1}, | |
| 53 | + {URL: card.URL, ProtocolBinding: "JSONRPC", ProtocolVersion: "0.3"}, | |
| 54 | + } | |
| 55 | + } | |
| 56 | + if token != "" { | |
| 57 | + card.SecuritySchemes = map[string]any{"bearer": map[string]any{"type": "http", "scheme": "bearer"}} | |
| 58 | + card.Security = []map[string][]string{{"bearer": {}}} | |
| 59 | + } | |
| 60 | + return &Server{card: card, handle: handle, token: token, tasks: map[string]Task{}, maxBody: 4 << 20} | |
| 61 | +} | |
| 62 | + | |
| 63 | +// ServeHTTP routes the card and the JSON-RPC endpoint. | |
| 64 | +func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
| 65 | + switch { | |
| 66 | + case r.Method == http.MethodGet && (r.URL.Path == CardPath || r.URL.Path == LegacyCardPath): | |
| 67 | + writeJSON(w, http.StatusOK, s.card) | |
| 68 | + case r.Method == http.MethodPost && (r.URL.Path == "/" || r.URL.Path == ""): | |
| 69 | + if !s.authorized(r) { | |
| 70 | + w.Header().Set("WWW-Authenticate", "Bearer") | |
| 71 | + http.Error(w, "unauthorized", http.StatusUnauthorized) | |
| 72 | + return | |
| 73 | + } | |
| 74 | + s.rpc(w, r) | |
| 75 | + default: | |
| 76 | + http.NotFound(w, r) | |
| 77 | + } | |
| 78 | +} | |
| 79 | + | |
| 80 | +func (s *Server) authorized(r *http.Request) bool { | |
| 81 | + if s.token == "" { | |
| 82 | + return true | |
| 83 | + } | |
| 84 | + got, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") | |
| 85 | + return ok && subtle.ConstantTimeCompare([]byte(got), []byte(s.token)) == 1 | |
| 86 | +} | |
| 87 | + | |
| 88 | +func (s *Server) rpc(w http.ResponseWriter, r *http.Request) { | |
| 89 | + body, err := io.ReadAll(io.LimitReader(r.Body, s.maxBody)) | |
| 90 | + var req rpcRequest | |
| 91 | + if err != nil || json.Unmarshal(body, &req) != nil { | |
| 92 | + writeJSON(w, http.StatusOK, rpcResponse{JSONRPC: "2.0", ID: json.RawMessage("null"), Error: &rpcError{codeParse, "parse error"}}) | |
| 93 | + return | |
| 94 | + } | |
| 95 | + resp := rpcResponse{JSONRPC: "2.0", ID: req.ID} | |
| 96 | + if req.JSONRPC != "2.0" || req.Method == "" { | |
| 97 | + resp.Error = &rpcError{codeInvalidRequest, "invalid request"} | |
| 98 | + writeJSON(w, http.StatusOK, resp) | |
| 99 | + return | |
| 100 | + } | |
| 101 | + // 1.0 names its methods SendMessage and GetTask, 0.3 message/send and | |
| 102 | + // tasks/get: the same work, each answered in its version's shape. | |
| 103 | + v1 := req.Method == "SendMessage" || req.Method == "GetTask" | |
| 104 | + switch req.Method { | |
| 105 | + case "SendMessage", "message/send": | |
| 106 | + var p messageSendParams | |
| 107 | + if json.Unmarshal(req.Params, &p) != nil || strings.TrimSpace(p.Message.Text()) == "" { | |
| 108 | + resp.Error = &rpcError{codeInvalidParams, req.Method + " needs a message with a text part"} | |
| 109 | + break | |
| 110 | + } | |
| 111 | + p.Message.Kind, p.Message.Role = "message", "user" | |
| 112 | + t := s.send(r.Context(), p.Message) | |
| 113 | + if v1 { | |
| 114 | + resp.Result = map[string]any{"task": v1Task(t)} | |
| 115 | + } else { | |
| 116 | + resp.Result = t | |
| 117 | + } | |
| 118 | + case "GetTask", "tasks/get": | |
| 119 | + var p taskQueryParams | |
| 120 | + _ = json.Unmarshal(req.Params, &p) | |
| 121 | + s.mu.Lock() | |
| 122 | + t, ok := s.tasks[p.ID] | |
| 123 | + s.mu.Unlock() | |
| 124 | + switch { | |
| 125 | + case !ok: | |
| 126 | + resp.Error = &rpcError{codeTaskNotFound, "task not found"} | |
| 127 | + case v1: | |
| 128 | + resp.Result = v1Task(t) | |
| 129 | + default: | |
| 130 | + resp.Result = t | |
| 131 | + } | |
| 132 | + default: | |
| 133 | + resp.Error = &rpcError{codeMethodNotFound, fmt.Sprintf("method %q is not supported (SendMessage and GetTask are, or message/send and tasks/get)", req.Method)} | |
| 134 | + } | |
| 135 | + writeJSON(w, http.StatusOK, resp) | |
| 136 | +} | |
| 137 | + | |
| 138 | +// send answers m and returns the finished task. | |
| 139 | +func (s *Server) send(ctx context.Context, m Message) Task { | |
| 140 | + contextID := m.ContextID | |
| 141 | + if contextID == "" { | |
| 142 | + contextID = NewID() | |
| 143 | + } | |
| 144 | + m.ContextID = contextID | |
| 145 | + t := Task{Kind: "task", ID: NewID(), ContextID: contextID} | |
| 146 | + m.TaskID = t.ID | |
| 147 | + | |
| 148 | + s.turn.Lock() | |
| 149 | + answer, err := s.handle(ctx, contextID, m.Text()) | |
| 150 | + s.turn.Unlock() | |
| 151 | + | |
| 152 | + now := time.Now().UTC().Format(time.RFC3339) | |
| 153 | + if err != nil { | |
| 154 | + reply := TextMessage("agent", err.Error(), contextID) | |
| 155 | + reply.TaskID = t.ID | |
| 156 | + t.Status = TaskStatus{State: StateFailed, Message: &reply, Timestamp: now} | |
| 157 | + } else { | |
| 158 | + reply := TextMessage("agent", answer, contextID) | |
| 159 | + reply.TaskID = t.ID | |
| 160 | + t.Status = TaskStatus{State: StateCompleted, Message: &reply, Timestamp: now} | |
| 161 | + t.Artifacts = []Artifact{{ArtifactID: NewID(), Name: "answer", Parts: []Part{{Kind: "text", Text: answer}}}} | |
| 162 | + } | |
| 163 | + t.History = []Message{m} | |
| 164 | + s.keep(t) | |
| 165 | + return t | |
| 166 | +} | |
| 167 | + | |
| 168 | +func (s *Server) keep(t Task) { | |
| 169 | + s.mu.Lock() | |
| 170 | + defer s.mu.Unlock() | |
| 171 | + if len(s.tasks) >= maxTasks { | |
| 172 | + for id := range s.tasks { // any one: a map has no order, the bound is what matters | |
| 173 | + delete(s.tasks, id) | |
| 174 | + break | |
| 175 | + } | |
| 176 | + } | |
| 177 | + s.tasks[t.ID] = t | |
| 178 | +} | |
| 179 | + | |
| 180 | +func writeJSON(w http.ResponseWriter, code int, v any) { | |
| 181 | + w.Header().Set("Content-Type", "application/json") | |
| 182 | + w.WriteHeader(code) | |
| 183 | + _ = json.NewEncoder(w).Encode(v) | |
| 184 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,184 @@ | |||
| 1 | +package a2a | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "context" | ||
| 5 | + "crypto/subtle" | ||
| 6 | + "encoding/json" | ||
| 7 | + "fmt" | ||
| 8 | + "io" | ||
| 9 | + "net/http" | ||
| 10 | + "strings" | ||
| 11 | + "sync" | ||
| 12 | + "time" | ||
| 13 | +) | ||
| 14 | + | ||
| 15 | +// Handler answers one message of the conversation contextID; an error makes | ||
| 16 | +// the task "failed", its text the reason. | ||
| 17 | +type Handler func(ctx context.Context, contextID, text string) (string, error) | ||
| 18 | + | ||
| 19 | +// Server serves one agent: its card and message/send. Messages are answered | ||
| 20 | +// one at a time — mm runs one generation at a time — in the order they | ||
| 21 | +// arrive. | ||
| 22 | +type Server struct { | ||
| 23 | + card AgentCard | ||
| 24 | + handle Handler | ||
| 25 | + token string // "" = no authentication | ||
| 26 | + mu sync.Mutex | ||
| 27 | + tasks map[string]Task | ||
| 28 | + turn sync.Mutex // one generation at a time | ||
| 29 | + maxBody int64 | ||
| 30 | +} | ||
| 31 | + | ||
| 32 | +// maxTasks bounds the tasks kept for tasks/get; the oldest are forgotten. | ||
| 33 | +const maxTasks = 200 | ||
| 34 | + | ||
| 35 | +// NewServer serves card and answers with handle. A non-empty token makes | ||
| 36 | +// every JSON-RPC call require "Authorization: Bearer <token>"; the card | ||
| 37 | +// stays public, and says so. | ||
| 38 | +func NewServer(card AgentCard, handle Handler, token string) *Server { | ||
| 39 | + card.ProtocolVersion = ProtocolVersion | ||
| 40 | + card.PreferredTransport = "JSONRPC" | ||
| 41 | + if card.DefaultInputModes == nil { | ||
| 42 | + card.DefaultInputModes = []string{"text/plain"} | ||
| 43 | + } | ||
| 44 | + if card.DefaultOutputModes == nil { | ||
| 45 | + card.DefaultOutputModes = []string{"text/plain"} | ||
| 46 | + } | ||
| 47 | + if card.Skills == nil { | ||
| 48 | + card.Skills = []Skill{} | ||
| 49 | + } | ||
| 50 | + if card.URL != "" && card.SupportedInterfaces == nil { | ||
| 51 | + card.SupportedInterfaces = []AgentInterface{ | ||
| 52 | + {URL: card.URL, ProtocolBinding: "JSONRPC", ProtocolVersion: ProtocolVersion1}, | ||
| 53 | + {URL: card.URL, ProtocolBinding: "JSONRPC", ProtocolVersion: "0.3"}, | ||
| 54 | + } | ||
| 55 | + } | ||
| 56 | + if token != "" { | ||
| 57 | + card.SecuritySchemes = map[string]any{"bearer": map[string]any{"type": "http", "scheme": "bearer"}} | ||
| 58 | + card.Security = []map[string][]string{{"bearer": {}}} | ||
| 59 | + } | ||
| 60 | + return &Server{card: card, handle: handle, token: token, tasks: map[string]Task{}, maxBody: 4 << 20} | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +// ServeHTTP routes the card and the JSON-RPC endpoint. | ||
| 64 | +func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { | ||
| 65 | + switch { | ||
| 66 | + case r.Method == http.MethodGet && (r.URL.Path == CardPath || r.URL.Path == LegacyCardPath): | ||
| 67 | + writeJSON(w, http.StatusOK, s.card) | ||
| 68 | + case r.Method == http.MethodPost && (r.URL.Path == "/" || r.URL.Path == ""): | ||
| 69 | + if !s.authorized(r) { | ||
| 70 | + w.Header().Set("WWW-Authenticate", "Bearer") | ||
| 71 | + http.Error(w, "unauthorized", http.StatusUnauthorized) | ||
| 72 | + return | ||
| 73 | + } | ||
| 74 | + s.rpc(w, r) | ||
| 75 | + default: | ||
| 76 | + http.NotFound(w, r) | ||
| 77 | + } | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +func (s *Server) authorized(r *http.Request) bool { | ||
| 81 | + if s.token == "" { | ||
| 82 | + return true | ||
| 83 | + } | ||
| 84 | + got, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") | ||
| 85 | + return ok && subtle.ConstantTimeCompare([]byte(got), []byte(s.token)) == 1 | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +func (s *Server) rpc(w http.ResponseWriter, r *http.Request) { | ||
| 89 | + body, err := io.ReadAll(io.LimitReader(r.Body, s.maxBody)) | ||
| 90 | + var req rpcRequest | ||
| 91 | + if err != nil || json.Unmarshal(body, &req) != nil { | ||
| 92 | + writeJSON(w, http.StatusOK, rpcResponse{JSONRPC: "2.0", ID: json.RawMessage("null"), Error: &rpcError{codeParse, "parse error"}}) | ||
| 93 | + return | ||
| 94 | + } | ||
| 95 | + resp := rpcResponse{JSONRPC: "2.0", ID: req.ID} | ||
| 96 | + if req.JSONRPC != "2.0" || req.Method == "" { | ||
| 97 | + resp.Error = &rpcError{codeInvalidRequest, "invalid request"} | ||
| 98 | + writeJSON(w, http.StatusOK, resp) | ||
| 99 | + return | ||
| 100 | + } | ||
| 101 | + // 1.0 names its methods SendMessage and GetTask, 0.3 message/send and | ||
| 102 | + // tasks/get: the same work, each answered in its version's shape. | ||
| 103 | + v1 := req.Method == "SendMessage" || req.Method == "GetTask" | ||
| 104 | + switch req.Method { | ||
| 105 | + case "SendMessage", "message/send": | ||
| 106 | + var p messageSendParams | ||
| 107 | + if json.Unmarshal(req.Params, &p) != nil || strings.TrimSpace(p.Message.Text()) == "" { | ||
| 108 | + resp.Error = &rpcError{codeInvalidParams, req.Method + " needs a message with a text part"} | ||
| 109 | + break | ||
| 110 | + } | ||
| 111 | + p.Message.Kind, p.Message.Role = "message", "user" | ||
| 112 | + t := s.send(r.Context(), p.Message) | ||
| 113 | + if v1 { | ||
| 114 | + resp.Result = map[string]any{"task": v1Task(t)} | ||
| 115 | + } else { | ||
| 116 | + resp.Result = t | ||
| 117 | + } | ||
| 118 | + case "GetTask", "tasks/get": | ||
| 119 | + var p taskQueryParams | ||
| 120 | + _ = json.Unmarshal(req.Params, &p) | ||
| 121 | + s.mu.Lock() | ||
| 122 | + t, ok := s.tasks[p.ID] | ||
| 123 | + s.mu.Unlock() | ||
| 124 | + switch { | ||
| 125 | + case !ok: | ||
| 126 | + resp.Error = &rpcError{codeTaskNotFound, "task not found"} | ||
| 127 | + case v1: | ||
| 128 | + resp.Result = v1Task(t) | ||
| 129 | + default: | ||
| 130 | + resp.Result = t | ||
| 131 | + } | ||
| 132 | + default: | ||
| 133 | + resp.Error = &rpcError{codeMethodNotFound, fmt.Sprintf("method %q is not supported (SendMessage and GetTask are, or message/send and tasks/get)", req.Method)} | ||
| 134 | + } | ||
| 135 | + writeJSON(w, http.StatusOK, resp) | ||
| 136 | +} | ||
| 137 | + | ||
| 138 | +// send answers m and returns the finished task. | ||
| 139 | +func (s *Server) send(ctx context.Context, m Message) Task { | ||
| 140 | + contextID := m.ContextID | ||
| 141 | + if contextID == "" { | ||
| 142 | + contextID = NewID() | ||
| 143 | + } | ||
| 144 | + m.ContextID = contextID | ||
| 145 | + t := Task{Kind: "task", ID: NewID(), ContextID: contextID} | ||
| 146 | + m.TaskID = t.ID | ||
| 147 | + | ||
| 148 | + s.turn.Lock() | ||
| 149 | + answer, err := s.handle(ctx, contextID, m.Text()) | ||
| 150 | + s.turn.Unlock() | ||
| 151 | + | ||
| 152 | + now := time.Now().UTC().Format(time.RFC3339) | ||
| 153 | + if err != nil { | ||
| 154 | + reply := TextMessage("agent", err.Error(), contextID) | ||
| 155 | + reply.TaskID = t.ID | ||
| 156 | + t.Status = TaskStatus{State: StateFailed, Message: &reply, Timestamp: now} | ||
| 157 | + } else { | ||
| 158 | + reply := TextMessage("agent", answer, contextID) | ||
| 159 | + reply.TaskID = t.ID | ||
| 160 | + t.Status = TaskStatus{State: StateCompleted, Message: &reply, Timestamp: now} | ||
| 161 | + t.Artifacts = []Artifact{{ArtifactID: NewID(), Name: "answer", Parts: []Part{{Kind: "text", Text: answer}}}} | ||
| 162 | + } | ||
| 163 | + t.History = []Message{m} | ||
| 164 | + s.keep(t) | ||
| 165 | + return t | ||
| 166 | +} | ||
| 167 | + | ||
| 168 | +func (s *Server) keep(t Task) { | ||
| 169 | + s.mu.Lock() | ||
| 170 | + defer s.mu.Unlock() | ||
| 171 | + if len(s.tasks) >= maxTasks { | ||
| 172 | + for id := range s.tasks { // any one: a map has no order, the bound is what matters | ||
| 173 | + delete(s.tasks, id) | ||
| 174 | + break | ||
| 175 | + } | ||
| 176 | + } | ||
| 177 | + s.tasks[t.ID] = t | ||
| 178 | +} | ||
| 179 | + | ||
| 180 | +func writeJSON(w http.ResponseWriter, code int, v any) { | ||
| 181 | + w.Header().Set("Content-Type", "application/json") | ||
| 182 | + w.WriteHeader(code) | ||
| 183 | + _ = json.NewEncoder(w).Encode(v) | ||
| 184 | +} | ||
added
internal/config/a2a.go +78 -0 | new file mode 100644 | ||
| @@ -0,0 +1,78 @@ | ||
| 1 | +package config | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "fmt" | |
| 5 | + "net/url" | |
| 6 | + "regexp" | |
| 7 | +) | |
| 8 | + | |
| 9 | +// A2AConfig is the `a2a:` block (ticket 243): how `mm a2a` serves this agent | |
| 10 | +// to other agents, and the remote A2A agents its model can talk to. | |
| 11 | +// | |
| 12 | +// a2a: | |
| 13 | +// port: 9101 # mm a2a listens on 127.0.0.1:9101 | |
| 14 | +// description: An optimist who argues for the idea. | |
| 15 | +// agents: # declares the ask_a2a_agent tool | |
| 16 | +// bob: | |
| 17 | +// url: http://127.0.0.1:9102 | |
| 18 | +// description: A sceptic who argues against. | |
| 19 | +type A2AConfig struct { | |
| 20 | + // Host and Port are where `mm a2a` listens (127.0.0.1 and 9100 by | |
| 21 | + // default; --a2a-port overrides the port). Loopback by default: an A2A | |
| 22 | + // agent runs tools for whoever calls it. | |
| 23 | + Host string `yaml:"host"` | |
| 24 | + Port int `yaml:"port"` | |
| 25 | + // Description is the Agent Card's: what this agent is for, read by the | |
| 26 | + // agents that call it. Default: acp.title. | |
| 27 | + Description string `yaml:"description"` | |
| 28 | + // TokenEnv names the variable holding the token every caller must send | |
| 29 | + // (Authorization: Bearer …). Empty = no authentication. | |
| 30 | + TokenEnv string `yaml:"tokenEnv"` | |
| 31 | + // Agents are the remote A2A agents the model can talk to through the | |
| 32 | + // ask_a2a_agent tool, by name. | |
| 33 | + Agents map[string]A2AAgent `yaml:"agents"` | |
| 34 | +} | |
| 35 | + | |
| 36 | +// A2AAgent is one remote A2A agent. | |
| 37 | +type A2AAgent struct { | |
| 38 | + URL string `yaml:"url"` | |
| 39 | + Description string `yaml:"description"` | |
| 40 | + // TokenEnv names the variable holding that agent's token, if it wants one. | |
| 41 | + TokenEnv string `yaml:"tokenEnv"` | |
| 42 | +} | |
| 43 | + | |
| 44 | +// DefaultA2AHost and DefaultA2APort are where `mm a2a` listens by default. | |
| 45 | +const ( | |
| 46 | + DefaultA2AHost = "127.0.0.1" | |
| 47 | + DefaultA2APort = 9100 | |
| 48 | +) | |
| 49 | + | |
| 50 | +var a2aAgentName = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*$`) | |
| 51 | + | |
| 52 | +func (a A2AConfig) validate() error { | |
| 53 | + if a.Port < 0 || a.Port > 65535 { | |
| 54 | + return fmt.Errorf("a2a.port must be between 0 and 65535, not %d", a.Port) | |
| 55 | + } | |
| 56 | + for _, name := range sortedA2ANames(a.Agents) { | |
| 57 | + if !a2aAgentName.MatchString(name) { | |
| 58 | + return fmt.Errorf("a2a.agents: %q is not a valid name (lowercase letters, digits and '-')", name) | |
| 59 | + } | |
| 60 | + u, err := url.Parse(a.Agents[name].URL) | |
| 61 | + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { | |
| 62 | + return fmt.Errorf("a2a.agents.%s.url must be an http(s) address, not %q", name, a.Agents[name].URL) | |
| 63 | + } | |
| 64 | + } | |
| 65 | + return nil | |
| 66 | +} | |
| 67 | + | |
| 68 | +// A2AAgentNames is the remote agents' names, sorted. | |
| 69 | +func A2AAgentNames() []string { return sortedA2ANames(Cfg.A2A.Agents) } | |
| 70 | + | |
| 71 | +func sortedA2ANames(m map[string]A2AAgent) []string { | |
| 72 | + names := make([]string, 0, len(m)) | |
| 73 | + for k := range m { | |
| 74 | + names = append(names, k) | |
| 75 | + } | |
| 76 | + sortStrings(names) | |
| 77 | + return names | |
| 78 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,78 @@ | |||
| 1 | +package config | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "fmt" | ||
| 5 | + "net/url" | ||
| 6 | + "regexp" | ||
| 7 | +) | ||
| 8 | + | ||
| 9 | +// A2AConfig is the `a2a:` block (ticket 243): how `mm a2a` serves this agent | ||
| 10 | +// to other agents, and the remote A2A agents its model can talk to. | ||
| 11 | +// | ||
| 12 | +// a2a: | ||
| 13 | +// port: 9101 # mm a2a listens on 127.0.0.1:9101 | ||
| 14 | +// description: An optimist who argues for the idea. | ||
| 15 | +// agents: # declares the ask_a2a_agent tool | ||
| 16 | +// bob: | ||
| 17 | +// url: http://127.0.0.1:9102 | ||
| 18 | +// description: A sceptic who argues against. | ||
| 19 | +type A2AConfig struct { | ||
| 20 | + // Host and Port are where `mm a2a` listens (127.0.0.1 and 9100 by | ||
| 21 | + // default; --a2a-port overrides the port). Loopback by default: an A2A | ||
| 22 | + // agent runs tools for whoever calls it. | ||
| 23 | + Host string `yaml:"host"` | ||
| 24 | + Port int `yaml:"port"` | ||
| 25 | + // Description is the Agent Card's: what this agent is for, read by the | ||
| 26 | + // agents that call it. Default: acp.title. | ||
| 27 | + Description string `yaml:"description"` | ||
| 28 | + // TokenEnv names the variable holding the token every caller must send | ||
| 29 | + // (Authorization: Bearer …). Empty = no authentication. | ||
| 30 | + TokenEnv string `yaml:"tokenEnv"` | ||
| 31 | + // Agents are the remote A2A agents the model can talk to through the | ||
| 32 | + // ask_a2a_agent tool, by name. | ||
| 33 | + Agents map[string]A2AAgent `yaml:"agents"` | ||
| 34 | +} | ||
| 35 | + | ||
| 36 | +// A2AAgent is one remote A2A agent. | ||
| 37 | +type A2AAgent struct { | ||
| 38 | + URL string `yaml:"url"` | ||
| 39 | + Description string `yaml:"description"` | ||
| 40 | + // TokenEnv names the variable holding that agent's token, if it wants one. | ||
| 41 | + TokenEnv string `yaml:"tokenEnv"` | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +// DefaultA2AHost and DefaultA2APort are where `mm a2a` listens by default. | ||
| 45 | +const ( | ||
| 46 | + DefaultA2AHost = "127.0.0.1" | ||
| 47 | + DefaultA2APort = 9100 | ||
| 48 | +) | ||
| 49 | + | ||
| 50 | +var a2aAgentName = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*$`) | ||
| 51 | + | ||
| 52 | +func (a A2AConfig) validate() error { | ||
| 53 | + if a.Port < 0 || a.Port > 65535 { | ||
| 54 | + return fmt.Errorf("a2a.port must be between 0 and 65535, not %d", a.Port) | ||
| 55 | + } | ||
| 56 | + for _, name := range sortedA2ANames(a.Agents) { | ||
| 57 | + if !a2aAgentName.MatchString(name) { | ||
| 58 | + return fmt.Errorf("a2a.agents: %q is not a valid name (lowercase letters, digits and '-')", name) | ||
| 59 | + } | ||
| 60 | + u, err := url.Parse(a.Agents[name].URL) | ||
| 61 | + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { | ||
| 62 | + return fmt.Errorf("a2a.agents.%s.url must be an http(s) address, not %q", name, a.Agents[name].URL) | ||
| 63 | + } | ||
| 64 | + } | ||
| 65 | + return nil | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +// A2AAgentNames is the remote agents' names, sorted. | ||
| 69 | +func A2AAgentNames() []string { return sortedA2ANames(Cfg.A2A.Agents) } | ||
| 70 | + | ||
| 71 | +func sortedA2ANames(m map[string]A2AAgent) []string { | ||
| 72 | + names := make([]string, 0, len(m)) | ||
| 73 | + for k := range m { | ||
| 74 | + names = append(names, k) | ||
| 75 | + } | ||
| 76 | + sortStrings(names) | ||
| 77 | + return names | ||
| 78 | +} | ||
modified
internal/config/config.go +7 -0 | @@ -213,6 +213,10 @@ type Config struct { | ||
| 213 | 213 | // streamed token to the last. On by default. |
| 214 | 214 | ShowSpeed bool `yaml:"showSpeed"` |
| 215 | 215 | |
| 216 | + // A2A: the Agent2Agent protocol (ticket 243) — `mm a2a` serves this | |
| 217 | + // agent, ask_a2a_agent talks to remote ones. See A2AConfig. | |
| 218 | + A2A A2AConfig `yaml:"a2a"` | |
| 219 | + | |
| 216 | 220 | // LlamaCpp: provider llamacpp only — mm starts llama-server itself |
| 217 | 221 | // when nothing answers (ticket 223). See LlamaCppConfig. |
| 218 | 222 | LlamaCpp LlamaCppConfig `yaml:"llamacpp"` |
| @@ -1150,6 +1154,9 @@ func (c Config) validate() error { | ||
| 1150 | 1154 | if err := c.LlamaCpp.validate(); err != nil { |
| 1151 | 1155 | return err |
| 1152 | 1156 | } |
| 1157 | + if err := c.A2A.validate(); err != nil { | |
| 1158 | + return err | |
| 1159 | + } | |
| 1153 | 1160 | if err := validatePrompt(c.System, c.Variables); err != nil { |
| 1154 | 1161 | return err |
| 1155 | 1162 | } |
| @@ -213,6 +213,10 @@ type Config struct { | |||
| 213 | // streamed token to the last. On by default. | 213 | // streamed token to the last. On by default. |
| 214 | ShowSpeed bool `yaml:"showSpeed"` | 214 | ShowSpeed bool `yaml:"showSpeed"` |
| 215 | 215 | ||
| 216 | + // A2A: the Agent2Agent protocol (ticket 243) — `mm a2a` serves this | ||
| 217 | + // agent, ask_a2a_agent talks to remote ones. See A2AConfig. | ||
| 218 | + A2A A2AConfig `yaml:"a2a"` | ||
| 219 | + | ||
| 216 | // LlamaCpp: provider llamacpp only — mm starts llama-server itself | 220 | // LlamaCpp: provider llamacpp only — mm starts llama-server itself |
| 217 | // when nothing answers (ticket 223). See LlamaCppConfig. | 221 | // when nothing answers (ticket 223). See LlamaCppConfig. |
| 218 | LlamaCpp LlamaCppConfig `yaml:"llamacpp"` | 222 | LlamaCpp LlamaCppConfig `yaml:"llamacpp"` |
| @@ -1150,6 +1154,9 @@ func (c Config) validate() error { | |||
| 1150 | if err := c.LlamaCpp.validate(); err != nil { | 1154 | if err := c.LlamaCpp.validate(); err != nil { |
| 1151 | return err | 1155 | return err |
| 1152 | } | 1156 | } |
| 1157 | + if err := c.A2A.validate(); err != nil { | ||
| 1158 | + return err | ||
| 1159 | + } | ||
| 1153 | if err := validatePrompt(c.System, c.Variables); err != nil { | 1160 | if err := validatePrompt(c.System, c.Variables); err != nil { |
| 1154 | return err | 1161 | return err |
| 1155 | } | 1162 | } |
modified
internal/config/promptvars.go +2 -0 | @@ -154,6 +154,8 @@ func sortedKeys(m map[string]string) []string { | ||
| 154 | 154 | return keys |
| 155 | 155 | } |
| 156 | 156 | |
| 157 | +func sortStrings(s []string) { sort.Strings(s) } | |
| 158 | + | |
| 157 | 159 | // PromptWarnings is one banner line per {{env.NAME}} of the system prompt |
| 158 | 160 | // whose variable is not set: it is replaced by nothing. |
| 159 | 161 | func (c Config) PromptWarnings() []string { |
| @@ -154,6 +154,8 @@ func sortedKeys(m map[string]string) []string { | |||
| 154 | return keys | 154 | return keys |
| 155 | } | 155 | } |
| 156 | 156 | ||
| 157 | +func sortStrings(s []string) { sort.Strings(s) } | ||
| 158 | + | ||
| 157 | // PromptWarnings is one banner line per {{env.NAME}} of the system prompt | 159 | // PromptWarnings is one banner line per {{env.NAME}} of the system prompt |
| 158 | // whose variable is not set: it is replaced by nothing. | 160 | // whose variable is not set: it is replaced by nothing. |
| 159 | func (c Config) PromptWarnings() []string { | 161 | func (c Config) PromptWarnings() []string { |
added
internal/tools/a2a.go +140 -0 | new file mode 100644 | ||
| @@ -0,0 +1,140 @@ | ||
| 1 | +package tools | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "context" | |
| 5 | + "fmt" | |
| 6 | + "os" | |
| 7 | + "strings" | |
| 8 | + "sync" | |
| 9 | + "time" | |
| 10 | + | |
| 11 | + "mm/internal/a2a" | |
| 12 | + "mm/internal/config" | |
| 13 | + "mm/internal/detector" | |
| 14 | + "mm/internal/engine" | |
| 15 | + "mm/internal/spinner" | |
| 16 | + "mm/internal/ui" | |
| 17 | + | |
| 18 | + "github.com/firebase/genkit/go/ai" | |
| 19 | + "github.com/firebase/genkit/go/genkit" | |
| 20 | +) | |
| 21 | + | |
| 22 | +// ask_a2a_agent (ticket 243): the model talks to a remote A2A agent declared | |
| 23 | +// under a2a.agents — another mm started with `mm a2a`, or any agent that | |
| 24 | +// speaks A2A over JSON-RPC. Each agent's conversation goes on from one call | |
| 25 | +// to the next (the A2A contextId is kept per agent, for this process), so a | |
| 26 | +// debate can run over several turns; new_conversation starts over. | |
| 27 | + | |
| 28 | +type askA2AInput struct { | |
| 29 | + Agent string `json:"agent" jsonschema_description:"The agent's name, one of the list in this tool's description."` | |
| 30 | + Message string `json:"message" jsonschema_description:"What to say to the agent. It only sees what you send it, and its own earlier answers to you."` | |
| 31 | + NewConversation bool `json:"new_conversation,omitempty" jsonschema_description:"true to start a new conversation with that agent, forgetting the earlier messages."` | |
| 32 | +} | |
| 33 | + | |
| 34 | +// a2aTimeout bounds one call: a remote model can take minutes. | |
| 35 | +const a2aTimeout = 10 * time.Minute | |
| 36 | + | |
| 37 | +var ( | |
| 38 | + a2aMu sync.Mutex | |
| 39 | + a2aContexts = map[string]string{} // agent name → contextId | |
| 40 | +) | |
| 41 | + | |
| 42 | +// AskA2AAgent declares the tool over the agents of a2a.agents. | |
| 43 | +func AskA2AAgent(g *genkit.Genkit, d *detector.LoopDetector) ai.ToolRef { | |
| 44 | + return genkit.DefineTool(g, "ask_a2a_agent", askA2ADescription(), | |
| 45 | + func(tctx *ai.ToolContext, in askA2AInput) (string, error) { | |
| 46 | + return askA2A(tctx, d, in) | |
| 47 | + }) | |
| 48 | +} | |
| 49 | + | |
| 50 | +func askA2ADescription() string { | |
| 51 | + var b strings.Builder | |
| 52 | + b.WriteString(`Send a message to another agent over the A2A protocol and get its answer back as this tool's result. Each agent is a separate assistant; the conversation with it goes on from one call to the next, so you can answer what it said. Use it when the request is about what that agent is for — below. Its answer is text: read it, then go on. | |
| 53 | +Agents:`) | |
| 54 | + for _, name := range config.A2AAgentNames() { | |
| 55 | + desc := strings.TrimSpace(config.Cfg.A2A.Agents[name].Description) | |
| 56 | + if desc == "" { | |
| 57 | + desc = "(no description)" | |
| 58 | + } | |
| 59 | + fmt.Fprintf(&b, "\n %s — %s", name, desc) | |
| 60 | + } | |
| 61 | + return b.String() | |
| 62 | +} | |
| 63 | + | |
| 64 | +func askA2A(ctx context.Context, d *detector.LoopDetector, in askA2AInput) (string, error) { | |
| 65 | + agent, ok := config.Cfg.A2A.Agents[in.Agent] | |
| 66 | + key := in.Agent + ": " + in.Message | |
| 67 | + title := "ask_a2a_agent: " + in.Agent | |
| 68 | + if !ok { | |
| 69 | + out := fmt.Sprintf("[ask_a2a_agent: no agent %q — use one of: %s]", in.Agent, strings.Join(config.A2AAgentNames(), ", ")) | |
| 70 | + return recordFailure(d, "ask_a2a_agent", key, out) | |
| 71 | + } | |
| 72 | + if strings.TrimSpace(in.Message) == "" { | |
| 73 | + return recordFailure(d, "ask_a2a_agent", key, "[ask_a2a_agent: empty message — say something to the agent]") | |
| 74 | + } | |
| 75 | + | |
| 76 | + a2aMu.Lock() | |
| 77 | + if in.NewConversation { | |
| 78 | + delete(a2aContexts, in.Agent) | |
| 79 | + } | |
| 80 | + contextID := a2aContexts[in.Agent] | |
| 81 | + a2aMu.Unlock() | |
| 82 | + | |
| 83 | + // The remote agent's model can think for minutes, and nothing streams | |
| 84 | + // back meanwhile: the call beats the generation's watchdog every second | |
| 85 | + // (like ask_user waiting for a person), bounded by a2aTimeout instead. | |
| 86 | + beat := engine.Heartbeat(ctx) | |
| 87 | + call := func() (string, bool) { | |
| 88 | + token := "" | |
| 89 | + if agent.TokenEnv != "" { | |
| 90 | + token = os.Getenv(agent.TokenEnv) | |
| 91 | + } | |
| 92 | + cctx, cancel := context.WithTimeout(ctx, a2aTimeout) | |
| 93 | + defer cancel() | |
| 94 | + answer, ctxID, err := a2a.Client{}.Send(cctx, agent.URL, token, contextID, in.Message) | |
| 95 | + if ctxID != "" { | |
| 96 | + a2aMu.Lock() | |
| 97 | + a2aContexts[in.Agent] = ctxID | |
| 98 | + a2aMu.Unlock() | |
| 99 | + } | |
| 100 | + if err != nil { | |
| 101 | + return fmt.Sprintf("[ask_a2a_agent: %s did not answer — %v]", in.Agent, err), true | |
| 102 | + } | |
| 103 | + return strings.TrimSpace(answer), false | |
| 104 | + } | |
| 105 | + run := func() (string, bool) { | |
| 106 | + type result struct { | |
| 107 | + out string | |
| 108 | + failed bool | |
| 109 | + } | |
| 110 | + done := make(chan result, 1) | |
| 111 | + go func() { out, failed := call(); done <- result{out, failed} }() | |
| 112 | + ticker := time.NewTicker(time.Second) | |
| 113 | + defer ticker.Stop() | |
| 114 | + for { | |
| 115 | + select { | |
| 116 | + case r := <-done: | |
| 117 | + beat() | |
| 118 | + return r.out, r.failed | |
| 119 | + case <-ticker.C: | |
| 120 | + beat() | |
| 121 | + } | |
| 122 | + } | |
| 123 | + } | |
| 124 | + | |
| 125 | + if s := ui.ActiveSink(); s != nil { | |
| 126 | + ev := ui.ToolEvent{ID: ui.NextCallID(), Tool: "ask_a2a_agent", Title: title, Kind: "other", | |
| 127 | + Input: map[string]any{"agent": in.Agent, "message": in.Message}} | |
| 128 | + s.ToolStart(ev) | |
| 129 | + s.ToolRunning(ev.ID) | |
| 130 | + out, failed := run() | |
| 131 | + s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: failed}) | |
| 132 | + return recordOutcome(d, "ask_a2a_agent", key, out, failed) | |
| 133 | + } | |
| 134 | + announce("🤝 " + title) | |
| 135 | + spinner.Start("Waiting for " + in.Agent) | |
| 136 | + out, failed := run() | |
| 137 | + spinner.Stop() | |
| 138 | + spinner.Suspend(func() { echoOutput(out) }) | |
| 139 | + return recordOutcome(d, "ask_a2a_agent", key, out, failed) | |
| 140 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,140 @@ | |||
| 1 | +package tools | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "context" | ||
| 5 | + "fmt" | ||
| 6 | + "os" | ||
| 7 | + "strings" | ||
| 8 | + "sync" | ||
| 9 | + "time" | ||
| 10 | + | ||
| 11 | + "mm/internal/a2a" | ||
| 12 | + "mm/internal/config" | ||
| 13 | + "mm/internal/detector" | ||
| 14 | + "mm/internal/engine" | ||
| 15 | + "mm/internal/spinner" | ||
| 16 | + "mm/internal/ui" | ||
| 17 | + | ||
| 18 | + "github.com/firebase/genkit/go/ai" | ||
| 19 | + "github.com/firebase/genkit/go/genkit" | ||
| 20 | +) | ||
| 21 | + | ||
| 22 | +// ask_a2a_agent (ticket 243): the model talks to a remote A2A agent declared | ||
| 23 | +// under a2a.agents — another mm started with `mm a2a`, or any agent that | ||
| 24 | +// speaks A2A over JSON-RPC. Each agent's conversation goes on from one call | ||
| 25 | +// to the next (the A2A contextId is kept per agent, for this process), so a | ||
| 26 | +// debate can run over several turns; new_conversation starts over. | ||
| 27 | + | ||
| 28 | +type askA2AInput struct { | ||
| 29 | + Agent string `json:"agent" jsonschema_description:"The agent's name, one of the list in this tool's description."` | ||
| 30 | + Message string `json:"message" jsonschema_description:"What to say to the agent. It only sees what you send it, and its own earlier answers to you."` | ||
| 31 | + NewConversation bool `json:"new_conversation,omitempty" jsonschema_description:"true to start a new conversation with that agent, forgetting the earlier messages."` | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +// a2aTimeout bounds one call: a remote model can take minutes. | ||
| 35 | +const a2aTimeout = 10 * time.Minute | ||
| 36 | + | ||
| 37 | +var ( | ||
| 38 | + a2aMu sync.Mutex | ||
| 39 | + a2aContexts = map[string]string{} // agent name → contextId | ||
| 40 | +) | ||
| 41 | + | ||
| 42 | +// AskA2AAgent declares the tool over the agents of a2a.agents. | ||
| 43 | +func AskA2AAgent(g *genkit.Genkit, d *detector.LoopDetector) ai.ToolRef { | ||
| 44 | + return genkit.DefineTool(g, "ask_a2a_agent", askA2ADescription(), | ||
| 45 | + func(tctx *ai.ToolContext, in askA2AInput) (string, error) { | ||
| 46 | + return askA2A(tctx, d, in) | ||
| 47 | + }) | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +func askA2ADescription() string { | ||
| 51 | + var b strings.Builder | ||
| 52 | + b.WriteString(`Send a message to another agent over the A2A protocol and get its answer back as this tool's result. Each agent is a separate assistant; the conversation with it goes on from one call to the next, so you can answer what it said. Use it when the request is about what that agent is for — below. Its answer is text: read it, then go on. | ||
| 53 | +Agents:`) | ||
| 54 | + for _, name := range config.A2AAgentNames() { | ||
| 55 | + desc := strings.TrimSpace(config.Cfg.A2A.Agents[name].Description) | ||
| 56 | + if desc == "" { | ||
| 57 | + desc = "(no description)" | ||
| 58 | + } | ||
| 59 | + fmt.Fprintf(&b, "\n %s — %s", name, desc) | ||
| 60 | + } | ||
| 61 | + return b.String() | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +func askA2A(ctx context.Context, d *detector.LoopDetector, in askA2AInput) (string, error) { | ||
| 65 | + agent, ok := config.Cfg.A2A.Agents[in.Agent] | ||
| 66 | + key := in.Agent + ": " + in.Message | ||
| 67 | + title := "ask_a2a_agent: " + in.Agent | ||
| 68 | + if !ok { | ||
| 69 | + out := fmt.Sprintf("[ask_a2a_agent: no agent %q — use one of: %s]", in.Agent, strings.Join(config.A2AAgentNames(), ", ")) | ||
| 70 | + return recordFailure(d, "ask_a2a_agent", key, out) | ||
| 71 | + } | ||
| 72 | + if strings.TrimSpace(in.Message) == "" { | ||
| 73 | + return recordFailure(d, "ask_a2a_agent", key, "[ask_a2a_agent: empty message — say something to the agent]") | ||
| 74 | + } | ||
| 75 | + | ||
| 76 | + a2aMu.Lock() | ||
| 77 | + if in.NewConversation { | ||
| 78 | + delete(a2aContexts, in.Agent) | ||
| 79 | + } | ||
| 80 | + contextID := a2aContexts[in.Agent] | ||
| 81 | + a2aMu.Unlock() | ||
| 82 | + | ||
| 83 | + // The remote agent's model can think for minutes, and nothing streams | ||
| 84 | + // back meanwhile: the call beats the generation's watchdog every second | ||
| 85 | + // (like ask_user waiting for a person), bounded by a2aTimeout instead. | ||
| 86 | + beat := engine.Heartbeat(ctx) | ||
| 87 | + call := func() (string, bool) { | ||
| 88 | + token := "" | ||
| 89 | + if agent.TokenEnv != "" { | ||
| 90 | + token = os.Getenv(agent.TokenEnv) | ||
| 91 | + } | ||
| 92 | + cctx, cancel := context.WithTimeout(ctx, a2aTimeout) | ||
| 93 | + defer cancel() | ||
| 94 | + answer, ctxID, err := a2a.Client{}.Send(cctx, agent.URL, token, contextID, in.Message) | ||
| 95 | + if ctxID != "" { | ||
| 96 | + a2aMu.Lock() | ||
| 97 | + a2aContexts[in.Agent] = ctxID | ||
| 98 | + a2aMu.Unlock() | ||
| 99 | + } | ||
| 100 | + if err != nil { | ||
| 101 | + return fmt.Sprintf("[ask_a2a_agent: %s did not answer — %v]", in.Agent, err), true | ||
| 102 | + } | ||
| 103 | + return strings.TrimSpace(answer), false | ||
| 104 | + } | ||
| 105 | + run := func() (string, bool) { | ||
| 106 | + type result struct { | ||
| 107 | + out string | ||
| 108 | + failed bool | ||
| 109 | + } | ||
| 110 | + done := make(chan result, 1) | ||
| 111 | + go func() { out, failed := call(); done <- result{out, failed} }() | ||
| 112 | + ticker := time.NewTicker(time.Second) | ||
| 113 | + defer ticker.Stop() | ||
| 114 | + for { | ||
| 115 | + select { | ||
| 116 | + case r := <-done: | ||
| 117 | + beat() | ||
| 118 | + return r.out, r.failed | ||
| 119 | + case <-ticker.C: | ||
| 120 | + beat() | ||
| 121 | + } | ||
| 122 | + } | ||
| 123 | + } | ||
| 124 | + | ||
| 125 | + if s := ui.ActiveSink(); s != nil { | ||
| 126 | + ev := ui.ToolEvent{ID: ui.NextCallID(), Tool: "ask_a2a_agent", Title: title, Kind: "other", | ||
| 127 | + Input: map[string]any{"agent": in.Agent, "message": in.Message}} | ||
| 128 | + s.ToolStart(ev) | ||
| 129 | + s.ToolRunning(ev.ID) | ||
| 130 | + out, failed := run() | ||
| 131 | + s.ToolEnd(ev.ID, ui.ToolResult{Output: out, Failed: failed}) | ||
| 132 | + return recordOutcome(d, "ask_a2a_agent", key, out, failed) | ||
| 133 | + } | ||
| 134 | + announce("🤝 " + title) | ||
| 135 | + spinner.Start("Waiting for " + in.Agent) | ||
| 136 | + out, failed := run() | ||
| 137 | + spinner.Stop() | ||
| 138 | + spinner.Suspend(func() { echoOutput(out) }) | ||
| 139 | + return recordOutcome(d, "ask_a2a_agent", key, out, failed) | ||
| 140 | +} | ||
modified
main.go +22 -2 | @@ -98,6 +98,11 @@ func main() { | ||
| 98 | 98 | if len(os.Args) > 1 && isSbxInit(os.Args[1]) { |
| 99 | 99 | os.Exit(sbxinit.Main(os.Args[2:], os.Stdin, os.Stdout)) |
| 100 | 100 | } |
| 101 | + // `mm a2a-send` (ticket 243): one message to an A2A agent, from a script. | |
| 102 | + // No configuration, no model: answered before anything is read. | |
| 103 | + if len(os.Args) > 1 && (os.Args[1] == "a2a-send" || os.Args[1] == "--a2a-send" || os.Args[1] == "-a2a-send") { | |
| 104 | + os.Exit(a2aSendMain(os.Args[2:], os.Stdin, os.Stdout, os.Stderr)) | |
| 105 | + } | |
| 101 | 106 | // `mm skillcreate` (ticket 206): a wizard that writes a new skill where |
| 102 | 107 | // the agent's config reads its skills; it reads the config itself. |
| 103 | 108 | if len(os.Args) > 1 && isSkillCreate(os.Args[1]) { |
| @@ -138,6 +143,9 @@ func main() { | ||
| 138 | 143 | os.Args = append([]string{os.Args[0]}, remainingArgs...) |
| 139 | 144 | |
| 140 | 145 | configPath := flag.String("config", "", "path to the YAML config file (default: $AGENT_CONFIG, then ./agent.yaml, then ./.mm/agent.yaml)") |
| 146 | + a2aMode := flag.Bool("a2a", false, "serve this agent over the Agent2Agent protocol (A2A, JSON-RPC over HTTP) on a2a.host:a2a.port, 127.0.0.1:9100 by default (same as: mm a2a)") | |
| 147 | + a2aPort := flag.Int("a2a-port", 0, "with -a2a: the port to listen on, instead of a2a.port") | |
| 148 | + flag.Bool("a2a-send", false, "send one message to an A2A agent and print its answer (same as mm a2a-send; mm a2a-send -h for its flags)") | |
| 141 | 149 | acpMode := flag.Bool("acp", false, "serve the Agent Client Protocol on stdio (for Zed, JetBrains, Neovim…) instead of the terminal REPL (same as: mm acp)") |
| 142 | 150 | tuiMode := flag.Bool("tui", false, "open the single-window mode (conversation above, input box below); falls back to the line mode when stdout is not a terminal (same as: mm tui)") |
| 143 | 151 | promptMode := flag.String("prompt", "", "run a single prompt and exit") |
| @@ -265,7 +273,7 @@ func main() { | ||
| 265 | 273 | asker := ask.NewPool() |
| 266 | 274 | defer asker.Close() |
| 267 | 275 | |
| 268 | - window, banner := windowMode((*tuiMode || config.Cfg.TUI) && !*acpMode) | |
| 276 | + window, banner := windowMode((*tuiMode || config.Cfg.TUI) && !*acpMode && !*a2aMode) | |
| 269 | 277 | |
| 270 | 278 | // Every way out from here on — main returning, exit(), a signal — runs |
| 271 | 279 | // onExit: the model's unload (unloadOnExit, ticket 255), then the |
| @@ -364,6 +372,13 @@ func main() { | ||
| 364 | 372 | acp.Run(ctx, e, config.Cfg.System, agentTools, loopDetector, asker) |
| 365 | 373 | return |
| 366 | 374 | } |
| 375 | + if *a2aMode { | |
| 376 | + if err := runA2A(ctx, e, config.Cfg.System, agentTools, *a2aPort); err != nil { | |
| 377 | + fail("[a2a: %v ]", err) | |
| 378 | + exit(1) | |
| 379 | + } | |
| 380 | + return | |
| 381 | + } | |
| 367 | 382 | if window { |
| 368 | 383 | runWindow(ctx, e, agentTools, loopDetector, strings.TrimSpace(banner.String()), asker) |
| 369 | 384 | return |
| @@ -531,6 +546,11 @@ func assembleTools(e *engine.Engine, d *detector.LoopDetector, asker tools.Agent | ||
| 531 | 546 | set.tools = append(set.tools, tools.AskAgent(e.G, d, asker)) |
| 532 | 547 | set.names = append(set.names, "ask_agent") |
| 533 | 548 | } |
| 549 | + // a2a.agents (ticket 243): the remote A2A agents the model can talk to. | |
| 550 | + if len(config.Cfg.A2A.Agents) > 0 { | |
| 551 | + set.tools = append(set.tools, tools.AskA2AAgent(e.G, d)) | |
| 552 | + set.names = append(set.names, "ask_a2a_agent") | |
| 553 | + } | |
| 534 | 554 | assembleLSP(e, d, &set) |
| 535 | 555 | assembleMCP(e, d, &set) |
| 536 | 556 | assembleDeclared(e, d, &set) |
| @@ -1013,7 +1033,7 @@ func isSbxInit(arg string) bool { | ||
| 1013 | 1033 | // Only the first argument is a mode word: `mm agent.yaml tui` still names two |
| 1014 | 1034 | // config files, and a config file called tui is reached as ./tui. |
| 1015 | 1035 | func modeWordAsFlag(args []string) []string { |
| 1016 | - if len(args) < 2 || (args[1] != "tui" && args[1] != "acp") { | |
| 1036 | + if len(args) < 2 || (args[1] != "tui" && args[1] != "acp" && args[1] != "a2a") { | |
| 1017 | 1037 | return args |
| 1018 | 1038 | } |
| 1019 | 1039 | return append([]string{args[0], "-" + args[1]}, args[2:]...) |
| @@ -98,6 +98,11 @@ func main() { | |||
| 98 | if len(os.Args) > 1 && isSbxInit(os.Args[1]) { | 98 | if len(os.Args) > 1 && isSbxInit(os.Args[1]) { |
| 99 | os.Exit(sbxinit.Main(os.Args[2:], os.Stdin, os.Stdout)) | 99 | os.Exit(sbxinit.Main(os.Args[2:], os.Stdin, os.Stdout)) |
| 100 | } | 100 | } |
| 101 | + // `mm a2a-send` (ticket 243): one message to an A2A agent, from a script. | ||
| 102 | + // No configuration, no model: answered before anything is read. | ||
| 103 | + if len(os.Args) > 1 && (os.Args[1] == "a2a-send" || os.Args[1] == "--a2a-send" || os.Args[1] == "-a2a-send") { | ||
| 104 | + os.Exit(a2aSendMain(os.Args[2:], os.Stdin, os.Stdout, os.Stderr)) | ||
| 105 | + } | ||
| 101 | // `mm skillcreate` (ticket 206): a wizard that writes a new skill where | 106 | // `mm skillcreate` (ticket 206): a wizard that writes a new skill where |
| 102 | // the agent's config reads its skills; it reads the config itself. | 107 | // the agent's config reads its skills; it reads the config itself. |
| 103 | if len(os.Args) > 1 && isSkillCreate(os.Args[1]) { | 108 | if len(os.Args) > 1 && isSkillCreate(os.Args[1]) { |
| @@ -138,6 +143,9 @@ func main() { | |||
| 138 | os.Args = append([]string{os.Args[0]}, remainingArgs...) | 143 | os.Args = append([]string{os.Args[0]}, remainingArgs...) |
| 139 | 144 | ||
| 140 | configPath := flag.String("config", "", "path to the YAML config file (default: $AGENT_CONFIG, then ./agent.yaml, then ./.mm/agent.yaml)") | 145 | configPath := flag.String("config", "", "path to the YAML config file (default: $AGENT_CONFIG, then ./agent.yaml, then ./.mm/agent.yaml)") |
| 146 | + a2aMode := flag.Bool("a2a", false, "serve this agent over the Agent2Agent protocol (A2A, JSON-RPC over HTTP) on a2a.host:a2a.port, 127.0.0.1:9100 by default (same as: mm a2a)") | ||
| 147 | + a2aPort := flag.Int("a2a-port", 0, "with -a2a: the port to listen on, instead of a2a.port") | ||
| 148 | + flag.Bool("a2a-send", false, "send one message to an A2A agent and print its answer (same as mm a2a-send; mm a2a-send -h for its flags)") | ||
| 141 | acpMode := flag.Bool("acp", false, "serve the Agent Client Protocol on stdio (for Zed, JetBrains, Neovim…) instead of the terminal REPL (same as: mm acp)") | 149 | acpMode := flag.Bool("acp", false, "serve the Agent Client Protocol on stdio (for Zed, JetBrains, Neovim…) instead of the terminal REPL (same as: mm acp)") |
| 142 | tuiMode := flag.Bool("tui", false, "open the single-window mode (conversation above, input box below); falls back to the line mode when stdout is not a terminal (same as: mm tui)") | 150 | tuiMode := flag.Bool("tui", false, "open the single-window mode (conversation above, input box below); falls back to the line mode when stdout is not a terminal (same as: mm tui)") |
| 143 | promptMode := flag.String("prompt", "", "run a single prompt and exit") | 151 | promptMode := flag.String("prompt", "", "run a single prompt and exit") |
| @@ -265,7 +273,7 @@ func main() { | |||
| 265 | asker := ask.NewPool() | 273 | asker := ask.NewPool() |
| 266 | defer asker.Close() | 274 | defer asker.Close() |
| 267 | 275 | ||
| 268 | - window, banner := windowMode((*tuiMode || config.Cfg.TUI) && !*acpMode) | 276 | + window, banner := windowMode((*tuiMode || config.Cfg.TUI) && !*acpMode && !*a2aMode) |
| 269 | 277 | ||
| 270 | // Every way out from here on — main returning, exit(), a signal — runs | 278 | // Every way out from here on — main returning, exit(), a signal — runs |
| 271 | // onExit: the model's unload (unloadOnExit, ticket 255), then the | 279 | // onExit: the model's unload (unloadOnExit, ticket 255), then the |
| @@ -364,6 +372,13 @@ func main() { | |||
| 364 | acp.Run(ctx, e, config.Cfg.System, agentTools, loopDetector, asker) | 372 | acp.Run(ctx, e, config.Cfg.System, agentTools, loopDetector, asker) |
| 365 | return | 373 | return |
| 366 | } | 374 | } |
| 375 | + if *a2aMode { | ||
| 376 | + if err := runA2A(ctx, e, config.Cfg.System, agentTools, *a2aPort); err != nil { | ||
| 377 | + fail("[a2a: %v ]", err) | ||
| 378 | + exit(1) | ||
| 379 | + } | ||
| 380 | + return | ||
| 381 | + } | ||
| 367 | if window { | 382 | if window { |
| 368 | runWindow(ctx, e, agentTools, loopDetector, strings.TrimSpace(banner.String()), asker) | 383 | runWindow(ctx, e, agentTools, loopDetector, strings.TrimSpace(banner.String()), asker) |
| 369 | return | 384 | return |
| @@ -531,6 +546,11 @@ func assembleTools(e *engine.Engine, d *detector.LoopDetector, asker tools.Agent | |||
| 531 | set.tools = append(set.tools, tools.AskAgent(e.G, d, asker)) | 546 | set.tools = append(set.tools, tools.AskAgent(e.G, d, asker)) |
| 532 | set.names = append(set.names, "ask_agent") | 547 | set.names = append(set.names, "ask_agent") |
| 533 | } | 548 | } |
| 549 | + // a2a.agents (ticket 243): the remote A2A agents the model can talk to. | ||
| 550 | + if len(config.Cfg.A2A.Agents) > 0 { | ||
| 551 | + set.tools = append(set.tools, tools.AskA2AAgent(e.G, d)) | ||
| 552 | + set.names = append(set.names, "ask_a2a_agent") | ||
| 553 | + } | ||
| 534 | assembleLSP(e, d, &set) | 554 | assembleLSP(e, d, &set) |
| 535 | assembleMCP(e, d, &set) | 555 | assembleMCP(e, d, &set) |
| 536 | assembleDeclared(e, d, &set) | 556 | assembleDeclared(e, d, &set) |
| @@ -1013,7 +1033,7 @@ func isSbxInit(arg string) bool { | |||
| 1013 | // Only the first argument is a mode word: `mm agent.yaml tui` still names two | 1033 | // Only the first argument is a mode word: `mm agent.yaml tui` still names two |
| 1014 | // config files, and a config file called tui is reached as ./tui. | 1034 | // config files, and a config file called tui is reached as ./tui. |
| 1015 | func modeWordAsFlag(args []string) []string { | 1035 | func modeWordAsFlag(args []string) []string { |
| 1016 | - if len(args) < 2 || (args[1] != "tui" && args[1] != "acp") { | 1036 | + if len(args) < 2 || (args[1] != "tui" && args[1] != "acp" && args[1] != "a2a") { |
| 1017 | return args | 1037 | return args |
| 1018 | } | 1038 | } |
| 1019 | return append([]string{args[0], "-" + args[1]}, args[2:]...) | 1039 | return append([]string{args[0], "-" + args[1]}, args[2:]...) |