bots-garden/sidekickspublic Fork
⑂ cf64214
Commits
⬇ Clone ▾
git clone https://git.rickub.com/bots-garden/sidekicks.git
git clone ssh://git@rickub.com/bots-garden/sidekicks.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP

#26 Un agent passe la parole à un autre membre du channel en le mentionnant (@nom)

Chaîne bornée par limits.maxAgentHandoffs (3 par défaut, 0 désactive), message
système handoff-limit, ■ arrête tout. Seuls les membres, pas soi-même, pas dans
du code, pas après une commande. Tests Go, docs EN + FR. #26 dans M8.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
k33g committed 2026-11-09T20:08:51+01:00 Browse files
cf64214 parent: f1d3e7d
modified .memory/history.md +1 -0
@@ -218,3 +218,4 @@
218218 - Verified in the app under Xvfb (Linux): colouring, selection, drag and drop (HTML5 DnD works in WebKitGTK with slow xdotool moves), F2, menu, Move to…, delete to trash, terminal running while away, 3 terminals, close, exit/restart, no shell left after quit. Trap: the sandbox's `tty` prints no newline (not an app bug). `make verify` green. Not checked on macOS.
219219 - Also filed #75–#80 (collective memory REST API, MCP mode question, MCP gateway, plugins, acting outside, prompt injection), no milestone.
220220 - **2026-11-09 — #51 unload a model from the Log panel** (owner: "/unload already works; from the Log panel, unload the selected model or all of them"): convention kept — an agent that announces the `unload` slash command can unload its model. `channels.Manager.Unload` sends `/unload` in a throwaway session (no trace in conversations; refuses no-command / answering agents), `AgentService.Unload` also refuses a stopped agent and writes the answer to the agent log (`unload: …`), `UnloadAll` returns `{unloaded, skipped}` without starting stopped agents. UI: ⏏ Unload the model + ⏏ Unload all in the Log panel (result line), ⏏ on the agent row and in the agent view header; the frontend decides visibility from `appState.commands` (no `canUnload` in `List()`, it would be lost on agent:state events). Verified under Xvfb with two fake ACP agents (Python, scratchpad). Docs EN/FR: memory-pressure how-to, memory explanation, AgentService reference.
221+- **2026-11-09 — #26 agents calling agents** (owner: "add #26 to the milestone and implement it"): chose @mentions in answers over an MCP "ask_agent" tool (mm ignores mcpServers). In a channel, members mentioned in an agent's answer answer next (`channels.Manager.answer` loop; `HandoffPrompt` tells them who addressed them; unseen includes the user's message). Guards: members only, not self, not already queued, not in code, not after a /command, not in direct conversations; `limits.maxAgentHandoffs` (default 3, 0–10, 0 = off; `*int` in raw config, read per message via `Options.Handoffs` → `Core.maxAgentHandoffs`), then system message `handoff-limit`; ■ stops the chain. Verified under Xvfb with two fake agents mentioning each other. Docs EN/FR: manage-channels how-to, channels-and-context explanation, configuration + agents-and-events references.
@@ -218,3 +218,4 @@
218 - Verified in the app under Xvfb (Linux): colouring, selection, drag and drop (HTML5 DnD works in WebKitGTK with slow xdotool moves), F2, menu, Move to…, delete to trash, terminal running while away, 3 terminals, close, exit/restart, no shell left after quit. Trap: the sandbox's `tty` prints no newline (not an app bug). `make verify` green. Not checked on macOS.218 - Verified in the app under Xvfb (Linux): colouring, selection, drag and drop (HTML5 DnD works in WebKitGTK with slow xdotool moves), F2, menu, Move to…, delete to trash, terminal running while away, 3 terminals, close, exit/restart, no shell left after quit. Trap: the sandbox's `tty` prints no newline (not an app bug). `make verify` green. Not checked on macOS.
219 - Also filed #75–#80 (collective memory REST API, MCP mode question, MCP gateway, plugins, acting outside, prompt injection), no milestone.219 - Also filed #75–#80 (collective memory REST API, MCP mode question, MCP gateway, plugins, acting outside, prompt injection), no milestone.
220 - **2026-11-09 — #51 unload a model from the Log panel** (owner: "/unload already works; from the Log panel, unload the selected model or all of them"): convention kept — an agent that announces the `unload` slash command can unload its model. `channels.Manager.Unload` sends `/unload` in a throwaway session (no trace in conversations; refuses no-command / answering agents), `AgentService.Unload` also refuses a stopped agent and writes the answer to the agent log (`unload: …`), `UnloadAll` returns `{unloaded, skipped}` without starting stopped agents. UI: ⏏ Unload the model + ⏏ Unload all in the Log panel (result line), ⏏ on the agent row and in the agent view header; the frontend decides visibility from `appState.commands` (no `canUnload` in `List()`, it would be lost on agent:state events). Verified under Xvfb with two fake ACP agents (Python, scratchpad). Docs EN/FR: memory-pressure how-to, memory explanation, AgentService reference.220 - **2026-11-09 — #51 unload a model from the Log panel** (owner: "/unload already works; from the Log panel, unload the selected model or all of them"): convention kept — an agent that announces the `unload` slash command can unload its model. `channels.Manager.Unload` sends `/unload` in a throwaway session (no trace in conversations; refuses no-command / answering agents), `AgentService.Unload` also refuses a stopped agent and writes the answer to the agent log (`unload: …`), `UnloadAll` returns `{unloaded, skipped}` without starting stopped agents. UI: ⏏ Unload the model + ⏏ Unload all in the Log panel (result line), ⏏ on the agent row and in the agent view header; the frontend decides visibility from `appState.commands` (no `canUnload` in `List()`, it would be lost on agent:state events). Verified under Xvfb with two fake ACP agents (Python, scratchpad). Docs EN/FR: memory-pressure how-to, memory explanation, AgentService reference.
221+- **2026-11-09 — #26 agents calling agents** (owner: "add #26 to the milestone and implement it"): chose @mentions in answers over an MCP "ask_agent" tool (mm ignores mcpServers). In a channel, members mentioned in an agent's answer answer next (`channels.Manager.answer` loop; `HandoffPrompt` tells them who addressed them; unseen includes the user's message). Guards: members only, not self, not already queued, not in code, not after a /command, not in direct conversations; `limits.maxAgentHandoffs` (default 3, 0–10, 0 = off; `*int` in raw config, read per message via `Options.Handoffs` → `Core.maxAgentHandoffs`), then system message `handoff-limit`; ■ stops the chain. Verified under Xvfb with two fake agents mentioning each other. Docs EN/FR: manage-channels how-to, channels-and-context explanation, configuration + agents-and-events references.
modified .tickets/issues/0026-spike-permettre-a-un-agent-d-invoquer-un-autre-a.yaml +44 -7
@@ -1,17 +1,18 @@
11 # Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
22 id: 26
33 title: "Spike : permettre à un agent d'invoquer un autre agent"
4-state: open
4+state: closed
55 author:
66 name: k33g
77 email: ph.charriere@gmail.com
88 createdAt: 2026-10-29T07:20:24.000Z
9-updatedAt: 2026-10-29T07:20:24.000Z
9+updatedAt: 2026-11-09T19:08:51.000Z
1010 labels:
1111 - "kind::spike"
1212 - "area::acp"
1313 - "priority::low"
1414 - "size::M"
15+milestone: "M8 · Divers ajouts"
1516 epic: "Channels & multi-agents"
1617 related:
1718 - 23
@@ -29,34 +30,70 @@ body: |
2930 tasks:
3031 - id: 1
3132 title: "Étudier la détection de mentions dans les réponses"
32- state: open
33+ state: closed
3334 priority: medium
3435 author:
3536 name: k33g
3637 email: ph.charriere@gmail.com
3738 createdAt: 2026-10-29T07:20:24.000Z
39+ updatedAt: 2026-11-09T19:08:51.000Z
40+ closedAt: 2026-11-09T19:08:51.000Z
3841 - id: 2
3942 title: "Étudier un serveur MCP fourni par Sidekicks"
40- state: open
43+ state: closed
4144 priority: medium
4245 author:
4346 name: k33g
4447 email: ph.charriere@gmail.com
4548 createdAt: 2026-10-29T07:20:24.000Z
49+ updatedAt: 2026-11-09T19:08:51.000Z
50+ closedAt: 2026-11-09T19:08:51.000Z
4651 - id: 3
4752 title: "Définir les garde-fous anti-boucle"
48- state: open
53+ state: closed
4954 priority: medium
5055 author:
5156 name: k33g
5257 email: ph.charriere@gmail.com
5358 createdAt: 2026-10-29T07:20:24.000Z
59+ updatedAt: 2026-11-09T19:08:51.000Z
60+ closedAt: 2026-11-09T19:08:51.000Z
5461 - id: 4
5562 title: "Prototype"
56- state: open
63+ state: closed
5764 priority: low
5865 author:
5966 name: k33g
6067 email: ph.charriere@gmail.com
6168 createdAt: 2026-10-29T07:20:24.000Z
62-comments: []
69+ updatedAt: 2026-11-09T19:08:51.000Z
70+ closedAt: 2026-11-09T19:08:51.000Z
71+comments:
72+ - id: 1
73+ author:
74+ name: k33g
75+ email: ph.charriere@gmail.com
76+ createdAt: 2026-11-09T19:08:51.000Z
77+ body: |
78+ Implémenté avec la **détection des mentions dans les réponses**.
79+
80+ - **Choix** : la piste MCP est écartée. mm ignore les `mcpServers` proposés par le client, et
81+ les mentions ne demandent rien à l'agent ; l'utilisateur voit tout l'échange dans le channel.
82+ - **Règle** : dans un channel, quand la réponse d'un agent mentionne d'autres **membres** avec
83+ `@nom`, ils répondent ensuite, dans l'ordre. Chacun reçoit ce qu'il n'a pas vu (le message de
84+ l'utilisateur et la réponse de l'agent qui l'appelle), puis « alice mentioned you (@bob)…:
85+ answer alice directly » (`HandoffPrompt`).
86+ - **Garde-fous** :
87+ - seuls les membres (un agent n'en invite jamais un nouveau, donc pas de modèle en plus) ;
88+ - pas l'agent lui-même, ni un agent qui répond déjà au message ;
89+ - pas de mention dans du code, ni dans la réponse à une `/commande` ;
90+ - rien en conversation directe ;
91+ - au plus `limits.maxAgentHandoffs` passages par message (3 par défaut, de 0 à 10, 0 désactive),
92+ puis le message système `handoff-limit` ;
93+ - **■** arrête toute la chaîne.
94+ - **Config** : schéma, chargeur, suggestions de clés ; la limite est relue à chaque message.
95+ - **Tests** : 6 tests Go (`internal/channels/handoff_test.go`), plus les tests de config. Vérifié
96+ dans l'application avec deux faux agents qui se mentionnent l'un l'autre : Alice → Bob → Alice,
97+ puis la chaîne s'arrête avec le message.
98+ - **Docs EN + FR** : guide « Gérer les channels » (section « Laisser les agents s'appeler entre
99+ eux »), explication « Channels et contexte », référence configuration et agents/événements.
@@ -1,17 +1,18 @@
1 # Managed by IssueSpec. Hand edits are welcome; keep the schema valid.1 # Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2 id: 262 id: 26
3 title: "Spike : permettre à un agent d'invoquer un autre agent"3 title: "Spike : permettre à un agent d'invoquer un autre agent"
4-state: open4+state: closed
5 author:5 author:
6 name: k33g6 name: k33g
7 email: ph.charriere@gmail.com7 email: ph.charriere@gmail.com
8 createdAt: 2026-10-29T07:20:24.000Z8 createdAt: 2026-10-29T07:20:24.000Z
9-updatedAt: 2026-10-29T07:20:24.000Z9+updatedAt: 2026-11-09T19:08:51.000Z
10 labels:10 labels:
11 - "kind::spike"11 - "kind::spike"
12 - "area::acp"12 - "area::acp"
13 - "priority::low"13 - "priority::low"
14 - "size::M"14 - "size::M"
15+milestone: "M8 · Divers ajouts"
15 epic: "Channels & multi-agents"16 epic: "Channels & multi-agents"
16 related:17 related:
17 - 2318 - 23
@@ -29,34 +30,70 @@ body: |
29 tasks:30 tasks:
30 - id: 131 - id: 1
31 title: "Étudier la détection de mentions dans les réponses"32 title: "Étudier la détection de mentions dans les réponses"
32- state: open33+ state: closed
33 priority: medium34 priority: medium
34 author:35 author:
35 name: k33g36 name: k33g
36 email: ph.charriere@gmail.com37 email: ph.charriere@gmail.com
37 createdAt: 2026-10-29T07:20:24.000Z38 createdAt: 2026-10-29T07:20:24.000Z
39+ updatedAt: 2026-11-09T19:08:51.000Z
40+ closedAt: 2026-11-09T19:08:51.000Z
38 - id: 241 - id: 2
39 title: "Étudier un serveur MCP fourni par Sidekicks"42 title: "Étudier un serveur MCP fourni par Sidekicks"
40- state: open43+ state: closed
41 priority: medium44 priority: medium
42 author:45 author:
43 name: k33g46 name: k33g
44 email: ph.charriere@gmail.com47 email: ph.charriere@gmail.com
45 createdAt: 2026-10-29T07:20:24.000Z48 createdAt: 2026-10-29T07:20:24.000Z
49+ updatedAt: 2026-11-09T19:08:51.000Z
50+ closedAt: 2026-11-09T19:08:51.000Z
46 - id: 351 - id: 3
47 title: "Définir les garde-fous anti-boucle"52 title: "Définir les garde-fous anti-boucle"
48- state: open53+ state: closed
49 priority: medium54 priority: medium
50 author:55 author:
51 name: k33g56 name: k33g
52 email: ph.charriere@gmail.com57 email: ph.charriere@gmail.com
53 createdAt: 2026-10-29T07:20:24.000Z58 createdAt: 2026-10-29T07:20:24.000Z
59+ updatedAt: 2026-11-09T19:08:51.000Z
60+ closedAt: 2026-11-09T19:08:51.000Z
54 - id: 461 - id: 4
55 title: "Prototype"62 title: "Prototype"
56- state: open63+ state: closed
57 priority: low64 priority: low
58 author:65 author:
59 name: k33g66 name: k33g
60 email: ph.charriere@gmail.com67 email: ph.charriere@gmail.com
61 createdAt: 2026-10-29T07:20:24.000Z68 createdAt: 2026-10-29T07:20:24.000Z
62-comments: []69+ updatedAt: 2026-11-09T19:08:51.000Z
70+ closedAt: 2026-11-09T19:08:51.000Z
71+comments:
72+ - id: 1
73+ author:
74+ name: k33g
75+ email: ph.charriere@gmail.com
76+ createdAt: 2026-11-09T19:08:51.000Z
77+ body: |
78+ Implémenté avec la **détection des mentions dans les réponses**.
79+
80+ - **Choix** : la piste MCP est écartée. mm ignore les `mcpServers` proposés par le client, et
81+ les mentions ne demandent rien à l'agent ; l'utilisateur voit tout l'échange dans le channel.
82+ - **Règle** : dans un channel, quand la réponse d'un agent mentionne d'autres **membres** avec
83+ `@nom`, ils répondent ensuite, dans l'ordre. Chacun reçoit ce qu'il n'a pas vu (le message de
84+ l'utilisateur et la réponse de l'agent qui l'appelle), puis « alice mentioned you (@bob)…:
85+ answer alice directly » (`HandoffPrompt`).
86+ - **Garde-fous** :
87+ - seuls les membres (un agent n'en invite jamais un nouveau, donc pas de modèle en plus) ;
88+ - pas l'agent lui-même, ni un agent qui répond déjà au message ;
89+ - pas de mention dans du code, ni dans la réponse à une `/commande` ;
90+ - rien en conversation directe ;
91+ - au plus `limits.maxAgentHandoffs` passages par message (3 par défaut, de 0 à 10, 0 désactive),
92+ puis le message système `handoff-limit` ;
93+ - **■** arrête toute la chaîne.
94+ - **Config** : schéma, chargeur, suggestions de clés ; la limite est relue à chaque message.
95+ - **Tests** : 6 tests Go (`internal/channels/handoff_test.go`), plus les tests de config. Vérifié
96+ dans l'application avec deux faux agents qui se mentionnent l'un l'autre : Alice → Bob → Alice,
97+ puis la chaîne s'arrête avec le message.
98+ - **Docs EN + FR** : guide « Gérer les channels » (section « Laisser les agents s'appeler entre
99+ eux »), explication « Channels et contexte », référence configuration et agents/événements.
modified docs/en/explanation/channels-and-context.md +8 -0
@@ -18,6 +18,14 @@ A message goes to the agents it mentions, in order; without a mention, to the la
1818
1919 Agents answer one after the other, never at the same time. On a laptop, two local models generating together are each slower than one after the other, and memory is the real limit (two small models on the reference machine). Answering in turn also lets the second agent read the first one's answer: "@alice @bob compare" gives Bob Alice's answer to compare with. For the same reason an agent answers one channel at a time: a second channel waits, and shows whose turn it is.
2020
21+## When an agent calls another one
22+
23+An agent may need another one: Alice plans a trip, Bob knows the trains. Sidekicks lets an agent hand the floor on the way the user does — by mentioning a member with `@name` in its answer (issue #26). The mentioned agent answers next, reads the channel as usual (the user's message and Alice's answer among what it has not seen) and is told that Alice addressed it, so it answers her rather than the user.
24+
25+Mentions were preferred to a tool offered to the agents (an MCP server "ask an agent"): it needs nothing from the agent — mm ignores the MCP servers a client offers — and the user sees the whole exchange in the channel, as if they had written the mention themselves.
26+
27+The risk is a loop: two polite agents can thank each other forever, and each turn keeps a model busy. So the chain is bounded: a message is handed on `limits.maxAgentHandoffs` times at most (3 by default), then the channel says it stops. Only members can be called — an agent never brings a new one in, which would load another model — an agent cannot call itself, and **■** stops the whole chain. In a direct conversation, there is nobody to call.
28+
2129 ## Commands are sent alone
2230
2331 `/idioms Il pleut des cordes` asks Garfield to run a skill. The agent recognises a command by its first character. If the transcript of the channel came before it, the command would no longer be a command. So a message starting with `/` is sent as it is, without context, and `/garfield:idioms …` picks the agent when several are in the channel. An agent announces its commands as soon as a session opens, before any question — and mm does so without loading its model. So the first `/` typed in a conversation starts the members that never announced theirs and opens their session (the one their first answer will use); the list fills in a fraction of a second. Sidekicks then keeps the commands, and offers them at once the next times.
@@ -18,6 +18,14 @@ A message goes to the agents it mentions, in order; without a mention, to the la
18 18
19 Agents answer one after the other, never at the same time. On a laptop, two local models generating together are each slower than one after the other, and memory is the real limit (two small models on the reference machine). Answering in turn also lets the second agent read the first one's answer: "@alice @bob compare" gives Bob Alice's answer to compare with. For the same reason an agent answers one channel at a time: a second channel waits, and shows whose turn it is.19 Agents answer one after the other, never at the same time. On a laptop, two local models generating together are each slower than one after the other, and memory is the real limit (two small models on the reference machine). Answering in turn also lets the second agent read the first one's answer: "@alice @bob compare" gives Bob Alice's answer to compare with. For the same reason an agent answers one channel at a time: a second channel waits, and shows whose turn it is.
20 20
21+## When an agent calls another one
22+
23+An agent may need another one: Alice plans a trip, Bob knows the trains. Sidekicks lets an agent hand the floor on the way the user does — by mentioning a member with `@name` in its answer (issue #26). The mentioned agent answers next, reads the channel as usual (the user's message and Alice's answer among what it has not seen) and is told that Alice addressed it, so it answers her rather than the user.
24+
25+Mentions were preferred to a tool offered to the agents (an MCP server "ask an agent"): it needs nothing from the agent — mm ignores the MCP servers a client offers — and the user sees the whole exchange in the channel, as if they had written the mention themselves.
26+
27+The risk is a loop: two polite agents can thank each other forever, and each turn keeps a model busy. So the chain is bounded: a message is handed on `limits.maxAgentHandoffs` times at most (3 by default), then the channel says it stops. Only members can be called — an agent never brings a new one in, which would load another model — an agent cannot call itself, and **■** stops the whole chain. In a direct conversation, there is nobody to call.
28+
21 ## Commands are sent alone29 ## Commands are sent alone
22 30
23 `/idioms Il pleut des cordes` asks Garfield to run a skill. The agent recognises a command by its first character. If the transcript of the channel came before it, the command would no longer be a command. So a message starting with `/` is sent as it is, without context, and `/garfield:idioms …` picks the agent when several are in the channel. An agent announces its commands as soon as a session opens, before any question — and mm does so without loading its model. So the first `/` typed in a conversation starts the members that never announced theirs and opens their session (the one their first answer will use); the list fills in a fraction of a second. Sidekicks then keeps the commands, and offers them at once the next times.31 `/idioms Il pleut des cordes` asks Garfield to run a skill. The agent recognises a command by its first character. If the transcript of the channel came before it, the command would no longer be a command. So a message starting with `/` is sent as it is, without context, and `/garfield:idioms …` picks the agent when several are in the channel. An agent announces its commands as soon as a session opens, before any question — and mm does so without loading its model. So the first `/` typed in a conversation starts the members that never announced theirs and opens their session (the one their first answer will use); the list fills in a fraction of a second. Sidekicks then keeps the commands, and offers them at once the next times.
modified docs/en/how-to/manage-channels.md +11 -0
@@ -44,9 +44,20 @@ While an agent is answering, the history cannot be cleared: stop it (**■**) or
4444 | --- | --- |
4545 | a specific agent to answer | `@name your message` (the list after `@` filters as you type; Tab or Enter picks) |
4646 | several agents to answer in turn | `@alice @bob compare your answers` |
47+| an agent to involve another one | ask it: `@alice …, and ask @bob` ([below](#let-the-agents-call-each-other)) |
4748 | the agent you were talking with | your message, without mention |
4849 | an agent's command | `/` then pick it in the list; with several agents, `/agent:command` |
4950
51+## Let the agents call each other
52+
53+In a channel, an agent can hand the floor to another member by mentioning it in its answer: when Alice answers "@bob knows the trains better", Bob answers right after, told that Alice addressed him (he also reads your message and Alice's answer).
54+
55+1. Put the agents in the same channel (only **members** can be called this way: an agent never brings a new one in).
56+2. Ask one of them, e.g. `@alice plan a trip to Lyon, and ask @bob for the trains`. Most agents only mention another one when asked to, or when their instructions say who is in the team.
57+3. To stop a chain, click **■**: the agent answering stops, and the others do not answer.
58+
59+An agent does not call itself, an agent that answers your message anyway is not asked twice, a mention inside code does not count, and the answer to a `/command` calls nobody. A message is handed from agent to agent **3 times at most**; then the channel says the chain stops, and you can mention the next agent yourself. Change the limit with `limits.maxAgentHandoffs` in the [configuration](../reference/configuration.md#limits) (`0` turns it off). In a direct conversation, mentions stay plain text.
60+
5061 ## Variants
5162
5263 - **Fold the lists of the left panel**: click the heading **AGENTS** or **CHANNELS** to fold the list under it, again to unfold it. Folded, the heading still shows how many agents or channels there are and, in blue, the answers you have not read yet. Sidekicks remembers it at the next launch. ⌘N unfolds the channels to create one; **Add an agent** stays in the command palette (⌘K) and on ⇧⌘N.
@@ -44,9 +44,20 @@ While an agent is answering, the history cannot be cleared: stop it (**■**) or
44 | --- | --- |44 | --- | --- |
45 | a specific agent to answer | `@name your message` (the list after `@` filters as you type; Tab or Enter picks) |45 | a specific agent to answer | `@name your message` (the list after `@` filters as you type; Tab or Enter picks) |
46 | several agents to answer in turn | `@alice @bob compare your answers` |46 | several agents to answer in turn | `@alice @bob compare your answers` |
47+| an agent to involve another one | ask it: `@alice …, and ask @bob` ([below](#let-the-agents-call-each-other)) |
47 | the agent you were talking with | your message, without mention |48 | the agent you were talking with | your message, without mention |
48 | an agent's command | `/` then pick it in the list; with several agents, `/agent:command` |49 | an agent's command | `/` then pick it in the list; with several agents, `/agent:command` |
49 50
51+## Let the agents call each other
52+
53+In a channel, an agent can hand the floor to another member by mentioning it in its answer: when Alice answers "@bob knows the trains better", Bob answers right after, told that Alice addressed him (he also reads your message and Alice's answer).
54+
55+1. Put the agents in the same channel (only **members** can be called this way: an agent never brings a new one in).
56+2. Ask one of them, e.g. `@alice plan a trip to Lyon, and ask @bob for the trains`. Most agents only mention another one when asked to, or when their instructions say who is in the team.
57+3. To stop a chain, click **■**: the agent answering stops, and the others do not answer.
58+
59+An agent does not call itself, an agent that answers your message anyway is not asked twice, a mention inside code does not count, and the answer to a `/command` calls nobody. A message is handed from agent to agent **3 times at most**; then the channel says the chain stops, and you can mention the next agent yourself. Change the limit with `limits.maxAgentHandoffs` in the [configuration](../reference/configuration.md#limits) (`0` turns it off). In a direct conversation, mentions stay plain text.
60+
50 ## Variants61 ## Variants
51 62
52 - **Fold the lists of the left panel**: click the heading **AGENTS** or **CHANNELS** to fold the list under it, again to unfold it. Folded, the heading still shows how many agents or channels there are and, in blue, the answers you have not read yet. Sidekicks remembers it at the next launch. ⌘N unfolds the channels to create one; **Add an agent** stays in the command palette (⌘K) and on ⇧⌘N.63 - **Fold the lists of the left panel**: click the heading **AGENTS** or **CHANNELS** to fold the list under it, again to unfold it. Folded, the heading still shows how many agents or channels there are and, in blue, the answers you have not read yet. Sidekicks remembers it at the next launch. ⌘N unfolds the channels to create one; **Add an agent** stays in the command palette (⌘K) and on ⇧⌘N.
modified docs/en/reference/agents-and-events.md +2 -1
@@ -77,6 +77,7 @@ A channel holds a conversation between the user and one or several agents. A dir
7777 | no mention | the last agent who answered in the channel; with a single member, that member |
7878 | no mention and nobody answered yet, several members | nobody: system message `no-recipient` |
7979 | any message in a direct conversation | its agent; mentions are plain text there |
80+| an agent's answer, in a channel, mentions other **members** with `@name` (issue #26) | those members answer next, in order, each told who addressed it; not the agent itself, not an agent that answers the message anyway, not a non-member, not a mention inside code, not the answer to a command. At most `limits.maxAgentHandoffs` hand-offs per user message (3 by default; `0` turns it off), then the system message `handoff-limit`; **■** stops the whole chain |
8081
8182 A message starting with `/` (possibly after mentions) is a command: it is sent alone. Any other message is sent with the channel messages the agent has not seen yet (at most the last 20, each cut at 1500 characters). An agent answers one channel at a time; a channel waiting for it shows whose turn it is.
8283
@@ -107,7 +108,7 @@ A file is read when the agent's turn comes (5 MB at most); one that cannot be re
107108 | `queued` | a user message waiting for the current answers |
108109 | `stopReason` | how an agent message ended: `end_turn`, `cancelled`, `max_tokens`, `max_turn_requests`, `refusal` |
109110 | `error` | why an agent message ended without a stop reason (the agent's own explanation), or `cancelled` for a queued message dropped by Stop |
110-| `code` | system messages: `agent-joined`, `agent-left`, `no-recipient`, `agent-unavailable` (could not start or reach it; `error` says why), `attachment-unavailable` (a joined file was not sent to `agent`; `error` names it and says why) |
111+| `code` | system messages: `agent-joined`, `agent-left`, `no-recipient`, `agent-unavailable` (could not start or reach it; `error` says why), `attachment-unavailable` (a joined file was not sent to `agent`; `error` names it and says why), `handoff-limit` (`agent` mentioned a member, but the message was already handed on `limits.maxAgentHandoffs` times) |
111112 | `attachments` | user messages: the files joined with `$path`, as `{agent, path}` (the agent whose folder holds it). Only the reference is kept, never the content. |
112113
113114 A tool call has `id, title, kind` (`read, edit, delete, move, search, execute, think, fetch, other`), `status` (`pending, in_progress, completed, failed`), `input` (compact JSON), `output`, `locations`, `diffs` (`path, oldText, newText, newFile`).
@@ -77,6 +77,7 @@ A channel holds a conversation between the user and one or several agents. A dir
77 | no mention | the last agent who answered in the channel; with a single member, that member |77 | no mention | the last agent who answered in the channel; with a single member, that member |
78 | no mention and nobody answered yet, several members | nobody: system message `no-recipient` |78 | no mention and nobody answered yet, several members | nobody: system message `no-recipient` |
79 | any message in a direct conversation | its agent; mentions are plain text there |79 | any message in a direct conversation | its agent; mentions are plain text there |
80+| an agent's answer, in a channel, mentions other **members** with `@name` (issue #26) | those members answer next, in order, each told who addressed it; not the agent itself, not an agent that answers the message anyway, not a non-member, not a mention inside code, not the answer to a command. At most `limits.maxAgentHandoffs` hand-offs per user message (3 by default; `0` turns it off), then the system message `handoff-limit`; **■** stops the whole chain |
80 81
81 A message starting with `/` (possibly after mentions) is a command: it is sent alone. Any other message is sent with the channel messages the agent has not seen yet (at most the last 20, each cut at 1500 characters). An agent answers one channel at a time; a channel waiting for it shows whose turn it is.82 A message starting with `/` (possibly after mentions) is a command: it is sent alone. Any other message is sent with the channel messages the agent has not seen yet (at most the last 20, each cut at 1500 characters). An agent answers one channel at a time; a channel waiting for it shows whose turn it is.
82 83
@@ -107,7 +108,7 @@ A file is read when the agent's turn comes (5 MB at most); one that cannot be re
107 | `queued` | a user message waiting for the current answers |108 | `queued` | a user message waiting for the current answers |
108 | `stopReason` | how an agent message ended: `end_turn`, `cancelled`, `max_tokens`, `max_turn_requests`, `refusal` |109 | `stopReason` | how an agent message ended: `end_turn`, `cancelled`, `max_tokens`, `max_turn_requests`, `refusal` |
109 | `error` | why an agent message ended without a stop reason (the agent's own explanation), or `cancelled` for a queued message dropped by Stop |110 | `error` | why an agent message ended without a stop reason (the agent's own explanation), or `cancelled` for a queued message dropped by Stop |
110-| `code` | system messages: `agent-joined`, `agent-left`, `no-recipient`, `agent-unavailable` (could not start or reach it; `error` says why), `attachment-unavailable` (a joined file was not sent to `agent`; `error` names it and says why) |111+| `code` | system messages: `agent-joined`, `agent-left`, `no-recipient`, `agent-unavailable` (could not start or reach it; `error` says why), `attachment-unavailable` (a joined file was not sent to `agent`; `error` names it and says why), `handoff-limit` (`agent` mentioned a member, but the message was already handed on `limits.maxAgentHandoffs` times) |
111 | `attachments` | user messages: the files joined with `$path`, as `{agent, path}` (the agent whose folder holds it). Only the reference is kept, never the content. |112 | `attachments` | user messages: the files joined with `$path`, as `{agent, path}` (the agent whose folder holds it). Only the reference is kept, never the content. |
112 113
113 A tool call has `id, title, kind` (`read, edit, delete, move, search, execute, think, fetch, other`), `status` (`pending, in_progress, completed, failed`), `input` (compact JSON), `output`, `locations`, `diffs` (`path, oldText, newText, newFile`).114 A tool call has `id, title, kind` (`read, edit, delete, move, search, execute, think, fetch, other`), `status` (`pending, in_progress, completed, failed`), `input` (compact JSON), `output`, `locations`, `diffs` (`path, oldText, newText, newFile`).
modified docs/en/reference/configuration.md +1 -0
@@ -56,6 +56,7 @@ Unknown keys are **errors**, at every level: a misspelt `comand:` must be report
5656 | --- | --- | --- | --- |
5757 | `maxRunningAgents` | integer ≥ 1 | `2` | Agents running at the same time. Each local agent keeps a model in memory; the default fits a 32 GB laptop with small models. |
5858 | `stopIdleAgentsAfter` | Go duration (`30s`, `10m`, `1h30m`), or `0` (number or text) | `10m` | Stops an agent unused for this long, to free its memory. `0` never stops it. |
59+| `maxAgentHandoffs` | integer, 0 to 10 | `3` | In a channel, how many times one message may be handed from agent to agent: an agent whose answer mentions another member with `@name` gives it the floor ([Manage channels](../how-to/manage-channels.md#let-the-agents-call-each-other)). Once the limit is reached the chain stops, and says so. `0` turns it off. |
5960
6061 ### An agent
6162
@@ -56,6 +56,7 @@ Unknown keys are **errors**, at every level: a misspelt `comand:` must be report
56 | --- | --- | --- | --- |56 | --- | --- | --- | --- |
57 | `maxRunningAgents` | integer ≥ 1 | `2` | Agents running at the same time. Each local agent keeps a model in memory; the default fits a 32 GB laptop with small models. |57 | `maxRunningAgents` | integer ≥ 1 | `2` | Agents running at the same time. Each local agent keeps a model in memory; the default fits a 32 GB laptop with small models. |
58 | `stopIdleAgentsAfter` | Go duration (`30s`, `10m`, `1h30m`), or `0` (number or text) | `10m` | Stops an agent unused for this long, to free its memory. `0` never stops it. |58 | `stopIdleAgentsAfter` | Go duration (`30s`, `10m`, `1h30m`), or `0` (number or text) | `10m` | Stops an agent unused for this long, to free its memory. `0` never stops it. |
59+| `maxAgentHandoffs` | integer, 0 to 10 | `3` | In a channel, how many times one message may be handed from agent to agent: an agent whose answer mentions another member with `@name` gives it the floor ([Manage channels](../how-to/manage-channels.md#let-the-agents-call-each-other)). Once the limit is reached the chain stops, and says so. `0` turns it off. |
59 60
60 ### An agent61 ### An agent
61 62
modified docs/fr/explanation/channels-et-contexte.md +8 -0
@@ -18,6 +18,14 @@ Un message va aux agents qu'il mentionne, dans l'ordre ; sans mention, au dernie
1818
1919 Les agents répondent l'un après l'autre, jamais en même temps. Sur un portable, deux modèles locaux qui génèrent ensemble sont chacun plus lents qu'à tour de rôle, et la mémoire est la vraie limite (deux petits modèles sur la machine de référence). Répondre à tour de rôle permet aussi au second agent de lire la réponse du premier : « @alice @bob comparez » donne à Bob la réponse d'Alice à comparer. Pour la même raison, un agent répond à un seul channel à la fois : un second channel attend, et indique à qui c'est le tour.
2020
21+## Quand un agent en appelle un autre
22+
23+Un agent peut avoir besoin d'un autre : Alice prépare un voyage, Bob connaît les trains. Sidekicks laisse un agent passer la parole comme le fait l'utilisateur — en mentionnant un membre avec `@nom` dans sa réponse (ticket #26). L'agent mentionné répond ensuite, lit le channel comme d'habitude (le message de l'utilisateur et la réponse d'Alice parmi ce qu'il n'a pas vu) et apprend qu'Alice s'adresse à lui : il lui répond, à elle, plutôt qu'à l'utilisateur.
24+
25+Les mentions ont été préférées à un outil offert aux agents (un serveur MCP « demander à un agent ») : elles ne demandent rien à l'agent — mm ignore les serveurs MCP qu'un client lui propose — et l'utilisateur voit tout l'échange dans le channel, comme s'il avait écrit la mention lui-même.
26+
27+Le risque est la boucle : deux agents polis peuvent se remercier sans fin, et chaque tour occupe un modèle. La chaîne est donc bornée : un message passe au plus `limits.maxAgentHandoffs` fois d'agent en agent (3 par défaut), puis le channel indique qu'elle s'arrête. Seuls les membres peuvent être appelés — un agent n'en fait jamais entrer un nouveau, ce qui chargerait un autre modèle —, un agent ne peut pas s'appeler lui-même, et **■** arrête toute la chaîne. Dans une conversation directe, il n'y a personne à appeler.
28+
2129 ## Les commandes partent seules
2230
2331 `/idioms Il pleut des cordes` demande à Garfield d'exécuter une skill. L'agent reconnaît une commande à son premier caractère. Si la transcription du channel la précédait, la commande n'en serait plus une. Un message qui commence par `/` est donc envoyé tel quel, sans contexte, et `/garfield:idioms …` choisit l'agent quand le channel en compte plusieurs. Un agent annonce ses commandes dès qu'une session s'ouvre, avant toute question — et mm le fait sans charger son modèle. Le premier `/` tapé dans une conversation démarre donc les membres qui n'ont jamais annoncé les leurs et ouvre leur session (celle que servira leur première réponse) ; la liste se remplit en une fraction de seconde. Sidekicks garde ensuite les commandes et les propose aussitôt les fois suivantes.
@@ -18,6 +18,14 @@ Un message va aux agents qu'il mentionne, dans l'ordre ; sans mention, au dernie
18 18
19 Les agents répondent l'un après l'autre, jamais en même temps. Sur un portable, deux modèles locaux qui génèrent ensemble sont chacun plus lents qu'à tour de rôle, et la mémoire est la vraie limite (deux petits modèles sur la machine de référence). Répondre à tour de rôle permet aussi au second agent de lire la réponse du premier : « @alice @bob comparez » donne à Bob la réponse d'Alice à comparer. Pour la même raison, un agent répond à un seul channel à la fois : un second channel attend, et indique à qui c'est le tour.19 Les agents répondent l'un après l'autre, jamais en même temps. Sur un portable, deux modèles locaux qui génèrent ensemble sont chacun plus lents qu'à tour de rôle, et la mémoire est la vraie limite (deux petits modèles sur la machine de référence). Répondre à tour de rôle permet aussi au second agent de lire la réponse du premier : « @alice @bob comparez » donne à Bob la réponse d'Alice à comparer. Pour la même raison, un agent répond à un seul channel à la fois : un second channel attend, et indique à qui c'est le tour.
20 20
21+## Quand un agent en appelle un autre
22+
23+Un agent peut avoir besoin d'un autre : Alice prépare un voyage, Bob connaît les trains. Sidekicks laisse un agent passer la parole comme le fait l'utilisateur — en mentionnant un membre avec `@nom` dans sa réponse (ticket #26). L'agent mentionné répond ensuite, lit le channel comme d'habitude (le message de l'utilisateur et la réponse d'Alice parmi ce qu'il n'a pas vu) et apprend qu'Alice s'adresse à lui : il lui répond, à elle, plutôt qu'à l'utilisateur.
24+
25+Les mentions ont été préférées à un outil offert aux agents (un serveur MCP « demander à un agent ») : elles ne demandent rien à l'agent — mm ignore les serveurs MCP qu'un client lui propose — et l'utilisateur voit tout l'échange dans le channel, comme s'il avait écrit la mention lui-même.
26+
27+Le risque est la boucle : deux agents polis peuvent se remercier sans fin, et chaque tour occupe un modèle. La chaîne est donc bornée : un message passe au plus `limits.maxAgentHandoffs` fois d'agent en agent (3 par défaut), puis le channel indique qu'elle s'arrête. Seuls les membres peuvent être appelés — un agent n'en fait jamais entrer un nouveau, ce qui chargerait un autre modèle —, un agent ne peut pas s'appeler lui-même, et **■** arrête toute la chaîne. Dans une conversation directe, il n'y a personne à appeler.
28+
21 ## Les commandes partent seules29 ## Les commandes partent seules
22 30
23 `/idioms Il pleut des cordes` demande à Garfield d'exécuter une skill. L'agent reconnaît une commande à son premier caractère. Si la transcription du channel la précédait, la commande n'en serait plus une. Un message qui commence par `/` est donc envoyé tel quel, sans contexte, et `/garfield:idioms …` choisit l'agent quand le channel en compte plusieurs. Un agent annonce ses commandes dès qu'une session s'ouvre, avant toute question — et mm le fait sans charger son modèle. Le premier `/` tapé dans une conversation démarre donc les membres qui n'ont jamais annoncé les leurs et ouvre leur session (celle que servira leur première réponse) ; la liste se remplit en une fraction de seconde. Sidekicks garde ensuite les commandes et les propose aussitôt les fois suivantes.31 `/idioms Il pleut des cordes` demande à Garfield d'exécuter une skill. L'agent reconnaît une commande à son premier caractère. Si la transcription du channel la précédait, la commande n'en serait plus une. Un message qui commence par `/` est donc envoyé tel quel, sans contexte, et `/garfield:idioms …` choisit l'agent quand le channel en compte plusieurs. Un agent annonce ses commandes dès qu'une session s'ouvre, avant toute question — et mm le fait sans charger son modèle. Le premier `/` tapé dans une conversation démarre donc les membres qui n'ont jamais annoncé les leurs et ouvre leur session (celle que servira leur première réponse) ; la liste se remplit en une fraction de seconde. Sidekicks garde ensuite les commandes et les propose aussitôt les fois suivantes.
modified docs/fr/how-to/gerer-les-channels.md +11 -0
@@ -44,9 +44,20 @@ Pendant qu'un agent répond, l'historique ne peut pas être vidé : arrêtez-le
4444 | --- | --- |
4545 | qu'un agent précis réponde | `@nom votre message` (la liste après `@` se filtre pendant la frappe ; Tab ou Entrée choisit) |
4646 | que plusieurs agents répondent à tour de rôle | `@alice @bob comparez vos réponses` |
47+| qu'un agent en fasse intervenir un autre | demandez-le-lui : `@alice …, et demande à @bob` ([plus bas](#laisser-les-agents-sappeler-entre-eux)) |
4748 | continuer avec l'agent à qui vous parliez | votre message, sans mention |
4849 | une commande d'un agent | `/` puis choisissez-la dans la liste ; avec plusieurs agents, `/agent:commande` |
4950
51+## Laisser les agents s'appeler entre eux
52+
53+Dans un channel, un agent peut passer la parole à un autre membre en le mentionnant dans sa réponse : quand Alice répond « @bob connaît mieux les trains », Bob répond juste après, en sachant qu'Alice s'adresse à lui (il lit aussi votre message et la réponse d'Alice).
54+
55+1. Mettez les agents dans le même channel (seuls les **membres** peuvent être appelés ainsi : un agent n'en fait jamais entrer un nouveau).
56+2. Demandez à l'un d'eux, par exemple `@alice prépare un voyage à Lyon, et demande à @bob pour les trains`. La plupart des agents ne mentionnent un autre agent que si on le leur demande, ou si leurs instructions disent qui est dans l'équipe.
57+3. Pour arrêter une chaîne, cliquez sur **■** : l'agent qui répond s'arrête, et les autres ne répondent pas.
58+
59+Un agent ne s'appelle pas lui-même, un agent qui répond de toute façon à votre message n'est pas sollicité deux fois, une mention dans du code ne compte pas, et la réponse à une `/commande` n'appelle personne. Un message passe d'agent en agent **3 fois au plus** ; ensuite le channel indique que la chaîne s'arrête, et vous pouvez mentionner vous-même l'agent suivant. Changez la limite avec `limits.maxAgentHandoffs` dans la [configuration](../reference/configuration.md#limits) (`0` désactive). Dans une conversation directe, les mentions restent du simple texte.
60+
5061 ## Variantes
5162
5263 - **Replier les listes du panneau de gauche** : cliquez sur le titre **AGENTS** ou **CHANNELS** pour replier la liste, à nouveau pour la déplier. Repliée, le titre indique toujours combien il y a d'agents ou de channels et, en bleu, les réponses pas encore lues. Sidekicks s'en souvient au lancement suivant. ⌘N déplie les channels pour en créer un ; **Ajouter un agent** reste dans la palette de commandes (⌘K) et sur ⇧⌘N.
@@ -44,9 +44,20 @@ Pendant qu'un agent répond, l'historique ne peut pas être vidé : arrêtez-le
44 | --- | --- |44 | --- | --- |
45 | qu'un agent précis réponde | `@nom votre message` (la liste après `@` se filtre pendant la frappe ; Tab ou Entrée choisit) |45 | qu'un agent précis réponde | `@nom votre message` (la liste après `@` se filtre pendant la frappe ; Tab ou Entrée choisit) |
46 | que plusieurs agents répondent à tour de rôle | `@alice @bob comparez vos réponses` |46 | que plusieurs agents répondent à tour de rôle | `@alice @bob comparez vos réponses` |
47+| qu'un agent en fasse intervenir un autre | demandez-le-lui : `@alice …, et demande à @bob` ([plus bas](#laisser-les-agents-sappeler-entre-eux)) |
47 | continuer avec l'agent à qui vous parliez | votre message, sans mention |48 | continuer avec l'agent à qui vous parliez | votre message, sans mention |
48 | une commande d'un agent | `/` puis choisissez-la dans la liste ; avec plusieurs agents, `/agent:commande` |49 | une commande d'un agent | `/` puis choisissez-la dans la liste ; avec plusieurs agents, `/agent:commande` |
49 50
51+## Laisser les agents s'appeler entre eux
52+
53+Dans un channel, un agent peut passer la parole à un autre membre en le mentionnant dans sa réponse : quand Alice répond « @bob connaît mieux les trains », Bob répond juste après, en sachant qu'Alice s'adresse à lui (il lit aussi votre message et la réponse d'Alice).
54+
55+1. Mettez les agents dans le même channel (seuls les **membres** peuvent être appelés ainsi : un agent n'en fait jamais entrer un nouveau).
56+2. Demandez à l'un d'eux, par exemple `@alice prépare un voyage à Lyon, et demande à @bob pour les trains`. La plupart des agents ne mentionnent un autre agent que si on le leur demande, ou si leurs instructions disent qui est dans l'équipe.
57+3. Pour arrêter une chaîne, cliquez sur **■** : l'agent qui répond s'arrête, et les autres ne répondent pas.
58+
59+Un agent ne s'appelle pas lui-même, un agent qui répond de toute façon à votre message n'est pas sollicité deux fois, une mention dans du code ne compte pas, et la réponse à une `/commande` n'appelle personne. Un message passe d'agent en agent **3 fois au plus** ; ensuite le channel indique que la chaîne s'arrête, et vous pouvez mentionner vous-même l'agent suivant. Changez la limite avec `limits.maxAgentHandoffs` dans la [configuration](../reference/configuration.md#limits) (`0` désactive). Dans une conversation directe, les mentions restent du simple texte.
60+
50 ## Variantes61 ## Variantes
51 62
52 - **Replier les listes du panneau de gauche** : cliquez sur le titre **AGENTS** ou **CHANNELS** pour replier la liste, à nouveau pour la déplier. Repliée, le titre indique toujours combien il y a d'agents ou de channels et, en bleu, les réponses pas encore lues. Sidekicks s'en souvient au lancement suivant. ⌘N déplie les channels pour en créer un ; **Ajouter un agent** reste dans la palette de commandes (⌘K) et sur ⇧⌘N.63 - **Replier les listes du panneau de gauche** : cliquez sur le titre **AGENTS** ou **CHANNELS** pour replier la liste, à nouveau pour la déplier. Repliée, le titre indique toujours combien il y a d'agents ou de channels et, en bleu, les réponses pas encore lues. Sidekicks s'en souvient au lancement suivant. ⌘N déplie les channels pour en créer un ; **Ajouter un agent** reste dans la palette de commandes (⌘K) et sur ⇧⌘N.
modified docs/fr/reference/agents-et-evenements.md +2 -1
@@ -77,6 +77,7 @@ Un channel contient une conversation entre l'utilisateur et un ou plusieurs agen
7777 | sans mention | le dernier agent qui a répondu dans le channel ; avec un seul membre, ce membre |
7878 | sans mention, personne n'a encore répondu, plusieurs membres | personne : message système `no-recipient` |
7979 | tout message d'une conversation directe | son agent ; les mentions y sont du simple texte |
80+| la réponse d'un agent, dans un channel, mentionne d'autres **membres** avec `@nom` (ticket #26) | ces membres répondent ensuite, dans l'ordre, chacun informé de qui s'adresse à lui ; ni l'agent lui-même, ni un agent qui répond de toute façon au message, ni un non-membre, ni une mention dans du code, ni la réponse à une commande. Au plus `limits.maxAgentHandoffs` passages de parole par message de l'utilisateur (3 par défaut ; `0` désactive), puis le message système `handoff-limit` ; **■** arrête toute la chaîne |
8081
8182 Un message qui commence par `/` (éventuellement après des mentions) est une commande : il est envoyé seul. Tout autre message est envoyé avec les messages du channel que l'agent n'a pas encore vus (au plus les 20 derniers, chacun coupé à 1500 caractères). Un agent répond à un seul channel à la fois ; un channel qui l'attend indique à qui c'est le tour.
8283
@@ -107,7 +108,7 @@ Un fichier est lu quand vient le tour de l'agent (5 Mo au plus) ; un fichier ill
107108 | `queued` | un message de l'utilisateur qui attend la fin des réponses en cours |
108109 | `stopReason` | comment un message d'agent s'est terminé : `end_turn`, `cancelled`, `max_tokens`, `max_turn_requests`, `refusal` |
109110 | `error` | pourquoi un message d'agent s'est terminé sans raison d'arrêt (l'explication de l'agent), ou `cancelled` pour un message en attente abandonné par Stop |
110-| `code` | messages système : `agent-joined`, `agent-left`, `no-recipient`, `agent-unavailable` (impossible de le démarrer ou de le joindre ; `error` dit pourquoi), `attachment-unavailable` (un fichier joint n'a pas été envoyé à `agent` ; `error` le nomme et dit pourquoi) |
111+| `code` | messages système : `agent-joined`, `agent-left`, `no-recipient`, `agent-unavailable` (impossible de le démarrer ou de le joindre ; `error` dit pourquoi), `attachment-unavailable` (un fichier joint n'a pas été envoyé à `agent` ; `error` le nomme et dit pourquoi), `handoff-limit` (`agent` a mentionné un membre, mais le message est déjà passé `limits.maxAgentHandoffs` fois d'agent en agent) |
111112 | `attachments` | messages de l'utilisateur : les fichiers joints avec `$chemin`, sous la forme `{agent, path}` (l'agent dont le dossier le contient). Seule la référence est gardée, jamais le contenu. |
112113
113114 Un appel d'outil a `id, title, kind` (`read, edit, delete, move, search, execute, think, fetch, other`), `status` (`pending, in_progress, completed, failed`), `input` (JSON compact), `output`, `locations`, `diffs` (`path, oldText, newText, newFile`).
@@ -77,6 +77,7 @@ Un channel contient une conversation entre l'utilisateur et un ou plusieurs agen
77 | sans mention | le dernier agent qui a répondu dans le channel ; avec un seul membre, ce membre |77 | sans mention | le dernier agent qui a répondu dans le channel ; avec un seul membre, ce membre |
78 | sans mention, personne n'a encore répondu, plusieurs membres | personne : message système `no-recipient` |78 | sans mention, personne n'a encore répondu, plusieurs membres | personne : message système `no-recipient` |
79 | tout message d'une conversation directe | son agent ; les mentions y sont du simple texte |79 | tout message d'une conversation directe | son agent ; les mentions y sont du simple texte |
80+| la réponse d'un agent, dans un channel, mentionne d'autres **membres** avec `@nom` (ticket #26) | ces membres répondent ensuite, dans l'ordre, chacun informé de qui s'adresse à lui ; ni l'agent lui-même, ni un agent qui répond de toute façon au message, ni un non-membre, ni une mention dans du code, ni la réponse à une commande. Au plus `limits.maxAgentHandoffs` passages de parole par message de l'utilisateur (3 par défaut ; `0` désactive), puis le message système `handoff-limit` ; **■** arrête toute la chaîne |
80 81
81 Un message qui commence par `/` (éventuellement après des mentions) est une commande : il est envoyé seul. Tout autre message est envoyé avec les messages du channel que l'agent n'a pas encore vus (au plus les 20 derniers, chacun coupé à 1500 caractères). Un agent répond à un seul channel à la fois ; un channel qui l'attend indique à qui c'est le tour.82 Un message qui commence par `/` (éventuellement après des mentions) est une commande : il est envoyé seul. Tout autre message est envoyé avec les messages du channel que l'agent n'a pas encore vus (au plus les 20 derniers, chacun coupé à 1500 caractères). Un agent répond à un seul channel à la fois ; un channel qui l'attend indique à qui c'est le tour.
82 83
@@ -107,7 +108,7 @@ Un fichier est lu quand vient le tour de l'agent (5 Mo au plus) ; un fichier ill
107 | `queued` | un message de l'utilisateur qui attend la fin des réponses en cours |108 | `queued` | un message de l'utilisateur qui attend la fin des réponses en cours |
108 | `stopReason` | comment un message d'agent s'est terminé : `end_turn`, `cancelled`, `max_tokens`, `max_turn_requests`, `refusal` |109 | `stopReason` | comment un message d'agent s'est terminé : `end_turn`, `cancelled`, `max_tokens`, `max_turn_requests`, `refusal` |
109 | `error` | pourquoi un message d'agent s'est terminé sans raison d'arrêt (l'explication de l'agent), ou `cancelled` pour un message en attente abandonné par Stop |110 | `error` | pourquoi un message d'agent s'est terminé sans raison d'arrêt (l'explication de l'agent), ou `cancelled` pour un message en attente abandonné par Stop |
110-| `code` | messages système : `agent-joined`, `agent-left`, `no-recipient`, `agent-unavailable` (impossible de le démarrer ou de le joindre ; `error` dit pourquoi), `attachment-unavailable` (un fichier joint n'a pas été envoyé à `agent` ; `error` le nomme et dit pourquoi) |111+| `code` | messages système : `agent-joined`, `agent-left`, `no-recipient`, `agent-unavailable` (impossible de le démarrer ou de le joindre ; `error` dit pourquoi), `attachment-unavailable` (un fichier joint n'a pas été envoyé à `agent` ; `error` le nomme et dit pourquoi), `handoff-limit` (`agent` a mentionné un membre, mais le message est déjà passé `limits.maxAgentHandoffs` fois d'agent en agent) |
111 | `attachments` | messages de l'utilisateur : les fichiers joints avec `$chemin`, sous la forme `{agent, path}` (l'agent dont le dossier le contient). Seule la référence est gardée, jamais le contenu. |112 | `attachments` | messages de l'utilisateur : les fichiers joints avec `$chemin`, sous la forme `{agent, path}` (l'agent dont le dossier le contient). Seule la référence est gardée, jamais le contenu. |
112 113
113 Un appel d'outil a `id, title, kind` (`read, edit, delete, move, search, execute, think, fetch, other`), `status` (`pending, in_progress, completed, failed`), `input` (JSON compact), `output`, `locations`, `diffs` (`path, oldText, newText, newFile`).114 Un appel d'outil a `id, title, kind` (`read, edit, delete, move, search, execute, think, fetch, other`), `status` (`pending, in_progress, completed, failed`), `input` (JSON compact), `output`, `locations`, `diffs` (`path, oldText, newText, newFile`).
modified docs/fr/reference/configuration.md +1 -0
@@ -56,6 +56,7 @@ Les clés inconnues sont des **erreurs**, à tous les niveaux : une faute de fra
5656 | --- | --- | --- | --- |
5757 | `maxRunningAgents` | entier ≥ 1 | `2` | Agents actifs en même temps. Chaque agent local garde un modèle en mémoire ; la valeur par défaut convient à un portable de 32 Go avec de petits modèles. |
5858 | `stopIdleAgentsAfter` | durée Go (`30s`, `10m`, `1h30m`), ou `0` (nombre ou texte) | `10m` | Arrête un agent inutilisé depuis ce délai pour libérer sa mémoire. `0` ne l'arrête jamais. |
59+| `maxAgentHandoffs` | entier, de 0 à 10 | `3` | Dans un channel, combien de fois un même message peut passer d'agent en agent : un agent dont la réponse mentionne un autre membre avec `@nom` lui passe la parole ([Gérer les channels](../how-to/gerer-les-channels.md#laisser-les-agents-sappeler-entre-eux)). La limite atteinte, la chaîne s'arrête et le dit. `0` désactive. |
5960
6061 ### Un agent
6162
@@ -56,6 +56,7 @@ Les clés inconnues sont des **erreurs**, à tous les niveaux : une faute de fra
56 | --- | --- | --- | --- |56 | --- | --- | --- | --- |
57 | `maxRunningAgents` | entier ≥ 1 | `2` | Agents actifs en même temps. Chaque agent local garde un modèle en mémoire ; la valeur par défaut convient à un portable de 32 Go avec de petits modèles. |57 | `maxRunningAgents` | entier ≥ 1 | `2` | Agents actifs en même temps. Chaque agent local garde un modèle en mémoire ; la valeur par défaut convient à un portable de 32 Go avec de petits modèles. |
58 | `stopIdleAgentsAfter` | durée Go (`30s`, `10m`, `1h30m`), ou `0` (nombre ou texte) | `10m` | Arrête un agent inutilisé depuis ce délai pour libérer sa mémoire. `0` ne l'arrête jamais. |58 | `stopIdleAgentsAfter` | durée Go (`30s`, `10m`, `1h30m`), ou `0` (nombre ou texte) | `10m` | Arrête un agent inutilisé depuis ce délai pour libérer sa mémoire. `0` ne l'arrête jamais. |
59+| `maxAgentHandoffs` | entier, de 0 à 10 | `3` | Dans un channel, combien de fois un même message peut passer d'agent en agent : un agent dont la réponse mentionne un autre membre avec `@nom` lui passe la parole ([Gérer les channels](../how-to/gerer-les-channels.md#laisser-les-agents-sappeler-entre-eux)). La limite atteinte, la chaîne s'arrête et le dit. `0` désactive. |
59 60
60 ### Un agent61 ### Un agent
61 62
modified frontend/src/lib/i18n/messages.ts +2 -0
@@ -122,6 +122,7 @@ export const en = {
122122 'system.no-recipient': 'Nobody was addressed: mention an agent with @ (for example @{example}).',
123123 'system.agent-unavailable': '{agent} could not answer.',
124124 'system.attachment-unavailable': 'A file was not sent to {agent}.',
125+ 'system.handoff-limit': '{agent} mentioned another agent, but this message was already handed from agent to agent as often as allowed (limits.maxAgentHandoffs): the chain stops here. Mention the agent yourself to go on.',
125126
126127 // tool calls
127128 'tool.status.pending': 'waiting',
@@ -513,6 +514,7 @@ export const fr: Record<MessageKey, string> = {
513514 'system.no-recipient': "Personne n'est désigné : mentionnez un agent avec @ (par exemple @{example}).",
514515 'system.agent-unavailable': "{agent} n'a pas pu répondre.",
515516 'system.attachment-unavailable': "Un fichier n'a pas été envoyé à {agent}.",
517+ 'system.handoff-limit': "{agent} a mentionné un autre agent, mais ce message est déjà passé d'agent en agent autant de fois que permis (limits.maxAgentHandoffs) : la chaîne s'arrête ici. Mentionnez vous-même l'agent pour continuer.",
516518
517519 'tool.status.pending': 'en attente',
518520 'tool.status.in_progress': 'en cours',
@@ -122,6 +122,7 @@ export const en = {
122 'system.no-recipient': 'Nobody was addressed: mention an agent with @ (for example @{example}).',122 'system.no-recipient': 'Nobody was addressed: mention an agent with @ (for example @{example}).',
123 'system.agent-unavailable': '{agent} could not answer.',123 'system.agent-unavailable': '{agent} could not answer.',
124 'system.attachment-unavailable': 'A file was not sent to {agent}.',124 'system.attachment-unavailable': 'A file was not sent to {agent}.',
125+ 'system.handoff-limit': '{agent} mentioned another agent, but this message was already handed from agent to agent as often as allowed (limits.maxAgentHandoffs): the chain stops here. Mention the agent yourself to go on.',
125 126
126 // tool calls127 // tool calls
127 'tool.status.pending': 'waiting',128 'tool.status.pending': 'waiting',
@@ -513,6 +514,7 @@ export const fr: Record<MessageKey, string> = {
513 'system.no-recipient': "Personne n'est désigné : mentionnez un agent avec @ (par exemple @{example}).",514 'system.no-recipient': "Personne n'est désigné : mentionnez un agent avec @ (par exemple @{example}).",
514 'system.agent-unavailable': "{agent} n'a pas pu répondre.",515 'system.agent-unavailable': "{agent} n'a pas pu répondre.",
515 'system.attachment-unavailable': "Un fichier n'a pas été envoyé à {agent}.",516 'system.attachment-unavailable': "Un fichier n'a pas été envoyé à {agent}.",
517+ 'system.handoff-limit': "{agent} a mentionné un autre agent, mais ce message est déjà passé d'agent en agent autant de fois que permis (limits.maxAgentHandoffs) : la chaîne s'arrête ici. Mentionnez vous-même l'agent pour continuer.",
516 518
517 'tool.status.pending': 'en attente',519 'tool.status.pending': 'en attente',
518 'tool.status.in_progress': 'en cours',520 'tool.status.in_progress': 'en cours',
modified internal/app/app.go +14 -2
@@ -123,12 +123,13 @@ func (c *Core) openChannels() {
123123 problem = err.Error()
124124 db, _ = store.OpenInMemory()
125125 }
126- manager, err := channels.NewManager(c.manager, db, channels.Options{Emitter: c.options.Emitter, Files: agentFiles{core: c}})
126+ options := channels.Options{Emitter: c.options.Emitter, Files: agentFiles{core: c}, Handoffs: c.maxAgentHandoffs}
127+ manager, err := channels.NewManager(c.manager, db, options)
127128 if err != nil {
128129 problem = err.Error()
129130 _ = db.Close()
130131 db, _ = store.OpenInMemory()
131- manager, _ = channels.NewManager(c.manager, db, channels.Options{Emitter: c.options.Emitter, Files: agentFiles{core: c}})
132+ manager, _ = channels.NewManager(c.manager, db, options)
132133 }
133134 _ = manager.Declare(declared)
134135 c.mu.Lock()
@@ -302,3 +303,14 @@ func messages(problems []config.Problem) []string {
302303 }
303304 return result
304305 }
306+
307+// maxAgentHandoffs is limits.maxAgentHandoffs of the current configuration,
308+// read by the channels for each message (issue #26).
309+func (c *Core) maxAgentHandoffs() int {
310+ c.mu.Lock()
311+ defer c.mu.Unlock()
312+ if c.cfg == nil {
313+ return config.DefaultMaxAgentHandoffs
314+ }
315+ return c.cfg.Limits.MaxAgentHandoffs
316+}
@@ -123,12 +123,13 @@ func (c *Core) openChannels() {
123 problem = err.Error()123 problem = err.Error()
124 db, _ = store.OpenInMemory()124 db, _ = store.OpenInMemory()
125 }125 }
126- manager, err := channels.NewManager(c.manager, db, channels.Options{Emitter: c.options.Emitter, Files: agentFiles{core: c}})126+ options := channels.Options{Emitter: c.options.Emitter, Files: agentFiles{core: c}, Handoffs: c.maxAgentHandoffs}
127+ manager, err := channels.NewManager(c.manager, db, options)
127 if err != nil {128 if err != nil {
128 problem = err.Error()129 problem = err.Error()
129 _ = db.Close()130 _ = db.Close()
130 db, _ = store.OpenInMemory()131 db, _ = store.OpenInMemory()
131- manager, _ = channels.NewManager(c.manager, db, channels.Options{Emitter: c.options.Emitter, Files: agentFiles{core: c}})132+ manager, _ = channels.NewManager(c.manager, db, options)
132 }133 }
133 _ = manager.Declare(declared)134 _ = manager.Declare(declared)
134 c.mu.Lock()135 c.mu.Lock()
@@ -302,3 +303,14 @@ func messages(problems []config.Problem) []string {
302 }303 }
303 return result304 return result
304 }305 }
306+
307+// maxAgentHandoffs is limits.maxAgentHandoffs of the current configuration,
308+// read by the channels for each message (issue #26).
309+func (c *Core) maxAgentHandoffs() int {
310+ c.mu.Lock()
311+ defer c.mu.Unlock()
312+ if c.cfg == nil {
313+ return config.DefaultMaxAgentHandoffs
314+ }
315+ return c.cfg.Limits.MaxAgentHandoffs
316+}
modified internal/channels/channels.go +16 -1
@@ -66,8 +66,16 @@ const (
6666 // CodeAttachmentUnavailable: a file joined with $ could not be sent to
6767 // the agent (Agent); Error names the file and says why.
6868 CodeAttachmentUnavailable = "attachment-unavailable"
69+ // CodeHandoffLimit: an agent (Agent) addressed another one, but the
70+ // message was already handed from agent to agent as many times as
71+ // allowed (Options.Handoffs); the chain stops there.
72+ CodeHandoffLimit = "handoff-limit"
6973 )
7074
75+// DefaultHandoffs is how many times the agents may hand one message on to
76+// each other with @name, unless Options.Handoffs says otherwise.
77+const DefaultHandoffs = 3
78+
7179 // How many messages a channel loads when it is opened; older ones are paged
7280 // with Older.
7381 const pageSize = 100
@@ -231,6 +239,11 @@ type Options struct {
231239 // Files reads the files joined with $; nil sends none (their
232240 // references stay in the text).
233241 Files FileSource
242+ // Handoffs returns how many times, for one user message, an agent's
243+ // answer may hand the floor to another member of the channel by
244+ // mentioning it with @name (issue #26; limits.maxAgentHandoffs). It is
245+ // read for each message; 0 turns hand-offs off. nil: DefaultHandoffs.
246+ Handoffs func() int
234247 }
235248
236249 // Manager holds the channels. It is safe for concurrent use.
@@ -240,6 +253,8 @@ type Manager struct {
240253 emitter events.Emitter
241254 now func() time.Time
242255 files FileSource
256+ // handoffs: see Options.Handoffs.
257+ handoffs func() int
243258
244259 mu sync.Mutex
245260 channels map[string]*channel
@@ -301,7 +316,7 @@ func NewManager(source AgentSource, db *store.Store, options Options) (*Manager,
301316 options.Now = time.Now
302317 }
303318 m := &Manager{
304- agents: source, db: db, emitter: options.Emitter, now: options.Now, files: options.Files,
319+ agents: source, db: db, emitter: options.Emitter, now: options.Now, files: options.Files, handoffs: options.Handoffs,
305320 channels: map[string]*channel{}, permissions: map[string]*pendingPermission{},
306321 commands: map[string][]acp.Command{}, turns: map[string]chan struct{}{},
307322 }
@@ -66,8 +66,16 @@ const (
66 // CodeAttachmentUnavailable: a file joined with $ could not be sent to66 // CodeAttachmentUnavailable: a file joined with $ could not be sent to
67 // the agent (Agent); Error names the file and says why.67 // the agent (Agent); Error names the file and says why.
68 CodeAttachmentUnavailable = "attachment-unavailable"68 CodeAttachmentUnavailable = "attachment-unavailable"
69+ // CodeHandoffLimit: an agent (Agent) addressed another one, but the
70+ // message was already handed from agent to agent as many times as
71+ // allowed (Options.Handoffs); the chain stops there.
72+ CodeHandoffLimit = "handoff-limit"
69 )73 )
70 74
75+// DefaultHandoffs is how many times the agents may hand one message on to
76+// each other with @name, unless Options.Handoffs says otherwise.
77+const DefaultHandoffs = 3
78+
71 // How many messages a channel loads when it is opened; older ones are paged79 // How many messages a channel loads when it is opened; older ones are paged
72 // with Older.80 // with Older.
73 const pageSize = 10081 const pageSize = 100
@@ -231,6 +239,11 @@ type Options struct {
231 // Files reads the files joined with $; nil sends none (their239 // Files reads the files joined with $; nil sends none (their
232 // references stay in the text).240 // references stay in the text).
233 Files FileSource241 Files FileSource
242+ // Handoffs returns how many times, for one user message, an agent's
243+ // answer may hand the floor to another member of the channel by
244+ // mentioning it with @name (issue #26; limits.maxAgentHandoffs). It is
245+ // read for each message; 0 turns hand-offs off. nil: DefaultHandoffs.
246+ Handoffs func() int
234 }247 }
235 248
236 // Manager holds the channels. It is safe for concurrent use.249 // Manager holds the channels. It is safe for concurrent use.
@@ -240,6 +253,8 @@ type Manager struct {
240 emitter events.Emitter253 emitter events.Emitter
241 now func() time.Time254 now func() time.Time
242 files FileSource255 files FileSource
256+ // handoffs: see Options.Handoffs.
257+ handoffs func() int
243 258
244 mu sync.Mutex259 mu sync.Mutex
245 channels map[string]*channel260 channels map[string]*channel
@@ -301,7 +316,7 @@ func NewManager(source AgentSource, db *store.Store, options Options) (*Manager,
301 options.Now = time.Now316 options.Now = time.Now
302 }317 }
303 m := &Manager{318 m := &Manager{
304- agents: source, db: db, emitter: options.Emitter, now: options.Now, files: options.Files,319+ agents: source, db: db, emitter: options.Emitter, now: options.Now, files: options.Files, handoffs: options.Handoffs,
305 channels: map[string]*channel{}, permissions: map[string]*pendingPermission{},320 channels: map[string]*channel{}, permissions: map[string]*pendingPermission{},
306 commands: map[string][]acp.Command{}, turns: map[string]chan struct{}{},321 commands: map[string][]acp.Command{}, turns: map[string]chan struct{}{},
307 }322 }
modified internal/channels/fakes_test.go +8 -1
@@ -37,6 +37,8 @@ type fakeConn struct {
3737 attachments [][]acp.Attachment
3838 cancelled chan struct{}
3939 scripts map[string]script
40+ // reply, when set, gives the answer to a prompt that has no script.
41+ reply func(prompt string) string
4042 }
4143
4244 func newFakeConn(agent string, scripts map[string]script) *fakeConn {
@@ -82,9 +84,14 @@ func (c *fakeConn) Prompt(ctx context.Context, sessionID string, text string, at
8284 c.attachments = append(c.attachments, attachments)
8385 handler := c.handlers[sessionID]
8486 play := c.scripts[text]
87+ reply := c.reply
8588 c.mu.Unlock()
8689 if play == nil {
87- handler.Update(acp.Update{Kind: acp.UpdateMessage, Text: c.agent + " ok"})
90+ answer := c.agent + " ok"
91+ if reply != nil {
92+ answer = reply(text)
93+ }
94+ handler.Update(acp.Update{Kind: acp.UpdateMessage, Text: answer})
8895 return acp.TurnResult{StopReason: "end_turn"}, nil
8996 }
9097 return play(withCancel(ctx, c.cancelled), handler)
@@ -37,6 +37,8 @@ type fakeConn struct {
37 attachments [][]acp.Attachment37 attachments [][]acp.Attachment
38 cancelled chan struct{}38 cancelled chan struct{}
39 scripts map[string]script39 scripts map[string]script
40+ // reply, when set, gives the answer to a prompt that has no script.
41+ reply func(prompt string) string
40 }42 }
41 43
42 func newFakeConn(agent string, scripts map[string]script) *fakeConn {44 func newFakeConn(agent string, scripts map[string]script) *fakeConn {
@@ -82,9 +84,14 @@ func (c *fakeConn) Prompt(ctx context.Context, sessionID string, text string, at
82 c.attachments = append(c.attachments, attachments)84 c.attachments = append(c.attachments, attachments)
83 handler := c.handlers[sessionID]85 handler := c.handlers[sessionID]
84 play := c.scripts[text]86 play := c.scripts[text]
87+ reply := c.reply
85 c.mu.Unlock()88 c.mu.Unlock()
86 if play == nil {89 if play == nil {
87- handler.Update(acp.Update{Kind: acp.UpdateMessage, Text: c.agent + " ok"})90+ answer := c.agent + " ok"
91+ if reply != nil {
92+ answer = reply(text)
93+ }
94+ handler.Update(acp.Update{Kind: acp.UpdateMessage, Text: answer})
88 return acp.TurnResult{StopReason: "end_turn"}, nil95 return acp.TurnResult{StopReason: "end_turn"}, nil
89 }96 }
90 return play(withCancel(ctx, c.cancelled), handler)97 return play(withCancel(ctx, c.cancelled), handler)
added internal/channels/handoff_test.go +118 -0
new file mode 100644
@@ -0,0 +1,118 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+package channels_test
4+
5+import (
6+ "strings"
7+ "testing"
8+
9+ "git.rickub.com/bots-garden/sidekicks/internal/channels"
10+ "git.rickub.com/bots-garden/sidekicks/internal/events"
11+ "git.rickub.com/bots-garden/sidekicks/internal/store"
12+)
13+
14+// Issue #26: an agent hands the floor to another member with @name.
15+
16+func setupHandoffs(t *testing.T, limit int) *fixture {
17+ t.Helper()
18+ db, err := store.OpenInMemory()
19+ if err != nil {
20+ t.Fatal(err)
21+ }
22+ t.Cleanup(func() { _ = db.Close() })
23+ source := newFakeSource(nil)
24+ recorder := &events.Recorder{}
25+ manager, err := channels.NewManager(source, db, channels.Options{Emitter: recorder, Handoffs: func() int { return limit }})
26+ if err != nil {
27+ t.Fatal(err)
28+ }
29+ t.Cleanup(manager.Close)
30+ return &fixture{manager: manager, source: source, db: db, recorder: recorder}
31+}
32+
33+func TestAnAgentMentioningAMemberHandsItTheFloor(t *testing.T) {
34+ f := setup(t, nil)
35+ general := f.channel(t, "general", "alice", "bob")
36+ f.source.conn("alice").reply = func(string) string { return "Good question, @bob knows the trains." }
37+ f.send(t, general.ID, "@alice how do I get to Lyon?")
38+ view := f.idle(t, general.ID, 4)
39+ if got := describe(view.Messages[len(view.Messages)-3:]); got != "user:::@alice how do I get to Lyon? | agent:alice::Good question, @bob knows the trains. | agent:bob::bob ok" {
40+ t.Fatalf("bob answers after alice: %s", got)
41+ }
42+ sent := f.source.conn("bob").sent()
43+ if len(sent) != 1 {
44+ t.Fatalf("bob prompts: %q", sent)
45+ }
46+ for _, want := range []string{"user: @alice how do I get to Lyon?", "alice: Good question, @bob knows the trains.", "alice mentioned you (@bob) in its last message in #general"} {
47+ if !strings.Contains(sent[0], want) {
48+ t.Fatalf("bob's prompt lacks %q:\n%s", want, sent[0])
49+ }
50+ }
51+}
52+
53+func TestOnlyOtherMembersMentionedOutsideCodeGetTheFloor(t *testing.T) {
54+ f := setup(t, nil)
55+ general := f.channel(t, "general", "alice", "bob")
56+ // garfield is an agent but not a member; @alice is alice herself; @bob is in code.
57+ f.source.conn("alice").reply = func(string) string { return "Ask @garfield, or me (@alice). Run `notify @bob`." }
58+ f.send(t, general.ID, "@alice hi")
59+ f.idle(t, general.ID, 3)
60+ if sent := f.source.conn("bob").sent(); len(sent) != 0 {
61+ t.Fatalf("nobody gets the floor: bob got %q", sent)
62+ }
63+ if sent := f.source.conn("garfield").sent(); len(sent) != 0 {
64+ t.Fatalf("garfield is not invited by an agent: %q", sent)
65+ }
66+}
67+
68+func TestAnAgentAlreadyAddressedByTheUserIsNotAskedTwice(t *testing.T) {
69+ f := setup(t, nil)
70+ general := f.channel(t, "general", "alice", "bob")
71+ f.source.conn("alice").reply = func(string) string { return "@bob, your turn." }
72+ f.send(t, general.ID, "@alice @bob hi")
73+ f.idle(t, general.ID, 3)
74+ if sent := f.source.conn("bob").sent(); len(sent) != 1 {
75+ t.Fatalf("bob answers once: %q", sent)
76+ }
77+}
78+
79+func TestTheHandoffsOfAMessageAreBounded(t *testing.T) {
80+ f := setupHandoffs(t, 2)
81+ general := f.channel(t, "general", "alice", "bob")
82+ f.source.conn("alice").reply = func(string) string { return "@bob?" }
83+ f.source.conn("bob").reply = func(string) string { return "@alice!" }
84+ f.send(t, general.ID, "@alice start")
85+ view := f.idle(t, general.ID, 5)
86+ got := describe(view.Messages[len(view.Messages)-5:])
87+ if got != "user:::@alice start | agent:alice::@bob? | agent:bob::@alice! | agent:alice::@bob? | system:alice:handoff-limit:" {
88+ t.Fatalf("two hand-offs, then the chain stops and says so: %s", got)
89+ }
90+ // The next message starts a new count.
91+ f.send(t, general.ID, "@alice again")
92+ f.idle(t, general.ID, 10)
93+}
94+
95+func TestHandoffsCanBeTurnedOff(t *testing.T) {
96+ f := setupHandoffs(t, 0)
97+ general := f.channel(t, "general", "alice", "bob")
98+ f.source.conn("alice").reply = func(string) string { return "@bob?" }
99+ f.send(t, general.ID, "@alice start")
100+ view := f.idle(t, general.ID, 3)
101+ if sent := f.source.conn("bob").sent(); len(sent) != 0 {
102+ t.Fatalf("bob stays silent: %q", sent)
103+ }
104+ if last := view.Messages[len(view.Messages)-1]; last.Role != channels.RoleAgent {
105+ t.Fatalf("no system message when hand-offs are off: %s", describe(view.Messages))
106+ }
107+}
108+
109+func TestACommandIsNotHandedOn(t *testing.T) {
110+ f := setup(t, nil)
111+ general := f.channel(t, "general", "alice", "bob")
112+ f.source.conn("alice").reply = func(string) string { return "@bob" }
113+ f.send(t, general.ID, "@alice /compact")
114+ f.idle(t, general.ID, 3)
115+ if sent := f.source.conn("bob").sent(); len(sent) != 0 {
116+ t.Fatalf("a command's answer hands nothing on: %q", sent)
117+ }
118+}
new file mode 100644
@@ -0,0 +1,118 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+package channels_test
4+
5+import (
6+ "strings"
7+ "testing"
8+
9+ "git.rickub.com/bots-garden/sidekicks/internal/channels"
10+ "git.rickub.com/bots-garden/sidekicks/internal/events"
11+ "git.rickub.com/bots-garden/sidekicks/internal/store"
12+)
13+
14+// Issue #26: an agent hands the floor to another member with @name.
15+
16+func setupHandoffs(t *testing.T, limit int) *fixture {
17+ t.Helper()
18+ db, err := store.OpenInMemory()
19+ if err != nil {
20+ t.Fatal(err)
21+ }
22+ t.Cleanup(func() { _ = db.Close() })
23+ source := newFakeSource(nil)
24+ recorder := &events.Recorder{}
25+ manager, err := channels.NewManager(source, db, channels.Options{Emitter: recorder, Handoffs: func() int { return limit }})
26+ if err != nil {
27+ t.Fatal(err)
28+ }
29+ t.Cleanup(manager.Close)
30+ return &fixture{manager: manager, source: source, db: db, recorder: recorder}
31+}
32+
33+func TestAnAgentMentioningAMemberHandsItTheFloor(t *testing.T) {
34+ f := setup(t, nil)
35+ general := f.channel(t, "general", "alice", "bob")
36+ f.source.conn("alice").reply = func(string) string { return "Good question, @bob knows the trains." }
37+ f.send(t, general.ID, "@alice how do I get to Lyon?")
38+ view := f.idle(t, general.ID, 4)
39+ if got := describe(view.Messages[len(view.Messages)-3:]); got != "user:::@alice how do I get to Lyon? | agent:alice::Good question, @bob knows the trains. | agent:bob::bob ok" {
40+ t.Fatalf("bob answers after alice: %s", got)
41+ }
42+ sent := f.source.conn("bob").sent()
43+ if len(sent) != 1 {
44+ t.Fatalf("bob prompts: %q", sent)
45+ }
46+ for _, want := range []string{"user: @alice how do I get to Lyon?", "alice: Good question, @bob knows the trains.", "alice mentioned you (@bob) in its last message in #general"} {
47+ if !strings.Contains(sent[0], want) {
48+ t.Fatalf("bob's prompt lacks %q:\n%s", want, sent[0])
49+ }
50+ }
51+}
52+
53+func TestOnlyOtherMembersMentionedOutsideCodeGetTheFloor(t *testing.T) {
54+ f := setup(t, nil)
55+ general := f.channel(t, "general", "alice", "bob")
56+ // garfield is an agent but not a member; @alice is alice herself; @bob is in code.
57+ f.source.conn("alice").reply = func(string) string { return "Ask @garfield, or me (@alice). Run `notify @bob`." }
58+ f.send(t, general.ID, "@alice hi")
59+ f.idle(t, general.ID, 3)
60+ if sent := f.source.conn("bob").sent(); len(sent) != 0 {
61+ t.Fatalf("nobody gets the floor: bob got %q", sent)
62+ }
63+ if sent := f.source.conn("garfield").sent(); len(sent) != 0 {
64+ t.Fatalf("garfield is not invited by an agent: %q", sent)
65+ }
66+}
67+
68+func TestAnAgentAlreadyAddressedByTheUserIsNotAskedTwice(t *testing.T) {
69+ f := setup(t, nil)
70+ general := f.channel(t, "general", "alice", "bob")
71+ f.source.conn("alice").reply = func(string) string { return "@bob, your turn." }
72+ f.send(t, general.ID, "@alice @bob hi")
73+ f.idle(t, general.ID, 3)
74+ if sent := f.source.conn("bob").sent(); len(sent) != 1 {
75+ t.Fatalf("bob answers once: %q", sent)
76+ }
77+}
78+
79+func TestTheHandoffsOfAMessageAreBounded(t *testing.T) {
80+ f := setupHandoffs(t, 2)
81+ general := f.channel(t, "general", "alice", "bob")
82+ f.source.conn("alice").reply = func(string) string { return "@bob?" }
83+ f.source.conn("bob").reply = func(string) string { return "@alice!" }
84+ f.send(t, general.ID, "@alice start")
85+ view := f.idle(t, general.ID, 5)
86+ got := describe(view.Messages[len(view.Messages)-5:])
87+ if got != "user:::@alice start | agent:alice::@bob? | agent:bob::@alice! | agent:alice::@bob? | system:alice:handoff-limit:" {
88+ t.Fatalf("two hand-offs, then the chain stops and says so: %s", got)
89+ }
90+ // The next message starts a new count.
91+ f.send(t, general.ID, "@alice again")
92+ f.idle(t, general.ID, 10)
93+}
94+
95+func TestHandoffsCanBeTurnedOff(t *testing.T) {
96+ f := setupHandoffs(t, 0)
97+ general := f.channel(t, "general", "alice", "bob")
98+ f.source.conn("alice").reply = func(string) string { return "@bob?" }
99+ f.send(t, general.ID, "@alice start")
100+ view := f.idle(t, general.ID, 3)
101+ if sent := f.source.conn("bob").sent(); len(sent) != 0 {
102+ t.Fatalf("bob stays silent: %q", sent)
103+ }
104+ if last := view.Messages[len(view.Messages)-1]; last.Role != channels.RoleAgent {
105+ t.Fatalf("no system message when hand-offs are off: %s", describe(view.Messages))
106+ }
107+}
108+
109+func TestACommandIsNotHandedOn(t *testing.T) {
110+ f := setup(t, nil)
111+ general := f.channel(t, "general", "alice", "bob")
112+ f.source.conn("alice").reply = func(string) string { return "@bob" }
113+ f.send(t, general.ID, "@alice /compact")
114+ f.idle(t, general.ID, 3)
115+ if sent := f.source.conn("bob").sent(); len(sent) != 0 {
116+ t.Fatalf("a command's answer hands nothing on: %q", sent)
117+ }
118+}
modified internal/channels/route.go +27 -4
@@ -120,11 +120,22 @@ func Prompt(agent, channelName, text string, unseen []Line) string {
120120 if len(unseen) == 0 {
121121 return text
122122 }
123+ var builder strings.Builder
124+ writeUnseen(&builder, agent, channelName, unseen)
125+ fmt.Fprintf(&builder, "The user now writes to you (answer directly, without your name in front):\n%s", text)
126+ return builder.String()
127+}
128+
129+// writeUnseen writes the last unseen messages, between markers, as agent
130+// reads them; nothing when there is none.
131+func writeUnseen(builder *strings.Builder, agent, channelName string, unseen []Line) {
132+ if len(unseen) == 0 {
133+ return
134+ }
123135 if len(unseen) > contextMessages {
124136 unseen = unseen[len(unseen)-contextMessages:]
125137 }
126- var builder strings.Builder
127- fmt.Fprintf(&builder, "[Messages in %s you have not seen yet]\n", channelName)
138+ fmt.Fprintf(builder, "[Messages in %s you have not seen yet]\n", channelName)
128139 for _, line := range unseen {
129140 author := line.Author
130141 if author == agent {
@@ -134,8 +145,20 @@ func Prompt(agent, channelName, text string, unseen []Line) string {
134145 if runes := []rune(lineText); len(runes) > maxLineLength {
135146 lineText = string(runes[:maxLineLength]) + "…"
136147 }
137- fmt.Fprintf(&builder, "%s: %s\n", author, lineText)
148+ fmt.Fprintf(builder, "%s: %s\n", author, lineText)
138149 }
139- fmt.Fprintf(&builder, "[End of the messages]\n\nThe user now writes to you (answer directly, without your name in front):\n%s", text)
150+ builder.WriteString("[End of the messages]\n\n")
151+}
152+
153+// HandoffPrompt builds what agent receives when another agent, from,
154+// mentioned it with @agent in its answer (issue #26): the channel messages
155+// agent has not seen — the user's message and from's answer among them —
156+// then who addresses it.
157+//
158+// HandoffPrompt("bob", "alice", "#general", []Line{{Author: "user", Text: "@alice plan the trip"}, {Author: "alice", Text: "@bob, which train?"}})
159+func HandoffPrompt(agent, from, channelName string, unseen []Line) string {
160+ var builder strings.Builder
161+ writeUnseen(&builder, agent, channelName, unseen)
162+ fmt.Fprintf(&builder, "%s mentioned you (@%s) in its last message in %s: answer %s directly, without your name in front.", from, agent, channelName, from)
140163 return builder.String()
141164 }
@@ -120,11 +120,22 @@ func Prompt(agent, channelName, text string, unseen []Line) string {
120 if len(unseen) == 0 {120 if len(unseen) == 0 {
121 return text121 return text
122 }122 }
123+ var builder strings.Builder
124+ writeUnseen(&builder, agent, channelName, unseen)
125+ fmt.Fprintf(&builder, "The user now writes to you (answer directly, without your name in front):\n%s", text)
126+ return builder.String()
127+}
128+
129+// writeUnseen writes the last unseen messages, between markers, as agent
130+// reads them; nothing when there is none.
131+func writeUnseen(builder *strings.Builder, agent, channelName string, unseen []Line) {
132+ if len(unseen) == 0 {
133+ return
134+ }
123 if len(unseen) > contextMessages {135 if len(unseen) > contextMessages {
124 unseen = unseen[len(unseen)-contextMessages:]136 unseen = unseen[len(unseen)-contextMessages:]
125 }137 }
126- var builder strings.Builder138+ fmt.Fprintf(builder, "[Messages in %s you have not seen yet]\n", channelName)
127- fmt.Fprintf(&builder, "[Messages in %s you have not seen yet]\n", channelName)
128 for _, line := range unseen {139 for _, line := range unseen {
129 author := line.Author140 author := line.Author
130 if author == agent {141 if author == agent {
@@ -134,8 +145,20 @@ func Prompt(agent, channelName, text string, unseen []Line) string {
134 if runes := []rune(lineText); len(runes) > maxLineLength {145 if runes := []rune(lineText); len(runes) > maxLineLength {
135 lineText = string(runes[:maxLineLength]) + "…"146 lineText = string(runes[:maxLineLength]) + "…"
136 }147 }
137- fmt.Fprintf(&builder, "%s: %s\n", author, lineText)148+ fmt.Fprintf(builder, "%s: %s\n", author, lineText)
138 }149 }
139- fmt.Fprintf(&builder, "[End of the messages]\n\nThe user now writes to you (answer directly, without your name in front):\n%s", text)150+ builder.WriteString("[End of the messages]\n\n")
151+}
152+
153+// HandoffPrompt builds what agent receives when another agent, from,
154+// mentioned it with @agent in its answer (issue #26): the channel messages
155+// agent has not seen — the user's message and from's answer among them —
156+// then who addresses it.
157+//
158+// HandoffPrompt("bob", "alice", "#general", []Line{{Author: "user", Text: "@alice plan the trip"}, {Author: "alice", Text: "@bob, which train?"}})
159+func HandoffPrompt(agent, from, channelName string, unseen []Line) string {
160+ var builder strings.Builder
161+ writeUnseen(&builder, agent, channelName, unseen)
162+ fmt.Fprintf(&builder, "%s mentioned you (@%s) in its last message in %s: answer %s directly, without your name in front.", from, agent, channelName, from)
140 return builder.String()163 return builder.String()
141 }164 }
modified internal/channels/turns.go +71 -17
@@ -7,6 +7,7 @@ import (
77 "encoding/json"
88 "errors"
99 "fmt"
10+ "slices"
1011 "strings"
1112
1213 "git.rickub.com/bots-garden/sidekicks/internal/acp"
@@ -140,17 +141,13 @@ func (m *Manager) invite(ch *channel, names []string) {
140141 }
141142
142143 // run answers item, then the queued messages one by one; each message is
143-// answered by its agents in order.
144+// answered by its agents in order, then by the agents they hand it to.
144145 func (m *Manager) run(ch *channel, item *pending) {
145146 for item != nil {
146147 m.mu.Lock()
147148 ch.stopped = false
148149 m.mu.Unlock()
149- for _, agent := range item.route.Agents {
150- if !m.turn(ch, item, agent) {
151- break // stopped by the user: the other agents do not answer
152- }
153- }
150+ m.answer(ch, item)
154151 m.mu.Lock()
155152 item = nil
156153 ch.answering = ""
@@ -166,37 +163,89 @@ func (m *Manager) run(ch *channel, item *pending) {
166163 }
167164 }
168165
169-// turn has agent answer item and streams its answer. It returns false when
170-// the user stopped the channel.
171-func (m *Manager) turn(ch *channel, item *pending, agent string) bool {
166+// answer has the agents of item's route answer it, one after the other. In
167+// a channel, an agent whose answer mentions another member with @name hands
168+// it the floor (issue #26): that member answers next, told who addressed it.
169+// The hand-offs of one message are bounded (Options.Handoffs); the user stops
170+// the whole chain with Cancel.
171+func (m *Manager) answer(ch *channel, item *pending) {
172+ queue := append([]string(nil), item.route.Agents...)
173+ from := make([]string, len(queue)) // who handed the floor to queue[i]; "" for the user
174+ handoffs, limit := 0, m.handoffLimit()
175+ for i := 0; i < len(queue); i++ {
176+ text, ok := m.turn(ch, item, queue[i], from[i])
177+ if !ok {
178+ return // stopped by the user: the other agents do not answer
179+ }
180+ if item.route.Command != "" || ch.info.Direct != "" {
181+ continue
182+ }
183+ for _, next := range m.addressed(ch, queue[i], text, queue[i+1:]) {
184+ if handoffs >= limit {
185+ if limit > 0 {
186+ m.mu.Lock()
187+ m.systemMessage(ch, CodeHandoffLimit, queue[i], "")
188+ m.mu.Unlock()
189+ }
190+ break
191+ }
192+ handoffs++
193+ queue, from = append(queue, next), append(from, queue[i])
194+ }
195+ }
196+}
197+
198+// addressed lists the members of ch that agent's answer mentions with @name,
199+// apart from agent itself and the ones that answer anyway (waiting). Code
200+// is not looked into.
201+func (m *Manager) addressed(ch *channel, agent, text string, waiting []string) []string {
202+ m.mu.Lock()
203+ defer m.mu.Unlock()
204+ member := func(name string) bool {
205+ return name != agent && ch.member(name) != nil && !slices.Contains(waiting, name)
206+ }
207+ return Mentions(codePattern.ReplaceAllString(text, " "), member)
208+}
209+
210+func (m *Manager) handoffLimit() int {
211+ if m.handoffs == nil {
212+ return DefaultHandoffs
213+ }
214+ return m.handoffs()
215+}
216+
217+// turn has agent answer item and streams its answer; from is the agent that
218+// handed it the floor, "" when the user asked. It returns the text of the
219+// answer, and false when the user stopped the channel.
220+func (m *Manager) turn(ch *channel, item *pending, agent, from string) (string, bool) {
172221 ctx, cancel := context.WithCancel(context.Background())
173222 defer cancel()
174223 m.mu.Lock()
175224 if ch.stopped {
176225 m.mu.Unlock()
177- return false
226+ return "", false
178227 }
179228 ch.cancel, ch.answering = cancel, agent
180229 m.emitTurn(ch)
181230 m.mu.Unlock()
182231
183232 if !m.waitTurn(ctx, agent) {
184- return false
233+ return "", false
185234 }
186235 defer m.endTurn(agent)
187236 conn, release, err := m.agents.Acquire(ctx, agent)
188237 if err != nil {
189- return m.unavailable(ctx, ch, agent, err)
238+ return "", m.unavailable(ctx, ch, agent, err)
190239 }
191240 defer release()
192241 sessionID, fresh, err := m.session(ctx, ch, agent, conn)
193242 if err != nil {
194- return m.unavailable(ctx, ch, agent, err)
243+ return "", m.unavailable(ctx, ch, agent, err)
195244 }
196245 attachments := m.readAttachments(ctx, ch, agent, item)
197246
198247 m.mu.Lock()
199- prompt := m.prompt(ch, agent, item, fresh)
248+ prompt := m.prompt(ch, agent, item, from, fresh)
200249 answer := m.newMessage(ch, RoleAgent, agent)
201250 ch.messages = append(ch.messages, answer)
202251 ch.current, ch.rejected = answer, 0
@@ -219,7 +268,7 @@ func (m *Manager) turn(ch *channel, item *pending, agent string) bool {
219268 ch.current, ch.cancel = nil, nil
220269 m.emitMessage(answer)
221270 m.seen(ch, agent)
222- return !ch.stopped && ctx.Err() == nil
271+ return textOf(answer), !ch.stopped && ctx.Err() == nil
223272 }
224273
225274 // maxEmbeddedText is the largest text file sent with its content; a larger
@@ -409,8 +458,10 @@ func (m *Manager) tryTurn(agent string) bool {
409458 }
410459
411460 // prompt is what agent receives for item: the command alone, or the text
412-// with the channel messages it has not seen. The caller holds m.mu.
413-func (m *Manager) prompt(ch *channel, agent string, item *pending, fresh bool) string {
461+// with the channel messages it has not seen; when another agent (from)
462+// handed it the floor, those messages, the user's included, and who
463+// addresses it. The caller holds m.mu.
464+func (m *Manager) prompt(ch *channel, agent string, item *pending, from string, fresh bool) string {
414465 if item.route.Command != "" {
415466 return item.route.Command
416467 }
@@ -418,6 +469,9 @@ func (m *Manager) prompt(ch *channel, agent string, item *pending, fresh bool) s
418469 if ch.info.Direct != "" {
419470 place = "this conversation"
420471 }
472+ if from != "" {
473+ return HandoffPrompt(agent, from, place, unseen(ch, agent, nil, fresh))
474+ }
421475 return Prompt(agent, place, textOf(item.message), unseen(ch, agent, item.message, fresh))
422476 }
423477
@@ -7,6 +7,7 @@ import (
7 "encoding/json"7 "encoding/json"
8 "errors"8 "errors"
9 "fmt"9 "fmt"
10+ "slices"
10 "strings"11 "strings"
11 12
12 "git.rickub.com/bots-garden/sidekicks/internal/acp"13 "git.rickub.com/bots-garden/sidekicks/internal/acp"
@@ -140,17 +141,13 @@ func (m *Manager) invite(ch *channel, names []string) {
140 }141 }
141 142
142 // run answers item, then the queued messages one by one; each message is143 // run answers item, then the queued messages one by one; each message is
143-// answered by its agents in order.144+// answered by its agents in order, then by the agents they hand it to.
144 func (m *Manager) run(ch *channel, item *pending) {145 func (m *Manager) run(ch *channel, item *pending) {
145 for item != nil {146 for item != nil {
146 m.mu.Lock()147 m.mu.Lock()
147 ch.stopped = false148 ch.stopped = false
148 m.mu.Unlock()149 m.mu.Unlock()
149- for _, agent := range item.route.Agents {150+ m.answer(ch, item)
150- if !m.turn(ch, item, agent) {
151- break // stopped by the user: the other agents do not answer
152- }
153- }
154 m.mu.Lock()151 m.mu.Lock()
155 item = nil152 item = nil
156 ch.answering = ""153 ch.answering = ""
@@ -166,37 +163,89 @@ func (m *Manager) run(ch *channel, item *pending) {
166 }163 }
167 }164 }
168 165
169-// turn has agent answer item and streams its answer. It returns false when166+// answer has the agents of item's route answer it, one after the other. In
170-// the user stopped the channel.167+// a channel, an agent whose answer mentions another member with @name hands
171-func (m *Manager) turn(ch *channel, item *pending, agent string) bool {168+// it the floor (issue #26): that member answers next, told who addressed it.
169+// The hand-offs of one message are bounded (Options.Handoffs); the user stops
170+// the whole chain with Cancel.
171+func (m *Manager) answer(ch *channel, item *pending) {
172+ queue := append([]string(nil), item.route.Agents...)
173+ from := make([]string, len(queue)) // who handed the floor to queue[i]; "" for the user
174+ handoffs, limit := 0, m.handoffLimit()
175+ for i := 0; i < len(queue); i++ {
176+ text, ok := m.turn(ch, item, queue[i], from[i])
177+ if !ok {
178+ return // stopped by the user: the other agents do not answer
179+ }
180+ if item.route.Command != "" || ch.info.Direct != "" {
181+ continue
182+ }
183+ for _, next := range m.addressed(ch, queue[i], text, queue[i+1:]) {
184+ if handoffs >= limit {
185+ if limit > 0 {
186+ m.mu.Lock()
187+ m.systemMessage(ch, CodeHandoffLimit, queue[i], "")
188+ m.mu.Unlock()
189+ }
190+ break
191+ }
192+ handoffs++
193+ queue, from = append(queue, next), append(from, queue[i])
194+ }
195+ }
196+}
197+
198+// addressed lists the members of ch that agent's answer mentions with @name,
199+// apart from agent itself and the ones that answer anyway (waiting). Code
200+// is not looked into.
201+func (m *Manager) addressed(ch *channel, agent, text string, waiting []string) []string {
202+ m.mu.Lock()
203+ defer m.mu.Unlock()
204+ member := func(name string) bool {
205+ return name != agent && ch.member(name) != nil && !slices.Contains(waiting, name)
206+ }
207+ return Mentions(codePattern.ReplaceAllString(text, " "), member)
208+}
209+
210+func (m *Manager) handoffLimit() int {
211+ if m.handoffs == nil {
212+ return DefaultHandoffs
213+ }
214+ return m.handoffs()
215+}
216+
217+// turn has agent answer item and streams its answer; from is the agent that
218+// handed it the floor, "" when the user asked. It returns the text of the
219+// answer, and false when the user stopped the channel.
220+func (m *Manager) turn(ch *channel, item *pending, agent, from string) (string, bool) {
172 ctx, cancel := context.WithCancel(context.Background())221 ctx, cancel := context.WithCancel(context.Background())
173 defer cancel()222 defer cancel()
174 m.mu.Lock()223 m.mu.Lock()
175 if ch.stopped {224 if ch.stopped {
176 m.mu.Unlock()225 m.mu.Unlock()
177- return false226+ return "", false
178 }227 }
179 ch.cancel, ch.answering = cancel, agent228 ch.cancel, ch.answering = cancel, agent
180 m.emitTurn(ch)229 m.emitTurn(ch)
181 m.mu.Unlock()230 m.mu.Unlock()
182 231
183 if !m.waitTurn(ctx, agent) {232 if !m.waitTurn(ctx, agent) {
184- return false233+ return "", false
185 }234 }
186 defer m.endTurn(agent)235 defer m.endTurn(agent)
187 conn, release, err := m.agents.Acquire(ctx, agent)236 conn, release, err := m.agents.Acquire(ctx, agent)
188 if err != nil {237 if err != nil {
189- return m.unavailable(ctx, ch, agent, err)238+ return "", m.unavailable(ctx, ch, agent, err)
190 }239 }
191 defer release()240 defer release()
192 sessionID, fresh, err := m.session(ctx, ch, agent, conn)241 sessionID, fresh, err := m.session(ctx, ch, agent, conn)
193 if err != nil {242 if err != nil {
194- return m.unavailable(ctx, ch, agent, err)243+ return "", m.unavailable(ctx, ch, agent, err)
195 }244 }
196 attachments := m.readAttachments(ctx, ch, agent, item)245 attachments := m.readAttachments(ctx, ch, agent, item)
197 246
198 m.mu.Lock()247 m.mu.Lock()
199- prompt := m.prompt(ch, agent, item, fresh)248+ prompt := m.prompt(ch, agent, item, from, fresh)
200 answer := m.newMessage(ch, RoleAgent, agent)249 answer := m.newMessage(ch, RoleAgent, agent)
201 ch.messages = append(ch.messages, answer)250 ch.messages = append(ch.messages, answer)
202 ch.current, ch.rejected = answer, 0251 ch.current, ch.rejected = answer, 0
@@ -219,7 +268,7 @@ func (m *Manager) turn(ch *channel, item *pending, agent string) bool {
219 ch.current, ch.cancel = nil, nil268 ch.current, ch.cancel = nil, nil
220 m.emitMessage(answer)269 m.emitMessage(answer)
221 m.seen(ch, agent)270 m.seen(ch, agent)
222- return !ch.stopped && ctx.Err() == nil271+ return textOf(answer), !ch.stopped && ctx.Err() == nil
223 }272 }
224 273
225 // maxEmbeddedText is the largest text file sent with its content; a larger274 // maxEmbeddedText is the largest text file sent with its content; a larger
@@ -409,8 +458,10 @@ func (m *Manager) tryTurn(agent string) bool {
409 }458 }
410 459
411 // prompt is what agent receives for item: the command alone, or the text460 // prompt is what agent receives for item: the command alone, or the text
412-// with the channel messages it has not seen. The caller holds m.mu.461+// with the channel messages it has not seen; when another agent (from)
413-func (m *Manager) prompt(ch *channel, agent string, item *pending, fresh bool) string {462+// handed it the floor, those messages, the user's included, and who
463+// addresses it. The caller holds m.mu.
464+func (m *Manager) prompt(ch *channel, agent string, item *pending, from string, fresh bool) string {
414 if item.route.Command != "" {465 if item.route.Command != "" {
415 return item.route.Command466 return item.route.Command
416 }467 }
@@ -418,6 +469,9 @@ func (m *Manager) prompt(ch *channel, agent string, item *pending, fresh bool) s
418 if ch.info.Direct != "" {469 if ch.info.Direct != "" {
419 place = "this conversation"470 place = "this conversation"
420 }471 }
472+ if from != "" {
473+ return HandoffPrompt(agent, from, place, unseen(ch, agent, nil, fresh))
474+ }
421 return Prompt(agent, place, textOf(item.message), unseen(ch, agent, item.message, fresh))475 return Prompt(agent, place, textOf(item.message), unseen(ch, agent, item.message, fresh))
422 }476 }
423 477
modified internal/config/config.go +10 -0
@@ -34,6 +34,7 @@ const (
3434 DefaultLanguage = "en"
3535 DefaultMaxRunningAgents = 2
3636 DefaultStopIdleAgentsAfter = 10 * time.Minute
37+ DefaultMaxAgentHandoffs = 3
3738 RuntimeLocal = "local"
3839 )
3940
@@ -62,6 +63,10 @@ type Limits struct {
6263 MaxRunningAgents int
6364 // StopIdleAgentsAfter is 0 when idle agents are never stopped.
6465 StopIdleAgentsAfter time.Duration
66+ // MaxAgentHandoffs is how many times, for one message in a channel, an
67+ // agent may hand the floor to another one by mentioning it with @name
68+ // (issue #26); 0 turns it off.
69+ MaxAgentHandoffs int
6570 }
6671
6772 // Agent describes one agent Sidekicks can start.
@@ -328,6 +333,7 @@ type rawConfig struct {
328333 Limits struct {
329334 MaxRunningAgents int `yaml:"maxRunningAgents"`
330335 StopIdleAgentsAfter string `yaml:"stopIdleAgentsAfter"`
336+ MaxAgentHandoffs *int `yaml:"maxAgentHandoffs"`
331337 } `yaml:"limits"`
332338 Agents []struct {
333339 Name string `yaml:"name"`
@@ -367,8 +373,12 @@ func (raw *rawConfig) toConfig(baseDir string) *Config {
367373 Limits: Limits{
368374 MaxRunningAgents: DefaultMaxRunningAgents,
369375 StopIdleAgentsAfter: DefaultStopIdleAgentsAfter,
376+ MaxAgentHandoffs: DefaultMaxAgentHandoffs,
370377 },
371378 }
379+ if raw.Limits.MaxAgentHandoffs != nil {
380+ cfg.Limits.MaxAgentHandoffs = *raw.Limits.MaxAgentHandoffs
381+ }
372382 if raw.Limits.MaxRunningAgents > 0 {
373383 cfg.Limits.MaxRunningAgents = raw.Limits.MaxRunningAgents
374384 }
@@ -34,6 +34,7 @@ const (
34 DefaultLanguage = "en"34 DefaultLanguage = "en"
35 DefaultMaxRunningAgents = 235 DefaultMaxRunningAgents = 2
36 DefaultStopIdleAgentsAfter = 10 * time.Minute36 DefaultStopIdleAgentsAfter = 10 * time.Minute
37+ DefaultMaxAgentHandoffs = 3
37 RuntimeLocal = "local"38 RuntimeLocal = "local"
38 )39 )
39 40
@@ -62,6 +63,10 @@ type Limits struct {
62 MaxRunningAgents int63 MaxRunningAgents int
63 // StopIdleAgentsAfter is 0 when idle agents are never stopped.64 // StopIdleAgentsAfter is 0 when idle agents are never stopped.
64 StopIdleAgentsAfter time.Duration65 StopIdleAgentsAfter time.Duration
66+ // MaxAgentHandoffs is how many times, for one message in a channel, an
67+ // agent may hand the floor to another one by mentioning it with @name
68+ // (issue #26); 0 turns it off.
69+ MaxAgentHandoffs int
65 }70 }
66 71
67 // Agent describes one agent Sidekicks can start.72 // Agent describes one agent Sidekicks can start.
@@ -328,6 +333,7 @@ type rawConfig struct {
328 Limits struct {333 Limits struct {
329 MaxRunningAgents int `yaml:"maxRunningAgents"`334 MaxRunningAgents int `yaml:"maxRunningAgents"`
330 StopIdleAgentsAfter string `yaml:"stopIdleAgentsAfter"`335 StopIdleAgentsAfter string `yaml:"stopIdleAgentsAfter"`
336+ MaxAgentHandoffs *int `yaml:"maxAgentHandoffs"`
331 } `yaml:"limits"`337 } `yaml:"limits"`
332 Agents []struct {338 Agents []struct {
333 Name string `yaml:"name"`339 Name string `yaml:"name"`
@@ -367,8 +373,12 @@ func (raw *rawConfig) toConfig(baseDir string) *Config {
367 Limits: Limits{373 Limits: Limits{
368 MaxRunningAgents: DefaultMaxRunningAgents,374 MaxRunningAgents: DefaultMaxRunningAgents,
369 StopIdleAgentsAfter: DefaultStopIdleAgentsAfter,375 StopIdleAgentsAfter: DefaultStopIdleAgentsAfter,
376+ MaxAgentHandoffs: DefaultMaxAgentHandoffs,
370 },377 },
371 }378 }
379+ if raw.Limits.MaxAgentHandoffs != nil {
380+ cfg.Limits.MaxAgentHandoffs = *raw.Limits.MaxAgentHandoffs
381+ }
372 if raw.Limits.MaxRunningAgents > 0 {382 if raw.Limits.MaxRunningAgents > 0 {
373 cfg.Limits.MaxRunningAgents = raw.Limits.MaxRunningAgents383 cfg.Limits.MaxRunningAgents = raw.Limits.MaxRunningAgents
374 }384 }
modified internal/config/config_test.go +4 -3
@@ -51,7 +51,7 @@ func TestMinimalFileGetsTheDefaults(t *testing.T) {
5151 if cfg.UI.Theme != "system" || cfg.UI.Language != "en" {
5252 t.Errorf("ui defaults: %+v", cfg.UI)
5353 }
54- if cfg.Limits.MaxRunningAgents != 2 || cfg.Limits.StopIdleAgentsAfter != 10*time.Minute {
54+ if cfg.Limits.MaxRunningAgents != 2 || cfg.Limits.StopIdleAgentsAfter != 10*time.Minute || cfg.Limits.MaxAgentHandoffs != 3 {
5555 t.Errorf("limits defaults: %+v", cfg.Limits)
5656 }
5757 alice := cfg.Agents[0]
@@ -92,11 +92,11 @@ agents:
9292 }
9393
9494 func TestLimitsAndUIAreRead(t *testing.T) {
95- cfg, err := parse(t, "version: 1\nui:\n theme: dark\n language: en\nlimits:\n maxRunningAgents: 3\n stopIdleAgentsAfter: 0\nagents: []\n")
95+ cfg, err := parse(t, "version: 1\nui:\n theme: dark\n language: en\nlimits:\n maxRunningAgents: 3\n stopIdleAgentsAfter: 0\n maxAgentHandoffs: 0\nagents: []\n")
9696 if err != nil {
9797 t.Fatal(err)
9898 }
99- if cfg.UI.Theme != "dark" || cfg.UI.Language != "en" || cfg.Limits.MaxRunningAgents != 3 || cfg.Limits.StopIdleAgentsAfter != 0 {
99+ if cfg.UI.Theme != "dark" || cfg.UI.Language != "en" || cfg.Limits.MaxRunningAgents != 3 || cfg.Limits.StopIdleAgentsAfter != 0 || cfg.Limits.MaxAgentHandoffs != 0 {
100100 t.Fatalf("got %+v %+v", cfg.UI, cfg.Limits)
101101 }
102102 }
@@ -110,6 +110,7 @@ func TestProblemsAreLocatedAndExplained(t *testing.T) {
110110 {"unknown key with suggestion", "version: 1\nagents:\n - name: alice\n comand: mm\n", 4, "agents[0].comand", `did you mean "command"`},
111111 {"missing key", "version: 1\nagents:\n - name: alice\n", 3, "agents[0]", `the key "command" is missing`},
112112 {"invalid name", "version: 1\nagents:\n - name: Alice Smith\n command: mm\n", 3, "agents[0].name", `"Alice Smith" is not a valid name`},
113+ {"too many hand-offs", "version: 1\nlimits:\n maxAgentHandoffs: 11\nagents: []\n", 3, "limits.maxAgentHandoffs", ""},
113114 {"bad duration", "version: 1\nlimits:\n stopIdleAgentsAfter: dix minutes\nagents: []\n", 3, "limits.stopIdleAgentsAfter", "is not a valid duration"},
114115 {"number other than 0 as duration", "version: 1\nlimits:\n stopIdleAgentsAfter: 5\nagents: []\n", 3, "limits.stopIdleAgentsAfter", `"5" is not a valid duration`},
115116 {"unknown theme", "version: 1\nui:\n theme: blue\nagents: []\n", 3, "ui.theme", "choose among: system, light, dark"},
@@ -51,7 +51,7 @@ func TestMinimalFileGetsTheDefaults(t *testing.T) {
51 if cfg.UI.Theme != "system" || cfg.UI.Language != "en" {51 if cfg.UI.Theme != "system" || cfg.UI.Language != "en" {
52 t.Errorf("ui defaults: %+v", cfg.UI)52 t.Errorf("ui defaults: %+v", cfg.UI)
53 }53 }
54- if cfg.Limits.MaxRunningAgents != 2 || cfg.Limits.StopIdleAgentsAfter != 10*time.Minute {54+ if cfg.Limits.MaxRunningAgents != 2 || cfg.Limits.StopIdleAgentsAfter != 10*time.Minute || cfg.Limits.MaxAgentHandoffs != 3 {
55 t.Errorf("limits defaults: %+v", cfg.Limits)55 t.Errorf("limits defaults: %+v", cfg.Limits)
56 }56 }
57 alice := cfg.Agents[0]57 alice := cfg.Agents[0]
@@ -92,11 +92,11 @@ agents:
92 }92 }
93 93
94 func TestLimitsAndUIAreRead(t *testing.T) {94 func TestLimitsAndUIAreRead(t *testing.T) {
95- cfg, err := parse(t, "version: 1\nui:\n theme: dark\n language: en\nlimits:\n maxRunningAgents: 3\n stopIdleAgentsAfter: 0\nagents: []\n")95+ cfg, err := parse(t, "version: 1\nui:\n theme: dark\n language: en\nlimits:\n maxRunningAgents: 3\n stopIdleAgentsAfter: 0\n maxAgentHandoffs: 0\nagents: []\n")
96 if err != nil {96 if err != nil {
97 t.Fatal(err)97 t.Fatal(err)
98 }98 }
99- if cfg.UI.Theme != "dark" || cfg.UI.Language != "en" || cfg.Limits.MaxRunningAgents != 3 || cfg.Limits.StopIdleAgentsAfter != 0 {99+ if cfg.UI.Theme != "dark" || cfg.UI.Language != "en" || cfg.Limits.MaxRunningAgents != 3 || cfg.Limits.StopIdleAgentsAfter != 0 || cfg.Limits.MaxAgentHandoffs != 0 {
100 t.Fatalf("got %+v %+v", cfg.UI, cfg.Limits)100 t.Fatalf("got %+v %+v", cfg.UI, cfg.Limits)
101 }101 }
102 }102 }
@@ -110,6 +110,7 @@ func TestProblemsAreLocatedAndExplained(t *testing.T) {
110 {"unknown key with suggestion", "version: 1\nagents:\n - name: alice\n comand: mm\n", 4, "agents[0].comand", `did you mean "command"`},110 {"unknown key with suggestion", "version: 1\nagents:\n - name: alice\n comand: mm\n", 4, "agents[0].comand", `did you mean "command"`},
111 {"missing key", "version: 1\nagents:\n - name: alice\n", 3, "agents[0]", `the key "command" is missing`},111 {"missing key", "version: 1\nagents:\n - name: alice\n", 3, "agents[0]", `the key "command" is missing`},
112 {"invalid name", "version: 1\nagents:\n - name: Alice Smith\n command: mm\n", 3, "agents[0].name", `"Alice Smith" is not a valid name`},112 {"invalid name", "version: 1\nagents:\n - name: Alice Smith\n command: mm\n", 3, "agents[0].name", `"Alice Smith" is not a valid name`},
113+ {"too many hand-offs", "version: 1\nlimits:\n maxAgentHandoffs: 11\nagents: []\n", 3, "limits.maxAgentHandoffs", ""},
113 {"bad duration", "version: 1\nlimits:\n stopIdleAgentsAfter: dix minutes\nagents: []\n", 3, "limits.stopIdleAgentsAfter", "is not a valid duration"},114 {"bad duration", "version: 1\nlimits:\n stopIdleAgentsAfter: dix minutes\nagents: []\n", 3, "limits.stopIdleAgentsAfter", "is not a valid duration"},
114 {"number other than 0 as duration", "version: 1\nlimits:\n stopIdleAgentsAfter: 5\nagents: []\n", 3, "limits.stopIdleAgentsAfter", `"5" is not a valid duration`},115 {"number other than 0 as duration", "version: 1\nlimits:\n stopIdleAgentsAfter: 5\nagents: []\n", 3, "limits.stopIdleAgentsAfter", `"5" is not a valid duration`},
115 {"unknown theme", "version: 1\nui:\n theme: blue\nagents: []\n", 3, "ui.theme", "choose among: system, light, dark"},116 {"unknown theme", "version: 1\nui:\n theme: blue\nagents: []\n", 3, "ui.theme", "choose among: system, light, dark"},
modified internal/config/problems.go +1 -1
@@ -291,7 +291,7 @@ func allowedKeys(path []string) []string {
291291 case parent[0] == "ui":
292292 return []string{"theme", "language"}
293293 case parent[0] == "limits":
294- return []string{"maxRunningAgents", "stopIdleAgentsAfter"}
294+ return []string{"maxRunningAgents", "stopIdleAgentsAfter", "maxAgentHandoffs"}
295295 case parent[0] == "agents" && len(parent) == 2:
296296 return []string{"name", "title", "icon", "description", "command", "args", "afterStop", "env", "workspace", "runtime", "protect"}
297297 case parent[0] == "agents" && len(parent) == 3 && parent[2] == "runtime":
@@ -291,7 +291,7 @@ func allowedKeys(path []string) []string {
291 case parent[0] == "ui":291 case parent[0] == "ui":
292 return []string{"theme", "language"}292 return []string{"theme", "language"}
293 case parent[0] == "limits":293 case parent[0] == "limits":
294- return []string{"maxRunningAgents", "stopIdleAgentsAfter"}294+ return []string{"maxRunningAgents", "stopIdleAgentsAfter", "maxAgentHandoffs"}
295 case parent[0] == "agents" && len(parent) == 2:295 case parent[0] == "agents" && len(parent) == 2:
296 return []string{"name", "title", "icon", "description", "command", "args", "afterStop", "env", "workspace", "runtime", "protect"}296 return []string{"name", "title", "icon", "description", "command", "args", "afterStop", "env", "workspace", "runtime", "protect"}
297 case parent[0] == "agents" && len(parent) == 3 && parent[2] == "runtime":297 case parent[0] == "agents" && len(parent) == 3 && parent[2] == "runtime":
modified schema/config.schema.json +7 -0
@@ -84,6 +84,13 @@
8484 "default": "10m",
8585 "minimum": 0,
8686 "maximum": 0
87+ },
88+ "maxAgentHandoffs": {
89+ "description": "In a channel, how many times one message may be handed from agent to agent: an agent whose answer mentions another member with @name hands it the floor. 0 turns it off.",
90+ "type": "integer",
91+ "minimum": 0,
92+ "maximum": 10,
93+ "default": 3
8794 }
8895 }
8996 },
@@ -84,6 +84,13 @@
84 "default": "10m",84 "default": "10m",
85 "minimum": 0,85 "minimum": 0,
86 "maximum": 086 "maximum": 0
87+ },
88+ "maxAgentHandoffs": {
89+ "description": "In a channel, how many times one message may be handed from agent to agent: an agent whose answer mentions another member with @name hands it the floor. 0 turns it off.",
90+ "type": "integer",
91+ "minimum": 0,
92+ "maximum": 10,
93+ "default": 3
87 }94 }
88 }95 }
89 },96 },