#95 Formulaires des agents (ask_user de mini-me) dans les conversations
Tous les agents des conversations annoncent elicitation.form ; chaque formulaire va à la session nommée dans _meta["mm.elicitationScope"] (sinon au seul tour en cours) et s'affiche comme une carte sous la réponse : texte libre, choix, plusieurs choix, oui/non ; Répondre, Refuser, Arrêter. - acp : Spec.Forms, FormAsker, tours en cours par session - channels : FormRequest, form:requested / form:resolved, AnswerForm, Stop - interface : FormCard, FormFields partagé avec l'assistant de création - docs EN + FR ; ticket #95 dans v1.5.0 - note pour mini-me : MINI-ME-DOCKERINIT-UID.md (uid de dockerinit) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
0f3d2bf parent: 7fa255d modified
.memory/handoffs/2026-11-14-mini-me-creator.md +6 -0 | @@ -15,3 +15,9 @@ Branch `feature/94-mini-me-creator`, not pushed. Implemented, tested in the Linu | ||
| 15 | 15 | - No released mm 1.0.9 existed at the time (mini-me tree at v1.0.8-8): an mm built by hand says `unknown`, which the version check accepts on purpose. |
| 16 | 16 | - mm's wizard texts are English; only Sidekicks' own texts are translated. |
| 17 | 17 | - Emoji show as boxes under Xvfb (no emoji font in the sandbox), not a bug. |
| 18 | + | |
| 19 | +## Also on this branch: #95 (ask_user forms in conversations) | |
| 20 | + | |
| 21 | +- Done and tested with a fake agent; task 6 open: on the Mac, ask a mini-me agent something that makes it call `ask_user` with a free-text question, answer in the card. | |
| 22 | +- Every agent (Claude, Codex, Gemini, docker-agent too) now advertises `elicitation.form`; one that sends a form gets the card. Not tried with them. | |
| 23 | +- `MINI-ME-DOCKERINIT-UID.md` at the root is a note for the mini-me project (dockerinit uid defect); delete it once handed over. | |
| @@ -15,3 +15,9 @@ Branch `feature/94-mini-me-creator`, not pushed. Implemented, tested in the Linu | |||
| 15 | - No released mm 1.0.9 existed at the time (mini-me tree at v1.0.8-8): an mm built by hand says `unknown`, which the version check accepts on purpose. | 15 | - No released mm 1.0.9 existed at the time (mini-me tree at v1.0.8-8): an mm built by hand says `unknown`, which the version check accepts on purpose. |
| 16 | - mm's wizard texts are English; only Sidekicks' own texts are translated. | 16 | - mm's wizard texts are English; only Sidekicks' own texts are translated. |
| 17 | - Emoji show as boxes under Xvfb (no emoji font in the sandbox), not a bug. | 17 | - Emoji show as boxes under Xvfb (no emoji font in the sandbox), not a bug. |
| 18 | + | ||
| 19 | +## Also on this branch: #95 (ask_user forms in conversations) | ||
| 20 | + | ||
| 21 | +- Done and tested with a fake agent; task 6 open: on the Mac, ask a mini-me agent something that makes it call `ask_user` with a free-text question, answer in the card. | ||
| 22 | +- Every agent (Claude, Codex, Gemini, docker-agent too) now advertises `elicitation.form`; one that sends a form gets the card. Not tried with them. | ||
| 23 | +- `MINI-ME-DOCKERINIT-UID.md` at the root is a note for the mini-me project (dockerinit uid defect); delete it once handed over. | ||
modified
.memory/history.md +3 -0 | @@ -248,3 +248,6 @@ | ||
| 248 | 248 | - Fix found on the way: lifecycle commands now get `PWD=<folder>` — mm's `compose.yaml` mounts `${PWD}`, and Sidekicks' PWD is "/" from the Finder. |
| 249 | 249 | - Tests: Go (acp forms, creator, app service, lifecycle PWD, config), vitest (creator.ts), `make lint-go` and svelte-check clean; real mm 1.0.9 built from the read-only mini-me tree (`-ldflags -X mm/internal/version.stamped=v1.0.9`) in local/container/sbx; UI under Xvfb: local agent created end to end with the host's llmman (models listed), Back, Cancel (temp folder removed, mm stopped), mm missing, mm 1.0.8. `make lint-headers` fails only on the owner's untracked `citizens/` and `sbxenv.yaml`. qlty absent from this sandbox: no qlty gate. |
| 250 | 250 | - Not done: a created container/sbx agent actually started (needs the Mac); release notes v1.5.0 (with #93). Docs EN/FR: how-to create-a-mini-me-agent / creer-un-agent-mini-me, configuration (`agentsFolder`), agents-and-events (`CreatorService`), shortcuts (palette), READMEs, add-an-agent see-also. |
| 251 | +- **2026-11-14 — "I have no name!" in a created container's terminal** (owner): cause in mini-me, not Sidekicks — `mm dockerinit`'s compose.yaml runs the container as the host uid:gid (`${MM_UID:-<uid>}:${MM_GID:-<gid>}`, 501:20 on the Mac) while its Dockerfile only creates `mm` with uid 1000, so uid 501 has no /etc/passwd entry (bash prints "I have no name!", `whoami` fails, git without user.name/email and ssh refuse). Fix belongs to mini-me's dockerinit (create the user with the host uid via build args); mini-me is read-only in this sandbox. Nothing changed; waiting for the owner's choice. | |
| 252 | +- **2026-11-14 — note for mini-me + ticket #95** (owner): `MINI-ME-DOCKERINIT-UID.md` at the root explains the "I have no name!" defect of mm dockerinit (Dockerfile account uid 1000 vs compose `user:` = host uid) and the fix (account created from build args MM_UID/MM_GID, `groupadd -o`/`useradd -o`), checked in debian:bookworm-slim with -u 501:20 (whoami: before "cannot find name for user ID 501", after "mm"). #95 (no milestone): mm's `ask_user` text questions have no input in Sidekicks — conversation agents do not advertise `elicitation.form` (only #94's creator does), so mm falls back to permission dialogs (choices/yes-no only) or "unavailable"; routing needs the session id the SDK form type drops. Not committed. | |
| 253 | +- **2026-11-14 — #95 implemented** (owner: "#95 goes in v1.5.0, then implement it"): `acp.Spec.Forms` + `FormAsker` routing (`_meta["mm.elicitationScope"].sessionId`, else the only session with a turn in flight — `sessions.turns` counted in `Conn.Prompt`); agents manager sets `Forms: true` for every agent; channels `FormRequest`, events `form:requested|resolved`, `Manager.AnswerForm`, Cancel cancels forms; `ChannelService.AnswerForm`; UI `FormCard.svelte` + shared `FormFields.svelte` (the creator now uses it). Verified: Go/vitest/lint; Xvfb with a Python fake ACP agent imitating ask_user (empty required text refused, answer returned, Decline). Not verified: a real mm whose model calls ask_user. Docs EN/FR: agents-and-events (events, AnswerForm), permissions explanation. | |
| @@ -248,3 +248,6 @@ | |||
| 248 | - Fix found on the way: lifecycle commands now get `PWD=<folder>` — mm's `compose.yaml` mounts `${PWD}`, and Sidekicks' PWD is "/" from the Finder. | 248 | - Fix found on the way: lifecycle commands now get `PWD=<folder>` — mm's `compose.yaml` mounts `${PWD}`, and Sidekicks' PWD is "/" from the Finder. |
| 249 | - Tests: Go (acp forms, creator, app service, lifecycle PWD, config), vitest (creator.ts), `make lint-go` and svelte-check clean; real mm 1.0.9 built from the read-only mini-me tree (`-ldflags -X mm/internal/version.stamped=v1.0.9`) in local/container/sbx; UI under Xvfb: local agent created end to end with the host's llmman (models listed), Back, Cancel (temp folder removed, mm stopped), mm missing, mm 1.0.8. `make lint-headers` fails only on the owner's untracked `citizens/` and `sbxenv.yaml`. qlty absent from this sandbox: no qlty gate. | 249 | - Tests: Go (acp forms, creator, app service, lifecycle PWD, config), vitest (creator.ts), `make lint-go` and svelte-check clean; real mm 1.0.9 built from the read-only mini-me tree (`-ldflags -X mm/internal/version.stamped=v1.0.9`) in local/container/sbx; UI under Xvfb: local agent created end to end with the host's llmman (models listed), Back, Cancel (temp folder removed, mm stopped), mm missing, mm 1.0.8. `make lint-headers` fails only on the owner's untracked `citizens/` and `sbxenv.yaml`. qlty absent from this sandbox: no qlty gate. |
| 250 | - Not done: a created container/sbx agent actually started (needs the Mac); release notes v1.5.0 (with #93). Docs EN/FR: how-to create-a-mini-me-agent / creer-un-agent-mini-me, configuration (`agentsFolder`), agents-and-events (`CreatorService`), shortcuts (palette), READMEs, add-an-agent see-also. | 250 | - Not done: a created container/sbx agent actually started (needs the Mac); release notes v1.5.0 (with #93). Docs EN/FR: how-to create-a-mini-me-agent / creer-un-agent-mini-me, configuration (`agentsFolder`), agents-and-events (`CreatorService`), shortcuts (palette), READMEs, add-an-agent see-also. |
| 251 | +- **2026-11-14 — "I have no name!" in a created container's terminal** (owner): cause in mini-me, not Sidekicks — `mm dockerinit`'s compose.yaml runs the container as the host uid:gid (`${MM_UID:-<uid>}:${MM_GID:-<gid>}`, 501:20 on the Mac) while its Dockerfile only creates `mm` with uid 1000, so uid 501 has no /etc/passwd entry (bash prints "I have no name!", `whoami` fails, git without user.name/email and ssh refuse). Fix belongs to mini-me's dockerinit (create the user with the host uid via build args); mini-me is read-only in this sandbox. Nothing changed; waiting for the owner's choice. | ||
| 252 | +- **2026-11-14 — note for mini-me + ticket #95** (owner): `MINI-ME-DOCKERINIT-UID.md` at the root explains the "I have no name!" defect of mm dockerinit (Dockerfile account uid 1000 vs compose `user:` = host uid) and the fix (account created from build args MM_UID/MM_GID, `groupadd -o`/`useradd -o`), checked in debian:bookworm-slim with -u 501:20 (whoami: before "cannot find name for user ID 501", after "mm"). #95 (no milestone): mm's `ask_user` text questions have no input in Sidekicks — conversation agents do not advertise `elicitation.form` (only #94's creator does), so mm falls back to permission dialogs (choices/yes-no only) or "unavailable"; routing needs the session id the SDK form type drops. Not committed. | ||
| 253 | +- **2026-11-14 — #95 implemented** (owner: "#95 goes in v1.5.0, then implement it"): `acp.Spec.Forms` + `FormAsker` routing (`_meta["mm.elicitationScope"].sessionId`, else the only session with a turn in flight — `sessions.turns` counted in `Conn.Prompt`); agents manager sets `Forms: true` for every agent; channels `FormRequest`, events `form:requested|resolved`, `Manager.AnswerForm`, Cancel cancels forms; `ChannelService.AnswerForm`; UI `FormCard.svelte` + shared `FormFields.svelte` (the creator now uses it). Verified: Go/vitest/lint; Xvfb with a Python fake ACP agent imitating ask_user (empty required text refused, answer returned, Decline). Not verified: a real mm whose model calls ask_user. Docs EN/FR: agents-and-events (events, AnswerForm), permissions explanation. | ||
modified
.memory/summary.md +1 -0 | @@ -25,6 +25,7 @@ What exists: | ||
| 25 | 25 | - Channels: ADR 0006 — routing (`/agent:cmd` > mentions in order > last speaker > nobody), one session per (channel, agent), unseen messages re-sent (20 max, 1500 chars each, prompt ends with "answer directly, without your name in front"), one channel at a time per agent, commands sent alone, fresh session after restart gets the last messages, no Sidekicks-local slash commands (owner's choice), deleting a channel deletes its history after confirmation. Store: keys of ADR 0003 + `direct/<agent>` + `value/<key>`, `ErrClosed` after Close, in-memory fallback when the DB is locked (`historyProblem`). |
| 26 | 26 | - Workspaces: ADR 0007 — one `Workspace` interface (local: os/fsnotify/creack pty; container: docker exec + busybox-compatible POSIX scripts; sbx: ErrNotSupported until #39); paths relative, never leaving the folder; versioned writes (content hash) + atomic rename; local delete → system trash (EXDEV → final), container delete final; only the shown workspace is watched (fsnotify / 2 s polling in containers); terminals: output events every 16 ms/32 KB UTF-8-safe, Close hangs up the whole session (`pkill -s`) and, in a container, the session inside it (pid file + /proc); `docker` looked up in PATH then Docker Desktop/Homebrew paths. |
| 27 | 27 | - Mini-me creation assistant (#94, `CreatorService`, page `CreateMiniMeAgent.svelte`): Sidekicks is the ACP client of `mm --acp-create --project yes --output .mm/agent.yaml` (mm ≥ 1.0.9, checked with `mm --version`; an unparsable version is accepted); `.mm` layout imposed; the wizard runs in `<agentsFolder>/.sidekicks-new-agent-*`, renamed to `<agentsFolder>/<name>` at Finish (name = folder = agent name; an existing folder is never touched); container/sbx files come from `/dockerinit` / `/sbxinit` in an mm restarted in the final folder. `agentsFolder` (top-level config key) defaults to `~/Documents`. mm's questions stay in English (they are mm's). |
| 28 | +- Agent forms (#95): every conversation agent is started with `acp.Spec.Forms` (advertises `elicitation.form`); a form goes to the session named in `_meta["mm.elicitationScope"]`, else to the only session with a prompt in flight, and is shown as a `FormCard` under the answer (`form:requested`/`form:resolved`, `ChannelService.AnswerForm`); Stop cancels it. Fields rendered by `chat/FormFields.svelte`, shared with the creator. | |
| 28 | 29 | - Interface language: ADR 0005 — `ui.language` defaults to `en`; every UI text is a key of `frontend/src/lib/i18n/messages.ts` (`fr` typed `Record<MessageKey,string>`, test checks keys and variables); config errors use the Go catalogue in the same language; agent titles and channel names are user data, never translated. Default config file and `examples/test-agents.yaml` are in English. |
| 29 | 30 | - Packages and data model: ADR 0003 + Amendments 1 and 2 (main at the root, only main.go imports Wails, `internal/events` with an `Emitter` interface, LRU eviction of idle agents at the limit). |
| 30 | 31 | - Frontend dependencies with **pnpm 12.11.2** and `frontend/pnpm-workspace.yaml` `supportedArchitectures` (darwin+linux): the repository folder is shared between the Mac and the Linux sandbox. Never use npm in `frontend/`. |
| @@ -25,6 +25,7 @@ What exists: | |||
| 25 | - Channels: ADR 0006 — routing (`/agent:cmd` > mentions in order > last speaker > nobody), one session per (channel, agent), unseen messages re-sent (20 max, 1500 chars each, prompt ends with "answer directly, without your name in front"), one channel at a time per agent, commands sent alone, fresh session after restart gets the last messages, no Sidekicks-local slash commands (owner's choice), deleting a channel deletes its history after confirmation. Store: keys of ADR 0003 + `direct/<agent>` + `value/<key>`, `ErrClosed` after Close, in-memory fallback when the DB is locked (`historyProblem`). | 25 | - Channels: ADR 0006 — routing (`/agent:cmd` > mentions in order > last speaker > nobody), one session per (channel, agent), unseen messages re-sent (20 max, 1500 chars each, prompt ends with "answer directly, without your name in front"), one channel at a time per agent, commands sent alone, fresh session after restart gets the last messages, no Sidekicks-local slash commands (owner's choice), deleting a channel deletes its history after confirmation. Store: keys of ADR 0003 + `direct/<agent>` + `value/<key>`, `ErrClosed` after Close, in-memory fallback when the DB is locked (`historyProblem`). |
| 26 | - Workspaces: ADR 0007 — one `Workspace` interface (local: os/fsnotify/creack pty; container: docker exec + busybox-compatible POSIX scripts; sbx: ErrNotSupported until #39); paths relative, never leaving the folder; versioned writes (content hash) + atomic rename; local delete → system trash (EXDEV → final), container delete final; only the shown workspace is watched (fsnotify / 2 s polling in containers); terminals: output events every 16 ms/32 KB UTF-8-safe, Close hangs up the whole session (`pkill -s`) and, in a container, the session inside it (pid file + /proc); `docker` looked up in PATH then Docker Desktop/Homebrew paths. | 26 | - Workspaces: ADR 0007 — one `Workspace` interface (local: os/fsnotify/creack pty; container: docker exec + busybox-compatible POSIX scripts; sbx: ErrNotSupported until #39); paths relative, never leaving the folder; versioned writes (content hash) + atomic rename; local delete → system trash (EXDEV → final), container delete final; only the shown workspace is watched (fsnotify / 2 s polling in containers); terminals: output events every 16 ms/32 KB UTF-8-safe, Close hangs up the whole session (`pkill -s`) and, in a container, the session inside it (pid file + /proc); `docker` looked up in PATH then Docker Desktop/Homebrew paths. |
| 27 | - Mini-me creation assistant (#94, `CreatorService`, page `CreateMiniMeAgent.svelte`): Sidekicks is the ACP client of `mm --acp-create --project yes --output .mm/agent.yaml` (mm ≥ 1.0.9, checked with `mm --version`; an unparsable version is accepted); `.mm` layout imposed; the wizard runs in `<agentsFolder>/.sidekicks-new-agent-*`, renamed to `<agentsFolder>/<name>` at Finish (name = folder = agent name; an existing folder is never touched); container/sbx files come from `/dockerinit` / `/sbxinit` in an mm restarted in the final folder. `agentsFolder` (top-level config key) defaults to `~/Documents`. mm's questions stay in English (they are mm's). | 27 | - Mini-me creation assistant (#94, `CreatorService`, page `CreateMiniMeAgent.svelte`): Sidekicks is the ACP client of `mm --acp-create --project yes --output .mm/agent.yaml` (mm ≥ 1.0.9, checked with `mm --version`; an unparsable version is accepted); `.mm` layout imposed; the wizard runs in `<agentsFolder>/.sidekicks-new-agent-*`, renamed to `<agentsFolder>/<name>` at Finish (name = folder = agent name; an existing folder is never touched); container/sbx files come from `/dockerinit` / `/sbxinit` in an mm restarted in the final folder. `agentsFolder` (top-level config key) defaults to `~/Documents`. mm's questions stay in English (they are mm's). |
| 28 | +- Agent forms (#95): every conversation agent is started with `acp.Spec.Forms` (advertises `elicitation.form`); a form goes to the session named in `_meta["mm.elicitationScope"]`, else to the only session with a prompt in flight, and is shown as a `FormCard` under the answer (`form:requested`/`form:resolved`, `ChannelService.AnswerForm`); Stop cancels it. Fields rendered by `chat/FormFields.svelte`, shared with the creator. | ||
| 28 | - Interface language: ADR 0005 — `ui.language` defaults to `en`; every UI text is a key of `frontend/src/lib/i18n/messages.ts` (`fr` typed `Record<MessageKey,string>`, test checks keys and variables); config errors use the Go catalogue in the same language; agent titles and channel names are user data, never translated. Default config file and `examples/test-agents.yaml` are in English. | 29 | - Interface language: ADR 0005 — `ui.language` defaults to `en`; every UI text is a key of `frontend/src/lib/i18n/messages.ts` (`fr` typed `Record<MessageKey,string>`, test checks keys and variables); config errors use the Go catalogue in the same language; agent titles and channel names are user data, never translated. Default config file and `examples/test-agents.yaml` are in English. |
| 29 | - Packages and data model: ADR 0003 + Amendments 1 and 2 (main at the root, only main.go imports Wails, `internal/events` with an `Emitter` interface, LRU eviction of idle agents at the limit). | 30 | - Packages and data model: ADR 0003 + Amendments 1 and 2 (main at the root, only main.go imports Wails, `internal/events` with an `Emitter` interface, LRU eviction of idle agents at the limit). |
| 30 | - Frontend dependencies with **pnpm 12.11.2** and `frontend/pnpm-workspace.yaml` `supportedArchitectures` (darwin+linux): the repository folder is shared between the Mac and the Linux sandbox. Never use npm in `frontend/`. | 31 | - Frontend dependencies with **pnpm 12.11.2** and `frontend/pnpm-workspace.yaml` `supportedArchitectures` (darwin+linux): the repository folder is shared between the Mac and the Linux sandbox. Never use npm in `frontend/`. |
modified
.tickets/issues/0093-publier-la-version-1-5-0.yaml +2 -1 | @@ -6,7 +6,7 @@ author: | ||
| 6 | 6 | name: k33g |
| 7 | 7 | email: ph.charriere@gmail.com |
| 8 | 8 | createdAt: 2026-11-14T05:24:28.000Z |
| 9 | -updatedAt: 2026-11-14T16:32:06.000Z | |
| 9 | +updatedAt: 2026-11-14T17:25:17.000Z | |
| 10 | 10 | labels: |
| 11 | 11 | - kind::chore |
| 12 | 12 | - area::infra |
| @@ -17,6 +17,7 @@ related: | ||
| 17 | 17 | body: | |
| 18 | 18 | Publier Sidekicks 1.5.0 avec ce qui sera fait après la 1.4.0 (liste à compléter) : |
| 19 | 19 | - [#94](.tickets/issues/0094-assistant-de-creation-d-agents-mini-me-pour-les.yaml) — assistant de création d'agents mini-me pour les utilisateurs non techniques |
| 20 | + - [#95](.tickets/issues/0095-ask-user-de-mini-me-pas-de-zone-de-saisie-dans-s.yaml) — `ask_user` de mini-me : zone de saisie dans la conversation | |
| 20 | 21 | |
| 21 | 22 | Même déroulé que [#92 — Publier la version 1.4.0](.tickets/issues/0092-publier-la-version-1-4-0.yaml), en suivant |
| 22 | 23 | [RELEASING.fr.md](RELEASING.fr.md) (scripts `local-ci-*.sh`), **kDrive en pause** pendant la construction. |
| @@ -6,7 +6,7 @@ author: | |||
| 6 | name: k33g | 6 | name: k33g |
| 7 | email: ph.charriere@gmail.com | 7 | email: ph.charriere@gmail.com |
| 8 | createdAt: 2026-11-14T05:24:28.000Z | 8 | createdAt: 2026-11-14T05:24:28.000Z |
| 9 | -updatedAt: 2026-11-14T16:32:06.000Z | 9 | +updatedAt: 2026-11-14T17:25:17.000Z |
| 10 | labels: | 10 | labels: |
| 11 | - kind::chore | 11 | - kind::chore |
| 12 | - area::infra | 12 | - area::infra |
| @@ -17,6 +17,7 @@ related: | |||
| 17 | body: | | 17 | body: | |
| 18 | Publier Sidekicks 1.5.0 avec ce qui sera fait après la 1.4.0 (liste à compléter) : | 18 | Publier Sidekicks 1.5.0 avec ce qui sera fait après la 1.4.0 (liste à compléter) : |
| 19 | - [#94](.tickets/issues/0094-assistant-de-creation-d-agents-mini-me-pour-les.yaml) — assistant de création d'agents mini-me pour les utilisateurs non techniques | 19 | - [#94](.tickets/issues/0094-assistant-de-creation-d-agents-mini-me-pour-les.yaml) — assistant de création d'agents mini-me pour les utilisateurs non techniques |
| 20 | + - [#95](.tickets/issues/0095-ask-user-de-mini-me-pas-de-zone-de-saisie-dans-s.yaml) — `ask_user` de mini-me : zone de saisie dans la conversation | ||
| 20 | 21 | ||
| 21 | Même déroulé que [#92 — Publier la version 1.4.0](.tickets/issues/0092-publier-la-version-1-4-0.yaml), en suivant | 22 | Même déroulé que [#92 — Publier la version 1.4.0](.tickets/issues/0092-publier-la-version-1-4-0.yaml), en suivant |
| 22 | [RELEASING.fr.md](RELEASING.fr.md) (scripts `local-ci-*.sh`), **kDrive en pause** pendant la construction. | 23 | [RELEASING.fr.md](RELEASING.fr.md) (scripts `local-ci-*.sh`), **kDrive en pause** pendant la construction. |
added
.tickets/issues/0095-ask-user-de-mini-me-pas-de-zone-de-saisie-dans-s.yaml +131 -0 | new file mode 100644 | ||
| @@ -0,0 +1,131 @@ | ||
| 1 | +# Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | |
| 2 | +id: 95 | |
| 3 | +title: "ask_user de mini-me : pas de zone de saisie dans Sidekicks" | |
| 4 | +state: open | |
| 5 | +author: | |
| 6 | + name: k33g | |
| 7 | + email: ph.charriere@gmail.com | |
| 8 | +createdAt: 2026-11-14T17:21:25.000Z | |
| 9 | +updatedAt: 2026-11-14T17:30:42.000Z | |
| 10 | +labels: | |
| 11 | + - kind::bug | |
| 12 | + - area::acp | |
| 13 | + - area::ui | |
| 14 | + - citizen-ux | |
| 15 | + - real-agents | |
| 16 | +milestone: "v1.5.0 · Release" | |
| 17 | +epic: Client ACP | |
| 18 | +related: | |
| 19 | + - 94 | |
| 20 | +body: | | |
| 21 | + Constat (owner) : quand un agent mini-me appelle son outil `ask_user` et attend une réponse, Sidekicks ne | |
| 22 | + propose pas de zone de saisie. | |
| 23 | + | |
| 24 | + ## Cause (lue dans le code de mini-me, `internal/acp/elicit.go`) | |
| 25 | + mm pose les questions d'`ask_user` de la meilleure façon que le client permet : | |
| 26 | + 1. le client a annoncé `clientCapabilities.elicitation.form` à l'`initialize` → tout le formulaire part en une | |
| 27 | + requête `elicitation/create` (texte libre, choix, plusieurs choix, oui/non) ; | |
| 28 | + 2. sinon, si toutes les questions sont des choix ou des oui/non → une boîte `session/request_permission` par | |
| 29 | + question, dont les boutons sont les options (Sidekicks l'affiche comme une carte de permission) ; | |
| 30 | + 3. sinon (texte libre, plusieurs choix) → personne ne peut répondre : l'outil répond « indisponible » au modèle. | |
| 31 | + | |
| 32 | + Sidekicks n'annonce `elicitation.form` que pour l'assistant de création ([#94](.tickets/issues/0094-assistant-de-creation-d-agents-mini-me-pour-les.yaml), | |
| 33 | + `Spec.OnForm`), pas pour les agents des conversations : une question à réponse libre tombe donc dans le cas 3, sans | |
| 34 | + zone de saisie, et un choix multiple aussi. | |
| 35 | + | |
| 36 | + ## Proposition | |
| 37 | + - Donner un `OnForm` aux agents des conversations (`internal/agents` → `acp.Spec`) : la capacité est alors annoncée | |
| 38 | + et mm envoie ses formulaires. | |
| 39 | + - Afficher le formulaire **dans la conversation**, comme une carte de permission (événements `form:requested` / | |
| 40 | + `form:resolved`, à la manière de `permission:requested|resolved`) : champs texte, choix, plusieurs choix, oui/non, | |
| 41 | + boutons Répondre / Refuser. Réutiliser le rendu des champs de `CreateMiniMeAgent.svelte` (`lib/creator.ts`) en | |
| 42 | + l'extrayant dans un composant commun. | |
| 43 | + - Stop (■) pendant la question → `cancel` ; changement de channel → la carte reste en attente dans sa conversation. | |
| 44 | + | |
| 45 | + ## Points à vérifier | |
| 46 | + - **Routage** : la requête de mm porte la session dans `sessionId` (et `toolCallId`) au niveau de la requête, | |
| 47 | + mais le type `UnstableCreateElicitationForm` du SDK Go v0.13.5 ne les expose pas. Pistes : un agent ne répond | |
| 48 | + que dans un channel à la fois (ADR 0006), donc la session dont le tour est en cours ; ou lire le JSON brut. | |
| 49 | + - Les autres agents ACP (Claude, Codex, Gemini, docker-agent) : annoncer la capacité ne doit rien changer pour eux. | |
| 50 | + - Un agent qui pose une question à un autre agent (#26, ask_agent côté mm) : à qui va le formulaire. | |
| 51 | + | |
| 52 | + ## Critères d'acceptation | |
| 53 | + - Un agent mini-me qui appelle `ask_user` avec une question à réponse libre affiche une zone de saisie dans la | |
| 54 | + conversation ; la réponse revient au modèle. | |
| 55 | + - Les choix, plusieurs choix et oui/non passent aussi par le formulaire. | |
| 56 | + - Refuser ou Stop rend la main au modèle sans bloquer le tour. | |
| 57 | + - Tests unitaires (faux agent qui envoie un formulaire), essai avec un vrai mm ; doc EN + FR. | |
| 58 | +tasks: | |
| 59 | + - id: 1 | |
| 60 | + title: "acp : Spec.Forms, routage par session (_meta mm.elicitationScope, sinon le seul tour en cours)" | |
| 61 | + state: closed | |
| 62 | + priority: high | |
| 63 | + author: | |
| 64 | + name: k33g | |
| 65 | + email: ph.charriere@gmail.com | |
| 66 | + createdAt: 2026-11-14T17:30:42.000Z | |
| 67 | + updatedAt: 2026-11-14T17:30:42.000Z | |
| 68 | + closedAt: 2026-11-14T17:30:42.000Z | |
| 69 | + - id: 2 | |
| 70 | + title: "channels : FormRequest, événements form:requested / form:resolved, AnswerForm, annulé par Stop" | |
| 71 | + state: closed | |
| 72 | + priority: high | |
| 73 | + author: | |
| 74 | + name: k33g | |
| 75 | + email: ph.charriere@gmail.com | |
| 76 | + createdAt: 2026-11-14T17:30:42.000Z | |
| 77 | + updatedAt: 2026-11-14T17:30:42.000Z | |
| 78 | + closedAt: 2026-11-14T17:30:42.000Z | |
| 79 | + - id: 3 | |
| 80 | + title: "Interface : carte de formulaire dans la conversation, champs partagés avec l'assistant de création (FormFields)" | |
| 81 | + state: closed | |
| 82 | + priority: high | |
| 83 | + author: | |
| 84 | + name: k33g | |
| 85 | + email: ph.charriere@gmail.com | |
| 86 | + createdAt: 2026-11-14T17:30:42.000Z | |
| 87 | + updatedAt: 2026-11-14T17:30:42.000Z | |
| 88 | + closedAt: 2026-11-14T17:30:42.000Z | |
| 89 | + - id: 4 | |
| 90 | + title: "Tests Go + vitest, essai sous Xvfb avec un faux agent ACP" | |
| 91 | + state: closed | |
| 92 | + priority: high | |
| 93 | + author: | |
| 94 | + name: k33g | |
| 95 | + email: ph.charriere@gmail.com | |
| 96 | + createdAt: 2026-11-14T17:30:42.000Z | |
| 97 | + updatedAt: 2026-11-14T17:30:42.000Z | |
| 98 | + closedAt: 2026-11-14T17:30:42.000Z | |
| 99 | + - id: 5 | |
| 100 | + title: "Doc EN + FR (référence, explication des permissions)" | |
| 101 | + state: closed | |
| 102 | + priority: medium | |
| 103 | + author: | |
| 104 | + name: k33g | |
| 105 | + email: ph.charriere@gmail.com | |
| 106 | + createdAt: 2026-11-14T17:30:42.000Z | |
| 107 | + updatedAt: 2026-11-14T17:30:42.000Z | |
| 108 | + closedAt: 2026-11-14T17:30:42.000Z | |
| 109 | + - id: 6 | |
| 110 | + title: "Essai avec un vrai agent mini-me qui appelle ask_user (sur le Mac)" | |
| 111 | + state: open | |
| 112 | + priority: high | |
| 113 | + author: | |
| 114 | + name: k33g | |
| 115 | + email: ph.charriere@gmail.com | |
| 116 | + createdAt: 2026-11-14T17:30:42.000Z | |
| 117 | +comments: | |
| 118 | + - id: 1 | |
| 119 | + author: | |
| 120 | + name: k33g | |
| 121 | + email: ph.charriere@gmail.com | |
| 122 | + createdAt: 2026-11-14T17:30:42.000Z | |
| 123 | + body: | | |
| 124 | + Implémenté sur la branche `feature/94-mini-me-creator`. Tous les agents des conversations annoncent | |
| 125 | + `elicitation.form` ; chaque formulaire s'affiche comme une carte sous la réponse (texte, choix, plusieurs choix, | |
| 126 | + oui/non ; Répondre, Refuser, Arrêter). Routage : la session lue dans `_meta["mm.elicitationScope"]` (mm l'y | |
| 127 | + recopie parce que le SDK perd `sessionId`), sinon la seule session dont un tour est en cours. | |
| 128 | + | |
| 129 | + Vérifié : tests Go (acp, channels) et vitest, lint ; sous Xvfb avec un faux agent ACP (Python) qui imite | |
| 130 | + `ask_user` : texte obligatoire refusé vide, réponse « Lyon » + « coffee » rendue à l'agent, Refuser. | |
| 131 | + Reste : un vrai mm dont le modèle appelle `ask_user` (tâche 6). | |
| new file mode 100644 | |||
| @@ -0,0 +1,131 @@ | |||
| 1 | +# Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | ||
| 2 | +id: 95 | ||
| 3 | +title: "ask_user de mini-me : pas de zone de saisie dans Sidekicks" | ||
| 4 | +state: open | ||
| 5 | +author: | ||
| 6 | + name: k33g | ||
| 7 | + email: ph.charriere@gmail.com | ||
| 8 | +createdAt: 2026-11-14T17:21:25.000Z | ||
| 9 | +updatedAt: 2026-11-14T17:30:42.000Z | ||
| 10 | +labels: | ||
| 11 | + - kind::bug | ||
| 12 | + - area::acp | ||
| 13 | + - area::ui | ||
| 14 | + - citizen-ux | ||
| 15 | + - real-agents | ||
| 16 | +milestone: "v1.5.0 · Release" | ||
| 17 | +epic: Client ACP | ||
| 18 | +related: | ||
| 19 | + - 94 | ||
| 20 | +body: | | ||
| 21 | + Constat (owner) : quand un agent mini-me appelle son outil `ask_user` et attend une réponse, Sidekicks ne | ||
| 22 | + propose pas de zone de saisie. | ||
| 23 | + | ||
| 24 | + ## Cause (lue dans le code de mini-me, `internal/acp/elicit.go`) | ||
| 25 | + mm pose les questions d'`ask_user` de la meilleure façon que le client permet : | ||
| 26 | + 1. le client a annoncé `clientCapabilities.elicitation.form` à l'`initialize` → tout le formulaire part en une | ||
| 27 | + requête `elicitation/create` (texte libre, choix, plusieurs choix, oui/non) ; | ||
| 28 | + 2. sinon, si toutes les questions sont des choix ou des oui/non → une boîte `session/request_permission` par | ||
| 29 | + question, dont les boutons sont les options (Sidekicks l'affiche comme une carte de permission) ; | ||
| 30 | + 3. sinon (texte libre, plusieurs choix) → personne ne peut répondre : l'outil répond « indisponible » au modèle. | ||
| 31 | + | ||
| 32 | + Sidekicks n'annonce `elicitation.form` que pour l'assistant de création ([#94](.tickets/issues/0094-assistant-de-creation-d-agents-mini-me-pour-les.yaml), | ||
| 33 | + `Spec.OnForm`), pas pour les agents des conversations : une question à réponse libre tombe donc dans le cas 3, sans | ||
| 34 | + zone de saisie, et un choix multiple aussi. | ||
| 35 | + | ||
| 36 | + ## Proposition | ||
| 37 | + - Donner un `OnForm` aux agents des conversations (`internal/agents` → `acp.Spec`) : la capacité est alors annoncée | ||
| 38 | + et mm envoie ses formulaires. | ||
| 39 | + - Afficher le formulaire **dans la conversation**, comme une carte de permission (événements `form:requested` / | ||
| 40 | + `form:resolved`, à la manière de `permission:requested|resolved`) : champs texte, choix, plusieurs choix, oui/non, | ||
| 41 | + boutons Répondre / Refuser. Réutiliser le rendu des champs de `CreateMiniMeAgent.svelte` (`lib/creator.ts`) en | ||
| 42 | + l'extrayant dans un composant commun. | ||
| 43 | + - Stop (■) pendant la question → `cancel` ; changement de channel → la carte reste en attente dans sa conversation. | ||
| 44 | + | ||
| 45 | + ## Points à vérifier | ||
| 46 | + - **Routage** : la requête de mm porte la session dans `sessionId` (et `toolCallId`) au niveau de la requête, | ||
| 47 | + mais le type `UnstableCreateElicitationForm` du SDK Go v0.13.5 ne les expose pas. Pistes : un agent ne répond | ||
| 48 | + que dans un channel à la fois (ADR 0006), donc la session dont le tour est en cours ; ou lire le JSON brut. | ||
| 49 | + - Les autres agents ACP (Claude, Codex, Gemini, docker-agent) : annoncer la capacité ne doit rien changer pour eux. | ||
| 50 | + - Un agent qui pose une question à un autre agent (#26, ask_agent côté mm) : à qui va le formulaire. | ||
| 51 | + | ||
| 52 | + ## Critères d'acceptation | ||
| 53 | + - Un agent mini-me qui appelle `ask_user` avec une question à réponse libre affiche une zone de saisie dans la | ||
| 54 | + conversation ; la réponse revient au modèle. | ||
| 55 | + - Les choix, plusieurs choix et oui/non passent aussi par le formulaire. | ||
| 56 | + - Refuser ou Stop rend la main au modèle sans bloquer le tour. | ||
| 57 | + - Tests unitaires (faux agent qui envoie un formulaire), essai avec un vrai mm ; doc EN + FR. | ||
| 58 | +tasks: | ||
| 59 | + - id: 1 | ||
| 60 | + title: "acp : Spec.Forms, routage par session (_meta mm.elicitationScope, sinon le seul tour en cours)" | ||
| 61 | + state: closed | ||
| 62 | + priority: high | ||
| 63 | + author: | ||
| 64 | + name: k33g | ||
| 65 | + email: ph.charriere@gmail.com | ||
| 66 | + createdAt: 2026-11-14T17:30:42.000Z | ||
| 67 | + updatedAt: 2026-11-14T17:30:42.000Z | ||
| 68 | + closedAt: 2026-11-14T17:30:42.000Z | ||
| 69 | + - id: 2 | ||
| 70 | + title: "channels : FormRequest, événements form:requested / form:resolved, AnswerForm, annulé par Stop" | ||
| 71 | + state: closed | ||
| 72 | + priority: high | ||
| 73 | + author: | ||
| 74 | + name: k33g | ||
| 75 | + email: ph.charriere@gmail.com | ||
| 76 | + createdAt: 2026-11-14T17:30:42.000Z | ||
| 77 | + updatedAt: 2026-11-14T17:30:42.000Z | ||
| 78 | + closedAt: 2026-11-14T17:30:42.000Z | ||
| 79 | + - id: 3 | ||
| 80 | + title: "Interface : carte de formulaire dans la conversation, champs partagés avec l'assistant de création (FormFields)" | ||
| 81 | + state: closed | ||
| 82 | + priority: high | ||
| 83 | + author: | ||
| 84 | + name: k33g | ||
| 85 | + email: ph.charriere@gmail.com | ||
| 86 | + createdAt: 2026-11-14T17:30:42.000Z | ||
| 87 | + updatedAt: 2026-11-14T17:30:42.000Z | ||
| 88 | + closedAt: 2026-11-14T17:30:42.000Z | ||
| 89 | + - id: 4 | ||
| 90 | + title: "Tests Go + vitest, essai sous Xvfb avec un faux agent ACP" | ||
| 91 | + state: closed | ||
| 92 | + priority: high | ||
| 93 | + author: | ||
| 94 | + name: k33g | ||
| 95 | + email: ph.charriere@gmail.com | ||
| 96 | + createdAt: 2026-11-14T17:30:42.000Z | ||
| 97 | + updatedAt: 2026-11-14T17:30:42.000Z | ||
| 98 | + closedAt: 2026-11-14T17:30:42.000Z | ||
| 99 | + - id: 5 | ||
| 100 | + title: "Doc EN + FR (référence, explication des permissions)" | ||
| 101 | + state: closed | ||
| 102 | + priority: medium | ||
| 103 | + author: | ||
| 104 | + name: k33g | ||
| 105 | + email: ph.charriere@gmail.com | ||
| 106 | + createdAt: 2026-11-14T17:30:42.000Z | ||
| 107 | + updatedAt: 2026-11-14T17:30:42.000Z | ||
| 108 | + closedAt: 2026-11-14T17:30:42.000Z | ||
| 109 | + - id: 6 | ||
| 110 | + title: "Essai avec un vrai agent mini-me qui appelle ask_user (sur le Mac)" | ||
| 111 | + state: open | ||
| 112 | + priority: high | ||
| 113 | + author: | ||
| 114 | + name: k33g | ||
| 115 | + email: ph.charriere@gmail.com | ||
| 116 | + createdAt: 2026-11-14T17:30:42.000Z | ||
| 117 | +comments: | ||
| 118 | + - id: 1 | ||
| 119 | + author: | ||
| 120 | + name: k33g | ||
| 121 | + email: ph.charriere@gmail.com | ||
| 122 | + createdAt: 2026-11-14T17:30:42.000Z | ||
| 123 | + body: | | ||
| 124 | + Implémenté sur la branche `feature/94-mini-me-creator`. Tous les agents des conversations annoncent | ||
| 125 | + `elicitation.form` ; chaque formulaire s'affiche comme une carte sous la réponse (texte, choix, plusieurs choix, | ||
| 126 | + oui/non ; Répondre, Refuser, Arrêter). Routage : la session lue dans `_meta["mm.elicitationScope"]` (mm l'y | ||
| 127 | + recopie parce que le SDK perd `sessionId`), sinon la seule session dont un tour est en cours. | ||
| 128 | + | ||
| 129 | + Vérifié : tests Go (acp, channels) et vitest, lint ; sous Xvfb avec un faux agent ACP (Python) qui imite | ||
| 130 | + `ask_user` : texte obligatoire refusé vide, réponse « Lyon » + « coffee » rendue à l'agent, Refuser. | ||
| 131 | + Reste : un vrai mm dont le modèle appelle `ask_user` (tâche 6). | ||
added
MINI-ME-DOCKERINIT-UID.md +123 -0 | new file mode 100644 | ||
| @@ -0,0 +1,123 @@ | ||
| 1 | +# mm dockerinit : « I have no name! » dans le conteneur | |
| 2 | + | |
| 3 | +Note pour le projet mini-me, rédigée depuis Sidekicks (ticket #94, assistant de création d'agents mini-me) le | |
| 4 | +2026-11-14. Elle décrit un défaut des fichiers écrits par `mm dockerinit` (et `/dockerinit` de `mm --acp-create`), | |
| 5 | +sa cause, et une correction vérifiée dans un conteneur Debian. | |
| 6 | + | |
| 7 | +## Symptôme | |
| 8 | + | |
| 9 | +Un agent créé avec l'option conteneur (Sidekicks → `/dockerinit` de `mm --acp-create`), puis un terminal ouvert dans | |
| 10 | +ce conteneur (`docker exec -it jimmy-box bash -l`, ce que fait l'onglet Terminal de Sidekicks), affiche le prompt : | |
| 11 | + | |
| 12 | +```text | |
| 13 | +I have no name!@cd5ed2bf5dad:/Users/k33g/Documents/jimmy$ | |
| 14 | +``` | |
| 15 | + | |
| 16 | +## Cause | |
| 17 | + | |
| 18 | +Les deux fichiers écrits par `mm dockerinit` ne s'accordent pas sur l'utilisateur : | |
| 19 | + | |
| 20 | +- `compose.yaml` lance le conteneur avec l'uid et le gid **de la machine qui a lancé `mm dockerinit`**, pour que les | |
| 21 | + fichiers créés par l'agent dans le projet monté appartiennent à l'utilisateur : | |
| 22 | + | |
| 23 | + ```yaml | |
| 24 | + user: "${MM_UID:-501}:${MM_GID:-20}" # 501:20 sur un Mac | |
| 25 | + ``` | |
| 26 | + | |
| 27 | +- le `Dockerfile` ne crée qu'un compte `mm` avec l'uid **1000** : | |
| 28 | + | |
| 29 | + ```dockerfile | |
| 30 | + RUN useradd --create-home --uid 1000 mm && chmod 777 /home/mm | |
| 31 | + ENV HOME=/home/mm | |
| 32 | + USER mm | |
| 33 | + ``` | |
| 34 | + | |
| 35 | +Sur un Mac, l'uid 501 n'a donc **aucune entrée dans `/etc/passwd`** de l'image. bash ne trouve pas de nom pour | |
| 36 | +`\u` dans son prompt et affiche « I have no name! ». Sous Linux, où l'utilisateur a souvent l'uid 1000, le défaut | |
| 37 | +ne se voit pas, ce qui explique qu'il soit passé inaperçu. | |
| 38 | + | |
| 39 | +## Conséquences | |
| 40 | + | |
| 41 | +Ce n'est pas seulement cosmétique : `HOME=/home/mm` est bien inscriptible (`chmod 777`), donc mm tourne, mais tout | |
| 42 | +programme qui cherche l'utilisateur courant dans `/etc/passwd` échoue : | |
| 43 | + | |
| 44 | +| Commande | Résultat (uid 501 sans compte) | | |
| 45 | +| --- | --- | | |
| 46 | +| `whoami` | `whoami: cannot find name for user ID 501` (constaté) | | |
| 47 | +| `id` | `uid=501 gid=20(dialout) groups=20(dialout)` — pas de nom d'utilisateur (constaté) | | |
| 48 | +| prompt de bash | `I have no name!@<conteneur>:…$` (constaté) | | |
| 49 | +| `git commit` sans `user.name` / `user.email` configurés | git ne peut pas déduire l'identité depuis le compte (non testé ici : `git` n'est pas dans l'image de test) | | |
| 50 | +| `ssh` | refuse de démarrer sans compte pour l'uid (non testé ici) | | |
| 51 | + | |
| 52 | +Un agent qui utilise git ou ssh avec son outil bash peut donc s'y heurter. | |
| 53 | + | |
| 54 | +## Correction proposée | |
| 55 | + | |
| 56 | +Créer le compte `mm` **avec l'uid et le gid de l'utilisateur**, au moment de construire l'image, en les passant de | |
| 57 | +`compose.yaml` au `Dockerfile` comme arguments de build. | |
| 58 | + | |
| 59 | +`Dockerfile` (remplace la ligne `useradd` actuelle) : | |
| 60 | + | |
| 61 | +```dockerfile | |
| 62 | +# The agent never runs as root. Its account has the uid and gid of the user | |
| 63 | +# who runs compose (MM_UID, MM_GID), so that every program finds it in | |
| 64 | +# /etc/passwd and the files it writes in the project belong to that user. | |
| 65 | +ARG MM_UID=1000 | |
| 66 | +ARG MM_GID=1000 | |
| 67 | +RUN groupadd -o -g "$MM_GID" mm \ | |
| 68 | + && useradd -o --create-home --uid "$MM_UID" --gid "$MM_GID" mm \ | |
| 69 | + && chmod 777 /home/mm | |
| 70 | +ENV HOME=/home/mm | |
| 71 | +USER mm | |
| 72 | +``` | |
| 73 | + | |
| 74 | +`compose.yaml` (le `build: .` actuel devient) : | |
| 75 | + | |
| 76 | +```yaml | |
| 77 | + build: | |
| 78 | + context: . | |
| 79 | + args: | |
| 80 | + MM_UID: ${MM_UID:-501} | |
| 81 | + MM_GID: ${MM_GID:-20} | |
| 82 | + image: mm-jimmy:latest | |
| 83 | + container_name: jimmy-box | |
| 84 | + user: "${MM_UID:-501}:${MM_GID:-20}" | |
| 85 | +``` | |
| 86 | + | |
| 87 | +Les valeurs par défaut sont celles que `mm dockerinit` écrit déjà dans `user:` (`usableID(uid)`, `usableID(gid)`), | |
| 88 | +il suffit de les écrire aussi sous `args:`. | |
| 89 | + | |
| 90 | +Points à noter : | |
| 91 | + | |
| 92 | +- **`-o` est nécessaire** : le gid 20 existe déjà dans Debian (`dialout`), et `groupadd` refuserait un gid en double. | |
| 93 | + Avec `-o`, le groupe `mm` partage le gid 20 ; `id` affiche toujours `gid=20(dialout)` (premier nom trouvé), | |
| 94 | + ce qui est sans conséquence. `useradd -o` couvre de même un uid déjà pris par un compte de l'image. | |
| 95 | +- **Une image par utilisateur** : l'uid fait partie de l'image. C'est déjà le cas en pratique (l'image est construite | |
| 96 | + sur la machine de l'utilisateur) ; une image poussée sur un registre (`docker buildx … --push`, mentionné dans | |
| 97 | + les commentaires de `compose.yaml`) garde l'uid 1000 par défaut, comme aujourd'hui. | |
| 98 | +- **Windows** : `usableID` remplace déjà un uid négatif ou nul par la valeur de repli ; rien ne change. | |
| 99 | +- **Les agents déjà créés** : après avoir modifié leurs deux fichiers, reconstruire l'image avec | |
| 100 | + `docker compose up -d --build`. | |
| 101 | + | |
| 102 | +## Vérification | |
| 103 | + | |
| 104 | +Faite le 2026-11-14 dans un conteneur `debian:bookworm-slim`, avec uniquement les lignes du compte (sans le | |
| 105 | +téléchargement de mm), lancé avec `-u 501:20` comme le fait `compose.yaml` sur un Mac : | |
| 106 | + | |
| 107 | +| | Avant (`useradd --uid 1000`) | Après (`--build-arg MM_UID=501 --build-arg MM_GID=20`) | | |
| 108 | +| --- | --- | --- | | |
| 109 | +| `whoami` | `cannot find name for user ID 501` | `mm` | | |
| 110 | +| `id` | `uid=501 gid=20(dialout)` | `uid=501(mm) gid=20(dialout)` | | |
| 111 | +| `HOME` inscriptible | oui | oui (`/home/mm`) | | |
| 112 | + | |
| 113 | +Avec les valeurs par défaut (`MM_UID=1000`, `MM_GID=1000`, cas Linux), `whoami` répond aussi `mm`. | |
| 114 | + | |
| 115 | +À vérifier côté mini-me avec le vrai `Dockerfile` : la construction complète (téléchargement de mm), puis | |
| 116 | +`docker compose exec <service> bash -l` (prompt `mm@…`), `git commit` et `mm tui` dans le conteneur. | |
| 117 | + | |
| 118 | +## Où regarder dans mini-me | |
| 119 | + | |
| 120 | +- `internal/dockerinit/files.go` : la constante `dockerfile` (ligne `useradd`) et la fonction `compose` | |
| 121 | + (ligne `build: .` et `user:`). | |
| 122 | +- Les tests de `internal/dockerinit` qui comparent le contenu écrit. | |
| 123 | +- La doc « run mini-me in a container » (EN et FR), qui explique `MM_UID` et `MM_GID`. | |
| new file mode 100644 | |||
| @@ -0,0 +1,123 @@ | |||
| 1 | +# mm dockerinit : « I have no name! » dans le conteneur | ||
| 2 | + | ||
| 3 | +Note pour le projet mini-me, rédigée depuis Sidekicks (ticket #94, assistant de création d'agents mini-me) le | ||
| 4 | +2026-11-14. Elle décrit un défaut des fichiers écrits par `mm dockerinit` (et `/dockerinit` de `mm --acp-create`), | ||
| 5 | +sa cause, et une correction vérifiée dans un conteneur Debian. | ||
| 6 | + | ||
| 7 | +## Symptôme | ||
| 8 | + | ||
| 9 | +Un agent créé avec l'option conteneur (Sidekicks → `/dockerinit` de `mm --acp-create`), puis un terminal ouvert dans | ||
| 10 | +ce conteneur (`docker exec -it jimmy-box bash -l`, ce que fait l'onglet Terminal de Sidekicks), affiche le prompt : | ||
| 11 | + | ||
| 12 | +```text | ||
| 13 | +I have no name!@cd5ed2bf5dad:/Users/k33g/Documents/jimmy$ | ||
| 14 | +``` | ||
| 15 | + | ||
| 16 | +## Cause | ||
| 17 | + | ||
| 18 | +Les deux fichiers écrits par `mm dockerinit` ne s'accordent pas sur l'utilisateur : | ||
| 19 | + | ||
| 20 | +- `compose.yaml` lance le conteneur avec l'uid et le gid **de la machine qui a lancé `mm dockerinit`**, pour que les | ||
| 21 | + fichiers créés par l'agent dans le projet monté appartiennent à l'utilisateur : | ||
| 22 | + | ||
| 23 | + ```yaml | ||
| 24 | + user: "${MM_UID:-501}:${MM_GID:-20}" # 501:20 sur un Mac | ||
| 25 | + ``` | ||
| 26 | + | ||
| 27 | +- le `Dockerfile` ne crée qu'un compte `mm` avec l'uid **1000** : | ||
| 28 | + | ||
| 29 | + ```dockerfile | ||
| 30 | + RUN useradd --create-home --uid 1000 mm && chmod 777 /home/mm | ||
| 31 | + ENV HOME=/home/mm | ||
| 32 | + USER mm | ||
| 33 | + ``` | ||
| 34 | + | ||
| 35 | +Sur un Mac, l'uid 501 n'a donc **aucune entrée dans `/etc/passwd`** de l'image. bash ne trouve pas de nom pour | ||
| 36 | +`\u` dans son prompt et affiche « I have no name! ». Sous Linux, où l'utilisateur a souvent l'uid 1000, le défaut | ||
| 37 | +ne se voit pas, ce qui explique qu'il soit passé inaperçu. | ||
| 38 | + | ||
| 39 | +## Conséquences | ||
| 40 | + | ||
| 41 | +Ce n'est pas seulement cosmétique : `HOME=/home/mm` est bien inscriptible (`chmod 777`), donc mm tourne, mais tout | ||
| 42 | +programme qui cherche l'utilisateur courant dans `/etc/passwd` échoue : | ||
| 43 | + | ||
| 44 | +| Commande | Résultat (uid 501 sans compte) | | ||
| 45 | +| --- | --- | | ||
| 46 | +| `whoami` | `whoami: cannot find name for user ID 501` (constaté) | | ||
| 47 | +| `id` | `uid=501 gid=20(dialout) groups=20(dialout)` — pas de nom d'utilisateur (constaté) | | ||
| 48 | +| prompt de bash | `I have no name!@<conteneur>:…$` (constaté) | | ||
| 49 | +| `git commit` sans `user.name` / `user.email` configurés | git ne peut pas déduire l'identité depuis le compte (non testé ici : `git` n'est pas dans l'image de test) | | ||
| 50 | +| `ssh` | refuse de démarrer sans compte pour l'uid (non testé ici) | | ||
| 51 | + | ||
| 52 | +Un agent qui utilise git ou ssh avec son outil bash peut donc s'y heurter. | ||
| 53 | + | ||
| 54 | +## Correction proposée | ||
| 55 | + | ||
| 56 | +Créer le compte `mm` **avec l'uid et le gid de l'utilisateur**, au moment de construire l'image, en les passant de | ||
| 57 | +`compose.yaml` au `Dockerfile` comme arguments de build. | ||
| 58 | + | ||
| 59 | +`Dockerfile` (remplace la ligne `useradd` actuelle) : | ||
| 60 | + | ||
| 61 | +```dockerfile | ||
| 62 | +# The agent never runs as root. Its account has the uid and gid of the user | ||
| 63 | +# who runs compose (MM_UID, MM_GID), so that every program finds it in | ||
| 64 | +# /etc/passwd and the files it writes in the project belong to that user. | ||
| 65 | +ARG MM_UID=1000 | ||
| 66 | +ARG MM_GID=1000 | ||
| 67 | +RUN groupadd -o -g "$MM_GID" mm \ | ||
| 68 | + && useradd -o --create-home --uid "$MM_UID" --gid "$MM_GID" mm \ | ||
| 69 | + && chmod 777 /home/mm | ||
| 70 | +ENV HOME=/home/mm | ||
| 71 | +USER mm | ||
| 72 | +``` | ||
| 73 | + | ||
| 74 | +`compose.yaml` (le `build: .` actuel devient) : | ||
| 75 | + | ||
| 76 | +```yaml | ||
| 77 | + build: | ||
| 78 | + context: . | ||
| 79 | + args: | ||
| 80 | + MM_UID: ${MM_UID:-501} | ||
| 81 | + MM_GID: ${MM_GID:-20} | ||
| 82 | + image: mm-jimmy:latest | ||
| 83 | + container_name: jimmy-box | ||
| 84 | + user: "${MM_UID:-501}:${MM_GID:-20}" | ||
| 85 | +``` | ||
| 86 | + | ||
| 87 | +Les valeurs par défaut sont celles que `mm dockerinit` écrit déjà dans `user:` (`usableID(uid)`, `usableID(gid)`), | ||
| 88 | +il suffit de les écrire aussi sous `args:`. | ||
| 89 | + | ||
| 90 | +Points à noter : | ||
| 91 | + | ||
| 92 | +- **`-o` est nécessaire** : le gid 20 existe déjà dans Debian (`dialout`), et `groupadd` refuserait un gid en double. | ||
| 93 | + Avec `-o`, le groupe `mm` partage le gid 20 ; `id` affiche toujours `gid=20(dialout)` (premier nom trouvé), | ||
| 94 | + ce qui est sans conséquence. `useradd -o` couvre de même un uid déjà pris par un compte de l'image. | ||
| 95 | +- **Une image par utilisateur** : l'uid fait partie de l'image. C'est déjà le cas en pratique (l'image est construite | ||
| 96 | + sur la machine de l'utilisateur) ; une image poussée sur un registre (`docker buildx … --push`, mentionné dans | ||
| 97 | + les commentaires de `compose.yaml`) garde l'uid 1000 par défaut, comme aujourd'hui. | ||
| 98 | +- **Windows** : `usableID` remplace déjà un uid négatif ou nul par la valeur de repli ; rien ne change. | ||
| 99 | +- **Les agents déjà créés** : après avoir modifié leurs deux fichiers, reconstruire l'image avec | ||
| 100 | + `docker compose up -d --build`. | ||
| 101 | + | ||
| 102 | +## Vérification | ||
| 103 | + | ||
| 104 | +Faite le 2026-11-14 dans un conteneur `debian:bookworm-slim`, avec uniquement les lignes du compte (sans le | ||
| 105 | +téléchargement de mm), lancé avec `-u 501:20` comme le fait `compose.yaml` sur un Mac : | ||
| 106 | + | ||
| 107 | +| | Avant (`useradd --uid 1000`) | Après (`--build-arg MM_UID=501 --build-arg MM_GID=20`) | | ||
| 108 | +| --- | --- | --- | | ||
| 109 | +| `whoami` | `cannot find name for user ID 501` | `mm` | | ||
| 110 | +| `id` | `uid=501 gid=20(dialout)` | `uid=501(mm) gid=20(dialout)` | | ||
| 111 | +| `HOME` inscriptible | oui | oui (`/home/mm`) | | ||
| 112 | + | ||
| 113 | +Avec les valeurs par défaut (`MM_UID=1000`, `MM_GID=1000`, cas Linux), `whoami` répond aussi `mm`. | ||
| 114 | + | ||
| 115 | +À vérifier côté mini-me avec le vrai `Dockerfile` : la construction complète (téléchargement de mm), puis | ||
| 116 | +`docker compose exec <service> bash -l` (prompt `mm@…`), `git commit` et `mm tui` dans le conteneur. | ||
| 117 | + | ||
| 118 | +## Où regarder dans mini-me | ||
| 119 | + | ||
| 120 | +- `internal/dockerinit/files.go` : la constante `dockerfile` (ligne `useradd`) et la fonction `compose` | ||
| 121 | + (ligne `build: .` et `user:`). | ||
| 122 | +- Les tests de `internal/dockerinit` qui comparent le contenu écrit. | ||
| 123 | +- La doc « run mini-me in a container » (EN et FR), qui explique `MM_UID` et `MM_GID`. | ||
modified
docs/en/explanation/permissions.md +4 -0 | @@ -20,6 +20,10 @@ Small local models do not take no for an answer. During the ACP spike, Riker ref | ||
| 20 | 20 | |
| 21 | 21 | The card appears in the conversation of the agent that asks, not in a window over everything: the other conversations go on, and the question stays next to what led to it. Stopping the agent answers its pending questions "cancelled", as ACP requires. |
| 22 | 22 | |
| 23 | +## Questions from an agent | |
| 24 | + | |
| 25 | +An agent may also ask the user questions — mini-me's `ask_user` tool does — with an ACP form (`elicitation/create`). Sidekicks tells every agent it can show forms, and shows each one as a card in the conversation of its session, under the answer that asks it, like a permission card: free text, a choice, several choices, yes or no; **Answer**, **Decline**, and **Stop**. Without forms, mini-me could only ask choices as permission buttons, and a question that needs typed text could not be asked at all (issue #95). | |
| 26 | + | |
| 23 | 27 | ## Rejected alternatives |
| 24 | 28 | |
| 25 | 29 | - **A modal dialog**: it blocks every conversation for one agent's question. |
| @@ -20,6 +20,10 @@ Small local models do not take no for an answer. During the ACP spike, Riker ref | |||
| 20 | 20 | ||
| 21 | The card appears in the conversation of the agent that asks, not in a window over everything: the other conversations go on, and the question stays next to what led to it. Stopping the agent answers its pending questions "cancelled", as ACP requires. | 21 | The card appears in the conversation of the agent that asks, not in a window over everything: the other conversations go on, and the question stays next to what led to it. Stopping the agent answers its pending questions "cancelled", as ACP requires. |
| 22 | 22 | ||
| 23 | +## Questions from an agent | ||
| 24 | + | ||
| 25 | +An agent may also ask the user questions — mini-me's `ask_user` tool does — with an ACP form (`elicitation/create`). Sidekicks tells every agent it can show forms, and shows each one as a card in the conversation of its session, under the answer that asks it, like a permission card: free text, a choice, several choices, yes or no; **Answer**, **Decline**, and **Stop**. Without forms, mini-me could only ask choices as permission buttons, and a question that needs typed text could not be asked at all (issue #95). | ||
| 26 | + | ||
| 23 | ## Rejected alternatives | 27 | ## Rejected alternatives |
| 24 | 28 | ||
| 25 | - **A modal dialog**: it blocks every conversation for one agent's question. | 29 | - **A modal dialog**: it blocks every conversation for one agent's question. |
modified
docs/en/reference/agents-and-events.md +5 -2 | @@ -124,6 +124,8 @@ A tool call has `id, title, kind` (`read, edit, delete, move, search, execute, t | ||
| 124 | 124 | | `turn:changed` | `{channel, busy, queued, answering, answerers}` | the channel starts or stops answering, or an agent's turn begins or ends; `queued` messages wait; `answerers` are all the agents answering (several after `/parallel`), `answering` the first of them | |
| 125 | 125 | | `permission:requested` | `{id, channel, agent, messageId, toolCall, options[], rejections}` | an agent asks to run a tool; `rejections` counts the refusals already given in this turn | |
| 126 | 126 | | `permission:resolved` | `{id, channel}` | the request was answered, or cancelled by Stop | |
| 127 | +| `form:requested` | `{id, channel, agent, messageId, form: {message, fields[], sessionId, toolCallId}}` | an agent asks the user to fill in a form (ACP `elicitation/create`, form mode; mini-me's `ask_user`, issue #95); the fields are those of [`CreatorService`](#creatorservice)'s forms | | |
| 128 | +| `form:resolved` | `{id, channel}` | the form was answered or declined, or cancelled by Stop or the end of the turn | | |
| 127 | 129 | | `usage:changed` | `{channel, agent, usage: {used, size}}` | an agent reported its context window use (`size` is 0 when unknown) | |
| 128 | 130 | | `commands:changed` | `{agent, commands[]}` | an agent announced its slash commands (`name, description, hint`) | |
| 129 | 131 | |
| @@ -139,9 +141,10 @@ A tool call has `id, title, kind` (`read, edit, delete, move, search, execute, t | ||
| 139 | 141 | | `AddMember(id, agent)`, `RemoveMember(id, agent)` | Invites or removes an agent; the channel shows `agent-joined` or `agent-left`. | |
| 140 | 142 | | `Direct(agent)` | The direct conversation with `agent`, created the first time. | |
| 141 | 143 | | `Send(id, text)` | Adds a user message and returns its id; the agents that answer are started if needed; the message is queued if the channel is answering. Empty text and unknown channels are errors. Each `$path` joins a file of an agent's folder (see [Joined files](#joined-files)); more than 10 is an error. | |
| 142 | -| `Cancel(id)` | Stops the current answer (`session/cancel`), the agents still to answer and the queued messages; answers pending permission requests "cancelled". | | |
| 144 | +| `Cancel(id)` | Stops the current answer (`session/cancel`), the agents still to answer and the queued messages; answers pending permission requests and forms "cancelled". | | |
| 143 | 145 | | `AnswerPermission(id, optionId)` | Answers a pending request with one of its options. | |
| 144 | -| `Conversation(id)` | `channel, messages` (the last 100), `more, busy, queued, answering, answerers, usage{agent: …}, permissions`. | | |
| 146 | +| `AnswerForm(id, answer)` | Answers a pending form: `{action: "accept", content: {name: value…}}`, `decline` or `cancel`. An unknown form or action is an error. | | |
| 147 | +| `Conversation(id)` | `channel, messages` (the last 100), `more, busy, queued, answering, answerers, usage{agent: …}, permissions, forms`. | | |
| 145 | 148 | | `Older(id, beforeId)` | `{messages, more}`: the 100 messages before `beforeId`. | |
| 146 | 149 | | `Commands(agent)` | The commands the agent announced last, kept from one run to the next; empty if it never announced any. | |
| 147 | 150 | | `Prepare(id)` | Starts the members of the channel that never announced their commands and opens their session for it (no model is loaded); returns once the sessions are open, the commands arrive as `commands:changed`. A member answering elsewhere is skipped. The session serves the member's first answer, which is still told the channel's past. | |
| @@ -124,6 +124,8 @@ A tool call has `id, title, kind` (`read, edit, delete, move, search, execute, t | |||
| 124 | | `turn:changed` | `{channel, busy, queued, answering, answerers}` | the channel starts or stops answering, or an agent's turn begins or ends; `queued` messages wait; `answerers` are all the agents answering (several after `/parallel`), `answering` the first of them | | 124 | | `turn:changed` | `{channel, busy, queued, answering, answerers}` | the channel starts or stops answering, or an agent's turn begins or ends; `queued` messages wait; `answerers` are all the agents answering (several after `/parallel`), `answering` the first of them | |
| 125 | | `permission:requested` | `{id, channel, agent, messageId, toolCall, options[], rejections}` | an agent asks to run a tool; `rejections` counts the refusals already given in this turn | | 125 | | `permission:requested` | `{id, channel, agent, messageId, toolCall, options[], rejections}` | an agent asks to run a tool; `rejections` counts the refusals already given in this turn | |
| 126 | | `permission:resolved` | `{id, channel}` | the request was answered, or cancelled by Stop | | 126 | | `permission:resolved` | `{id, channel}` | the request was answered, or cancelled by Stop | |
| 127 | +| `form:requested` | `{id, channel, agent, messageId, form: {message, fields[], sessionId, toolCallId}}` | an agent asks the user to fill in a form (ACP `elicitation/create`, form mode; mini-me's `ask_user`, issue #95); the fields are those of [`CreatorService`](#creatorservice)'s forms | | ||
| 128 | +| `form:resolved` | `{id, channel}` | the form was answered or declined, or cancelled by Stop or the end of the turn | | ||
| 127 | | `usage:changed` | `{channel, agent, usage: {used, size}}` | an agent reported its context window use (`size` is 0 when unknown) | | 129 | | `usage:changed` | `{channel, agent, usage: {used, size}}` | an agent reported its context window use (`size` is 0 when unknown) | |
| 128 | | `commands:changed` | `{agent, commands[]}` | an agent announced its slash commands (`name, description, hint`) | | 130 | | `commands:changed` | `{agent, commands[]}` | an agent announced its slash commands (`name, description, hint`) | |
| 129 | 131 | ||
| @@ -139,9 +141,10 @@ A tool call has `id, title, kind` (`read, edit, delete, move, search, execute, t | |||
| 139 | | `AddMember(id, agent)`, `RemoveMember(id, agent)` | Invites or removes an agent; the channel shows `agent-joined` or `agent-left`. | | 141 | | `AddMember(id, agent)`, `RemoveMember(id, agent)` | Invites or removes an agent; the channel shows `agent-joined` or `agent-left`. | |
| 140 | | `Direct(agent)` | The direct conversation with `agent`, created the first time. | | 142 | | `Direct(agent)` | The direct conversation with `agent`, created the first time. | |
| 141 | | `Send(id, text)` | Adds a user message and returns its id; the agents that answer are started if needed; the message is queued if the channel is answering. Empty text and unknown channels are errors. Each `$path` joins a file of an agent's folder (see [Joined files](#joined-files)); more than 10 is an error. | | 143 | | `Send(id, text)` | Adds a user message and returns its id; the agents that answer are started if needed; the message is queued if the channel is answering. Empty text and unknown channels are errors. Each `$path` joins a file of an agent's folder (see [Joined files](#joined-files)); more than 10 is an error. | |
| 142 | -| `Cancel(id)` | Stops the current answer (`session/cancel`), the agents still to answer and the queued messages; answers pending permission requests "cancelled". | | 144 | +| `Cancel(id)` | Stops the current answer (`session/cancel`), the agents still to answer and the queued messages; answers pending permission requests and forms "cancelled". | |
| 143 | | `AnswerPermission(id, optionId)` | Answers a pending request with one of its options. | | 145 | | `AnswerPermission(id, optionId)` | Answers a pending request with one of its options. | |
| 144 | -| `Conversation(id)` | `channel, messages` (the last 100), `more, busy, queued, answering, answerers, usage{agent: …}, permissions`. | | 146 | +| `AnswerForm(id, answer)` | Answers a pending form: `{action: "accept", content: {name: value…}}`, `decline` or `cancel`. An unknown form or action is an error. | |
| 147 | +| `Conversation(id)` | `channel, messages` (the last 100), `more, busy, queued, answering, answerers, usage{agent: …}, permissions, forms`. | | ||
| 145 | | `Older(id, beforeId)` | `{messages, more}`: the 100 messages before `beforeId`. | | 148 | | `Older(id, beforeId)` | `{messages, more}`: the 100 messages before `beforeId`. | |
| 146 | | `Commands(agent)` | The commands the agent announced last, kept from one run to the next; empty if it never announced any. | | 149 | | `Commands(agent)` | The commands the agent announced last, kept from one run to the next; empty if it never announced any. | |
| 147 | | `Prepare(id)` | Starts the members of the channel that never announced their commands and opens their session for it (no model is loaded); returns once the sessions are open, the commands arrive as `commands:changed`. A member answering elsewhere is skipped. The session serves the member's first answer, which is still told the channel's past. | | 150 | | `Prepare(id)` | Starts the members of the channel that never announced their commands and opens their session for it (no model is loaded); returns once the sessions are open, the commands arrive as `commands:changed`. A member answering elsewhere is skipped. The session serves the member's first answer, which is still told the channel's past. | |
modified
docs/fr/explanation/permissions-et-confiance.md +4 -0 | @@ -20,6 +20,10 @@ Les petits modèles locaux n'acceptent pas un refus. Pendant le spike ACP, Riker | ||
| 20 | 20 | |
| 21 | 21 | La carte apparaît dans la conversation de l'agent qui demande, pas dans une fenêtre par-dessus tout : les autres conversations continuent, et la question reste à côté de ce qui l'a amenée. Arrêter l'agent répond « annulé » à ses questions en attente, comme ACP l'exige. |
| 22 | 22 | |
| 23 | +## Les questions d'un agent | |
| 24 | + | |
| 25 | +Un agent peut aussi poser des questions à l'utilisateur — l'outil `ask_user` de mini-me le fait — avec un formulaire ACP (`elicitation/create`). Sidekicks dit à chaque agent qu'il sait afficher des formulaires, et montre chacun comme une carte dans la conversation de sa session, sous la réponse qui le pose, comme une carte de permission : texte libre, choix, plusieurs choix, oui ou non ; **Répondre**, **Refuser** et **Arrêter**. Sans formulaires, mini-me ne pouvait poser que des choix sous forme de boutons de permission, et une question qui demande un texte ne pouvait pas être posée du tout (issue #95). | |
| 26 | + | |
| 23 | 27 | ## Alternatives écartées |
| 24 | 28 | |
| 25 | 29 | - **Une fenêtre modale** : elle bloque toutes les conversations pour la question d'un seul agent. |
| @@ -20,6 +20,10 @@ Les petits modèles locaux n'acceptent pas un refus. Pendant le spike ACP, Riker | |||
| 20 | 20 | ||
| 21 | La carte apparaît dans la conversation de l'agent qui demande, pas dans une fenêtre par-dessus tout : les autres conversations continuent, et la question reste à côté de ce qui l'a amenée. Arrêter l'agent répond « annulé » à ses questions en attente, comme ACP l'exige. | 21 | La carte apparaît dans la conversation de l'agent qui demande, pas dans une fenêtre par-dessus tout : les autres conversations continuent, et la question reste à côté de ce qui l'a amenée. Arrêter l'agent répond « annulé » à ses questions en attente, comme ACP l'exige. |
| 22 | 22 | ||
| 23 | +## Les questions d'un agent | ||
| 24 | + | ||
| 25 | +Un agent peut aussi poser des questions à l'utilisateur — l'outil `ask_user` de mini-me le fait — avec un formulaire ACP (`elicitation/create`). Sidekicks dit à chaque agent qu'il sait afficher des formulaires, et montre chacun comme une carte dans la conversation de sa session, sous la réponse qui le pose, comme une carte de permission : texte libre, choix, plusieurs choix, oui ou non ; **Répondre**, **Refuser** et **Arrêter**. Sans formulaires, mini-me ne pouvait poser que des choix sous forme de boutons de permission, et une question qui demande un texte ne pouvait pas être posée du tout (issue #95). | ||
| 26 | + | ||
| 23 | ## Alternatives écartées | 27 | ## Alternatives écartées |
| 24 | 28 | ||
| 25 | - **Une fenêtre modale** : elle bloque toutes les conversations pour la question d'un seul agent. | 29 | - **Une fenêtre modale** : elle bloque toutes les conversations pour la question d'un seul agent. |
modified
docs/fr/reference/agents-et-evenements.md +5 -2 | @@ -124,6 +124,8 @@ Un appel d'outil a `id, title, kind` (`read, edit, delete, move, search, execute | ||
| 124 | 124 | | `turn:changed` | `{channel, busy, queued, answering, answerers}` | le channel commence ou arrête de répondre, ou le tour d'un agent commence ou finit ; `queued` messages attendent ; `answerers` sont tous les agents qui répondent (plusieurs après `/parallel`), `answering` le premier d'entre eux | |
| 125 | 125 | | `permission:requested` | `{id, channel, agent, messageId, toolCall, options[], rejections}` | un agent demande à utiliser un outil ; `rejections` compte les refus déjà donnés pendant ce tour | |
| 126 | 126 | | `permission:resolved` | `{id, channel}` | la demande a reçu une réponse, ou a été annulée par Stop | |
| 127 | +| `form:requested` | `{id, channel, agent, messageId, form: {message, fields[], sessionId, toolCallId}}` | un agent demande à l'utilisateur de remplir un formulaire (`elicitation/create` d'ACP, mode formulaire ; `ask_user` de mini-me, issue #95) ; les champs sont ceux des formulaires de [`CreatorService`](#creatorservice) | | |
| 128 | +| `form:resolved` | `{id, channel}` | le formulaire a reçu une réponse ou a été refusé, ou a été annulé par Stop ou la fin du tour | | |
| 127 | 129 | | `usage:changed` | `{channel, agent, usage: {used, size}}` | un agent a indiqué l'occupation de sa fenêtre de contexte (`size` vaut 0 si elle est inconnue) | |
| 128 | 130 | | `commands:changed` | `{agent, commands[]}` | un agent a annoncé ses commandes slash (`name, description, hint`) | |
| 129 | 131 | |
| @@ -139,9 +141,10 @@ Un appel d'outil a `id, title, kind` (`read, edit, delete, move, search, execute | ||
| 139 | 141 | | `AddMember(id, agent)`, `RemoveMember(id, agent)` | Invite ou retire un agent ; le channel affiche `agent-joined` ou `agent-left`. | |
| 140 | 142 | | `Direct(agent)` | La conversation directe avec `agent`, créée la première fois. | |
| 141 | 143 | | `Send(id, text)` | Ajoute un message de l'utilisateur et renvoie son id ; les agents qui répondent sont démarrés si besoin ; le message attend si le channel répond déjà. Un texte vide ou un channel inconnu sont des erreurs. Chaque `$chemin` joint un fichier du dossier d'un agent (voir [Fichiers joints](#fichiers-joints)) ; plus de 10 est une erreur. | |
| 142 | -| `Cancel(id)` | Arrête la réponse en cours (`session/cancel`), les agents qui devaient encore répondre et les messages en attente ; répond « cancelled » aux demandes de permission en attente. | | |
| 144 | +| `Cancel(id)` | Arrête la réponse en cours (`session/cancel`), les agents qui devaient encore répondre et les messages en attente ; répond « cancelled » aux demandes de permission et aux formulaires en attente. | | |
| 143 | 145 | | `AnswerPermission(id, optionId)` | Répond à une demande en attente avec l'une de ses options. | |
| 144 | -| `Conversation(id)` | `channel, messages` (les 100 derniers), `more, busy, queued, answering, answerers, usage{agent: …}, permissions`. | | |
| 146 | +| `AnswerForm(id, answer)` | Répond à un formulaire en attente : `{action: "accept", content: {nom: valeur…}}`, `decline` ou `cancel`. Un formulaire ou une action inconnus sont une erreur. | | |
| 147 | +| `Conversation(id)` | `channel, messages` (les 100 derniers), `more, busy, queued, answering, answerers, usage{agent: …}, permissions, forms`. | | |
| 145 | 148 | | `Older(id, beforeId)` | `{messages, more}` : les 100 messages précédant `beforeId`. | |
| 146 | 149 | | `Commands(agent)` | Les dernières commandes annoncées par l'agent, gardées d'un lancement à l'autre ; vide s'il n'en a jamais annoncé. | |
| 147 | 150 | | `Prepare(id)` | Démarre les membres du channel qui n'ont jamais annoncé leurs commandes et ouvre leur session pour ce channel (aucun modèle n'est chargé) ; rend la main une fois les sessions ouvertes, les commandes arrivent par `commands:changed`. Un membre qui répond ailleurs est ignoré. La session sert la première réponse du membre, à qui l'on donne quand même le passé du channel. | |
| @@ -124,6 +124,8 @@ Un appel d'outil a `id, title, kind` (`read, edit, delete, move, search, execute | |||
| 124 | | `turn:changed` | `{channel, busy, queued, answering, answerers}` | le channel commence ou arrête de répondre, ou le tour d'un agent commence ou finit ; `queued` messages attendent ; `answerers` sont tous les agents qui répondent (plusieurs après `/parallel`), `answering` le premier d'entre eux | | 124 | | `turn:changed` | `{channel, busy, queued, answering, answerers}` | le channel commence ou arrête de répondre, ou le tour d'un agent commence ou finit ; `queued` messages attendent ; `answerers` sont tous les agents qui répondent (plusieurs après `/parallel`), `answering` le premier d'entre eux | |
| 125 | | `permission:requested` | `{id, channel, agent, messageId, toolCall, options[], rejections}` | un agent demande à utiliser un outil ; `rejections` compte les refus déjà donnés pendant ce tour | | 125 | | `permission:requested` | `{id, channel, agent, messageId, toolCall, options[], rejections}` | un agent demande à utiliser un outil ; `rejections` compte les refus déjà donnés pendant ce tour | |
| 126 | | `permission:resolved` | `{id, channel}` | la demande a reçu une réponse, ou a été annulée par Stop | | 126 | | `permission:resolved` | `{id, channel}` | la demande a reçu une réponse, ou a été annulée par Stop | |
| 127 | +| `form:requested` | `{id, channel, agent, messageId, form: {message, fields[], sessionId, toolCallId}}` | un agent demande à l'utilisateur de remplir un formulaire (`elicitation/create` d'ACP, mode formulaire ; `ask_user` de mini-me, issue #95) ; les champs sont ceux des formulaires de [`CreatorService`](#creatorservice) | | ||
| 128 | +| `form:resolved` | `{id, channel}` | le formulaire a reçu une réponse ou a été refusé, ou a été annulé par Stop ou la fin du tour | | ||
| 127 | | `usage:changed` | `{channel, agent, usage: {used, size}}` | un agent a indiqué l'occupation de sa fenêtre de contexte (`size` vaut 0 si elle est inconnue) | | 129 | | `usage:changed` | `{channel, agent, usage: {used, size}}` | un agent a indiqué l'occupation de sa fenêtre de contexte (`size` vaut 0 si elle est inconnue) | |
| 128 | | `commands:changed` | `{agent, commands[]}` | un agent a annoncé ses commandes slash (`name, description, hint`) | | 130 | | `commands:changed` | `{agent, commands[]}` | un agent a annoncé ses commandes slash (`name, description, hint`) | |
| 129 | 131 | ||
| @@ -139,9 +141,10 @@ Un appel d'outil a `id, title, kind` (`read, edit, delete, move, search, execute | |||
| 139 | | `AddMember(id, agent)`, `RemoveMember(id, agent)` | Invite ou retire un agent ; le channel affiche `agent-joined` ou `agent-left`. | | 141 | | `AddMember(id, agent)`, `RemoveMember(id, agent)` | Invite ou retire un agent ; le channel affiche `agent-joined` ou `agent-left`. | |
| 140 | | `Direct(agent)` | La conversation directe avec `agent`, créée la première fois. | | 142 | | `Direct(agent)` | La conversation directe avec `agent`, créée la première fois. | |
| 141 | | `Send(id, text)` | Ajoute un message de l'utilisateur et renvoie son id ; les agents qui répondent sont démarrés si besoin ; le message attend si le channel répond déjà. Un texte vide ou un channel inconnu sont des erreurs. Chaque `$chemin` joint un fichier du dossier d'un agent (voir [Fichiers joints](#fichiers-joints)) ; plus de 10 est une erreur. | | 143 | | `Send(id, text)` | Ajoute un message de l'utilisateur et renvoie son id ; les agents qui répondent sont démarrés si besoin ; le message attend si le channel répond déjà. Un texte vide ou un channel inconnu sont des erreurs. Chaque `$chemin` joint un fichier du dossier d'un agent (voir [Fichiers joints](#fichiers-joints)) ; plus de 10 est une erreur. | |
| 142 | -| `Cancel(id)` | Arrête la réponse en cours (`session/cancel`), les agents qui devaient encore répondre et les messages en attente ; répond « cancelled » aux demandes de permission en attente. | | 144 | +| `Cancel(id)` | Arrête la réponse en cours (`session/cancel`), les agents qui devaient encore répondre et les messages en attente ; répond « cancelled » aux demandes de permission et aux formulaires en attente. | |
| 143 | | `AnswerPermission(id, optionId)` | Répond à une demande en attente avec l'une de ses options. | | 145 | | `AnswerPermission(id, optionId)` | Répond à une demande en attente avec l'une de ses options. | |
| 144 | -| `Conversation(id)` | `channel, messages` (les 100 derniers), `more, busy, queued, answering, answerers, usage{agent: …}, permissions`. | | 146 | +| `AnswerForm(id, answer)` | Répond à un formulaire en attente : `{action: "accept", content: {nom: valeur…}}`, `decline` ou `cancel`. Un formulaire ou une action inconnus sont une erreur. | |
| 147 | +| `Conversation(id)` | `channel, messages` (les 100 derniers), `more, busy, queued, answering, answerers, usage{agent: …}, permissions, forms`. | | ||
| 145 | | `Older(id, beforeId)` | `{messages, more}` : les 100 messages précédant `beforeId`. | | 148 | | `Older(id, beforeId)` | `{messages, more}` : les 100 messages précédant `beforeId`. | |
| 146 | | `Commands(agent)` | Les dernières commandes annoncées par l'agent, gardées d'un lancement à l'autre ; vide s'il n'en a jamais annoncé. | | 149 | | `Commands(agent)` | Les dernières commandes annoncées par l'agent, gardées d'un lancement à l'autre ; vide s'il n'en a jamais annoncé. | |
| 147 | | `Prepare(id)` | Démarre les membres du channel qui n'ont jamais annoncé leurs commandes et ouvre leur session pour ce channel (aucun modèle n'est chargé) ; rend la main une fois les sessions ouvertes, les commandes arrivent par `commands:changed`. Un membre qui répond ailleurs est ignoré. La session sert la première réponse du membre, à qui l'on donne quand même le passé du channel. | | 150 | | `Prepare(id)` | Démarre les membres du channel qui n'ont jamais annoncé leurs commandes et ouvre leur session pour ce channel (aucun modèle n'est chargé) ; rend la main une fois les sessions ouvertes, les commandes arrivent par `commands:changed`. Un membre qui répond ailleurs est ignoré. La session sert la première réponse du membre, à qui l'on donne quand même le passé du channel. | |
modified
frontend/bindings/events/index.ts +10 -0 | @@ -38,6 +38,16 @@ export const ConfigChanged = "config:changed"; | ||
| 38 | 38 | */ |
| 39 | 39 | export const FilesDropped = "files:dropped"; |
| 40 | 40 | |
| 41 | +/** | |
| 42 | + * Name of the custom event "form:requested". | |
| 43 | + */ | |
| 44 | +export const FormRequested = "form:requested"; | |
| 45 | + | |
| 46 | +/** | |
| 47 | + * Name of the custom event "form:resolved". | |
| 48 | + */ | |
| 49 | +export const FormResolved = "form:resolved"; | |
| 50 | + | |
| 41 | 51 | /** |
| 42 | 52 | * Name of the custom event "message:delta". |
| 43 | 53 | */ |
| @@ -38,6 +38,16 @@ export const ConfigChanged = "config:changed"; | |||
| 38 | */ | 38 | */ |
| 39 | export const FilesDropped = "files:dropped"; | 39 | export const FilesDropped = "files:dropped"; |
| 40 | 40 | ||
| 41 | +/** | ||
| 42 | + * Name of the custom event "form:requested". | ||
| 43 | + */ | ||
| 44 | +export const FormRequested = "form:requested"; | ||
| 45 | + | ||
| 46 | +/** | ||
| 47 | + * Name of the custom event "form:resolved". | ||
| 48 | + */ | ||
| 49 | +export const FormResolved = "form:resolved"; | ||
| 50 | + | ||
| 41 | /** | 51 | /** |
| 42 | * Name of the custom event "message:delta". | 52 | * Name of the custom event "message:delta". |
| 43 | */ | 53 | */ |
modified
frontend/bindings/git.rickub.com/bots-garden/sidekicks/internal/acp/models.ts +7 -0 | @@ -33,6 +33,13 @@ export interface Form { | ||
| 33 | 33 | */ |
| 34 | 34 | "message": string; |
| 35 | 35 | "fields": FormField[] | null; |
| 36 | + | |
| 37 | + /** | |
| 38 | + * SessionID and ToolCallID tie the form to a session and a tool call, | |
| 39 | + * when the agent says so; "" otherwise. | |
| 40 | + */ | |
| 41 | + "sessionId": string; | |
| 42 | + "toolCallId": string; | |
| 36 | 43 | } |
| 37 | 44 | |
| 38 | 45 | /** |
| @@ -33,6 +33,13 @@ export interface Form { | |||
| 33 | */ | 33 | */ |
| 34 | "message": string; | 34 | "message": string; |
| 35 | "fields": FormField[] | null; | 35 | "fields": FormField[] | null; |
| 36 | + | ||
| 37 | + /** | ||
| 38 | + * SessionID and ToolCallID tie the form to a session and a tool call, | ||
| 39 | + * when the agent says so; "" otherwise. | ||
| 40 | + */ | ||
| 41 | + "sessionId": string; | ||
| 42 | + "toolCallId": string; | ||
| 36 | } | 43 | } |
| 37 | 44 | ||
| 38 | /** | 45 | /** |
modified
frontend/bindings/git.rickub.com/bots-garden/sidekicks/internal/app/channelservice.ts +8 -0 | @@ -31,6 +31,14 @@ export function AddMember(id: string, agent: string): $CancellablePromise<void> | ||
| 31 | 31 | return $Call.ByID(863382753, id, agent); |
| 32 | 32 | } |
| 33 | 33 | |
| 34 | +/** | |
| 35 | + * AnswerForm gives the user's answer to a form an agent asked (issue #95): | |
| 36 | + * action accept with content (values by field name), decline or cancel. | |
| 37 | + */ | |
| 38 | +export function AnswerForm(id: string, answer: acp$0.FormAnswer): $CancellablePromise<void> { | |
| 39 | + return $Call.ByID(1558912636, id, answer); | |
| 40 | +} | |
| 41 | + | |
| 34 | 42 | /** |
| 35 | 43 | * AnswerPermission gives the user's choice for a permission request. |
| 36 | 44 | */ |
| @@ -31,6 +31,14 @@ export function AddMember(id: string, agent: string): $CancellablePromise<void> | |||
| 31 | return $Call.ByID(863382753, id, agent); | 31 | return $Call.ByID(863382753, id, agent); |
| 32 | } | 32 | } |
| 33 | 33 | ||
| 34 | +/** | ||
| 35 | + * AnswerForm gives the user's answer to a form an agent asked (issue #95): | ||
| 36 | + * action accept with content (values by field name), decline or cancel. | ||
| 37 | + */ | ||
| 38 | +export function AnswerForm(id: string, answer: acp$0.FormAnswer): $CancellablePromise<void> { | ||
| 39 | + return $Call.ByID(1558912636, id, answer); | ||
| 40 | +} | ||
| 41 | + | ||
| 34 | /** | 42 | /** |
| 35 | * AnswerPermission gives the user's choice for a permission request. | 43 | * AnswerPermission gives the user's choice for a permission request. |
| 36 | */ | 44 | */ |
modified
frontend/bindings/git.rickub.com/bots-garden/sidekicks/internal/channels/index.ts +2 -0 | @@ -11,6 +11,8 @@ export type { | ||
| 11 | 11 | CommandsPayload, |
| 12 | 12 | Conversation, |
| 13 | 13 | DeltaPayload, |
| 14 | + FormRequest, | |
| 15 | + FormResolvedPayload, | |
| 14 | 16 | ListPayload, |
| 15 | 17 | Message, |
| 16 | 18 | MessagePayload, |
| @@ -11,6 +11,8 @@ export type { | |||
| 11 | CommandsPayload, | 11 | CommandsPayload, |
| 12 | Conversation, | 12 | Conversation, |
| 13 | DeltaPayload, | 13 | DeltaPayload, |
| 14 | + FormRequest, | ||
| 15 | + FormResolvedPayload, | ||
| 14 | ListPayload, | 16 | ListPayload, |
| 15 | Message, | 17 | Message, |
| 16 | MessagePayload, | 18 | MessagePayload, |
modified
frontend/bindings/git.rickub.com/bots-garden/sidekicks/internal/channels/models.ts +25 -0 | @@ -66,6 +66,11 @@ export interface Conversation { | ||
| 66 | 66 | */ |
| 67 | 67 | "usage": { [_ in string]?: acp$0.Usage } | null; |
| 68 | 68 | "permissions": Permission[] | null; |
| 69 | + | |
| 70 | + /** | |
| 71 | + * Forms are the forms waiting for an answer (issue #95). | |
| 72 | + */ | |
| 73 | + "forms": FormRequest[] | null; | |
| 69 | 74 | } |
| 70 | 75 | |
| 71 | 76 | /** |
| @@ -81,6 +86,26 @@ export interface DeltaPayload { | ||
| 81 | 86 | "part"?: Part | null; |
| 82 | 87 | } |
| 83 | 88 | |
| 89 | +/** | |
| 90 | + * FormRequest is a form an agent asks the user to fill in, waiting for the | |
| 91 | + * answer (issue #95: mini-me's ask_user). | |
| 92 | + */ | |
| 93 | +export interface FormRequest { | |
| 94 | + "id": string; | |
| 95 | + "channel": string; | |
| 96 | + "agent": string; | |
| 97 | + "messageId": string; | |
| 98 | + "form": acp$0.Form; | |
| 99 | +} | |
| 100 | + | |
| 101 | +/** | |
| 102 | + * FormResolvedPayload says a form no longer waits. | |
| 103 | + */ | |
| 104 | +export interface FormResolvedPayload { | |
| 105 | + "id": string; | |
| 106 | + "channel": string; | |
| 107 | +} | |
| 108 | + | |
| 84 | 109 | /** |
| 85 | 110 | * ListPayload is the whole list of channels, after any change (channels:changed). |
| 86 | 111 | */ |
| @@ -66,6 +66,11 @@ export interface Conversation { | |||
| 66 | */ | 66 | */ |
| 67 | "usage": { [_ in string]?: acp$0.Usage } | null; | 67 | "usage": { [_ in string]?: acp$0.Usage } | null; |
| 68 | "permissions": Permission[] | null; | 68 | "permissions": Permission[] | null; |
| 69 | + | ||
| 70 | + /** | ||
| 71 | + * Forms are the forms waiting for an answer (issue #95). | ||
| 72 | + */ | ||
| 73 | + "forms": FormRequest[] | null; | ||
| 69 | } | 74 | } |
| 70 | 75 | ||
| 71 | /** | 76 | /** |
| @@ -81,6 +86,26 @@ export interface DeltaPayload { | |||
| 81 | "part"?: Part | null; | 86 | "part"?: Part | null; |
| 82 | } | 87 | } |
| 83 | 88 | ||
| 89 | +/** | ||
| 90 | + * FormRequest is a form an agent asks the user to fill in, waiting for the | ||
| 91 | + * answer (issue #95: mini-me's ask_user). | ||
| 92 | + */ | ||
| 93 | +export interface FormRequest { | ||
| 94 | + "id": string; | ||
| 95 | + "channel": string; | ||
| 96 | + "agent": string; | ||
| 97 | + "messageId": string; | ||
| 98 | + "form": acp$0.Form; | ||
| 99 | +} | ||
| 100 | + | ||
| 101 | +/** | ||
| 102 | + * FormResolvedPayload says a form no longer waits. | ||
| 103 | + */ | ||
| 104 | +export interface FormResolvedPayload { | ||
| 105 | + "id": string; | ||
| 106 | + "channel": string; | ||
| 107 | +} | ||
| 108 | + | ||
| 84 | /** | 109 | /** |
| 85 | * ListPayload is the whole list of channels, after any change (channels:changed). | 110 | * ListPayload is the whole list of channels, after any change (channels:changed). |
| 86 | */ | 111 | */ |
modified
frontend/bindings/github.com/wailsapp/wails/v3/internal/eventdata.d.ts +2 -0 | @@ -24,6 +24,8 @@ declare module "@wailsio/runtime" { | ||
| 24 | 24 | "commands:changed": channels$0.CommandsPayload; |
| 25 | 25 | "config:changed": events$0.ConfigChangedPayload; |
| 26 | 26 | "files:dropped": events$0.FilesDroppedPayload; |
| 27 | + "form:requested": channels$0.FormRequest; | |
| 28 | + "form:resolved": channels$0.FormResolvedPayload; | |
| 27 | 29 | "message:delta": channels$0.DeltaPayload; |
| 28 | 30 | "message:updated": channels$0.MessagePayload; |
| 29 | 31 | "permission:requested": channels$0.Permission; |
| @@ -24,6 +24,8 @@ declare module "@wailsio/runtime" { | |||
| 24 | "commands:changed": channels$0.CommandsPayload; | 24 | "commands:changed": channels$0.CommandsPayload; |
| 25 | "config:changed": events$0.ConfigChangedPayload; | 25 | "config:changed": events$0.ConfigChangedPayload; |
| 26 | "files:dropped": events$0.FilesDroppedPayload; | 26 | "files:dropped": events$0.FilesDroppedPayload; |
| 27 | + "form:requested": channels$0.FormRequest; | ||
| 28 | + "form:resolved": channels$0.FormResolvedPayload; | ||
| 27 | "message:delta": channels$0.DeltaPayload; | 29 | "message:delta": channels$0.DeltaPayload; |
| 28 | "message:updated": channels$0.MessagePayload; | 30 | "message:updated": channels$0.MessagePayload; |
| 29 | "permission:requested": channels$0.Permission; | 31 | "permission:requested": channels$0.Permission; |
modified
frontend/src/lib/agent/CreateMiniMeAgent.svelte +4 -61 | @@ -15,6 +15,7 @@ | ||
| 15 | 15 | import ErrorText from '../chat/ErrorText.svelte' |
| 16 | 16 | import Markdown from '../chat/Markdown.svelte' |
| 17 | 17 | import Spinner from '../chat/Spinner.svelte' |
| 18 | + import FormFields from '../chat/FormFields.svelte' | |
| 18 | 19 | |
| 19 | 20 | type Step = 'starting' | 'questions' | 'stopped' | 'ready' | 'failed' |
| 20 | 21 | |
| @@ -145,11 +146,6 @@ | ||
| 145 | 146 | appState.creator = false |
| 146 | 147 | } |
| 147 | 148 | |
| 148 | - function toggle(field: string, option: string, on: boolean) { | |
| 149 | - const chosen = (values[field] as string[]) ?? [] | |
| 150 | - values[field] = on ? [...chosen, option] : chosen.filter((value) => value !== option) | |
| 151 | - } | |
| 152 | - | |
| 153 | 149 | // Leaving the assistant before the end removes what mm wrote. |
| 154 | 150 | onDestroy(() => { |
| 155 | 151 | if (!finished) void CreatorService.Cancel() |
| @@ -183,59 +179,7 @@ | ||
| 183 | 179 | {/if} |
| 184 | 180 | <form class="questions" onsubmit={next} novalidate> |
| 185 | 181 | <fieldset disabled={busy}> |
| 186 | - {#each form.fields ?? [] as field (field.name)} | |
| 187 | - {#if field.type === 'boolean'} | |
| 188 | - <label class="check"> | |
| 189 | - <input type="checkbox" checked={values[field.name] === true} onchange={(event) => (values[field.name] = event.currentTarget.checked)} /> | |
| 190 | - {field.title} | |
| 191 | - </label> | |
| 192 | - {:else if field.type === 'choice' && (field.options ?? []).length <= 4} | |
| 193 | - <div class="group" role="radiogroup" aria-label={field.title}> | |
| 194 | - <span class="label">{field.title}</span> | |
| 195 | - <div class="choices"> | |
| 196 | - {#each field.options ?? [] as option (option)} | |
| 197 | - <label class="choice" class:chosen={values[field.name] === option}> | |
| 198 | - <input type="radio" name={field.name} value={option} checked={values[field.name] === option} onchange={() => (values[field.name] = option)} /> | |
| 199 | - {option} | |
| 200 | - </label> | |
| 201 | - {/each} | |
| 202 | - </div> | |
| 203 | - </div> | |
| 204 | - {:else if field.type === 'choice'} | |
| 205 | - <label> | |
| 206 | - {field.title} | |
| 207 | - <select value={values[field.name]} onchange={(event) => (values[field.name] = event.currentTarget.value)}> | |
| 208 | - {#each field.options ?? [] as option (option)}<option value={option}>{option}</option>{/each} | |
| 209 | - </select> | |
| 210 | - </label> | |
| 211 | - {:else if field.type === 'multi'} | |
| 212 | - <div class="group" aria-label={field.title}> | |
| 213 | - <span class="label">{field.title}</span> | |
| 214 | - <div class="choices"> | |
| 215 | - {#each field.options ?? [] as option (option)} | |
| 216 | - <label class="choice"> | |
| 217 | - <input type="checkbox" checked={((values[field.name] as string[]) ?? []).includes(option)} onchange={(event) => toggle(field.name, option, event.currentTarget.checked)} /> | |
| 218 | - {option} | |
| 219 | - </label> | |
| 220 | - {/each} | |
| 221 | - </div> | |
| 222 | - </div> | |
| 223 | - {:else} | |
| 224 | - <label> | |
| 225 | - {field.title} | |
| 226 | - <input | |
| 227 | - value={values[field.name] as string} | |
| 228 | - oninput={(event) => (values[field.name] = event.currentTarget.value)} | |
| 229 | - inputmode={field.type === 'number' ? 'decimal' : undefined} | |
| 230 | - aria-invalid={missing.includes(field.name)} | |
| 231 | - spellcheck="false" | |
| 232 | - autocapitalize="off" | |
| 233 | - /> | |
| 234 | - {#if missing.includes(field.name)}<small class="problem-text">{t('creator.missing')}</small>{/if} | |
| 235 | - </label> | |
| 236 | - {/if} | |
| 237 | - {#if field.description}<small>{field.description}</small>{/if} | |
| 238 | - {/each} | |
| 182 | + <FormFields {form} bind:values {missing} idPrefix="creator" /> | |
| 239 | 183 | </fieldset> |
| 240 | 184 | {#if form.message.includes('\n')} |
| 241 | 185 | <details class="about"> |
| @@ -327,12 +271,11 @@ | ||
| 327 | 271 | fieldset { border: 1px solid var(--border); border-radius: var(--radius); padding: 12px 14px 14px; display: flex; flex-direction: column; gap: 12px; background: var(--panel); margin: 0; } |
| 328 | 272 | label, .group { display: flex; flex-direction: column; gap: 4px; font-size: 13px; } |
| 329 | 273 | .label { font-size: 13px; } |
| 330 | - label.check { flex-direction: row; align-items: center; gap: 8px; } | |
| 331 | - input:not([type='radio']):not([type='checkbox']), select { font: inherit; padding: 6px 8px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); color: var(--text); } | |
| 274 | + input:not([type='radio']):not([type='checkbox']) { font: inherit; padding: 6px 8px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); color: var(--text); } | |
| 332 | 275 | input[aria-invalid='true'] { border-color: var(--danger); } |
| 333 | 276 | small { color: var(--muted); font-size: 12px; } |
| 334 | 277 | .problem-text { color: var(--danger); } |
| 335 | - .choices, .icons { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; } | |
| 278 | + .icons { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; } | |
| 336 | 279 | .choice { flex-direction: row; align-items: center; gap: 6px; border: 1px solid var(--border); border-radius: 6px; padding: 6px 10px; cursor: pointer; } |
| 337 | 280 | .choice.wide { align-items: flex-start; } |
| 338 | 281 | .choice.wide input { margin-top: 3px; } |
| @@ -15,6 +15,7 @@ | |||
| 15 | import ErrorText from '../chat/ErrorText.svelte' | 15 | import ErrorText from '../chat/ErrorText.svelte' |
| 16 | import Markdown from '../chat/Markdown.svelte' | 16 | import Markdown from '../chat/Markdown.svelte' |
| 17 | import Spinner from '../chat/Spinner.svelte' | 17 | import Spinner from '../chat/Spinner.svelte' |
| 18 | + import FormFields from '../chat/FormFields.svelte' | ||
| 18 | 19 | ||
| 19 | type Step = 'starting' | 'questions' | 'stopped' | 'ready' | 'failed' | 20 | type Step = 'starting' | 'questions' | 'stopped' | 'ready' | 'failed' |
| 20 | 21 | ||
| @@ -145,11 +146,6 @@ | |||
| 145 | appState.creator = false | 146 | appState.creator = false |
| 146 | } | 147 | } |
| 147 | 148 | ||
| 148 | - function toggle(field: string, option: string, on: boolean) { | ||
| 149 | - const chosen = (values[field] as string[]) ?? [] | ||
| 150 | - values[field] = on ? [...chosen, option] : chosen.filter((value) => value !== option) | ||
| 151 | - } | ||
| 152 | - | ||
| 153 | // Leaving the assistant before the end removes what mm wrote. | 149 | // Leaving the assistant before the end removes what mm wrote. |
| 154 | onDestroy(() => { | 150 | onDestroy(() => { |
| 155 | if (!finished) void CreatorService.Cancel() | 151 | if (!finished) void CreatorService.Cancel() |
| @@ -183,59 +179,7 @@ | |||
| 183 | {/if} | 179 | {/if} |
| 184 | <form class="questions" onsubmit={next} novalidate> | 180 | <form class="questions" onsubmit={next} novalidate> |
| 185 | <fieldset disabled={busy}> | 181 | <fieldset disabled={busy}> |
| 186 | - {#each form.fields ?? [] as field (field.name)} | 182 | + <FormFields {form} bind:values {missing} idPrefix="creator" /> |
| 187 | - {#if field.type === 'boolean'} | ||
| 188 | - <label class="check"> | ||
| 189 | - <input type="checkbox" checked={values[field.name] === true} onchange={(event) => (values[field.name] = event.currentTarget.checked)} /> | ||
| 190 | - {field.title} | ||
| 191 | - </label> | ||
| 192 | - {:else if field.type === 'choice' && (field.options ?? []).length <= 4} | ||
| 193 | - <div class="group" role="radiogroup" aria-label={field.title}> | ||
| 194 | - <span class="label">{field.title}</span> | ||
| 195 | - <div class="choices"> | ||
| 196 | - {#each field.options ?? [] as option (option)} | ||
| 197 | - <label class="choice" class:chosen={values[field.name] === option}> | ||
| 198 | - <input type="radio" name={field.name} value={option} checked={values[field.name] === option} onchange={() => (values[field.name] = option)} /> | ||
| 199 | - {option} | ||
| 200 | - </label> | ||
| 201 | - {/each} | ||
| 202 | - </div> | ||
| 203 | - </div> | ||
| 204 | - {:else if field.type === 'choice'} | ||
| 205 | - <label> | ||
| 206 | - {field.title} | ||
| 207 | - <select value={values[field.name]} onchange={(event) => (values[field.name] = event.currentTarget.value)}> | ||
| 208 | - {#each field.options ?? [] as option (option)}<option value={option}>{option}</option>{/each} | ||
| 209 | - </select> | ||
| 210 | - </label> | ||
| 211 | - {:else if field.type === 'multi'} | ||
| 212 | - <div class="group" aria-label={field.title}> | ||
| 213 | - <span class="label">{field.title}</span> | ||
| 214 | - <div class="choices"> | ||
| 215 | - {#each field.options ?? [] as option (option)} | ||
| 216 | - <label class="choice"> | ||
| 217 | - <input type="checkbox" checked={((values[field.name] as string[]) ?? []).includes(option)} onchange={(event) => toggle(field.name, option, event.currentTarget.checked)} /> | ||
| 218 | - {option} | ||
| 219 | - </label> | ||
| 220 | - {/each} | ||
| 221 | - </div> | ||
| 222 | - </div> | ||
| 223 | - {:else} | ||
| 224 | - <label> | ||
| 225 | - {field.title} | ||
| 226 | - <input | ||
| 227 | - value={values[field.name] as string} | ||
| 228 | - oninput={(event) => (values[field.name] = event.currentTarget.value)} | ||
| 229 | - inputmode={field.type === 'number' ? 'decimal' : undefined} | ||
| 230 | - aria-invalid={missing.includes(field.name)} | ||
| 231 | - spellcheck="false" | ||
| 232 | - autocapitalize="off" | ||
| 233 | - /> | ||
| 234 | - {#if missing.includes(field.name)}<small class="problem-text">{t('creator.missing')}</small>{/if} | ||
| 235 | - </label> | ||
| 236 | - {/if} | ||
| 237 | - {#if field.description}<small>{field.description}</small>{/if} | ||
| 238 | - {/each} | ||
| 239 | </fieldset> | 183 | </fieldset> |
| 240 | {#if form.message.includes('\n')} | 184 | {#if form.message.includes('\n')} |
| 241 | <details class="about"> | 185 | <details class="about"> |
| @@ -327,12 +271,11 @@ | |||
| 327 | fieldset { border: 1px solid var(--border); border-radius: var(--radius); padding: 12px 14px 14px; display: flex; flex-direction: column; gap: 12px; background: var(--panel); margin: 0; } | 271 | fieldset { border: 1px solid var(--border); border-radius: var(--radius); padding: 12px 14px 14px; display: flex; flex-direction: column; gap: 12px; background: var(--panel); margin: 0; } |
| 328 | label, .group { display: flex; flex-direction: column; gap: 4px; font-size: 13px; } | 272 | label, .group { display: flex; flex-direction: column; gap: 4px; font-size: 13px; } |
| 329 | .label { font-size: 13px; } | 273 | .label { font-size: 13px; } |
| 330 | - label.check { flex-direction: row; align-items: center; gap: 8px; } | 274 | + input:not([type='radio']):not([type='checkbox']) { font: inherit; padding: 6px 8px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); color: var(--text); } |
| 331 | - input:not([type='radio']):not([type='checkbox']), select { font: inherit; padding: 6px 8px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); color: var(--text); } | ||
| 332 | input[aria-invalid='true'] { border-color: var(--danger); } | 275 | input[aria-invalid='true'] { border-color: var(--danger); } |
| 333 | small { color: var(--muted); font-size: 12px; } | 276 | small { color: var(--muted); font-size: 12px; } |
| 334 | .problem-text { color: var(--danger); } | 277 | .problem-text { color: var(--danger); } |
| 335 | - .choices, .icons { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; } | 278 | + .icons { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; } |
| 336 | .choice { flex-direction: row; align-items: center; gap: 6px; border: 1px solid var(--border); border-radius: 6px; padding: 6px 10px; cursor: pointer; } | 279 | .choice { flex-direction: row; align-items: center; gap: 6px; border: 1px solid var(--border); border-radius: 6px; padding: 6px 10px; cursor: pointer; } |
| 337 | .choice.wide { align-items: flex-start; } | 280 | .choice.wide { align-items: flex-start; } |
| 338 | .choice.wide input { margin-top: 3px; } | 281 | .choice.wide input { margin-top: 3px; } |
added
frontend/src/lib/chat/FormCard.svelte +64 -0 | new file mode 100644 | ||
| @@ -0,0 +1,64 @@ | ||
| 1 | +<!-- Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE --> | |
| 2 | +<script lang="ts"> | |
| 3 | + // A form an agent asks in a conversation (issue #95): mini-me's ask_user | |
| 4 | + // sends its questions as an ACP elicitation form — free text included, | |
| 5 | + // which a permission card cannot ask. Shown under the answer, like a | |
| 6 | + // permission card: Answer sends the values, Decline tells the agent the | |
| 7 | + // user does not want to answer, Stop ends the agent's turn. | |
| 8 | + import { t } from '../i18n/index.svelte' | |
| 9 | + import type { FormRequest } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/channels' | |
| 10 | + import { agentTitle as titleOf, answerForm, cancel } from '../state.svelte' | |
| 11 | + import { contentOf, initialValues, missingFields, type Form, type Value } from '../creator' | |
| 12 | + import FormFields from './FormFields.svelte' | |
| 13 | + | |
| 14 | + let { request }: { request: FormRequest } = $props() | |
| 15 | + | |
| 16 | + const agentTitle = $derived(titleOf(request.agent)) | |
| 17 | + const form = $derived(request.form as Form) | |
| 18 | + // The values start from the form's defaults, once: the card is keyed by the request's id. | |
| 19 | + // svelte-ignore state_referenced_locally | |
| 20 | + let values = $state<Record<string, Value>>(initialValues(request.form as Form)) | |
| 21 | + let tried = $state(false) | |
| 22 | + let sending = $state(false) | |
| 23 | + const missing = $derived(tried ? missingFields(form, values) : []) | |
| 24 | + // mm's message repeats the questions: shown only when it says more than one line. | |
| 25 | + const message = $derived(form.message.trim()) | |
| 26 | + | |
| 27 | + async function answer(event: SubmitEvent) { | |
| 28 | + event.preventDefault() | |
| 29 | + tried = true | |
| 30 | + if (missingFields(form, values).length > 0) return | |
| 31 | + sending = true | |
| 32 | + await answerForm(request, { action: 'accept', content: contentOf(form, values) }) | |
| 33 | + sending = false | |
| 34 | + } | |
| 35 | + | |
| 36 | + async function decline() { | |
| 37 | + sending = true | |
| 38 | + await answerForm(request, { action: 'decline', content: {} }) | |
| 39 | + sending = false | |
| 40 | + } | |
| 41 | +</script> | |
| 42 | + | |
| 43 | +<form class="form-card" aria-label={t('form.label', { agent: agentTitle })} onsubmit={answer} novalidate> | |
| 44 | + <h3>{t('form.asks', { agent: agentTitle })}</h3> | |
| 45 | + {#if message && message.includes('\n')}<pre>{message}</pre>{/if} | |
| 46 | + <fieldset disabled={sending}> | |
| 47 | + <FormFields {form} bind:values {missing} idPrefix={request.id} /> | |
| 48 | + </fieldset> | |
| 49 | + <div class="buttons"> | |
| 50 | + <button type="submit" class="primary" disabled={sending}>{t('form.answer')}</button> | |
| 51 | + <button type="button" onclick={decline} disabled={sending}>{t('form.decline')}</button> | |
| 52 | + <button type="button" class="stop" onclick={() => cancel(request.channel)}>{t('conversation.stop', { agent: agentTitle })}</button> | |
| 53 | + </div> | |
| 54 | +</form> | |
| 55 | + | |
| 56 | +<style> | |
| 57 | + .form-card { margin: 8px 0; padding: 12px 14px; border: 2px solid var(--accent); border-radius: 12px; background: var(--panel); display: flex; flex-direction: column; gap: 10px; } | |
| 58 | + h3 { margin: 0; font-size: 15px; } | |
| 59 | + pre { margin: 0; padding: 8px 10px; background: var(--code-bg); border-radius: 6px; font-size: 13px; white-space: pre-wrap; overflow-wrap: anywhere; } | |
| 60 | + fieldset { border: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 10px; } | |
| 61 | + .buttons { display: flex; flex-wrap: wrap; gap: 6px; } | |
| 62 | + .primary { background: var(--accent); border-color: var(--accent); color: #fff; font-weight: 600; } | |
| 63 | + .stop { color: var(--danger); border-color: var(--danger); margin-left: auto; } | |
| 64 | +</style> | |
| new file mode 100644 | |||
| @@ -0,0 +1,64 @@ | |||
| 1 | +<!-- Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE --> | ||
| 2 | +<script lang="ts"> | ||
| 3 | + // A form an agent asks in a conversation (issue #95): mini-me's ask_user | ||
| 4 | + // sends its questions as an ACP elicitation form — free text included, | ||
| 5 | + // which a permission card cannot ask. Shown under the answer, like a | ||
| 6 | + // permission card: Answer sends the values, Decline tells the agent the | ||
| 7 | + // user does not want to answer, Stop ends the agent's turn. | ||
| 8 | + import { t } from '../i18n/index.svelte' | ||
| 9 | + import type { FormRequest } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/channels' | ||
| 10 | + import { agentTitle as titleOf, answerForm, cancel } from '../state.svelte' | ||
| 11 | + import { contentOf, initialValues, missingFields, type Form, type Value } from '../creator' | ||
| 12 | + import FormFields from './FormFields.svelte' | ||
| 13 | + | ||
| 14 | + let { request }: { request: FormRequest } = $props() | ||
| 15 | + | ||
| 16 | + const agentTitle = $derived(titleOf(request.agent)) | ||
| 17 | + const form = $derived(request.form as Form) | ||
| 18 | + // The values start from the form's defaults, once: the card is keyed by the request's id. | ||
| 19 | + // svelte-ignore state_referenced_locally | ||
| 20 | + let values = $state<Record<string, Value>>(initialValues(request.form as Form)) | ||
| 21 | + let tried = $state(false) | ||
| 22 | + let sending = $state(false) | ||
| 23 | + const missing = $derived(tried ? missingFields(form, values) : []) | ||
| 24 | + // mm's message repeats the questions: shown only when it says more than one line. | ||
| 25 | + const message = $derived(form.message.trim()) | ||
| 26 | + | ||
| 27 | + async function answer(event: SubmitEvent) { | ||
| 28 | + event.preventDefault() | ||
| 29 | + tried = true | ||
| 30 | + if (missingFields(form, values).length > 0) return | ||
| 31 | + sending = true | ||
| 32 | + await answerForm(request, { action: 'accept', content: contentOf(form, values) }) | ||
| 33 | + sending = false | ||
| 34 | + } | ||
| 35 | + | ||
| 36 | + async function decline() { | ||
| 37 | + sending = true | ||
| 38 | + await answerForm(request, { action: 'decline', content: {} }) | ||
| 39 | + sending = false | ||
| 40 | + } | ||
| 41 | +</script> | ||
| 42 | + | ||
| 43 | +<form class="form-card" aria-label={t('form.label', { agent: agentTitle })} onsubmit={answer} novalidate> | ||
| 44 | + <h3>{t('form.asks', { agent: agentTitle })}</h3> | ||
| 45 | + {#if message && message.includes('\n')}<pre>{message}</pre>{/if} | ||
| 46 | + <fieldset disabled={sending}> | ||
| 47 | + <FormFields {form} bind:values {missing} idPrefix={request.id} /> | ||
| 48 | + </fieldset> | ||
| 49 | + <div class="buttons"> | ||
| 50 | + <button type="submit" class="primary" disabled={sending}>{t('form.answer')}</button> | ||
| 51 | + <button type="button" onclick={decline} disabled={sending}>{t('form.decline')}</button> | ||
| 52 | + <button type="button" class="stop" onclick={() => cancel(request.channel)}>{t('conversation.stop', { agent: agentTitle })}</button> | ||
| 53 | + </div> | ||
| 54 | +</form> | ||
| 55 | + | ||
| 56 | +<style> | ||
| 57 | + .form-card { margin: 8px 0; padding: 12px 14px; border: 2px solid var(--accent); border-radius: 12px; background: var(--panel); display: flex; flex-direction: column; gap: 10px; } | ||
| 58 | + h3 { margin: 0; font-size: 15px; } | ||
| 59 | + pre { margin: 0; padding: 8px 10px; background: var(--code-bg); border-radius: 6px; font-size: 13px; white-space: pre-wrap; overflow-wrap: anywhere; } | ||
| 60 | + fieldset { border: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 10px; } | ||
| 61 | + .buttons { display: flex; flex-wrap: wrap; gap: 6px; } | ||
| 62 | + .primary { background: var(--accent); border-color: var(--accent); color: #fff; font-weight: 600; } | ||
| 63 | + .stop { color: var(--danger); border-color: var(--danger); margin-left: auto; } | ||
| 64 | +</style> | ||
added
frontend/src/lib/chat/FormFields.svelte +97 -0 | new file mode 100644 | ||
| @@ -0,0 +1,97 @@ | ||
| 1 | +<!-- Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE --> | |
| 2 | +<script lang="ts"> | |
| 3 | + // The fields of a form an agent asks (ACP elicitation): a checkbox for | |
| 4 | + // yes/no, radio buttons for a choice among few options, a list for more, | |
| 5 | + // checkboxes for several choices, an input for text and numbers. Used by | |
| 6 | + // the mini-me creation assistant (issue #94) and by the form card of a | |
| 7 | + // conversation (issue #95: mini-me's ask_user). The values live in the | |
| 8 | + // caller, which builds them with lib/creator.ts initialValues. | |
| 9 | + import { t } from '../i18n/index.svelte' | |
| 10 | + import type { Form, Value } from '../creator' | |
| 11 | + | |
| 12 | + let { | |
| 13 | + form, | |
| 14 | + values = $bindable(), | |
| 15 | + missing = [], | |
| 16 | + idPrefix, | |
| 17 | + }: { | |
| 18 | + form: Form | |
| 19 | + values: Record<string, Value> | |
| 20 | + /** The names of the required fields left empty, marked as such. */ | |
| 21 | + missing?: string[] | |
| 22 | + /** Makes the radio groups' names unique on the page. */ | |
| 23 | + idPrefix: string | |
| 24 | + } = $props() | |
| 25 | + | |
| 26 | + function toggle(field: string, option: string, on: boolean) { | |
| 27 | + const chosen = (values[field] as string[]) ?? [] | |
| 28 | + values[field] = on ? [...chosen, option] : chosen.filter((value) => value !== option) | |
| 29 | + } | |
| 30 | +</script> | |
| 31 | + | |
| 32 | +{#each form.fields ?? [] as field (field.name)} | |
| 33 | + {#if field.type === 'boolean'} | |
| 34 | + <label class="check"> | |
| 35 | + <input type="checkbox" checked={values[field.name] === true} onchange={(event) => (values[field.name] = event.currentTarget.checked)} /> | |
| 36 | + {field.title} | |
| 37 | + </label> | |
| 38 | + {:else if field.type === 'choice' && (field.options ?? []).length <= 4} | |
| 39 | + <div class="group" role="radiogroup" aria-label={field.title}> | |
| 40 | + <span class="label">{field.title}</span> | |
| 41 | + <div class="choices"> | |
| 42 | + {#each field.options ?? [] as option (option)} | |
| 43 | + <label class="choice" class:chosen={values[field.name] === option}> | |
| 44 | + <input type="radio" name={`${idPrefix}-${field.name}`} value={option} checked={values[field.name] === option} onchange={() => (values[field.name] = option)} /> | |
| 45 | + {option} | |
| 46 | + </label> | |
| 47 | + {/each} | |
| 48 | + </div> | |
| 49 | + </div> | |
| 50 | + {:else if field.type === 'choice'} | |
| 51 | + <label> | |
| 52 | + {field.title} | |
| 53 | + <select value={values[field.name]} onchange={(event) => (values[field.name] = event.currentTarget.value)}> | |
| 54 | + {#each field.options ?? [] as option (option)}<option value={option}>{option}</option>{/each} | |
| 55 | + </select> | |
| 56 | + </label> | |
| 57 | + {:else if field.type === 'multi'} | |
| 58 | + <div class="group" aria-label={field.title}> | |
| 59 | + <span class="label">{field.title}</span> | |
| 60 | + <div class="choices"> | |
| 61 | + {#each field.options ?? [] as option (option)} | |
| 62 | + <label class="choice"> | |
| 63 | + <input type="checkbox" checked={((values[field.name] as string[]) ?? []).includes(option)} onchange={(event) => toggle(field.name, option, event.currentTarget.checked)} /> | |
| 64 | + {option} | |
| 65 | + </label> | |
| 66 | + {/each} | |
| 67 | + </div> | |
| 68 | + </div> | |
| 69 | + {:else} | |
| 70 | + <label> | |
| 71 | + {field.title} | |
| 72 | + <input | |
| 73 | + value={values[field.name] as string} | |
| 74 | + oninput={(event) => (values[field.name] = event.currentTarget.value)} | |
| 75 | + inputmode={field.type === 'number' ? 'decimal' : undefined} | |
| 76 | + aria-invalid={missing.includes(field.name)} | |
| 77 | + spellcheck="false" | |
| 78 | + autocapitalize="off" | |
| 79 | + /> | |
| 80 | + {#if missing.includes(field.name)}<small class="problem-text">{t('form.missing')}</small>{/if} | |
| 81 | + </label> | |
| 82 | + {/if} | |
| 83 | + {#if field.description}<small>{field.description}</small>{/if} | |
| 84 | +{/each} | |
| 85 | + | |
| 86 | +<style> | |
| 87 | + label, .group { display: flex; flex-direction: column; gap: 4px; font-size: 13px; } | |
| 88 | + .label { font-size: 13px; } | |
| 89 | + label.check { flex-direction: row; align-items: center; gap: 8px; } | |
| 90 | + input:not([type='radio']):not([type='checkbox']), select { font: inherit; padding: 6px 8px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); color: var(--text); } | |
| 91 | + input[aria-invalid='true'] { border-color: var(--danger); } | |
| 92 | + small { color: var(--muted); font-size: 12px; } | |
| 93 | + .problem-text { color: var(--danger); } | |
| 94 | + .choices { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; } | |
| 95 | + .choice { flex-direction: row; align-items: center; gap: 6px; border: 1px solid var(--border); border-radius: 6px; padding: 6px 10px; cursor: pointer; } | |
| 96 | + .choice.chosen { border-color: var(--accent); } | |
| 97 | +</style> | |
| new file mode 100644 | |||
| @@ -0,0 +1,97 @@ | |||
| 1 | +<!-- Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE --> | ||
| 2 | +<script lang="ts"> | ||
| 3 | + // The fields of a form an agent asks (ACP elicitation): a checkbox for | ||
| 4 | + // yes/no, radio buttons for a choice among few options, a list for more, | ||
| 5 | + // checkboxes for several choices, an input for text and numbers. Used by | ||
| 6 | + // the mini-me creation assistant (issue #94) and by the form card of a | ||
| 7 | + // conversation (issue #95: mini-me's ask_user). The values live in the | ||
| 8 | + // caller, which builds them with lib/creator.ts initialValues. | ||
| 9 | + import { t } from '../i18n/index.svelte' | ||
| 10 | + import type { Form, Value } from '../creator' | ||
| 11 | + | ||
| 12 | + let { | ||
| 13 | + form, | ||
| 14 | + values = $bindable(), | ||
| 15 | + missing = [], | ||
| 16 | + idPrefix, | ||
| 17 | + }: { | ||
| 18 | + form: Form | ||
| 19 | + values: Record<string, Value> | ||
| 20 | + /** The names of the required fields left empty, marked as such. */ | ||
| 21 | + missing?: string[] | ||
| 22 | + /** Makes the radio groups' names unique on the page. */ | ||
| 23 | + idPrefix: string | ||
| 24 | + } = $props() | ||
| 25 | + | ||
| 26 | + function toggle(field: string, option: string, on: boolean) { | ||
| 27 | + const chosen = (values[field] as string[]) ?? [] | ||
| 28 | + values[field] = on ? [...chosen, option] : chosen.filter((value) => value !== option) | ||
| 29 | + } | ||
| 30 | +</script> | ||
| 31 | + | ||
| 32 | +{#each form.fields ?? [] as field (field.name)} | ||
| 33 | + {#if field.type === 'boolean'} | ||
| 34 | + <label class="check"> | ||
| 35 | + <input type="checkbox" checked={values[field.name] === true} onchange={(event) => (values[field.name] = event.currentTarget.checked)} /> | ||
| 36 | + {field.title} | ||
| 37 | + </label> | ||
| 38 | + {:else if field.type === 'choice' && (field.options ?? []).length <= 4} | ||
| 39 | + <div class="group" role="radiogroup" aria-label={field.title}> | ||
| 40 | + <span class="label">{field.title}</span> | ||
| 41 | + <div class="choices"> | ||
| 42 | + {#each field.options ?? [] as option (option)} | ||
| 43 | + <label class="choice" class:chosen={values[field.name] === option}> | ||
| 44 | + <input type="radio" name={`${idPrefix}-${field.name}`} value={option} checked={values[field.name] === option} onchange={() => (values[field.name] = option)} /> | ||
| 45 | + {option} | ||
| 46 | + </label> | ||
| 47 | + {/each} | ||
| 48 | + </div> | ||
| 49 | + </div> | ||
| 50 | + {:else if field.type === 'choice'} | ||
| 51 | + <label> | ||
| 52 | + {field.title} | ||
| 53 | + <select value={values[field.name]} onchange={(event) => (values[field.name] = event.currentTarget.value)}> | ||
| 54 | + {#each field.options ?? [] as option (option)}<option value={option}>{option}</option>{/each} | ||
| 55 | + </select> | ||
| 56 | + </label> | ||
| 57 | + {:else if field.type === 'multi'} | ||
| 58 | + <div class="group" aria-label={field.title}> | ||
| 59 | + <span class="label">{field.title}</span> | ||
| 60 | + <div class="choices"> | ||
| 61 | + {#each field.options ?? [] as option (option)} | ||
| 62 | + <label class="choice"> | ||
| 63 | + <input type="checkbox" checked={((values[field.name] as string[]) ?? []).includes(option)} onchange={(event) => toggle(field.name, option, event.currentTarget.checked)} /> | ||
| 64 | + {option} | ||
| 65 | + </label> | ||
| 66 | + {/each} | ||
| 67 | + </div> | ||
| 68 | + </div> | ||
| 69 | + {:else} | ||
| 70 | + <label> | ||
| 71 | + {field.title} | ||
| 72 | + <input | ||
| 73 | + value={values[field.name] as string} | ||
| 74 | + oninput={(event) => (values[field.name] = event.currentTarget.value)} | ||
| 75 | + inputmode={field.type === 'number' ? 'decimal' : undefined} | ||
| 76 | + aria-invalid={missing.includes(field.name)} | ||
| 77 | + spellcheck="false" | ||
| 78 | + autocapitalize="off" | ||
| 79 | + /> | ||
| 80 | + {#if missing.includes(field.name)}<small class="problem-text">{t('form.missing')}</small>{/if} | ||
| 81 | + </label> | ||
| 82 | + {/if} | ||
| 83 | + {#if field.description}<small>{field.description}</small>{/if} | ||
| 84 | +{/each} | ||
| 85 | + | ||
| 86 | +<style> | ||
| 87 | + label, .group { display: flex; flex-direction: column; gap: 4px; font-size: 13px; } | ||
| 88 | + .label { font-size: 13px; } | ||
| 89 | + label.check { flex-direction: row; align-items: center; gap: 8px; } | ||
| 90 | + input:not([type='radio']):not([type='checkbox']), select { font: inherit; padding: 6px 8px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); color: var(--text); } | ||
| 91 | + input[aria-invalid='true'] { border-color: var(--danger); } | ||
| 92 | + small { color: var(--muted); font-size: 12px; } | ||
| 93 | + .problem-text { color: var(--danger); } | ||
| 94 | + .choices { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; } | ||
| 95 | + .choice { flex-direction: row; align-items: center; gap: 6px; border: 1px solid var(--border); border-radius: 6px; padding: 6px 10px; cursor: pointer; } | ||
| 96 | + .choice.chosen { border-color: var(--accent); } | ||
| 97 | +</style> | ||
modified
frontend/src/lib/conversation.test.ts +12 -1 | @@ -3,7 +3,7 @@ | ||
| 3 | 3 | import { describe, expect, it } from 'vitest' |
| 4 | 4 | import type { Channel, Message } from '../../bindings/git.rickub.com/bots-garden/sidekicks/internal/channels' |
| 5 | 5 | import { Role } from '../../bindings/git.rickub.com/bots-garden/sidekicks/internal/channels' |
| 6 | -import { activityOf, addPermission, answerText, directOf, applyDelta, applyMessage, emptyConversation, notStreaming, prependMessages, removePermission, usagePercent } from './conversation' | |
| 6 | +import { activityOf, addForm, addPermission, answerText, directOf, applyDelta, applyMessage, emptyConversation, notStreaming, prependMessages, removeForm, removePermission, usagePercent } from './conversation' | |
| 7 | 7 | |
| 8 | 8 | const general: Channel = { id: 'c1', name: 'general', description: '', direct: '', members: ['alice'] } |
| 9 | 9 | |
| @@ -57,6 +57,17 @@ describe('conversation events', () => { | ||
| 57 | 57 | expect(conversation.permissions).toHaveLength(0) |
| 58 | 58 | }) |
| 59 | 59 | |
| 60 | + it('keeps each form once until it is resolved', () => { | |
| 61 | + const conversation = emptyConversation(general) | |
| 62 | + const request = { id: 'f-1', channel: 'c1', agent: 'alice', messageId: 'm-1', form: { message: '', fields: [], sessionId: '', toolCallId: '' } } | |
| 63 | + expect(conversation.forms).toEqual([]) | |
| 64 | + addForm(conversation, request) | |
| 65 | + addForm(conversation, request) | |
| 66 | + expect(conversation.forms).toHaveLength(1) | |
| 67 | + removeForm(conversation, 'f-1') | |
| 68 | + expect(conversation.forms).toHaveLength(0) | |
| 69 | + }) | |
| 70 | + | |
| 60 | 71 | it('computes the context gauge', () => { |
| 61 | 72 | const conversation = emptyConversation(general) |
| 62 | 73 | expect(usagePercent(conversation, 'alice')).toBeNull() |
| @@ -3,7 +3,7 @@ | |||
| 3 | import { describe, expect, it } from 'vitest' | 3 | import { describe, expect, it } from 'vitest' |
| 4 | import type { Channel, Message } from '../../bindings/git.rickub.com/bots-garden/sidekicks/internal/channels' | 4 | import type { Channel, Message } from '../../bindings/git.rickub.com/bots-garden/sidekicks/internal/channels' |
| 5 | import { Role } from '../../bindings/git.rickub.com/bots-garden/sidekicks/internal/channels' | 5 | import { Role } from '../../bindings/git.rickub.com/bots-garden/sidekicks/internal/channels' |
| 6 | -import { activityOf, addPermission, answerText, directOf, applyDelta, applyMessage, emptyConversation, notStreaming, prependMessages, removePermission, usagePercent } from './conversation' | 6 | +import { activityOf, addForm, addPermission, answerText, directOf, applyDelta, applyMessage, emptyConversation, notStreaming, prependMessages, removeForm, removePermission, usagePercent } from './conversation' |
| 7 | 7 | ||
| 8 | const general: Channel = { id: 'c1', name: 'general', description: '', direct: '', members: ['alice'] } | 8 | const general: Channel = { id: 'c1', name: 'general', description: '', direct: '', members: ['alice'] } |
| 9 | 9 | ||
| @@ -57,6 +57,17 @@ describe('conversation events', () => { | |||
| 57 | expect(conversation.permissions).toHaveLength(0) | 57 | expect(conversation.permissions).toHaveLength(0) |
| 58 | }) | 58 | }) |
| 59 | 59 | ||
| 60 | + it('keeps each form once until it is resolved', () => { | ||
| 61 | + const conversation = emptyConversation(general) | ||
| 62 | + const request = { id: 'f-1', channel: 'c1', agent: 'alice', messageId: 'm-1', form: { message: '', fields: [], sessionId: '', toolCallId: '' } } | ||
| 63 | + expect(conversation.forms).toEqual([]) | ||
| 64 | + addForm(conversation, request) | ||
| 65 | + addForm(conversation, request) | ||
| 66 | + expect(conversation.forms).toHaveLength(1) | ||
| 67 | + removeForm(conversation, 'f-1') | ||
| 68 | + expect(conversation.forms).toHaveLength(0) | ||
| 69 | + }) | ||
| 70 | + | ||
| 60 | it('computes the context gauge', () => { | 71 | it('computes the context gauge', () => { |
| 61 | const conversation = emptyConversation(general) | 72 | const conversation = emptyConversation(general) |
| 62 | expect(usagePercent(conversation, 'alice')).toBeNull() | 73 | expect(usagePercent(conversation, 'alice')).toBeNull() |
modified
frontend/src/lib/conversation.ts +13 -2 | @@ -3,11 +3,11 @@ | ||
| 3 | 3 | // Applies the channel events of the Go side to a conversation held by the |
| 4 | 4 | // interface (issues #15 and #23). Pure functions: the Svelte state calls them. |
| 5 | 5 | |
| 6 | -import type { Channel, Conversation, DeltaPayload, Message, Permission } from '../../bindings/git.rickub.com/bots-garden/sidekicks/internal/channels' | |
| 6 | +import type { Channel, Conversation, DeltaPayload, FormRequest, Message, Permission } from '../../bindings/git.rickub.com/bots-garden/sidekicks/internal/channels' | |
| 7 | 7 | |
| 8 | 8 | /** An empty conversation of channel, before the Go side has sent anything. */ |
| 9 | 9 | export function emptyConversation(channel: Channel): Conversation { |
| 10 | - return { channel, messages: [], more: false, busy: false, queued: 0, answering: '', answerers: [], usage: {}, permissions: [] } | |
| 10 | + return { channel, messages: [], more: false, busy: false, queued: 0, answering: '', answerers: [], usage: {}, permissions: [], forms: [] } | |
| 11 | 11 | } |
| 12 | 12 | |
| 13 | 13 | /** |
| @@ -74,6 +74,17 @@ export function removePermission(conversation: Conversation, id: string) { | ||
| 74 | 74 | conversation.permissions = (conversation.permissions ?? []).filter((candidate) => candidate.id !== id) |
| 75 | 75 | } |
| 76 | 76 | |
| 77 | +/** Adds a pending form (issue #95), once. */ | |
| 78 | +export function addForm(conversation: Conversation, request: FormRequest) { | |
| 79 | + const forms = (conversation.forms ??= []) | |
| 80 | + if (!forms.some((candidate) => candidate.id === request.id)) forms.push(request) | |
| 81 | +} | |
| 82 | + | |
| 83 | +/** Removes a form that was answered or cancelled. */ | |
| 84 | +export function removeForm(conversation: Conversation, id: string) { | |
| 85 | + conversation.forms = (conversation.forms ?? []).filter((candidate) => candidate.id !== id) | |
| 86 | +} | |
| 87 | + | |
| 77 | 88 | /** Share of agent's context window used, from 0 to 100, or null when unknown. */ |
| 78 | 89 | export function usagePercent(conversation: Conversation, agent: string): number | null { |
| 79 | 90 | const usage = conversation.usage?.[agent] |
| @@ -3,11 +3,11 @@ | |||
| 3 | // Applies the channel events of the Go side to a conversation held by the | 3 | // Applies the channel events of the Go side to a conversation held by the |
| 4 | // interface (issues #15 and #23). Pure functions: the Svelte state calls them. | 4 | // interface (issues #15 and #23). Pure functions: the Svelte state calls them. |
| 5 | 5 | ||
| 6 | -import type { Channel, Conversation, DeltaPayload, Message, Permission } from '../../bindings/git.rickub.com/bots-garden/sidekicks/internal/channels' | 6 | +import type { Channel, Conversation, DeltaPayload, FormRequest, Message, Permission } from '../../bindings/git.rickub.com/bots-garden/sidekicks/internal/channels' |
| 7 | 7 | ||
| 8 | /** An empty conversation of channel, before the Go side has sent anything. */ | 8 | /** An empty conversation of channel, before the Go side has sent anything. */ |
| 9 | export function emptyConversation(channel: Channel): Conversation { | 9 | export function emptyConversation(channel: Channel): Conversation { |
| 10 | - return { channel, messages: [], more: false, busy: false, queued: 0, answering: '', answerers: [], usage: {}, permissions: [] } | 10 | + return { channel, messages: [], more: false, busy: false, queued: 0, answering: '', answerers: [], usage: {}, permissions: [], forms: [] } |
| 11 | } | 11 | } |
| 12 | 12 | ||
| 13 | /** | 13 | /** |
| @@ -74,6 +74,17 @@ export function removePermission(conversation: Conversation, id: string) { | |||
| 74 | conversation.permissions = (conversation.permissions ?? []).filter((candidate) => candidate.id !== id) | 74 | conversation.permissions = (conversation.permissions ?? []).filter((candidate) => candidate.id !== id) |
| 75 | } | 75 | } |
| 76 | 76 | ||
| 77 | +/** Adds a pending form (issue #95), once. */ | ||
| 78 | +export function addForm(conversation: Conversation, request: FormRequest) { | ||
| 79 | + const forms = (conversation.forms ??= []) | ||
| 80 | + if (!forms.some((candidate) => candidate.id === request.id)) forms.push(request) | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +/** Removes a form that was answered or cancelled. */ | ||
| 84 | +export function removeForm(conversation: Conversation, id: string) { | ||
| 85 | + conversation.forms = (conversation.forms ?? []).filter((candidate) => candidate.id !== id) | ||
| 86 | +} | ||
| 87 | + | ||
| 77 | /** Share of agent's context window used, from 0 to 100, or null when unknown. */ | 88 | /** Share of agent's context window used, from 0 to 100, or null when unknown. */ |
| 78 | export function usagePercent(conversation: Conversation, agent: string): number | null { | 89 | export function usagePercent(conversation: Conversation, agent: string): number | null { |
| 79 | const usage = conversation.usage?.[agent] | 90 | const usage = conversation.usage?.[agent] |
modified
frontend/src/lib/i18n/messages.ts +10 -2 | @@ -339,7 +339,11 @@ export const en = { | ||
| 339 | 339 | 'creator.next': 'Next →', |
| 340 | 340 | 'creator.about': 'About these choices', |
| 341 | 341 | 'creator.details': 'What mini-me said', |
| 342 | - 'creator.missing': 'Please fill this in.', | |
| 342 | + 'form.missing': 'Please fill this in.', | |
| 343 | + 'form.label': 'Questions from {agent}', | |
| 344 | + 'form.asks': '{agent} asks you:', | |
| 345 | + 'form.answer': 'Answer', | |
| 346 | + 'form.decline': 'Decline', | |
| 343 | 347 | 'creator.noModelServer': 'No model server answered, so mini-me cannot list the models. Start your model server (Docker Model Runner, llmman, Ollama…), then click "Start again". You can also type the name of a model yourself.', |
| 344 | 348 | 'creator.stopped': 'The questions stopped: nothing was written yet.', |
| 345 | 349 | 'creator.continue': 'Continue', |
| @@ -771,7 +775,11 @@ export const fr: Record<MessageKey, string> = { | ||
| 771 | 775 | 'creator.next': 'Suivant →', |
| 772 | 776 | 'creator.about': 'À propos de ces choix', |
| 773 | 777 | 'creator.details': 'Ce que mini-me a dit', |
| 774 | - 'creator.missing': 'Merci de remplir ce champ.', | |
| 778 | + 'form.missing': 'Merci de remplir ce champ.', | |
| 779 | + 'form.label': 'Questions de {agent}', | |
| 780 | + 'form.asks': '{agent} vous demande :', | |
| 781 | + 'form.answer': 'Répondre', | |
| 782 | + 'form.decline': 'Refuser', | |
| 775 | 783 | 'creator.noModelServer': "Aucun serveur de modèles n'a répondu : mini-me ne peut pas lister les modèles. Démarrez votre serveur de modèles (Docker Model Runner, llmman, Ollama…), puis cliquez sur « Recommencer ». Vous pouvez aussi taper vous-même le nom d'un modèle.", |
| 776 | 784 | 'creator.stopped': "Les questions se sont arrêtées : rien n'est encore écrit.", |
| 777 | 785 | 'creator.continue': 'Continuer', |
| @@ -339,7 +339,11 @@ export const en = { | |||
| 339 | 'creator.next': 'Next →', | 339 | 'creator.next': 'Next →', |
| 340 | 'creator.about': 'About these choices', | 340 | 'creator.about': 'About these choices', |
| 341 | 'creator.details': 'What mini-me said', | 341 | 'creator.details': 'What mini-me said', |
| 342 | - 'creator.missing': 'Please fill this in.', | 342 | + 'form.missing': 'Please fill this in.', |
| 343 | + 'form.label': 'Questions from {agent}', | ||
| 344 | + 'form.asks': '{agent} asks you:', | ||
| 345 | + 'form.answer': 'Answer', | ||
| 346 | + 'form.decline': 'Decline', | ||
| 343 | 'creator.noModelServer': 'No model server answered, so mini-me cannot list the models. Start your model server (Docker Model Runner, llmman, Ollama…), then click "Start again". You can also type the name of a model yourself.', | 347 | 'creator.noModelServer': 'No model server answered, so mini-me cannot list the models. Start your model server (Docker Model Runner, llmman, Ollama…), then click "Start again". You can also type the name of a model yourself.', |
| 344 | 'creator.stopped': 'The questions stopped: nothing was written yet.', | 348 | 'creator.stopped': 'The questions stopped: nothing was written yet.', |
| 345 | 'creator.continue': 'Continue', | 349 | 'creator.continue': 'Continue', |
| @@ -771,7 +775,11 @@ export const fr: Record<MessageKey, string> = { | |||
| 771 | 'creator.next': 'Suivant →', | 775 | 'creator.next': 'Suivant →', |
| 772 | 'creator.about': 'À propos de ces choix', | 776 | 'creator.about': 'À propos de ces choix', |
| 773 | 'creator.details': 'Ce que mini-me a dit', | 777 | 'creator.details': 'Ce que mini-me a dit', |
| 774 | - 'creator.missing': 'Merci de remplir ce champ.', | 778 | + 'form.missing': 'Merci de remplir ce champ.', |
| 779 | + 'form.label': 'Questions de {agent}', | ||
| 780 | + 'form.asks': '{agent} vous demande :', | ||
| 781 | + 'form.answer': 'Répondre', | ||
| 782 | + 'form.decline': 'Refuser', | ||
| 775 | 'creator.noModelServer': "Aucun serveur de modèles n'a répondu : mini-me ne peut pas lister les modèles. Démarrez votre serveur de modèles (Docker Model Runner, llmman, Ollama…), puis cliquez sur « Recommencer ». Vous pouvez aussi taper vous-même le nom d'un modèle.", | 783 | 'creator.noModelServer': "Aucun serveur de modèles n'a répondu : mini-me ne peut pas lister les modèles. Démarrez votre serveur de modèles (Docker Model Runner, llmman, Ollama…), puis cliquez sur « Recommencer ». Vous pouvez aussi taper vous-même le nom d'un modèle.", |
| 776 | 'creator.stopped': "Les questions se sont arrêtées : rien n'est encore écrit.", | 784 | 'creator.stopped': "Les questions se sont arrêtées : rien n'est encore écrit.", |
| 777 | 'creator.continue': 'Continuer', | 785 | 'creator.continue': 'Continuer', |
modified
frontend/src/lib/panels/ConversationPanel.svelte +5 -0 | @@ -5,6 +5,7 @@ | ||
| 5 | 5 | import Composer from '../chat/Composer.svelte' |
| 6 | 6 | import MessageView from '../chat/MessageView.svelte' |
| 7 | 7 | import PermissionCard from '../chat/PermissionCard.svelte' |
| 8 | + import FormCard from '../chat/FormCard.svelte' | |
| 8 | 9 | import Spinner from '../chat/Spinner.svelte' |
| 9 | 10 | import AgentView from '../agent/AgentView.svelte' |
| 10 | 11 | import LinkedFilePanel from '../agent/LinkedFilePanel.svelte' |
| @@ -176,6 +177,7 @@ | ||
| 176 | 177 | JSON.stringify(conversation?.messages?.at(-1)) |
| 177 | 178 | void conversation?.messages?.length |
| 178 | 179 | void conversation?.permissions?.length |
| 180 | + void conversation?.forms?.length | |
| 179 | 181 | if (following && list) tick().then(() => list && (list.scrollTop = list.scrollHeight)) |
| 180 | 182 | }) |
| 181 | 183 | $effect(() => { |
| @@ -290,6 +292,9 @@ | ||
| 290 | 292 | {#each conversation.permissions ?? [] as permission (permission.id)} |
| 291 | 293 | <PermissionCard {permission} /> |
| 292 | 294 | {/each} |
| 295 | + {#each conversation.forms ?? [] as request (request.id)} | |
| 296 | + <FormCard {request} /> | |
| 297 | + {/each} | |
| 293 | 298 | </div> |
| 294 | 299 | {#if failures >= stuckAfter} |
| 295 | 300 | <div class="stuck" role="alert"> |
| @@ -5,6 +5,7 @@ | |||
| 5 | import Composer from '../chat/Composer.svelte' | 5 | import Composer from '../chat/Composer.svelte' |
| 6 | import MessageView from '../chat/MessageView.svelte' | 6 | import MessageView from '../chat/MessageView.svelte' |
| 7 | import PermissionCard from '../chat/PermissionCard.svelte' | 7 | import PermissionCard from '../chat/PermissionCard.svelte' |
| 8 | + import FormCard from '../chat/FormCard.svelte' | ||
| 8 | import Spinner from '../chat/Spinner.svelte' | 9 | import Spinner from '../chat/Spinner.svelte' |
| 9 | import AgentView from '../agent/AgentView.svelte' | 10 | import AgentView from '../agent/AgentView.svelte' |
| 10 | import LinkedFilePanel from '../agent/LinkedFilePanel.svelte' | 11 | import LinkedFilePanel from '../agent/LinkedFilePanel.svelte' |
| @@ -176,6 +177,7 @@ | |||
| 176 | JSON.stringify(conversation?.messages?.at(-1)) | 177 | JSON.stringify(conversation?.messages?.at(-1)) |
| 177 | void conversation?.messages?.length | 178 | void conversation?.messages?.length |
| 178 | void conversation?.permissions?.length | 179 | void conversation?.permissions?.length |
| 180 | + void conversation?.forms?.length | ||
| 179 | if (following && list) tick().then(() => list && (list.scrollTop = list.scrollHeight)) | 181 | if (following && list) tick().then(() => list && (list.scrollTop = list.scrollHeight)) |
| 180 | }) | 182 | }) |
| 181 | $effect(() => { | 183 | $effect(() => { |
| @@ -290,6 +292,9 @@ | |||
| 290 | {#each conversation.permissions ?? [] as permission (permission.id)} | 292 | {#each conversation.permissions ?? [] as permission (permission.id)} |
| 291 | <PermissionCard {permission} /> | 293 | <PermissionCard {permission} /> |
| 292 | {/each} | 294 | {/each} |
| 295 | + {#each conversation.forms ?? [] as request (request.id)} | ||
| 296 | + <FormCard {request} /> | ||
| 297 | + {/each} | ||
| 293 | </div> | 298 | </div> |
| 294 | {#if failures >= stuckAfter} | 299 | {#if failures >= stuckAfter} |
| 295 | <div class="stuck" role="alert"> | 300 | <div class="stuck" role="alert"> |
modified
frontend/src/lib/state.svelte.ts +12 -1 | @@ -17,6 +17,8 @@ import type { | ||
| 17 | 17 | CommandsPayload, |
| 18 | 18 | Conversation, |
| 19 | 19 | DeltaPayload, |
| 20 | + FormRequest, | |
| 21 | + FormResolvedPayload, | |
| 20 | 22 | MessagePayload, |
| 21 | 23 | Permission, |
| 22 | 24 | PermissionResolvedPayload, |
| @@ -29,6 +31,8 @@ import { | ||
| 29 | 31 | ChannelsChanged, |
| 30 | 32 | CommandsChanged, |
| 31 | 33 | ConfigChanged, |
| 34 | + FormRequested, | |
| 35 | + FormResolved, | |
| 32 | 36 | MessageDelta, |
| 33 | 37 | MessageUpdated, |
| 34 | 38 | PermissionRequested, |
| @@ -39,7 +43,7 @@ import { | ||
| 39 | 43 | UsageChanged, |
| 40 | 44 | WorkspaceChanged, |
| 41 | 45 | } from '../../bindings/events' |
| 42 | -import { addPermission, applyDelta, applyMessage, emptyConversation, prependMessages, removePermission } from './conversation' | |
| 46 | +import { addForm, addPermission, applyDelta, applyMessage, emptyConversation, prependMessages, removeForm, removePermission } from './conversation' | |
| 43 | 47 | import { createFrameBatcher, subscribe } from './events' |
| 44 | 48 | import { applyTheme } from './theme' |
| 45 | 49 | import { setLanguage } from './i18n/index.svelte' |
| @@ -316,6 +320,11 @@ export function answerPermission(permission: Permission, optionId: string) { | ||
| 316 | 320 | return act(() => ChannelService.AnswerPermission(permission.id, optionId)) |
| 317 | 321 | } |
| 318 | 322 | |
| 323 | +/** Answers a form an agent asked (issue #95): accept with the values, or decline. */ | |
| 324 | +export function answerForm(request: FormRequest, answer: { action: string; content: Record<string, unknown> }) { | |
| 325 | + return act(() => ChannelService.AnswerForm(request.id, answer)) | |
| 326 | +} | |
| 327 | + | |
| 319 | 328 | export function createChannel(name: string) { |
| 320 | 329 | return act(async () => { |
| 321 | 330 | const channel = await ChannelService.Create(name, '') |
| @@ -432,6 +441,8 @@ export function connect(): () => void { | ||
| 432 | 441 | }), |
| 433 | 442 | subscribe<Permission>(PermissionRequested, (payload) => addPermission(conversationOf(payload.channel), payload)), |
| 434 | 443 | subscribe<PermissionResolvedPayload>(PermissionResolved, (payload) => removePermission(conversationOf(payload.channel), payload.id)), |
| 444 | + subscribe<FormRequest>(FormRequested, (payload) => addForm(conversationOf(payload.channel), payload)), | |
| 445 | + subscribe<FormResolvedPayload>(FormResolved, (payload) => removeForm(conversationOf(payload.channel), payload.id)), | |
| 435 | 446 | subscribe<UsagePayload>(UsageChanged, (payload) => { |
| 436 | 447 | const conversation = conversationOf(payload.channel) |
| 437 | 448 | conversation.usage = { ...(conversation.usage ?? {}), [payload.agent]: payload.usage } |
| @@ -17,6 +17,8 @@ import type { | |||
| 17 | CommandsPayload, | 17 | CommandsPayload, |
| 18 | Conversation, | 18 | Conversation, |
| 19 | DeltaPayload, | 19 | DeltaPayload, |
| 20 | + FormRequest, | ||
| 21 | + FormResolvedPayload, | ||
| 20 | MessagePayload, | 22 | MessagePayload, |
| 21 | Permission, | 23 | Permission, |
| 22 | PermissionResolvedPayload, | 24 | PermissionResolvedPayload, |
| @@ -29,6 +31,8 @@ import { | |||
| 29 | ChannelsChanged, | 31 | ChannelsChanged, |
| 30 | CommandsChanged, | 32 | CommandsChanged, |
| 31 | ConfigChanged, | 33 | ConfigChanged, |
| 34 | + FormRequested, | ||
| 35 | + FormResolved, | ||
| 32 | MessageDelta, | 36 | MessageDelta, |
| 33 | MessageUpdated, | 37 | MessageUpdated, |
| 34 | PermissionRequested, | 38 | PermissionRequested, |
| @@ -39,7 +43,7 @@ import { | |||
| 39 | UsageChanged, | 43 | UsageChanged, |
| 40 | WorkspaceChanged, | 44 | WorkspaceChanged, |
| 41 | } from '../../bindings/events' | 45 | } from '../../bindings/events' |
| 42 | -import { addPermission, applyDelta, applyMessage, emptyConversation, prependMessages, removePermission } from './conversation' | 46 | +import { addForm, addPermission, applyDelta, applyMessage, emptyConversation, prependMessages, removeForm, removePermission } from './conversation' |
| 43 | import { createFrameBatcher, subscribe } from './events' | 47 | import { createFrameBatcher, subscribe } from './events' |
| 44 | import { applyTheme } from './theme' | 48 | import { applyTheme } from './theme' |
| 45 | import { setLanguage } from './i18n/index.svelte' | 49 | import { setLanguage } from './i18n/index.svelte' |
| @@ -316,6 +320,11 @@ export function answerPermission(permission: Permission, optionId: string) { | |||
| 316 | return act(() => ChannelService.AnswerPermission(permission.id, optionId)) | 320 | return act(() => ChannelService.AnswerPermission(permission.id, optionId)) |
| 317 | } | 321 | } |
| 318 | 322 | ||
| 323 | +/** Answers a form an agent asked (issue #95): accept with the values, or decline. */ | ||
| 324 | +export function answerForm(request: FormRequest, answer: { action: string; content: Record<string, unknown> }) { | ||
| 325 | + return act(() => ChannelService.AnswerForm(request.id, answer)) | ||
| 326 | +} | ||
| 327 | + | ||
| 319 | export function createChannel(name: string) { | 328 | export function createChannel(name: string) { |
| 320 | return act(async () => { | 329 | return act(async () => { |
| 321 | const channel = await ChannelService.Create(name, '') | 330 | const channel = await ChannelService.Create(name, '') |
| @@ -432,6 +441,8 @@ export function connect(): () => void { | |||
| 432 | }), | 441 | }), |
| 433 | subscribe<Permission>(PermissionRequested, (payload) => addPermission(conversationOf(payload.channel), payload)), | 442 | subscribe<Permission>(PermissionRequested, (payload) => addPermission(conversationOf(payload.channel), payload)), |
| 434 | subscribe<PermissionResolvedPayload>(PermissionResolved, (payload) => removePermission(conversationOf(payload.channel), payload.id)), | 443 | subscribe<PermissionResolvedPayload>(PermissionResolved, (payload) => removePermission(conversationOf(payload.channel), payload.id)), |
| 444 | + subscribe<FormRequest>(FormRequested, (payload) => addForm(conversationOf(payload.channel), payload)), | ||
| 445 | + subscribe<FormResolvedPayload>(FormResolved, (payload) => removeForm(conversationOf(payload.channel), payload.id)), | ||
| 435 | subscribe<UsagePayload>(UsageChanged, (payload) => { | 446 | subscribe<UsagePayload>(UsageChanged, (payload) => { |
| 436 | const conversation = conversationOf(payload.channel) | 447 | const conversation = conversationOf(payload.channel) |
| 437 | conversation.usage = { ...(conversation.usage ?? {}), [payload.agent]: payload.usage } | 448 | conversation.usage = { ...(conversation.usage ?? {}), [payload.agent]: payload.usage } |
modified
internal/acp/client.go +1 -0 | @@ -17,6 +17,7 @@ type client struct { | ||
| 17 | 17 | sessions *sessions |
| 18 | 18 | tools []Tool |
| 19 | 19 | onForm FormHandler |
| 20 | + forms bool | |
| 20 | 21 | } |
| 21 | 22 | |
| 22 | 23 | func (c *client) SessionUpdate(_ context.Context, notification sdk.SessionNotification) error { |
| @@ -17,6 +17,7 @@ type client struct { | |||
| 17 | sessions *sessions | 17 | sessions *sessions |
| 18 | tools []Tool | 18 | tools []Tool |
| 19 | onForm FormHandler | 19 | onForm FormHandler |
| 20 | + forms bool | ||
| 20 | } | 21 | } |
| 21 | 22 | ||
| 22 | func (c *client) SessionUpdate(_ context.Context, notification sdk.SessionNotification) error { | 23 | func (c *client) SessionUpdate(_ context.Context, notification sdk.SessionNotification) error { |
modified
internal/acp/conn.go +6 -3 | @@ -65,8 +65,11 @@ type Spec struct { | ||
| 65 | 65 | // ClientVersion is Sidekicks' version, told in initialize. |
| 66 | 66 | ClientVersion string |
| 67 | 67 | // OnForm answers the forms the agent asks the user to fill in (ACP |
| 68 | - // elicitation, issue #94); nil advertises no form support. | |
| 68 | + // elicitation, issue #94). Forms (issue #95) sends each form to the | |
| 69 | + // handler of its session instead, when it is a FormAsker. With neither, | |
| 70 | + // no form support is advertised. | |
| 69 | 71 | OnForm FormHandler |
| 72 | + Forms bool | |
| 70 | 73 | } |
| 71 | 74 | |
| 72 | 75 | // Options tunes Start. The zero value is usable. |
| @@ -162,7 +165,7 @@ func (c *Conn) launch(onStderr func(string)) error { | ||
| 162 | 165 | stderrDone := make(chan struct{}) |
| 163 | 166 | go c.readStderr(stderr, onStderr, stderrDone) |
| 164 | 167 | go c.wait(stderrDone) |
| 165 | - c.connection = sdk.NewClientSideConnection(&client{sessions: c.sessions, tools: c.spec.Tools, onForm: c.spec.OnForm}, stdin, stdout) | |
| 168 | + c.connection = sdk.NewClientSideConnection(&client{sessions: c.sessions, tools: c.spec.Tools, onForm: c.spec.OnForm, forms: c.spec.Forms}, stdin, stdout) | |
| 166 | 169 | // The SDK logs its own diagnostics ("connection closed"…); the agent's |
| 167 | 170 | // stderr already tells what matters. |
| 168 | 171 | c.connection.SetLogger(slog.New(slog.NewTextHandler(io.Discard, nil))) |
| @@ -210,7 +213,7 @@ func (c *Conn) initialize(ctx context.Context) error { | ||
| 210 | 213 | go func() { |
| 211 | 214 | response, err := c.connection.Initialize(ctx, sdk.InitializeRequest{ |
| 212 | 215 | ProtocolVersion: sdk.ProtocolVersion(ProtocolVersion), |
| 213 | - ClientCapabilities: sdk.ClientCapabilities{Meta: toolsMeta(c.spec.Tools, c.spec.ToolDiscovery), Elicitation: elicitationCapabilities(c.spec.OnForm)}, | |
| 216 | + ClientCapabilities: sdk.ClientCapabilities{Meta: toolsMeta(c.spec.Tools, c.spec.ToolDiscovery), Elicitation: elicitationCapabilities(c.spec.OnForm, c.spec.Forms)}, | |
| 214 | 217 | ClientInfo: &sdk.Implementation{Name: "sidekicks", Version: clientVersion(c.spec.ClientVersion)}, |
| 215 | 218 | }) |
| 216 | 219 | answer <- result{response, err} |
| @@ -65,8 +65,11 @@ type Spec struct { | |||
| 65 | // ClientVersion is Sidekicks' version, told in initialize. | 65 | // ClientVersion is Sidekicks' version, told in initialize. |
| 66 | ClientVersion string | 66 | ClientVersion string |
| 67 | // OnForm answers the forms the agent asks the user to fill in (ACP | 67 | // OnForm answers the forms the agent asks the user to fill in (ACP |
| 68 | - // elicitation, issue #94); nil advertises no form support. | 68 | + // elicitation, issue #94). Forms (issue #95) sends each form to the |
| 69 | + // handler of its session instead, when it is a FormAsker. With neither, | ||
| 70 | + // no form support is advertised. | ||
| 69 | OnForm FormHandler | 71 | OnForm FormHandler |
| 72 | + Forms bool | ||
| 70 | } | 73 | } |
| 71 | 74 | ||
| 72 | // Options tunes Start. The zero value is usable. | 75 | // Options tunes Start. The zero value is usable. |
| @@ -162,7 +165,7 @@ func (c *Conn) launch(onStderr func(string)) error { | |||
| 162 | stderrDone := make(chan struct{}) | 165 | stderrDone := make(chan struct{}) |
| 163 | go c.readStderr(stderr, onStderr, stderrDone) | 166 | go c.readStderr(stderr, onStderr, stderrDone) |
| 164 | go c.wait(stderrDone) | 167 | go c.wait(stderrDone) |
| 165 | - c.connection = sdk.NewClientSideConnection(&client{sessions: c.sessions, tools: c.spec.Tools, onForm: c.spec.OnForm}, stdin, stdout) | 168 | + c.connection = sdk.NewClientSideConnection(&client{sessions: c.sessions, tools: c.spec.Tools, onForm: c.spec.OnForm, forms: c.spec.Forms}, stdin, stdout) |
| 166 | // The SDK logs its own diagnostics ("connection closed"…); the agent's | 169 | // The SDK logs its own diagnostics ("connection closed"…); the agent's |
| 167 | // stderr already tells what matters. | 170 | // stderr already tells what matters. |
| 168 | c.connection.SetLogger(slog.New(slog.NewTextHandler(io.Discard, nil))) | 171 | c.connection.SetLogger(slog.New(slog.NewTextHandler(io.Discard, nil))) |
| @@ -210,7 +213,7 @@ func (c *Conn) initialize(ctx context.Context) error { | |||
| 210 | go func() { | 213 | go func() { |
| 211 | response, err := c.connection.Initialize(ctx, sdk.InitializeRequest{ | 214 | response, err := c.connection.Initialize(ctx, sdk.InitializeRequest{ |
| 212 | ProtocolVersion: sdk.ProtocolVersion(ProtocolVersion), | 215 | ProtocolVersion: sdk.ProtocolVersion(ProtocolVersion), |
| 213 | - ClientCapabilities: sdk.ClientCapabilities{Meta: toolsMeta(c.spec.Tools, c.spec.ToolDiscovery), Elicitation: elicitationCapabilities(c.spec.OnForm)}, | 216 | + ClientCapabilities: sdk.ClientCapabilities{Meta: toolsMeta(c.spec.Tools, c.spec.ToolDiscovery), Elicitation: elicitationCapabilities(c.spec.OnForm, c.spec.Forms)}, |
| 214 | ClientInfo: &sdk.Implementation{Name: "sidekicks", Version: clientVersion(c.spec.ClientVersion)}, | 217 | ClientInfo: &sdk.Implementation{Name: "sidekicks", Version: clientVersion(c.spec.ClientVersion)}, |
| 215 | }) | 218 | }) |
| 216 | answer <- result{response, err} | 219 | answer <- result{response, err} |
modified
internal/acp/conn_test.go +10 -3 | @@ -341,7 +341,10 @@ func (a *fakeAgent) Prompt(ctx context.Context, request sdk.PromptRequest) (sdk. | ||
| 341 | 341 | send(sdk.UpdateAgentMessageText(fmt.Sprintf("missing=%v", err))) |
| 342 | 342 | return sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn}, nil |
| 343 | 343 | case "form": |
| 344 | - send(sdk.UpdateAgentMessageText(a.askForm(ctx))) | |
| 344 | + send(sdk.UpdateAgentMessageText(a.askForm(ctx, ""))) | |
| 345 | + return sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn}, nil | |
| 346 | + case "form-scoped": | |
| 347 | + send(sdk.UpdateAgentMessageText(a.askForm(ctx, string(request.SessionId)))) | |
| 345 | 348 | return sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn}, nil |
| 346 | 349 | case "long": |
| 347 | 350 | for { |
| @@ -356,9 +359,10 @@ func (a *fakeAgent) Prompt(ctx context.Context, request sdk.PromptRequest) (sdk. | ||
| 356 | 359 | return sdk.PromptResponse{}, sdk.NewInternalError(map[string]any{"error": "exceeded maximum tool call iterations (40)"}) |
| 357 | 360 | } |
| 358 | 361 | |
| 359 | -// askForm plays mm acp-create: it asks a form and tells what came back and | |
| 362 | +// askForm plays mm acp-create, or mm's ask_user with session (its scope in | |
| 363 | +// _meta, as mm puts it): it asks a form and tells what came back and | |
| 360 | 364 | // whether initialize advertised forms. |
| 361 | -func (a *fakeAgent) askForm(ctx context.Context) string { | |
| 365 | +func (a *fakeAgent) askForm(ctx context.Context, session string) string { | |
| 362 | 366 | advertised := a.client.ClientCapabilities.Elicitation != nil && a.client.ClientCapabilities.Elicitation.Form != nil |
| 363 | 367 | req := sdk.NewUnstableCreateElicitationRequestForm(sdk.UnstableElicitationSchema{ |
| 364 | 368 | Type: sdk.UnstableElicitationSchemaTypeObject, |
| @@ -370,6 +374,9 @@ func (a *fakeAgent) askForm(ctx context.Context) string { | ||
| 370 | 374 | Required: []string{"provider", "yolo", "name"}, |
| 371 | 375 | }) |
| 372 | 376 | req.Form.Message = "mm init — create an agent" |
| 377 | + if session != "" { | |
| 378 | + req.Form.Meta = map[string]any{"mm.elicitationScope": map[string]any{"sessionId": session, "toolCallId": "call_7"}} | |
| 379 | + } | |
| 373 | 380 | resp, err := a.conn.UnstableCreateElicitation(ctx, req) |
| 374 | 381 | switch { |
| 375 | 382 | case err != nil: |
| @@ -341,7 +341,10 @@ func (a *fakeAgent) Prompt(ctx context.Context, request sdk.PromptRequest) (sdk. | |||
| 341 | send(sdk.UpdateAgentMessageText(fmt.Sprintf("missing=%v", err))) | 341 | send(sdk.UpdateAgentMessageText(fmt.Sprintf("missing=%v", err))) |
| 342 | return sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn}, nil | 342 | return sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn}, nil |
| 343 | case "form": | 343 | case "form": |
| 344 | - send(sdk.UpdateAgentMessageText(a.askForm(ctx))) | 344 | + send(sdk.UpdateAgentMessageText(a.askForm(ctx, ""))) |
| 345 | + return sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn}, nil | ||
| 346 | + case "form-scoped": | ||
| 347 | + send(sdk.UpdateAgentMessageText(a.askForm(ctx, string(request.SessionId)))) | ||
| 345 | return sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn}, nil | 348 | return sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn}, nil |
| 346 | case "long": | 349 | case "long": |
| 347 | for { | 350 | for { |
| @@ -356,9 +359,10 @@ func (a *fakeAgent) Prompt(ctx context.Context, request sdk.PromptRequest) (sdk. | |||
| 356 | return sdk.PromptResponse{}, sdk.NewInternalError(map[string]any{"error": "exceeded maximum tool call iterations (40)"}) | 359 | return sdk.PromptResponse{}, sdk.NewInternalError(map[string]any{"error": "exceeded maximum tool call iterations (40)"}) |
| 357 | } | 360 | } |
| 358 | 361 | ||
| 359 | -// askForm plays mm acp-create: it asks a form and tells what came back and | 362 | +// askForm plays mm acp-create, or mm's ask_user with session (its scope in |
| 363 | +// _meta, as mm puts it): it asks a form and tells what came back and | ||
| 360 | // whether initialize advertised forms. | 364 | // whether initialize advertised forms. |
| 361 | -func (a *fakeAgent) askForm(ctx context.Context) string { | 365 | +func (a *fakeAgent) askForm(ctx context.Context, session string) string { |
| 362 | advertised := a.client.ClientCapabilities.Elicitation != nil && a.client.ClientCapabilities.Elicitation.Form != nil | 366 | advertised := a.client.ClientCapabilities.Elicitation != nil && a.client.ClientCapabilities.Elicitation.Form != nil |
| 363 | req := sdk.NewUnstableCreateElicitationRequestForm(sdk.UnstableElicitationSchema{ | 367 | req := sdk.NewUnstableCreateElicitationRequestForm(sdk.UnstableElicitationSchema{ |
| 364 | Type: sdk.UnstableElicitationSchemaTypeObject, | 368 | Type: sdk.UnstableElicitationSchemaTypeObject, |
| @@ -370,6 +374,9 @@ func (a *fakeAgent) askForm(ctx context.Context) string { | |||
| 370 | Required: []string{"provider", "yolo", "name"}, | 374 | Required: []string{"provider", "yolo", "name"}, |
| 371 | }) | 375 | }) |
| 372 | req.Form.Message = "mm init — create an agent" | 376 | req.Form.Message = "mm init — create an agent" |
| 377 | + if session != "" { | ||
| 378 | + req.Form.Meta = map[string]any{"mm.elicitationScope": map[string]any{"sessionId": session, "toolCallId": "call_7"}} | ||
| 379 | + } | ||
| 373 | resp, err := a.conn.UnstableCreateElicitation(ctx, req) | 380 | resp, err := a.conn.UnstableCreateElicitation(ctx, req) |
| 374 | switch { | 381 | switch { |
| 375 | case err != nil: | 382 | case err != nil: |
modified
internal/acp/forms.go +40 -9 | @@ -11,11 +11,13 @@ import ( | ||
| 11 | 11 | sdk "github.com/coder/acp-go-sdk" |
| 12 | 12 | ) |
| 13 | 13 | |
| 14 | -// Forms (issue #94): an agent may ask the user to fill in a form with ACP's | |
| 15 | -// elicitation/create request, in its "form" mode (still marked unstable in | |
| 16 | -// the protocol). Sidekicks advertises clientCapabilities.elicitation.form | |
| 17 | -// only for a connection started with Spec.OnForm, and answers every request | |
| 18 | -// through it. The "url" mode is not supported: such a request is cancelled. | |
| 14 | +// Forms (issues #94 and #95): an agent may ask the user to fill in a form | |
| 15 | +// with ACP's elicitation/create request, in its "form" mode (still marked | |
| 16 | +// unstable in the protocol) — mini-me does for its ask_user tool. | |
| 17 | +// Sidekicks advertises clientCapabilities.elicitation.form when Spec.OnForm | |
| 18 | +// is set (every request goes to it) or Spec.Forms is true (each request goes | |
| 19 | +// to the handler of its session, when it is a FormAsker). The "url" mode is | |
| 20 | +// not supported: such a request is cancelled. | |
| 19 | 21 | |
| 20 | 22 | // Field types of a Form, from the JSON Schema of the request. |
| 21 | 23 | const ( |
| @@ -38,8 +40,24 @@ type Form struct { | ||
| 38 | 40 | // Message says what the form is for (Markdown or plain text). |
| 39 | 41 | Message string `json:"message"` |
| 40 | 42 | Fields []FormField `json:"fields"` |
| 43 | + // SessionID and ToolCallID tie the form to a session and a tool call, | |
| 44 | + // when the agent says so; "" otherwise. | |
| 45 | + SessionID string `json:"sessionId"` | |
| 46 | + ToolCallID string `json:"toolCallId"` | |
| 41 | 47 | } |
| 42 | 48 | |
| 49 | +// FormAsker is a SessionHandler that can show a form to the user (#95). It | |
| 50 | +// may block until the user answers, and must return a cancel answer once | |
| 51 | +// ctx is done. | |
| 52 | +type FormAsker interface { | |
| 53 | + RequestForm(ctx context.Context, form Form) FormAnswer | |
| 54 | +} | |
| 55 | + | |
| 56 | +// scopeMetaKey is where mini-me parks a form's session and tool call in | |
| 57 | +// `_meta`: the SDK drops the top-level sessionId and toolCallId that ACP | |
| 58 | +// specifies, so mm also copies them there. | |
| 59 | +const scopeMetaKey = "mm.elicitationScope" | |
| 60 | + | |
| 43 | 61 | // FormField is one question of a Form. |
| 44 | 62 | type FormField struct { |
| 45 | 63 | // Name is the key of the answer in FormAnswer.Content. |
| @@ -73,6 +91,9 @@ type FormHandler func(ctx context.Context, form Form) FormAnswer | ||
| 73 | 91 | func formFrom(request sdk.UnstableCreateElicitationForm) Form { |
| 74 | 92 | schema := request.RequestedSchema |
| 75 | 93 | form := Form{Message: request.Message, Fields: []FormField{}} |
| 94 | + if scope, ok := request.Meta[scopeMetaKey].(map[string]any); ok { | |
| 95 | + form.SessionID, form.ToolCallID = text(scope["sessionId"]), text(scope["toolCallId"]) | |
| 96 | + } | |
| 76 | 97 | names := make([]string, 0, len(schema.Properties)) |
| 77 | 98 | for name := range schema.Properties { |
| 78 | 99 | names = append(names, name) |
| @@ -173,8 +194,8 @@ func elicitationResponse(answer FormAnswer) sdk.UnstableCreateElicitationRespons | ||
| 173 | 194 | |
| 174 | 195 | // elicitationCapabilities is what initialize advertises: forms only, and |
| 175 | 196 | // only when someone answers them. |
| 176 | -func elicitationCapabilities(onForm FormHandler) *sdk.ElicitationCapabilities { | |
| 177 | - if onForm == nil { | |
| 197 | +func elicitationCapabilities(onForm FormHandler, forms bool) *sdk.ElicitationCapabilities { | |
| 198 | + if onForm == nil && !forms { | |
| 178 | 199 | return nil |
| 179 | 200 | } |
| 180 | 201 | return &sdk.ElicitationCapabilities{Form: &sdk.ElicitationFormCapabilities{}} |
| @@ -183,10 +204,20 @@ func elicitationCapabilities(onForm FormHandler) *sdk.ElicitationCapabilities { | ||
| 183 | 204 | // UnstableCreateElicitation answers an agent's elicitation/create request |
| 184 | 205 | // (the SDK finds it by this name). |
| 185 | 206 | func (c *client) UnstableCreateElicitation(ctx context.Context, request sdk.UnstableCreateElicitationRequest) (sdk.UnstableCreateElicitationResponse, error) { |
| 186 | - if c.onForm == nil || request.Form == nil { | |
| 207 | + if request.Form == nil { | |
| 187 | 208 | return elicitationResponse(FormAnswer{Action: FormCancel}), nil |
| 188 | 209 | } |
| 189 | - return elicitationResponse(c.onForm(ctx, formFrom(*request.Form))), nil | |
| 210 | + form := formFrom(*request.Form) | |
| 211 | + if c.onForm != nil { | |
| 212 | + return elicitationResponse(c.onForm(ctx, form)), nil | |
| 213 | + } | |
| 214 | + if !c.forms { | |
| 215 | + return elicitationResponse(FormAnswer{Action: FormCancel}), nil | |
| 216 | + } | |
| 217 | + if asker, ok := c.sessions.formAsker(form.SessionID); ok { | |
| 218 | + return elicitationResponse(asker.RequestForm(ctx, form)), nil | |
| 219 | + } | |
| 220 | + return elicitationResponse(FormAnswer{Action: FormCancel}), nil | |
| 190 | 221 | } |
| 191 | 222 | |
| 192 | 223 | // UnstableCompleteElicitation is the end of a "url" elicitation: nothing |
| @@ -11,11 +11,13 @@ import ( | |||
| 11 | sdk "github.com/coder/acp-go-sdk" | 11 | sdk "github.com/coder/acp-go-sdk" |
| 12 | ) | 12 | ) |
| 13 | 13 | ||
| 14 | -// Forms (issue #94): an agent may ask the user to fill in a form with ACP's | 14 | +// Forms (issues #94 and #95): an agent may ask the user to fill in a form |
| 15 | -// elicitation/create request, in its "form" mode (still marked unstable in | 15 | +// with ACP's elicitation/create request, in its "form" mode (still marked |
| 16 | -// the protocol). Sidekicks advertises clientCapabilities.elicitation.form | 16 | +// unstable in the protocol) — mini-me does for its ask_user tool. |
| 17 | -// only for a connection started with Spec.OnForm, and answers every request | 17 | +// Sidekicks advertises clientCapabilities.elicitation.form when Spec.OnForm |
| 18 | -// through it. The "url" mode is not supported: such a request is cancelled. | 18 | +// is set (every request goes to it) or Spec.Forms is true (each request goes |
| 19 | +// to the handler of its session, when it is a FormAsker). The "url" mode is | ||
| 20 | +// not supported: such a request is cancelled. | ||
| 19 | 21 | ||
| 20 | // Field types of a Form, from the JSON Schema of the request. | 22 | // Field types of a Form, from the JSON Schema of the request. |
| 21 | const ( | 23 | const ( |
| @@ -38,8 +40,24 @@ type Form struct { | |||
| 38 | // Message says what the form is for (Markdown or plain text). | 40 | // Message says what the form is for (Markdown or plain text). |
| 39 | Message string `json:"message"` | 41 | Message string `json:"message"` |
| 40 | Fields []FormField `json:"fields"` | 42 | Fields []FormField `json:"fields"` |
| 43 | + // SessionID and ToolCallID tie the form to a session and a tool call, | ||
| 44 | + // when the agent says so; "" otherwise. | ||
| 45 | + SessionID string `json:"sessionId"` | ||
| 46 | + ToolCallID string `json:"toolCallId"` | ||
| 41 | } | 47 | } |
| 42 | 48 | ||
| 49 | +// FormAsker is a SessionHandler that can show a form to the user (#95). It | ||
| 50 | +// may block until the user answers, and must return a cancel answer once | ||
| 51 | +// ctx is done. | ||
| 52 | +type FormAsker interface { | ||
| 53 | + RequestForm(ctx context.Context, form Form) FormAnswer | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +// scopeMetaKey is where mini-me parks a form's session and tool call in | ||
| 57 | +// `_meta`: the SDK drops the top-level sessionId and toolCallId that ACP | ||
| 58 | +// specifies, so mm also copies them there. | ||
| 59 | +const scopeMetaKey = "mm.elicitationScope" | ||
| 60 | + | ||
| 43 | // FormField is one question of a Form. | 61 | // FormField is one question of a Form. |
| 44 | type FormField struct { | 62 | type FormField struct { |
| 45 | // Name is the key of the answer in FormAnswer.Content. | 63 | // Name is the key of the answer in FormAnswer.Content. |
| @@ -73,6 +91,9 @@ type FormHandler func(ctx context.Context, form Form) FormAnswer | |||
| 73 | func formFrom(request sdk.UnstableCreateElicitationForm) Form { | 91 | func formFrom(request sdk.UnstableCreateElicitationForm) Form { |
| 74 | schema := request.RequestedSchema | 92 | schema := request.RequestedSchema |
| 75 | form := Form{Message: request.Message, Fields: []FormField{}} | 93 | form := Form{Message: request.Message, Fields: []FormField{}} |
| 94 | + if scope, ok := request.Meta[scopeMetaKey].(map[string]any); ok { | ||
| 95 | + form.SessionID, form.ToolCallID = text(scope["sessionId"]), text(scope["toolCallId"]) | ||
| 96 | + } | ||
| 76 | names := make([]string, 0, len(schema.Properties)) | 97 | names := make([]string, 0, len(schema.Properties)) |
| 77 | for name := range schema.Properties { | 98 | for name := range schema.Properties { |
| 78 | names = append(names, name) | 99 | names = append(names, name) |
| @@ -173,8 +194,8 @@ func elicitationResponse(answer FormAnswer) sdk.UnstableCreateElicitationRespons | |||
| 173 | 194 | ||
| 174 | // elicitationCapabilities is what initialize advertises: forms only, and | 195 | // elicitationCapabilities is what initialize advertises: forms only, and |
| 175 | // only when someone answers them. | 196 | // only when someone answers them. |
| 176 | -func elicitationCapabilities(onForm FormHandler) *sdk.ElicitationCapabilities { | 197 | +func elicitationCapabilities(onForm FormHandler, forms bool) *sdk.ElicitationCapabilities { |
| 177 | - if onForm == nil { | 198 | + if onForm == nil && !forms { |
| 178 | return nil | 199 | return nil |
| 179 | } | 200 | } |
| 180 | return &sdk.ElicitationCapabilities{Form: &sdk.ElicitationFormCapabilities{}} | 201 | return &sdk.ElicitationCapabilities{Form: &sdk.ElicitationFormCapabilities{}} |
| @@ -183,10 +204,20 @@ func elicitationCapabilities(onForm FormHandler) *sdk.ElicitationCapabilities { | |||
| 183 | // UnstableCreateElicitation answers an agent's elicitation/create request | 204 | // UnstableCreateElicitation answers an agent's elicitation/create request |
| 184 | // (the SDK finds it by this name). | 205 | // (the SDK finds it by this name). |
| 185 | func (c *client) UnstableCreateElicitation(ctx context.Context, request sdk.UnstableCreateElicitationRequest) (sdk.UnstableCreateElicitationResponse, error) { | 206 | func (c *client) UnstableCreateElicitation(ctx context.Context, request sdk.UnstableCreateElicitationRequest) (sdk.UnstableCreateElicitationResponse, error) { |
| 186 | - if c.onForm == nil || request.Form == nil { | 207 | + if request.Form == nil { |
| 187 | return elicitationResponse(FormAnswer{Action: FormCancel}), nil | 208 | return elicitationResponse(FormAnswer{Action: FormCancel}), nil |
| 188 | } | 209 | } |
| 189 | - return elicitationResponse(c.onForm(ctx, formFrom(*request.Form))), nil | 210 | + form := formFrom(*request.Form) |
| 211 | + if c.onForm != nil { | ||
| 212 | + return elicitationResponse(c.onForm(ctx, form)), nil | ||
| 213 | + } | ||
| 214 | + if !c.forms { | ||
| 215 | + return elicitationResponse(FormAnswer{Action: FormCancel}), nil | ||
| 216 | + } | ||
| 217 | + if asker, ok := c.sessions.formAsker(form.SessionID); ok { | ||
| 218 | + return elicitationResponse(asker.RequestForm(ctx, form)), nil | ||
| 219 | + } | ||
| 220 | + return elicitationResponse(FormAnswer{Action: FormCancel}), nil | ||
| 190 | } | 221 | } |
| 191 | 222 | ||
| 192 | // UnstableCompleteElicitation is the end of a "url" elicitation: nothing | 223 | // UnstableCompleteElicitation is the end of a "url" elicitation: nothing |
modified
internal/acp/forms_test.go +62 -0 | @@ -80,3 +80,65 @@ func TestWithoutOnFormNoFormIsAdvertisedAndFormsAreCancelled(t *testing.T) { | ||
| 80 | 80 | t.Fatalf("answer: %s", text) |
| 81 | 81 | } |
| 82 | 82 | } |
| 83 | + | |
| 84 | +// askingHandler is a session handler that shows forms (#95). | |
| 85 | +type askingHandler struct { | |
| 86 | + recordingHandler | |
| 87 | + forms chan acp.Form | |
| 88 | +} | |
| 89 | + | |
| 90 | +func (h *askingHandler) RequestForm(_ context.Context, form acp.Form) acp.FormAnswer { | |
| 91 | + h.forms <- form | |
| 92 | + return acp.FormAnswer{Action: acp.FormAccept, Content: map[string]any{"name": "from " + form.SessionID}} | |
| 93 | +} | |
| 94 | + | |
| 95 | +func TestWithFormsEachFormGoesToItsSessionsHandler(t *testing.T) { | |
| 96 | + spec := fakeSpec(t, "ready") | |
| 97 | + spec.Forms = true | |
| 98 | + conn, err := acp.Start(context.Background(), spec, acp.Options{}) | |
| 99 | + if err != nil { | |
| 100 | + t.Fatal(err) | |
| 101 | + } | |
| 102 | + defer func() { _ = conn.Close(context.Background()) }() | |
| 103 | + handler := &askingHandler{forms: make(chan acp.Form, 2)} | |
| 104 | + id, err := conn.NewSession(context.Background(), t.TempDir(), handler) | |
| 105 | + if err != nil { | |
| 106 | + t.Fatal(err) | |
| 107 | + } | |
| 108 | + for _, prompt := range []string{"form-scoped", "form"} { | |
| 109 | + if _, err := conn.Prompt(context.Background(), id, prompt); err != nil { | |
| 110 | + t.Fatal(err) | |
| 111 | + } | |
| 112 | + } | |
| 113 | + scoped, unscoped := <-handler.forms, <-handler.forms | |
| 114 | + if scoped.SessionID != id || scoped.ToolCallID != "call_7" || unscoped.SessionID != "" { | |
| 115 | + t.Fatalf("scopes: %+v / %+v", scoped, unscoped) | |
| 116 | + } | |
| 117 | + var text strings.Builder | |
| 118 | + for _, update := range handler.ofKind(acp.UpdateMessage) { | |
| 119 | + text.WriteString(update.Text + "|") | |
| 120 | + } | |
| 121 | + // The unscoped form went to the only session with a prompt in flight. | |
| 122 | + want := `advertised=true accept={"name":"from s-1"}|advertised=true accept={"name":"from "}|` | |
| 123 | + if text.String() != want { | |
| 124 | + t.Fatalf("answers:\n got %s\nwant %s", text.String(), want) | |
| 125 | + } | |
| 126 | +} | |
| 127 | + | |
| 128 | +func TestAFormForAHandlerThatCannotShowItIsCancelled(t *testing.T) { | |
| 129 | + spec := fakeSpec(t, "ready") | |
| 130 | + spec.Forms = true | |
| 131 | + conn, err := acp.Start(context.Background(), spec, acp.Options{}) | |
| 132 | + if err != nil { | |
| 133 | + t.Fatal(err) | |
| 134 | + } | |
| 135 | + defer func() { _ = conn.Close(context.Background()) }() | |
| 136 | + handler := &recordingHandler{} | |
| 137 | + id, err := conn.NewSession(context.Background(), t.TempDir(), handler) | |
| 138 | + if err != nil { | |
| 139 | + t.Fatal(err) | |
| 140 | + } | |
| 141 | + if text := answerText(t, conn, id, handler); text != "advertised=true cancel" { | |
| 142 | + t.Fatalf("answer: %s", text) | |
| 143 | + } | |
| 144 | +} | |
| @@ -80,3 +80,65 @@ func TestWithoutOnFormNoFormIsAdvertisedAndFormsAreCancelled(t *testing.T) { | |||
| 80 | t.Fatalf("answer: %s", text) | 80 | t.Fatalf("answer: %s", text) |
| 81 | } | 81 | } |
| 82 | } | 82 | } |
| 83 | + | ||
| 84 | +// askingHandler is a session handler that shows forms (#95). | ||
| 85 | +type askingHandler struct { | ||
| 86 | + recordingHandler | ||
| 87 | + forms chan acp.Form | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +func (h *askingHandler) RequestForm(_ context.Context, form acp.Form) acp.FormAnswer { | ||
| 91 | + h.forms <- form | ||
| 92 | + return acp.FormAnswer{Action: acp.FormAccept, Content: map[string]any{"name": "from " + form.SessionID}} | ||
| 93 | +} | ||
| 94 | + | ||
| 95 | +func TestWithFormsEachFormGoesToItsSessionsHandler(t *testing.T) { | ||
| 96 | + spec := fakeSpec(t, "ready") | ||
| 97 | + spec.Forms = true | ||
| 98 | + conn, err := acp.Start(context.Background(), spec, acp.Options{}) | ||
| 99 | + if err != nil { | ||
| 100 | + t.Fatal(err) | ||
| 101 | + } | ||
| 102 | + defer func() { _ = conn.Close(context.Background()) }() | ||
| 103 | + handler := &askingHandler{forms: make(chan acp.Form, 2)} | ||
| 104 | + id, err := conn.NewSession(context.Background(), t.TempDir(), handler) | ||
| 105 | + if err != nil { | ||
| 106 | + t.Fatal(err) | ||
| 107 | + } | ||
| 108 | + for _, prompt := range []string{"form-scoped", "form"} { | ||
| 109 | + if _, err := conn.Prompt(context.Background(), id, prompt); err != nil { | ||
| 110 | + t.Fatal(err) | ||
| 111 | + } | ||
| 112 | + } | ||
| 113 | + scoped, unscoped := <-handler.forms, <-handler.forms | ||
| 114 | + if scoped.SessionID != id || scoped.ToolCallID != "call_7" || unscoped.SessionID != "" { | ||
| 115 | + t.Fatalf("scopes: %+v / %+v", scoped, unscoped) | ||
| 116 | + } | ||
| 117 | + var text strings.Builder | ||
| 118 | + for _, update := range handler.ofKind(acp.UpdateMessage) { | ||
| 119 | + text.WriteString(update.Text + "|") | ||
| 120 | + } | ||
| 121 | + // The unscoped form went to the only session with a prompt in flight. | ||
| 122 | + want := `advertised=true accept={"name":"from s-1"}|advertised=true accept={"name":"from "}|` | ||
| 123 | + if text.String() != want { | ||
| 124 | + t.Fatalf("answers:\n got %s\nwant %s", text.String(), want) | ||
| 125 | + } | ||
| 126 | +} | ||
| 127 | + | ||
| 128 | +func TestAFormForAHandlerThatCannotShowItIsCancelled(t *testing.T) { | ||
| 129 | + spec := fakeSpec(t, "ready") | ||
| 130 | + spec.Forms = true | ||
| 131 | + conn, err := acp.Start(context.Background(), spec, acp.Options{}) | ||
| 132 | + if err != nil { | ||
| 133 | + t.Fatal(err) | ||
| 134 | + } | ||
| 135 | + defer func() { _ = conn.Close(context.Background()) }() | ||
| 136 | + handler := &recordingHandler{} | ||
| 137 | + id, err := conn.NewSession(context.Background(), t.TempDir(), handler) | ||
| 138 | + if err != nil { | ||
| 139 | + t.Fatal(err) | ||
| 140 | + } | ||
| 141 | + if text := answerText(t, conn, id, handler); text != "advertised=true cancel" { | ||
| 142 | + t.Fatalf("answer: %s", text) | ||
| 143 | + } | ||
| 144 | +} | ||
modified
internal/acp/session.go +30 -1 | @@ -166,6 +166,8 @@ type Attachment struct { | ||
| 166 | 166 | // An error is either a transport problem or an error the agent returned |
| 167 | 167 | // instead of a stop reason (mm does so when a tool loop goes on too long). |
| 168 | 168 | func (c *Conn) Prompt(ctx context.Context, sessionID, text string, attachments ...Attachment) (TurnResult, error) { |
| 169 | + c.sessions.turn(sessionID, 1) | |
| 170 | + defer c.sessions.turn(sessionID, -1) | |
| 169 | 171 | response, err := c.connection.Prompt(ctx, sdk.PromptRequest{ |
| 170 | 172 | SessionId: sdk.SessionId(sessionID), |
| 171 | 173 | Prompt: PromptBlocks(c.info, text, attachments), |
| @@ -256,12 +258,15 @@ type sessions struct { | ||
| 256 | 258 | mu sync.Mutex |
| 257 | 259 | handlers map[string]SessionHandler |
| 258 | 260 | early map[string][]Update |
| 261 | + // turns counts the prompts in flight by session, to find the session | |
| 262 | + // of a form that does not name one. | |
| 263 | + turns map[string]int | |
| 259 | 264 | } |
| 260 | 265 | |
| 261 | 266 | const maxEarlyUpdates = 100 |
| 262 | 267 | |
| 263 | 268 | func newSessions() *sessions { |
| 264 | - return &sessions{handlers: map[string]SessionHandler{}, early: map[string][]Update{}} | |
| 269 | + return &sessions{handlers: map[string]SessionHandler{}, early: map[string][]Update{}, turns: map[string]int{}} | |
| 265 | 270 | } |
| 266 | 271 | |
| 267 | 272 | func (s *sessions) register(id string, handler SessionHandler) { |
| @@ -281,6 +286,30 @@ func (s *sessions) handler(id string) SessionHandler { | ||
| 281 | 286 | return s.handlers[id] |
| 282 | 287 | } |
| 283 | 288 | |
| 289 | +// turn marks a prompt of session id in flight (+1) or over (-1). | |
| 290 | +func (s *sessions) turn(id string, delta int) { | |
| 291 | + s.mu.Lock() | |
| 292 | + defer s.mu.Unlock() | |
| 293 | + if s.turns[id] += delta; s.turns[id] <= 0 { | |
| 294 | + delete(s.turns, id) | |
| 295 | + } | |
| 296 | +} | |
| 297 | + | |
| 298 | +// formAsker is the handler of session id that can show a form. A form that | |
| 299 | +// names no session goes to the only session with a prompt in flight — an | |
| 300 | +// agent answers in one channel at a time (ADR 0006). | |
| 301 | +func (s *sessions) formAsker(id string) (FormAsker, bool) { | |
| 302 | + s.mu.Lock() | |
| 303 | + defer s.mu.Unlock() | |
| 304 | + if id == "" && len(s.turns) == 1 { | |
| 305 | + for only := range s.turns { | |
| 306 | + id = only | |
| 307 | + } | |
| 308 | + } | |
| 309 | + asker, ok := s.handlers[id].(FormAsker) | |
| 310 | + return asker, ok | |
| 311 | +} | |
| 312 | + | |
| 284 | 313 | func (s *sessions) deliver(id string, update Update) { |
| 285 | 314 | s.mu.Lock() |
| 286 | 315 | handler := s.handlers[id] |
| @@ -166,6 +166,8 @@ type Attachment struct { | |||
| 166 | // An error is either a transport problem or an error the agent returned | 166 | // An error is either a transport problem or an error the agent returned |
| 167 | // instead of a stop reason (mm does so when a tool loop goes on too long). | 167 | // instead of a stop reason (mm does so when a tool loop goes on too long). |
| 168 | func (c *Conn) Prompt(ctx context.Context, sessionID, text string, attachments ...Attachment) (TurnResult, error) { | 168 | func (c *Conn) Prompt(ctx context.Context, sessionID, text string, attachments ...Attachment) (TurnResult, error) { |
| 169 | + c.sessions.turn(sessionID, 1) | ||
| 170 | + defer c.sessions.turn(sessionID, -1) | ||
| 169 | response, err := c.connection.Prompt(ctx, sdk.PromptRequest{ | 171 | response, err := c.connection.Prompt(ctx, sdk.PromptRequest{ |
| 170 | SessionId: sdk.SessionId(sessionID), | 172 | SessionId: sdk.SessionId(sessionID), |
| 171 | Prompt: PromptBlocks(c.info, text, attachments), | 173 | Prompt: PromptBlocks(c.info, text, attachments), |
| @@ -256,12 +258,15 @@ type sessions struct { | |||
| 256 | mu sync.Mutex | 258 | mu sync.Mutex |
| 257 | handlers map[string]SessionHandler | 259 | handlers map[string]SessionHandler |
| 258 | early map[string][]Update | 260 | early map[string][]Update |
| 261 | + // turns counts the prompts in flight by session, to find the session | ||
| 262 | + // of a form that does not name one. | ||
| 263 | + turns map[string]int | ||
| 259 | } | 264 | } |
| 260 | 265 | ||
| 261 | const maxEarlyUpdates = 100 | 266 | const maxEarlyUpdates = 100 |
| 262 | 267 | ||
| 263 | func newSessions() *sessions { | 268 | func newSessions() *sessions { |
| 264 | - return &sessions{handlers: map[string]SessionHandler{}, early: map[string][]Update{}} | 269 | + return &sessions{handlers: map[string]SessionHandler{}, early: map[string][]Update{}, turns: map[string]int{}} |
| 265 | } | 270 | } |
| 266 | 271 | ||
| 267 | func (s *sessions) register(id string, handler SessionHandler) { | 272 | func (s *sessions) register(id string, handler SessionHandler) { |
| @@ -281,6 +286,30 @@ func (s *sessions) handler(id string) SessionHandler { | |||
| 281 | return s.handlers[id] | 286 | return s.handlers[id] |
| 282 | } | 287 | } |
| 283 | 288 | ||
| 289 | +// turn marks a prompt of session id in flight (+1) or over (-1). | ||
| 290 | +func (s *sessions) turn(id string, delta int) { | ||
| 291 | + s.mu.Lock() | ||
| 292 | + defer s.mu.Unlock() | ||
| 293 | + if s.turns[id] += delta; s.turns[id] <= 0 { | ||
| 294 | + delete(s.turns, id) | ||
| 295 | + } | ||
| 296 | +} | ||
| 297 | + | ||
| 298 | +// formAsker is the handler of session id that can show a form. A form that | ||
| 299 | +// names no session goes to the only session with a prompt in flight — an | ||
| 300 | +// agent answers in one channel at a time (ADR 0006). | ||
| 301 | +func (s *sessions) formAsker(id string) (FormAsker, bool) { | ||
| 302 | + s.mu.Lock() | ||
| 303 | + defer s.mu.Unlock() | ||
| 304 | + if id == "" && len(s.turns) == 1 { | ||
| 305 | + for only := range s.turns { | ||
| 306 | + id = only | ||
| 307 | + } | ||
| 308 | + } | ||
| 309 | + asker, ok := s.handlers[id].(FormAsker) | ||
| 310 | + return asker, ok | ||
| 311 | +} | ||
| 312 | + | ||
| 284 | func (s *sessions) deliver(id string, update Update) { | 313 | func (s *sessions) deliver(id string, update Update) { |
| 285 | s.mu.Lock() | 314 | s.mu.Lock() |
| 286 | handler := s.handlers[id] | 315 | handler := s.handlers[id] |
modified
internal/agents/manager.go +3 -0 | @@ -618,6 +618,9 @@ func (m *Manager) specFor(definition config.Agent) acp.Spec { | ||
| 618 | 618 | spec := acp.Spec{ |
| 619 | 619 | Name: definition.Name, Command: definition.Command, Args: definition.Args, |
| 620 | 620 | Env: definition.Env, Dir: definition.Workspace, ClientVersion: m.options.ClientVersion, |
| 621 | + // The forms an agent asks (mini-me's ask_user, issue #95) are shown | |
| 622 | + // in the conversation of their session. | |
| 623 | + Forms: true, | |
| 621 | 624 | } |
| 622 | 625 | if m.options.Tools != nil { |
| 623 | 626 | spec.Tools = m.options.Tools(definition) |
| @@ -618,6 +618,9 @@ func (m *Manager) specFor(definition config.Agent) acp.Spec { | |||
| 618 | spec := acp.Spec{ | 618 | spec := acp.Spec{ |
| 619 | Name: definition.Name, Command: definition.Command, Args: definition.Args, | 619 | Name: definition.Name, Command: definition.Command, Args: definition.Args, |
| 620 | Env: definition.Env, Dir: definition.Workspace, ClientVersion: m.options.ClientVersion, | 620 | Env: definition.Env, Dir: definition.Workspace, ClientVersion: m.options.ClientVersion, |
| 621 | + // The forms an agent asks (mini-me's ask_user, issue #95) are shown | ||
| 622 | + // in the conversation of their session. | ||
| 623 | + Forms: true, | ||
| 621 | } | 624 | } |
| 622 | if m.options.Tools != nil { | 625 | if m.options.Tools != nil { |
| 623 | spec.Tools = m.options.Tools(definition) | 626 | spec.Tools = m.options.Tools(definition) |
modified
internal/app/services.go +6 -0 | @@ -112,6 +112,12 @@ func (s *ChannelService) AnswerPermission(id, optionID string) error { | ||
| 112 | 112 | return s.Core.Channels().AnswerPermission(id, optionID) |
| 113 | 113 | } |
| 114 | 114 | |
| 115 | +// AnswerForm gives the user's answer to a form an agent asked (issue #95): | |
| 116 | +// action accept with content (values by field name), decline or cancel. | |
| 117 | +func (s *ChannelService) AnswerForm(id string, answer acp.FormAnswer) error { | |
| 118 | + return s.Core.Channels().AnswerForm(id, answer) | |
| 119 | +} | |
| 120 | + | |
| 115 | 121 | // Conversation returns the last messages and the state of a channel. |
| 116 | 122 | func (s *ChannelService) Conversation(id string) (channels.Conversation, error) { |
| 117 | 123 | return s.Core.Channels().Conversation(id) |
| @@ -112,6 +112,12 @@ func (s *ChannelService) AnswerPermission(id, optionID string) error { | |||
| 112 | return s.Core.Channels().AnswerPermission(id, optionID) | 112 | return s.Core.Channels().AnswerPermission(id, optionID) |
| 113 | } | 113 | } |
| 114 | 114 | ||
| 115 | +// AnswerForm gives the user's answer to a form an agent asked (issue #95): | ||
| 116 | +// action accept with content (values by field name), decline or cancel. | ||
| 117 | +func (s *ChannelService) AnswerForm(id string, answer acp.FormAnswer) error { | ||
| 118 | + return s.Core.Channels().AnswerForm(id, answer) | ||
| 119 | +} | ||
| 120 | + | ||
| 115 | // Conversation returns the last messages and the state of a channel. | 121 | // Conversation returns the last messages and the state of a channel. |
| 116 | func (s *ChannelService) Conversation(id string) (channels.Conversation, error) { | 122 | func (s *ChannelService) Conversation(id string) (channels.Conversation, error) { |
| 117 | return s.Core.Channels().Conversation(id) | 123 | return s.Core.Channels().Conversation(id) |
modified
internal/channels/channels.go +33 -3 | @@ -140,6 +140,16 @@ type Permission struct { | ||
| 140 | 140 | Rejections int `json:"rejections"` |
| 141 | 141 | } |
| 142 | 142 | |
| 143 | +// FormRequest is a form an agent asks the user to fill in, waiting for the | |
| 144 | +// answer (issue #95: mini-me's ask_user). | |
| 145 | +type FormRequest struct { | |
| 146 | + ID string `json:"id"` | |
| 147 | + Channel string `json:"channel"` | |
| 148 | + Agent string `json:"agent"` | |
| 149 | + MessageID string `json:"messageId"` | |
| 150 | + Form acp.Form `json:"form"` | |
| 151 | +} | |
| 152 | + | |
| 143 | 153 | // Channel is a channel as the interface lists it. |
| 144 | 154 | type Channel struct { |
| 145 | 155 | ID string `json:"id"` |
| @@ -166,6 +176,8 @@ type Conversation struct { | ||
| 166 | 176 | // Usage is the context window use of each member, by agent name. |
| 167 | 177 | Usage map[string]acp.Usage `json:"usage"` |
| 168 | 178 | Permissions []Permission `json:"permissions"` |
| 179 | + // Forms are the forms waiting for an answer (issue #95). | |
| 180 | + Forms []FormRequest `json:"forms"` | |
| 169 | 181 | } |
| 170 | 182 | |
| 171 | 183 | // Event payloads, registered with Wails in main.go. |
| @@ -209,6 +221,12 @@ type PermissionResolvedPayload struct { | ||
| 209 | 221 | Channel string `json:"channel"` |
| 210 | 222 | } |
| 211 | 223 | |
| 224 | +// FormResolvedPayload says a form no longer waits. | |
| 225 | +type FormResolvedPayload struct { | |
| 226 | + ID string `json:"id"` | |
| 227 | + Channel string `json:"channel"` | |
| 228 | +} | |
| 229 | + | |
| 212 | 230 | // UsagePayload is the context window use of an agent in a channel. |
| 213 | 231 | type UsagePayload struct { |
| 214 | 232 | Channel string `json:"channel"` |
| @@ -270,6 +288,7 @@ type Manager struct { | ||
| 270 | 288 | channels map[string]*channel |
| 271 | 289 | order []string // channel ids, oldest first |
| 272 | 290 | permissions map[string]*pendingPermission |
| 291 | + forms map[string]*pendingForm | |
| 273 | 292 | commands map[string][]acp.Command |
| 274 | 293 | // turns lets one agent answer one channel at a time: a local model |
| 275 | 294 | // serving two prompts at once would only be slower, and use more memory. |
| @@ -324,6 +343,12 @@ type pending struct { | ||
| 324 | 343 | route Route |
| 325 | 344 | } |
| 326 | 345 | |
| 346 | +type pendingForm struct { | |
| 347 | + request FormRequest | |
| 348 | + channel *channel | |
| 349 | + answer chan acp.FormAnswer | |
| 350 | +} | |
| 351 | + | |
| 327 | 352 | type pendingPermission struct { |
| 328 | 353 | permission Permission |
| 329 | 354 | channel *channel |
| @@ -341,7 +366,7 @@ func NewManager(source AgentSource, db *store.Store, options Options) (*Manager, | ||
| 341 | 366 | } |
| 342 | 367 | m := &Manager{ |
| 343 | 368 | agents: source, db: db, emitter: options.Emitter, now: options.Now, files: options.Files, handoffs: options.Handoffs, parallel: options.Parallel, |
| 344 | - channels: map[string]*channel{}, permissions: map[string]*pendingPermission{}, | |
| 369 | + channels: map[string]*channel{}, permissions: map[string]*pendingPermission{}, forms: map[string]*pendingForm{}, | |
| 345 | 370 | commands: map[string][]acp.Command{}, turns: map[string]chan struct{}{}, |
| 346 | 371 | } |
| 347 | 372 | stored, err := db.Channels() |
| @@ -611,7 +636,7 @@ func (m *Manager) commandsKnown(agent string) bool { | ||
| 611 | 636 | } |
| 612 | 637 | |
| 613 | 638 | // Conversation returns what the interface shows of a channel: its last |
| 614 | -// messages, its state and its pending permission requests. | |
| 639 | +// messages, its state, its pending permission requests and forms. | |
| 615 | 640 | func (m *Manager) Conversation(id string) (Conversation, error) { |
| 616 | 641 | m.mu.Lock() |
| 617 | 642 | defer m.mu.Unlock() |
| @@ -622,7 +647,7 @@ func (m *Manager) Conversation(id string) (Conversation, error) { | ||
| 622 | 647 | if err := m.load(ch); err != nil { |
| 623 | 648 | return Conversation{}, err |
| 624 | 649 | } |
| 625 | - view := Conversation{Channel: ch.view(), Messages: []Message{}, More: ch.more, Busy: ch.busy, Queued: len(ch.queue), Usage: map[string]acp.Usage{}, Permissions: []Permission{}} | |
| 650 | + view := Conversation{Channel: ch.view(), Messages: []Message{}, More: ch.more, Busy: ch.busy, Queued: len(ch.queue), Usage: map[string]acp.Usage{}, Permissions: []Permission{}, Forms: []FormRequest{}} | |
| 626 | 651 | for _, message := range ch.messages { |
| 627 | 652 | view.Messages = append(view.Messages, copyMessage(message)) |
| 628 | 653 | } |
| @@ -635,6 +660,11 @@ func (m *Manager) Conversation(id string) (Conversation, error) { | ||
| 635 | 660 | view.Permissions = append(view.Permissions, pending.permission) |
| 636 | 661 | } |
| 637 | 662 | } |
| 663 | + for _, pending := range m.forms { | |
| 664 | + if pending.channel == ch { | |
| 665 | + view.Forms = append(view.Forms, pending.request) | |
| 666 | + } | |
| 667 | + } | |
| 638 | 668 | return view, nil |
| 639 | 669 | } |
| 640 | 670 | |
| @@ -140,6 +140,16 @@ type Permission struct { | |||
| 140 | Rejections int `json:"rejections"` | 140 | Rejections int `json:"rejections"` |
| 141 | } | 141 | } |
| 142 | 142 | ||
| 143 | +// FormRequest is a form an agent asks the user to fill in, waiting for the | ||
| 144 | +// answer (issue #95: mini-me's ask_user). | ||
| 145 | +type FormRequest struct { | ||
| 146 | + ID string `json:"id"` | ||
| 147 | + Channel string `json:"channel"` | ||
| 148 | + Agent string `json:"agent"` | ||
| 149 | + MessageID string `json:"messageId"` | ||
| 150 | + Form acp.Form `json:"form"` | ||
| 151 | +} | ||
| 152 | + | ||
| 143 | // Channel is a channel as the interface lists it. | 153 | // Channel is a channel as the interface lists it. |
| 144 | type Channel struct { | 154 | type Channel struct { |
| 145 | ID string `json:"id"` | 155 | ID string `json:"id"` |
| @@ -166,6 +176,8 @@ type Conversation struct { | |||
| 166 | // Usage is the context window use of each member, by agent name. | 176 | // Usage is the context window use of each member, by agent name. |
| 167 | Usage map[string]acp.Usage `json:"usage"` | 177 | Usage map[string]acp.Usage `json:"usage"` |
| 168 | Permissions []Permission `json:"permissions"` | 178 | Permissions []Permission `json:"permissions"` |
| 179 | + // Forms are the forms waiting for an answer (issue #95). | ||
| 180 | + Forms []FormRequest `json:"forms"` | ||
| 169 | } | 181 | } |
| 170 | 182 | ||
| 171 | // Event payloads, registered with Wails in main.go. | 183 | // Event payloads, registered with Wails in main.go. |
| @@ -209,6 +221,12 @@ type PermissionResolvedPayload struct { | |||
| 209 | Channel string `json:"channel"` | 221 | Channel string `json:"channel"` |
| 210 | } | 222 | } |
| 211 | 223 | ||
| 224 | +// FormResolvedPayload says a form no longer waits. | ||
| 225 | +type FormResolvedPayload struct { | ||
| 226 | + ID string `json:"id"` | ||
| 227 | + Channel string `json:"channel"` | ||
| 228 | +} | ||
| 229 | + | ||
| 212 | // UsagePayload is the context window use of an agent in a channel. | 230 | // UsagePayload is the context window use of an agent in a channel. |
| 213 | type UsagePayload struct { | 231 | type UsagePayload struct { |
| 214 | Channel string `json:"channel"` | 232 | Channel string `json:"channel"` |
| @@ -270,6 +288,7 @@ type Manager struct { | |||
| 270 | channels map[string]*channel | 288 | channels map[string]*channel |
| 271 | order []string // channel ids, oldest first | 289 | order []string // channel ids, oldest first |
| 272 | permissions map[string]*pendingPermission | 290 | permissions map[string]*pendingPermission |
| 291 | + forms map[string]*pendingForm | ||
| 273 | commands map[string][]acp.Command | 292 | commands map[string][]acp.Command |
| 274 | // turns lets one agent answer one channel at a time: a local model | 293 | // turns lets one agent answer one channel at a time: a local model |
| 275 | // serving two prompts at once would only be slower, and use more memory. | 294 | // serving two prompts at once would only be slower, and use more memory. |
| @@ -324,6 +343,12 @@ type pending struct { | |||
| 324 | route Route | 343 | route Route |
| 325 | } | 344 | } |
| 326 | 345 | ||
| 346 | +type pendingForm struct { | ||
| 347 | + request FormRequest | ||
| 348 | + channel *channel | ||
| 349 | + answer chan acp.FormAnswer | ||
| 350 | +} | ||
| 351 | + | ||
| 327 | type pendingPermission struct { | 352 | type pendingPermission struct { |
| 328 | permission Permission | 353 | permission Permission |
| 329 | channel *channel | 354 | channel *channel |
| @@ -341,7 +366,7 @@ func NewManager(source AgentSource, db *store.Store, options Options) (*Manager, | |||
| 341 | } | 366 | } |
| 342 | m := &Manager{ | 367 | m := &Manager{ |
| 343 | agents: source, db: db, emitter: options.Emitter, now: options.Now, files: options.Files, handoffs: options.Handoffs, parallel: options.Parallel, | 368 | agents: source, db: db, emitter: options.Emitter, now: options.Now, files: options.Files, handoffs: options.Handoffs, parallel: options.Parallel, |
| 344 | - channels: map[string]*channel{}, permissions: map[string]*pendingPermission{}, | 369 | + channels: map[string]*channel{}, permissions: map[string]*pendingPermission{}, forms: map[string]*pendingForm{}, |
| 345 | commands: map[string][]acp.Command{}, turns: map[string]chan struct{}{}, | 370 | commands: map[string][]acp.Command{}, turns: map[string]chan struct{}{}, |
| 346 | } | 371 | } |
| 347 | stored, err := db.Channels() | 372 | stored, err := db.Channels() |
| @@ -611,7 +636,7 @@ func (m *Manager) commandsKnown(agent string) bool { | |||
| 611 | } | 636 | } |
| 612 | 637 | ||
| 613 | // Conversation returns what the interface shows of a channel: its last | 638 | // Conversation returns what the interface shows of a channel: its last |
| 614 | -// messages, its state and its pending permission requests. | 639 | +// messages, its state, its pending permission requests and forms. |
| 615 | func (m *Manager) Conversation(id string) (Conversation, error) { | 640 | func (m *Manager) Conversation(id string) (Conversation, error) { |
| 616 | m.mu.Lock() | 641 | m.mu.Lock() |
| 617 | defer m.mu.Unlock() | 642 | defer m.mu.Unlock() |
| @@ -622,7 +647,7 @@ func (m *Manager) Conversation(id string) (Conversation, error) { | |||
| 622 | if err := m.load(ch); err != nil { | 647 | if err := m.load(ch); err != nil { |
| 623 | return Conversation{}, err | 648 | return Conversation{}, err |
| 624 | } | 649 | } |
| 625 | - view := Conversation{Channel: ch.view(), Messages: []Message{}, More: ch.more, Busy: ch.busy, Queued: len(ch.queue), Usage: map[string]acp.Usage{}, Permissions: []Permission{}} | 650 | + view := Conversation{Channel: ch.view(), Messages: []Message{}, More: ch.more, Busy: ch.busy, Queued: len(ch.queue), Usage: map[string]acp.Usage{}, Permissions: []Permission{}, Forms: []FormRequest{}} |
| 626 | for _, message := range ch.messages { | 651 | for _, message := range ch.messages { |
| 627 | view.Messages = append(view.Messages, copyMessage(message)) | 652 | view.Messages = append(view.Messages, copyMessage(message)) |
| 628 | } | 653 | } |
| @@ -635,6 +660,11 @@ func (m *Manager) Conversation(id string) (Conversation, error) { | |||
| 635 | view.Permissions = append(view.Permissions, pending.permission) | 660 | view.Permissions = append(view.Permissions, pending.permission) |
| 636 | } | 661 | } |
| 637 | } | 662 | } |
| 663 | + for _, pending := range m.forms { | ||
| 664 | + if pending.channel == ch { | ||
| 665 | + view.Forms = append(view.Forms, pending.request) | ||
| 666 | + } | ||
| 667 | + } | ||
| 638 | return view, nil | 668 | return view, nil |
| 639 | } | 669 | } |
| 640 | 670 | ||
added
internal/channels/forms_test.go +76 -0 | new file mode 100644 | ||
| @@ -0,0 +1,76 @@ | ||
| 1 | +// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE | |
| 2 | + | |
| 3 | +package channels_test | |
| 4 | + | |
| 5 | +import ( | |
| 6 | + "context" | |
| 7 | + "errors" | |
| 8 | + "testing" | |
| 9 | + | |
| 10 | + "git.rickub.com/bots-garden/sidekicks/internal/acp" | |
| 11 | + "git.rickub.com/bots-garden/sidekicks/internal/channels" | |
| 12 | + "git.rickub.com/bots-garden/sidekicks/internal/events" | |
| 13 | +) | |
| 14 | + | |
| 15 | +// ask is mini-me's ask_user in short: one text question, then the answer | |
| 16 | +// written back in the agent's message. | |
| 17 | +func ask(ctx context.Context, h acp.SessionHandler) (acp.TurnResult, error) { | |
| 18 | + asker, ok := h.(acp.FormAsker) | |
| 19 | + if !ok { | |
| 20 | + return acp.TurnResult{}, errors.New("the handler cannot show forms") | |
| 21 | + } | |
| 22 | + h.Update(acp.Update{Kind: acp.UpdateMessage, Text: "One question: "}) | |
| 23 | + answer := asker.RequestForm(ctx, acp.Form{Message: "ask_user", Fields: []acp.FormField{{Name: "q1", Title: "Your city?", Type: acp.FieldText, Required: true}}}) | |
| 24 | + switch answer.Action { | |
| 25 | + case acp.FormAccept: | |
| 26 | + h.Update(acp.Update{Kind: acp.UpdateMessage, Text: "you live in " + answer.Content["q1"].(string)}) | |
| 27 | + default: | |
| 28 | + h.Update(acp.Update{Kind: acp.UpdateMessage, Text: answer.Action}) | |
| 29 | + } | |
| 30 | + return acp.TurnResult{StopReason: "end_turn"}, nil | |
| 31 | +} | |
| 32 | + | |
| 33 | +func TestAFormIsShownInTheConversationAndAnswered(t *testing.T) { | |
| 34 | + f := setup(t, map[string]script{"ask": ask}) | |
| 35 | + direct, _ := f.manager.Direct("alice") | |
| 36 | + f.send(t, direct.ID, "ask") | |
| 37 | + waitFor(t, func() bool { return len(f.recorder.Named(events.FormRequested)) == 1 }) | |
| 38 | + request := f.recorder.Named(events.FormRequested)[0].(channels.FormRequest) | |
| 39 | + if request.Channel != direct.ID || request.Agent != "alice" || request.MessageID == "" || request.Form.Fields[0].Title != "Your city?" { | |
| 40 | + t.Fatalf("request: %+v", request) | |
| 41 | + } | |
| 42 | + if view, _ := f.manager.Conversation(direct.ID); len(view.Forms) != 1 || view.Forms[0].ID != request.ID { | |
| 43 | + t.Fatalf("the form should wait in the conversation: %+v", view.Forms) | |
| 44 | + } | |
| 45 | + if err := f.manager.AnswerForm(request.ID, acp.FormAnswer{Action: "maybe"}); err == nil { | |
| 46 | + t.Fatal("an unknown action must be refused") | |
| 47 | + } | |
| 48 | + if err := f.manager.AnswerForm(request.ID, acp.FormAnswer{Action: acp.FormAccept, Content: map[string]any{"q1": "Lyon"}}); err != nil { | |
| 49 | + t.Fatal(err) | |
| 50 | + } | |
| 51 | + view := f.idle(t, direct.ID, 2) | |
| 52 | + if text := view.Messages[1].Parts[0].Text; text != "One question: you live in Lyon" { | |
| 53 | + t.Fatalf("answer: %q", text) | |
| 54 | + } | |
| 55 | + if len(view.Forms) != 0 || len(f.recorder.Named(events.FormResolved)) != 1 { | |
| 56 | + t.Fatal("the form should be resolved") | |
| 57 | + } | |
| 58 | + if err := f.manager.AnswerForm(request.ID, acp.FormAnswer{Action: acp.FormAccept}); err == nil { | |
| 59 | + t.Fatal("a form answered twice must be refused") | |
| 60 | + } | |
| 61 | +} | |
| 62 | + | |
| 63 | +func TestStopCancelsAWaitingForm(t *testing.T) { | |
| 64 | + f := setup(t, map[string]script{"ask": ask}) | |
| 65 | + direct, _ := f.manager.Direct("alice") | |
| 66 | + f.send(t, direct.ID, "ask") | |
| 67 | + waitFor(t, func() bool { return len(f.recorder.Named(events.FormRequested)) == 1 }) | |
| 68 | + f.manager.Cancel(direct.ID) | |
| 69 | + view := f.idle(t, direct.ID, 2) | |
| 70 | + if text := view.Messages[1].Parts[0].Text; text != "One question: cancel" { | |
| 71 | + t.Fatalf("answer: %q", text) | |
| 72 | + } | |
| 73 | + if len(f.recorder.Named(events.FormResolved)) != 1 { | |
| 74 | + t.Fatal("the form should be resolved") | |
| 75 | + } | |
| 76 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,76 @@ | |||
| 1 | +// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE | ||
| 2 | + | ||
| 3 | +package channels_test | ||
| 4 | + | ||
| 5 | +import ( | ||
| 6 | + "context" | ||
| 7 | + "errors" | ||
| 8 | + "testing" | ||
| 9 | + | ||
| 10 | + "git.rickub.com/bots-garden/sidekicks/internal/acp" | ||
| 11 | + "git.rickub.com/bots-garden/sidekicks/internal/channels" | ||
| 12 | + "git.rickub.com/bots-garden/sidekicks/internal/events" | ||
| 13 | +) | ||
| 14 | + | ||
| 15 | +// ask is mini-me's ask_user in short: one text question, then the answer | ||
| 16 | +// written back in the agent's message. | ||
| 17 | +func ask(ctx context.Context, h acp.SessionHandler) (acp.TurnResult, error) { | ||
| 18 | + asker, ok := h.(acp.FormAsker) | ||
| 19 | + if !ok { | ||
| 20 | + return acp.TurnResult{}, errors.New("the handler cannot show forms") | ||
| 21 | + } | ||
| 22 | + h.Update(acp.Update{Kind: acp.UpdateMessage, Text: "One question: "}) | ||
| 23 | + answer := asker.RequestForm(ctx, acp.Form{Message: "ask_user", Fields: []acp.FormField{{Name: "q1", Title: "Your city?", Type: acp.FieldText, Required: true}}}) | ||
| 24 | + switch answer.Action { | ||
| 25 | + case acp.FormAccept: | ||
| 26 | + h.Update(acp.Update{Kind: acp.UpdateMessage, Text: "you live in " + answer.Content["q1"].(string)}) | ||
| 27 | + default: | ||
| 28 | + h.Update(acp.Update{Kind: acp.UpdateMessage, Text: answer.Action}) | ||
| 29 | + } | ||
| 30 | + return acp.TurnResult{StopReason: "end_turn"}, nil | ||
| 31 | +} | ||
| 32 | + | ||
| 33 | +func TestAFormIsShownInTheConversationAndAnswered(t *testing.T) { | ||
| 34 | + f := setup(t, map[string]script{"ask": ask}) | ||
| 35 | + direct, _ := f.manager.Direct("alice") | ||
| 36 | + f.send(t, direct.ID, "ask") | ||
| 37 | + waitFor(t, func() bool { return len(f.recorder.Named(events.FormRequested)) == 1 }) | ||
| 38 | + request := f.recorder.Named(events.FormRequested)[0].(channels.FormRequest) | ||
| 39 | + if request.Channel != direct.ID || request.Agent != "alice" || request.MessageID == "" || request.Form.Fields[0].Title != "Your city?" { | ||
| 40 | + t.Fatalf("request: %+v", request) | ||
| 41 | + } | ||
| 42 | + if view, _ := f.manager.Conversation(direct.ID); len(view.Forms) != 1 || view.Forms[0].ID != request.ID { | ||
| 43 | + t.Fatalf("the form should wait in the conversation: %+v", view.Forms) | ||
| 44 | + } | ||
| 45 | + if err := f.manager.AnswerForm(request.ID, acp.FormAnswer{Action: "maybe"}); err == nil { | ||
| 46 | + t.Fatal("an unknown action must be refused") | ||
| 47 | + } | ||
| 48 | + if err := f.manager.AnswerForm(request.ID, acp.FormAnswer{Action: acp.FormAccept, Content: map[string]any{"q1": "Lyon"}}); err != nil { | ||
| 49 | + t.Fatal(err) | ||
| 50 | + } | ||
| 51 | + view := f.idle(t, direct.ID, 2) | ||
| 52 | + if text := view.Messages[1].Parts[0].Text; text != "One question: you live in Lyon" { | ||
| 53 | + t.Fatalf("answer: %q", text) | ||
| 54 | + } | ||
| 55 | + if len(view.Forms) != 0 || len(f.recorder.Named(events.FormResolved)) != 1 { | ||
| 56 | + t.Fatal("the form should be resolved") | ||
| 57 | + } | ||
| 58 | + if err := f.manager.AnswerForm(request.ID, acp.FormAnswer{Action: acp.FormAccept}); err == nil { | ||
| 59 | + t.Fatal("a form answered twice must be refused") | ||
| 60 | + } | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +func TestStopCancelsAWaitingForm(t *testing.T) { | ||
| 64 | + f := setup(t, map[string]script{"ask": ask}) | ||
| 65 | + direct, _ := f.manager.Direct("alice") | ||
| 66 | + f.send(t, direct.ID, "ask") | ||
| 67 | + waitFor(t, func() bool { return len(f.recorder.Named(events.FormRequested)) == 1 }) | ||
| 68 | + f.manager.Cancel(direct.ID) | ||
| 69 | + view := f.idle(t, direct.ID, 2) | ||
| 70 | + if text := view.Messages[1].Parts[0].Text; text != "One question: cancel" { | ||
| 71 | + t.Fatalf("answer: %q", text) | ||
| 72 | + } | ||
| 73 | + if len(f.recorder.Named(events.FormResolved)) != 1 { | ||
| 74 | + t.Fatal("the form should be resolved") | ||
| 75 | + } | ||
| 76 | +} | ||
modified
internal/channels/turns.go +60 -0 | @@ -640,6 +640,11 @@ func (m *Manager) Cancel(id string) { | ||
| 640 | 640 | m.resolve(requestID, acp.PermissionAnswer{}) |
| 641 | 641 | } |
| 642 | 642 | } |
| 643 | + for formID, pending := range m.forms { | |
| 644 | + if pending.channel == ch { | |
| 645 | + m.resolveForm(formID, acp.FormAnswer{Action: acp.FormCancel}) | |
| 646 | + } | |
| 647 | + } | |
| 643 | 648 | // An agent that streams is asked to stop (session/cancel); one that is |
| 644 | 649 | // still waited for, or starting, is given up. |
| 645 | 650 | var stops []func() |
| @@ -679,6 +684,31 @@ func (m *Manager) AnswerPermission(id, optionID string) error { | ||
| 679 | 684 | return fmt.Errorf("permission request %s has no option %s", id, optionID) |
| 680 | 685 | } |
| 681 | 686 | |
| 687 | +// AnswerForm gives the user's answer to a form: action accept (with the | |
| 688 | +// values by field name), decline or cancel. | |
| 689 | +func (m *Manager) AnswerForm(id string, answer acp.FormAnswer) error { | |
| 690 | + m.mu.Lock() | |
| 691 | + defer m.mu.Unlock() | |
| 692 | + if _, ok := m.forms[id]; !ok { | |
| 693 | + return fmt.Errorf("no form %s waits", id) | |
| 694 | + } | |
| 695 | + switch answer.Action { | |
| 696 | + case acp.FormAccept, acp.FormDecline, acp.FormCancel: | |
| 697 | + default: | |
| 698 | + return fmt.Errorf("unknown form action %q", answer.Action) | |
| 699 | + } | |
| 700 | + m.resolveForm(id, answer) | |
| 701 | + return nil | |
| 702 | +} | |
| 703 | + | |
| 704 | +// resolveForm answers a pending form. The caller holds m.mu. | |
| 705 | +func (m *Manager) resolveForm(id string, answer acp.FormAnswer) { | |
| 706 | + pending := m.forms[id] | |
| 707 | + delete(m.forms, id) | |
| 708 | + pending.answer <- answer | |
| 709 | + m.emitter.Emit(events.FormResolved, FormResolvedPayload{ID: id, Channel: pending.channel.info.ID}) | |
| 710 | +} | |
| 711 | + | |
| 682 | 712 | // resolve answers a pending request. The caller holds m.mu. |
| 683 | 713 | func (m *Manager) resolve(id string, answer acp.PermissionAnswer) { |
| 684 | 714 | pending := m.permissions[id] |
| @@ -805,6 +835,36 @@ func (h *handler) RequestPermission(ctx context.Context, request acp.PermissionR | ||
| 805 | 835 | } |
| 806 | 836 | } |
| 807 | 837 | |
| 838 | +// RequestForm shows the form the agent asks (issue #95: mini-me's ask_user) | |
| 839 | +// in the channel, attached to the answer being written, and waits for the | |
| 840 | +// user's answer; Stop or the end of the turn cancels it. | |
| 841 | +func (h *handler) RequestForm(ctx context.Context, form acp.Form) acp.FormAnswer { | |
| 842 | + m, ch := h.manager, h.channel | |
| 843 | + m.mu.Lock() | |
| 844 | + m.sequence++ | |
| 845 | + id := fmt.Sprintf("f-%d", m.sequence) | |
| 846 | + pending := &pendingForm{channel: ch, answer: make(chan acp.FormAnswer, 1)} | |
| 847 | + pending.request = FormRequest{ID: id, Channel: ch.info.ID, Agent: h.agent, Form: form} | |
| 848 | + if message := ch.current[h.agent]; message != nil { | |
| 849 | + pending.request.MessageID = message.ID | |
| 850 | + } | |
| 851 | + m.forms[id] = pending | |
| 852 | + m.emitter.Emit(events.FormRequested, pending.request) | |
| 853 | + m.mu.Unlock() | |
| 854 | + | |
| 855 | + select { | |
| 856 | + case answer := <-pending.answer: | |
| 857 | + return answer | |
| 858 | + case <-ctx.Done(): | |
| 859 | + m.mu.Lock() | |
| 860 | + if _, waiting := m.forms[id]; waiting { | |
| 861 | + m.resolveForm(id, acp.FormAnswer{Action: acp.FormCancel}) | |
| 862 | + } | |
| 863 | + m.mu.Unlock() | |
| 864 | + return acp.FormAnswer{Action: acp.FormCancel} | |
| 865 | + } | |
| 866 | +} | |
| 867 | + | |
| 808 | 868 | func toolIndex(message *Message, id string) int { |
| 809 | 869 | for i, part := range message.Parts { |
| 810 | 870 | if part.Kind == PartTool && part.Tool.ID == id { |
| @@ -640,6 +640,11 @@ func (m *Manager) Cancel(id string) { | |||
| 640 | m.resolve(requestID, acp.PermissionAnswer{}) | 640 | m.resolve(requestID, acp.PermissionAnswer{}) |
| 641 | } | 641 | } |
| 642 | } | 642 | } |
| 643 | + for formID, pending := range m.forms { | ||
| 644 | + if pending.channel == ch { | ||
| 645 | + m.resolveForm(formID, acp.FormAnswer{Action: acp.FormCancel}) | ||
| 646 | + } | ||
| 647 | + } | ||
| 643 | // An agent that streams is asked to stop (session/cancel); one that is | 648 | // An agent that streams is asked to stop (session/cancel); one that is |
| 644 | // still waited for, or starting, is given up. | 649 | // still waited for, or starting, is given up. |
| 645 | var stops []func() | 650 | var stops []func() |
| @@ -679,6 +684,31 @@ func (m *Manager) AnswerPermission(id, optionID string) error { | |||
| 679 | return fmt.Errorf("permission request %s has no option %s", id, optionID) | 684 | return fmt.Errorf("permission request %s has no option %s", id, optionID) |
| 680 | } | 685 | } |
| 681 | 686 | ||
| 687 | +// AnswerForm gives the user's answer to a form: action accept (with the | ||
| 688 | +// values by field name), decline or cancel. | ||
| 689 | +func (m *Manager) AnswerForm(id string, answer acp.FormAnswer) error { | ||
| 690 | + m.mu.Lock() | ||
| 691 | + defer m.mu.Unlock() | ||
| 692 | + if _, ok := m.forms[id]; !ok { | ||
| 693 | + return fmt.Errorf("no form %s waits", id) | ||
| 694 | + } | ||
| 695 | + switch answer.Action { | ||
| 696 | + case acp.FormAccept, acp.FormDecline, acp.FormCancel: | ||
| 697 | + default: | ||
| 698 | + return fmt.Errorf("unknown form action %q", answer.Action) | ||
| 699 | + } | ||
| 700 | + m.resolveForm(id, answer) | ||
| 701 | + return nil | ||
| 702 | +} | ||
| 703 | + | ||
| 704 | +// resolveForm answers a pending form. The caller holds m.mu. | ||
| 705 | +func (m *Manager) resolveForm(id string, answer acp.FormAnswer) { | ||
| 706 | + pending := m.forms[id] | ||
| 707 | + delete(m.forms, id) | ||
| 708 | + pending.answer <- answer | ||
| 709 | + m.emitter.Emit(events.FormResolved, FormResolvedPayload{ID: id, Channel: pending.channel.info.ID}) | ||
| 710 | +} | ||
| 711 | + | ||
| 682 | // resolve answers a pending request. The caller holds m.mu. | 712 | // resolve answers a pending request. The caller holds m.mu. |
| 683 | func (m *Manager) resolve(id string, answer acp.PermissionAnswer) { | 713 | func (m *Manager) resolve(id string, answer acp.PermissionAnswer) { |
| 684 | pending := m.permissions[id] | 714 | pending := m.permissions[id] |
| @@ -805,6 +835,36 @@ func (h *handler) RequestPermission(ctx context.Context, request acp.PermissionR | |||
| 805 | } | 835 | } |
| 806 | } | 836 | } |
| 807 | 837 | ||
| 838 | +// RequestForm shows the form the agent asks (issue #95: mini-me's ask_user) | ||
| 839 | +// in the channel, attached to the answer being written, and waits for the | ||
| 840 | +// user's answer; Stop or the end of the turn cancels it. | ||
| 841 | +func (h *handler) RequestForm(ctx context.Context, form acp.Form) acp.FormAnswer { | ||
| 842 | + m, ch := h.manager, h.channel | ||
| 843 | + m.mu.Lock() | ||
| 844 | + m.sequence++ | ||
| 845 | + id := fmt.Sprintf("f-%d", m.sequence) | ||
| 846 | + pending := &pendingForm{channel: ch, answer: make(chan acp.FormAnswer, 1)} | ||
| 847 | + pending.request = FormRequest{ID: id, Channel: ch.info.ID, Agent: h.agent, Form: form} | ||
| 848 | + if message := ch.current[h.agent]; message != nil { | ||
| 849 | + pending.request.MessageID = message.ID | ||
| 850 | + } | ||
| 851 | + m.forms[id] = pending | ||
| 852 | + m.emitter.Emit(events.FormRequested, pending.request) | ||
| 853 | + m.mu.Unlock() | ||
| 854 | + | ||
| 855 | + select { | ||
| 856 | + case answer := <-pending.answer: | ||
| 857 | + return answer | ||
| 858 | + case <-ctx.Done(): | ||
| 859 | + m.mu.Lock() | ||
| 860 | + if _, waiting := m.forms[id]; waiting { | ||
| 861 | + m.resolveForm(id, acp.FormAnswer{Action: acp.FormCancel}) | ||
| 862 | + } | ||
| 863 | + m.mu.Unlock() | ||
| 864 | + return acp.FormAnswer{Action: acp.FormCancel} | ||
| 865 | + } | ||
| 866 | +} | ||
| 867 | + | ||
| 808 | func toolIndex(message *Message, id string) int { | 868 | func toolIndex(message *Message, id string) int { |
| 809 | for i, part := range message.Parts { | 869 | for i, part := range message.Parts { |
| 810 | if part.Kind == PartTool && part.Tool.ID == id { | 870 | if part.Kind == PartTool && part.Tool.ID == id { |
modified
internal/events/events.go +4 -0 | @@ -37,6 +37,10 @@ const ( | ||
| 37 | 37 | PermissionRequested = "permission:requested" |
| 38 | 38 | // PermissionResolved: a permission request was answered or cancelled. Payload: channels.PermissionResolvedPayload. |
| 39 | 39 | PermissionResolved = "permission:resolved" |
| 40 | + // FormRequested: an agent asks the user to fill in a form (issue #95). Payload: channels.FormRequest. | |
| 41 | + FormRequested = "form:requested" | |
| 42 | + // FormResolved: a form was answered or cancelled. Payload: channels.FormResolvedPayload. | |
| 43 | + FormResolved = "form:resolved" | |
| 40 | 44 | // UsageChanged: the context window use of an agent in a channel changed. Payload: channels.UsagePayload. |
| 41 | 45 | UsageChanged = "usage:changed" |
| 42 | 46 | // CommandsChanged: an agent announced its slash commands. Payload: channels.CommandsPayload. |
| @@ -37,6 +37,10 @@ const ( | |||
| 37 | PermissionRequested = "permission:requested" | 37 | PermissionRequested = "permission:requested" |
| 38 | // PermissionResolved: a permission request was answered or cancelled. Payload: channels.PermissionResolvedPayload. | 38 | // PermissionResolved: a permission request was answered or cancelled. Payload: channels.PermissionResolvedPayload. |
| 39 | PermissionResolved = "permission:resolved" | 39 | PermissionResolved = "permission:resolved" |
| 40 | + // FormRequested: an agent asks the user to fill in a form (issue #95). Payload: channels.FormRequest. | ||
| 41 | + FormRequested = "form:requested" | ||
| 42 | + // FormResolved: a form was answered or cancelled. Payload: channels.FormResolvedPayload. | ||
| 43 | + FormResolved = "form:resolved" | ||
| 40 | // UsageChanged: the context window use of an agent in a channel changed. Payload: channels.UsagePayload. | 44 | // UsageChanged: the context window use of an agent in a channel changed. Payload: channels.UsagePayload. |
| 41 | UsageChanged = "usage:changed" | 45 | UsageChanged = "usage:changed" |
| 42 | // CommandsChanged: an agent announced its slash commands. Payload: channels.CommandsPayload. | 46 | // CommandsChanged: an agent announced its slash commands. Payload: channels.CommandsPayload. |
modified
main.go +2 -0 | @@ -51,6 +51,8 @@ func init() { | ||
| 51 | 51 | application.RegisterEvent[channels.TurnPayload](events.TurnChanged) |
| 52 | 52 | application.RegisterEvent[channels.Permission](events.PermissionRequested) |
| 53 | 53 | application.RegisterEvent[channels.PermissionResolvedPayload](events.PermissionResolved) |
| 54 | + application.RegisterEvent[channels.FormRequest](events.FormRequested) | |
| 55 | + application.RegisterEvent[channels.FormResolvedPayload](events.FormResolved) | |
| 54 | 56 | application.RegisterEvent[channels.UsagePayload](events.UsageChanged) |
| 55 | 57 | application.RegisterEvent[channels.CommandsPayload](events.CommandsChanged) |
| 56 | 58 | application.RegisterEvent[events.WorkspaceChangedPayload](events.WorkspaceChanged) |
| @@ -51,6 +51,8 @@ func init() { | |||
| 51 | application.RegisterEvent[channels.TurnPayload](events.TurnChanged) | 51 | application.RegisterEvent[channels.TurnPayload](events.TurnChanged) |
| 52 | application.RegisterEvent[channels.Permission](events.PermissionRequested) | 52 | application.RegisterEvent[channels.Permission](events.PermissionRequested) |
| 53 | application.RegisterEvent[channels.PermissionResolvedPayload](events.PermissionResolved) | 53 | application.RegisterEvent[channels.PermissionResolvedPayload](events.PermissionResolved) |
| 54 | + application.RegisterEvent[channels.FormRequest](events.FormRequested) | ||
| 55 | + application.RegisterEvent[channels.FormResolvedPayload](events.FormResolved) | ||
| 54 | application.RegisterEvent[channels.UsagePayload](events.UsageChanged) | 56 | application.RegisterEvent[channels.UsagePayload](events.UsageChanged) |
| 55 | application.RegisterEvent[channels.CommandsPayload](events.CommandsChanged) | 57 | application.RegisterEvent[channels.CommandsPayload](events.CommandsChanged) |
| 56 | application.RegisterEvent[events.WorkspaceChangedPayload](events.WorkspaceChanged) | 58 | application.RegisterEvent[events.WorkspaceChangedPayload](events.WorkspaceChanged) |