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

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

Download ZIP

#94 Assistant de création d'agents mini-me

Sidekicks devient le client ACP de mm --acp-create --project yes
--output .mm/agent.yaml (mini-me >= 1.0.9) et affiche ses questions en
formulaires (élicitation ACP). Le wizard travaille dans un dossier
temporaire de agentsFolder (défaut ~/Documents), renommé au nom de
l'agent ; /dockerinit ou /sbxinit pour un conteneur ou une sandbox, puis
l'agent est ajouté à la configuration avec son emoji.

- internal/acp : formulaires (Spec.OnForm, capacité elicitation.form)
- internal/creator (+ creatortest) et CreatorService
- réglage agentsFolder (schéma, fichier par défaut)
- page Créer un agent mini-me, accès depuis l'accueil, les agents, la palette
- lifecycle : PWD=<dossier> pour les commandes (compose.yaml de mm)
- docs EN + FR, ticket #94, .memory

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
agent committed 2026-11-14T18:04:59+01:00 Browse files
7fa255d parent: d601019
added .memory/handoffs/2026-11-14-mini-me-creator.md +17 -0
new file mode 100644
@@ -0,0 +1,17 @@
1+# Handoff — 2026-11-14 — #94 mini-me creation assistant
2+
3+## State
4+
5+Branch `feature/94-mini-me-creator`, not pushed. Implemented, tested in the Linux sandbox (unit + real mm 1.0.9 + Xvfb UI for a local agent). Ticket #94: tasks 1–6 closed, 7 and 8 open.
6+
7+## Next steps
8+
9+1. On the Mac with mm ≥ 1.0.9: create one agent per mode (local, Docker container, sbx) and start each from Sidekicks (task 7). For the container, the first start runs `docker compose up -d --wait` (build of mm's Dockerfile, network needed).
10+2. Release notes v1.5.0 EN/FR mention the assistant and `agentsFolder` (#93, task 8 of #94).
11+3. Merge into main when the owner agrees.
12+
13+## Watch out for
14+
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.
17+- Emoji show as boxes under Xvfb (no emoji font in the sandbox), not a bug.
new file mode 100644
@@ -0,0 +1,17 @@
1+# Handoff — 2026-11-14 — #94 mini-me creation assistant
2+
3+## State
4+
5+Branch `feature/94-mini-me-creator`, not pushed. Implemented, tested in the Linux sandbox (unit + real mm 1.0.9 + Xvfb UI for a local agent). Ticket #94: tasks 1–6 closed, 7 and 8 open.
6+
7+## Next steps
8+
9+1. On the Mac with mm ≥ 1.0.9: create one agent per mode (local, Docker container, sbx) and start each from Sidekicks (task 7). For the container, the first start runs `docker compose up -d --wait` (build of mm's Dockerfile, network needed).
10+2. Release notes v1.5.0 EN/FR mention the assistant and `agentsFolder` (#93, task 8 of #94).
11+3. Merge into main when the owner agrees.
12+
13+## Watch out for
14+
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.
17+- Emoji show as boxes under Xvfb (no emoji font in the sandbox), not a bug.
modified .memory/history.md +14 -0
@@ -234,3 +234,17 @@
234234 - **2026-11-10 — #68 done**: macOS install guide EN/FR — signed & notarized path (Open once), update by replacing the app; variants: spctl check, unsigned 0.1.0/1.0.0 keep Open Anyway / xattr.
235235 - **2026-11-10 — M8 closed, v1.3.0 prepared** (owner: "close M8 and prepare milestone v1.3.0"): branch release/v1.3.0 — info.version 1.3.0 + build assets synced (LSMinimumSystemVersion 13.0.0), release notes v1.3.0 EN/FR, README status, ticket #88 "Publier la version 1.3.0" (tasks 1–3 done; verify/push, build+sign on the Mac, draft/upload/publish, fetch tags left). make verify stops only on the owner's agents/ralph/hello.go; every other check passes. Not pushed, not merged.
236236 - **2026-11-11 — M9 and M10 closed, v1.4.0 prepared** (owner: "prepare the next release"): branch release/v1.4.0 — info.version 1.4.0 + build assets synced (LSMinimumSystemVersion 13.0.0), release notes v1.4.0 EN/FR (/parallel #89, agent tools #90/#91, drafts per conversation), README status, milestone v1.4.0 · Release, ticket #92 "Publier la version 1.4.0" (tasks 1–3 done; verify/push, build+sign on the Mac, draft/upload/publish, fetch tags left). Not pushed.
237+- **2026-11-14 — v1.4.0 closed, v1.5.0 opened** (owner: "close ticket 92 and its release, create a new release"): #92 closed (tasks 4–8 closed on the owner's word, comment added), milestone `v1.4.0 · Release` closed; new milestone `v1.5.0 · Release` (open, content to define) and ticket #93 "Publier la version 1.5.0" (same 8 tasks as #92, all open, related #92). Publication of v1.4.0 not verified from the sandbox (origin unreachable via ssh, local tags stop at v1.2.0). No version bump, no branch, not committed.
238+- **2026-11-14 — /zedconfig request, blocked** (owner: "after the /start wizard a Zed config is shown; add a /zedconfig command that shows the options for docker compose, sbxenv or neither"): the wizard is mini-me's ACP create mode (`mini-me/internal/acpcreate/session.go`: `commands`, `howToUse`), not Sidekicks; mini-me is mounted read-only in this sandbox, so nothing was changed. Needs a session with mini-me writable.
239+- **2026-11-14 — /zedconfig dropped** (owner: "forget this last request"): nothing to do, no follow-up.
240+- **2026-11-14 — ticket #94** (owner: "a new assistant to create mini-me agents, for non-technical users"): #94 in `v1.5.0 · Release`, epic Agents — one folder per agent (default: host Documents, setting to change it), `mm acp-create` (mini-me ≥ 1.0.9) driven by `/start`, ".mm folder" checked by default, then local / compose (`/dockerinit`) / sbx (`/sbxinit`) and the agent is added. Open points listed in the ticket (how to pre-check the .mm question: `--project yes` skips it). Listed in #93. Not committed.
241+- **2026-11-14 — #94 precised** (owner): Sidekicks is an ACP client of `mm --acp-create` (standard ACP: elicitation forms, messages, commands); folder = agent name (asked near the end of the wizard), emoji choice → agent `icon`; error messages agreed (mm missing/too old, no model server, folder exists).
242+- **2026-11-14 — #94 decisions** (owner): `.mm` layout imposed (`mm --acp-create --project yes`, question not asked; bare `--project` is a string flag needing yes/no); temporary folder renamed to the agent name if needed.
243+
244+## 2026-11-14 — #94 mini-me creation assistant (branch feature/94-mini-me-creator)
245+
246+- Asked: "create a feature branch and implement the ticket" (#94, decisions in the ticket: ACP client of `mm --acp-create`, `.mm` imposed with `--project yes`, folder = agent name with a temporary folder, emoji, plain errors).
247+- Done: `internal/acp/forms.go` (elicitation forms; capability advertised only with `Spec.OnForm`; fields ordered by `required`), `internal/creator` (+ `creatortest` fake mm), `internal/app/creator.go` `CreatorService` (Start/Answer/Send/Finish/Cancel; problems `nameTaken`/`folderExists`/`invalidName`), config key `agentsFolder` (default `~/Documents`; schema, default file, allowedKeys — which also lacked `agentTools`), page `CreateMiniMeAgent.svelte` + `lib/creator.ts`, entry points (welcome, Agents panel, palette). Also `--output .mm/agent.yaml` so the file question is not asked either.
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.
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.
@@ -234,3 +234,17 @@
234 - **2026-11-10 — #68 done**: macOS install guide EN/FR — signed & notarized path (Open once), update by replacing the app; variants: spctl check, unsigned 0.1.0/1.0.0 keep Open Anyway / xattr.234 - **2026-11-10 — #68 done**: macOS install guide EN/FR — signed & notarized path (Open once), update by replacing the app; variants: spctl check, unsigned 0.1.0/1.0.0 keep Open Anyway / xattr.
235 - **2026-11-10 — M8 closed, v1.3.0 prepared** (owner: "close M8 and prepare milestone v1.3.0"): branch release/v1.3.0 — info.version 1.3.0 + build assets synced (LSMinimumSystemVersion 13.0.0), release notes v1.3.0 EN/FR, README status, ticket #88 "Publier la version 1.3.0" (tasks 1–3 done; verify/push, build+sign on the Mac, draft/upload/publish, fetch tags left). make verify stops only on the owner's agents/ralph/hello.go; every other check passes. Not pushed, not merged.235 - **2026-11-10 — M8 closed, v1.3.0 prepared** (owner: "close M8 and prepare milestone v1.3.0"): branch release/v1.3.0 — info.version 1.3.0 + build assets synced (LSMinimumSystemVersion 13.0.0), release notes v1.3.0 EN/FR, README status, ticket #88 "Publier la version 1.3.0" (tasks 1–3 done; verify/push, build+sign on the Mac, draft/upload/publish, fetch tags left). make verify stops only on the owner's agents/ralph/hello.go; every other check passes. Not pushed, not merged.
236 - **2026-11-11 — M9 and M10 closed, v1.4.0 prepared** (owner: "prepare the next release"): branch release/v1.4.0 — info.version 1.4.0 + build assets synced (LSMinimumSystemVersion 13.0.0), release notes v1.4.0 EN/FR (/parallel #89, agent tools #90/#91, drafts per conversation), README status, milestone v1.4.0 · Release, ticket #92 "Publier la version 1.4.0" (tasks 1–3 done; verify/push, build+sign on the Mac, draft/upload/publish, fetch tags left). Not pushed.236 - **2026-11-11 — M9 and M10 closed, v1.4.0 prepared** (owner: "prepare the next release"): branch release/v1.4.0 — info.version 1.4.0 + build assets synced (LSMinimumSystemVersion 13.0.0), release notes v1.4.0 EN/FR (/parallel #89, agent tools #90/#91, drafts per conversation), README status, milestone v1.4.0 · Release, ticket #92 "Publier la version 1.4.0" (tasks 1–3 done; verify/push, build+sign on the Mac, draft/upload/publish, fetch tags left). Not pushed.
237+- **2026-11-14 — v1.4.0 closed, v1.5.0 opened** (owner: "close ticket 92 and its release, create a new release"): #92 closed (tasks 4–8 closed on the owner's word, comment added), milestone `v1.4.0 · Release` closed; new milestone `v1.5.0 · Release` (open, content to define) and ticket #93 "Publier la version 1.5.0" (same 8 tasks as #92, all open, related #92). Publication of v1.4.0 not verified from the sandbox (origin unreachable via ssh, local tags stop at v1.2.0). No version bump, no branch, not committed.
238+- **2026-11-14 — /zedconfig request, blocked** (owner: "after the /start wizard a Zed config is shown; add a /zedconfig command that shows the options for docker compose, sbxenv or neither"): the wizard is mini-me's ACP create mode (`mini-me/internal/acpcreate/session.go`: `commands`, `howToUse`), not Sidekicks; mini-me is mounted read-only in this sandbox, so nothing was changed. Needs a session with mini-me writable.
239+- **2026-11-14 — /zedconfig dropped** (owner: "forget this last request"): nothing to do, no follow-up.
240+- **2026-11-14 — ticket #94** (owner: "a new assistant to create mini-me agents, for non-technical users"): #94 in `v1.5.0 · Release`, epic Agents — one folder per agent (default: host Documents, setting to change it), `mm acp-create` (mini-me ≥ 1.0.9) driven by `/start`, ".mm folder" checked by default, then local / compose (`/dockerinit`) / sbx (`/sbxinit`) and the agent is added. Open points listed in the ticket (how to pre-check the .mm question: `--project yes` skips it). Listed in #93. Not committed.
241+- **2026-11-14 — #94 precised** (owner): Sidekicks is an ACP client of `mm --acp-create` (standard ACP: elicitation forms, messages, commands); folder = agent name (asked near the end of the wizard), emoji choice → agent `icon`; error messages agreed (mm missing/too old, no model server, folder exists).
242+- **2026-11-14 — #94 decisions** (owner): `.mm` layout imposed (`mm --acp-create --project yes`, question not asked; bare `--project` is a string flag needing yes/no); temporary folder renamed to the agent name if needed.
243+
244+## 2026-11-14 — #94 mini-me creation assistant (branch feature/94-mini-me-creator)
245+
246+- Asked: "create a feature branch and implement the ticket" (#94, decisions in the ticket: ACP client of `mm --acp-create`, `.mm` imposed with `--project yes`, folder = agent name with a temporary folder, emoji, plain errors).
247+- Done: `internal/acp/forms.go` (elicitation forms; capability advertised only with `Spec.OnForm`; fields ordered by `required`), `internal/creator` (+ `creatortest` fake mm), `internal/app/creator.go` `CreatorService` (Start/Answer/Send/Finish/Cancel; problems `nameTaken`/`folderExists`/`invalidName`), config key `agentsFolder` (default `~/Documents`; schema, default file, allowedKeys — which also lacked `agentTools`), page `CreateMiniMeAgent.svelte` + `lib/creator.ts`, entry points (welcome, Agents panel, palette). Also `--output .mm/agent.yaml` so the file question is not asked either.
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.
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.
modified .memory/summary.md +3 -2
@@ -13,7 +13,7 @@ Milestones **Initialize**, **M1**, **M2**, **M3** and **M4 · Workspace des agen
1313
1414 What exists:
1515
16-- `main.go` (root, only Wails importer; registers 11 typed events; injects the native file dialog; its emitter ignores events sent before the Wails app exists) · `internal/app` (Core, AgentService, ChannelService, ConfigService; opens the history per config file) · `internal/channels` (routing, sessions, context, queue, permissions) · `internal/store` (Pebble) · `internal/workspace` (Local, Container, Terminals; contract tests local + alpine container) · `internal/agents` · `internal/acp` (sessions, readable AgentError, stdin→TERM→KILL) · `internal/config` (+ `WatchWithReady`, `AppendAgent` keeps comments and unescapes emoji) · `internal/prefs` · `internal/events` · `internal/shellpath` · `schema`.
16+- `main.go` (root, only Wails importer; registers 11 typed events; injects the native file dialog; its emitter ignores events sent before the Wails app exists) · `internal/app` (Core, AgentService, ChannelService, ConfigService; opens the history per config file) · `internal/channels` (routing, sessions, context, queue, permissions) · `internal/store` (Pebble) · `internal/workspace` (Local, Container, Terminals; contract tests local + alpine container) · `internal/agents` · `internal/acp` (sessions, readable AgentError, stdin→TERM→KILL; elicitation forms with `Spec.OnForm`, #94) · `internal/creator` (drives `mm --acp-create` for the mini-me creation assistant, #94; fake mm in `creator/creatortest`) · `internal/config` (+ `WatchWithReady`, `AppendAgent` keeps comments and unescapes emoji) · `internal/prefs` · `internal/events` · `internal/shellpath` · `schema`.
1717 - `frontend/`: shell + panel registry, `state.svelte.ts` (`appState`, one ordered frame batcher for message events), `lib/chat/*` (Markdown, MessageView, ToolCallCard, PermissionCard, Composer), `lib/settings/ConfigEditor.svelte`, `lib/i18n` (en/fr catalogue, `t()`), pure modules with vitest (`markdown`, `conversation`, `composer`, `suggestions`, `tools`, `yamlSchema`, `events`, `theme`, `panels/registry`). State is keyed by channel id; a `$derived` must never call `conversationOf` (it writes state → `state_unsafe_mutation` freezes the UI).
1818 - Tooling: `Makefile`, golangci-lint (`tools/go.mod`), no hosted CI (owner's choice: checks run locally, `make verify`; releases by the local CI `local-ci-*.sh` + `.release.env`/`.ci.cd.token.env`, see RELEASING.md — the old workflow is `.github.bak/`; `make check-linux` runs `make check` in the Linux Docker image), `scripts/agents.sh`, `scripts/install-test-config.sh`, `scripts/check-license-headers.sh`, `scripts/package.sh` (+ `package_test.sh`), `scripts/build-release.sh`, `scripts/tag-release.sh` (+ `tag-release_test.sh`), `scripts/linux-packages.Dockerfile`, `scripts/check-linux.sh`, release workflow (tag push → release) `.github/workflows/release.yml`.
1919
@@ -24,6 +24,7 @@ What exists:
2424 - Conversations, permissions, settings: ADR 0004 (direct conversation per agent, in memory; new session after an agent restart + system message; queue; events `message:updated|delta`, `turn:changed`, `permission:requested|resolved`, `usage:changed`; never-before-reject ordering; stuck banner after 3 failed tool calls; Go validates, the editor only displays; prefs.json).
2525 - 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`).
2626 - 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).
2728 - 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.
2829 - 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).
2930 - 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/`.
@@ -38,7 +39,7 @@ What exists:
3839 | | |
3940 | --- | --- |
4041 | Before merging (no CI) | `make verify` = `make check` (lint + tests; needs `wails3`, `pnpm`, GTK/WebKit dev packages on Linux) + `make bindings-check` · Linux from the Mac: `make check-linux` |
41-| Tests only | `make test` (Go + vitest + shell) · real agents: `make test-real` |
42+| Tests only | `make test` (Go + vitest + shell) · real agents: `make test-real` (the creator's: `MM_BIN=<mm ≥ 1.0.9> go test -tags realagents ./internal/creator`, no model server needed) |
4243 | Run | `SIDEKICKS_CONFIG="$PWD/examples/test-agents.yaml" make dev` · build `make build` · macOS app `make package` |
4344 | Release | `make release-build` (Mac: all packages → dist/, Linux in Docker) · `make release-tag` · single systems: `make package-linux` / `package-windows` / `package-macos`; see RELEASING.md |
4445 | Bindings | `make bindings` after changing a service/event, stage them; `make bindings-check` compares with the index |
@@ -13,7 +13,7 @@ Milestones **Initialize**, **M1**, **M2**, **M3** and **M4 · Workspace des agen
13 13
14 What exists:14 What exists:
15 15
16-- `main.go` (root, only Wails importer; registers 11 typed events; injects the native file dialog; its emitter ignores events sent before the Wails app exists) · `internal/app` (Core, AgentService, ChannelService, ConfigService; opens the history per config file) · `internal/channels` (routing, sessions, context, queue, permissions) · `internal/store` (Pebble) · `internal/workspace` (Local, Container, Terminals; contract tests local + alpine container) · `internal/agents` · `internal/acp` (sessions, readable AgentError, stdin→TERM→KILL) · `internal/config` (+ `WatchWithReady`, `AppendAgent` keeps comments and unescapes emoji) · `internal/prefs` · `internal/events` · `internal/shellpath` · `schema`.16+- `main.go` (root, only Wails importer; registers 11 typed events; injects the native file dialog; its emitter ignores events sent before the Wails app exists) · `internal/app` (Core, AgentService, ChannelService, ConfigService; opens the history per config file) · `internal/channels` (routing, sessions, context, queue, permissions) · `internal/store` (Pebble) · `internal/workspace` (Local, Container, Terminals; contract tests local + alpine container) · `internal/agents` · `internal/acp` (sessions, readable AgentError, stdin→TERM→KILL; elicitation forms with `Spec.OnForm`, #94) · `internal/creator` (drives `mm --acp-create` for the mini-me creation assistant, #94; fake mm in `creator/creatortest`) · `internal/config` (+ `WatchWithReady`, `AppendAgent` keeps comments and unescapes emoji) · `internal/prefs` · `internal/events` · `internal/shellpath` · `schema`.
17 - `frontend/`: shell + panel registry, `state.svelte.ts` (`appState`, one ordered frame batcher for message events), `lib/chat/*` (Markdown, MessageView, ToolCallCard, PermissionCard, Composer), `lib/settings/ConfigEditor.svelte`, `lib/i18n` (en/fr catalogue, `t()`), pure modules with vitest (`markdown`, `conversation`, `composer`, `suggestions`, `tools`, `yamlSchema`, `events`, `theme`, `panels/registry`). State is keyed by channel id; a `$derived` must never call `conversationOf` (it writes state → `state_unsafe_mutation` freezes the UI).17 - `frontend/`: shell + panel registry, `state.svelte.ts` (`appState`, one ordered frame batcher for message events), `lib/chat/*` (Markdown, MessageView, ToolCallCard, PermissionCard, Composer), `lib/settings/ConfigEditor.svelte`, `lib/i18n` (en/fr catalogue, `t()`), pure modules with vitest (`markdown`, `conversation`, `composer`, `suggestions`, `tools`, `yamlSchema`, `events`, `theme`, `panels/registry`). State is keyed by channel id; a `$derived` must never call `conversationOf` (it writes state → `state_unsafe_mutation` freezes the UI).
18 - Tooling: `Makefile`, golangci-lint (`tools/go.mod`), no hosted CI (owner's choice: checks run locally, `make verify`; releases by the local CI `local-ci-*.sh` + `.release.env`/`.ci.cd.token.env`, see RELEASING.md — the old workflow is `.github.bak/`; `make check-linux` runs `make check` in the Linux Docker image), `scripts/agents.sh`, `scripts/install-test-config.sh`, `scripts/check-license-headers.sh`, `scripts/package.sh` (+ `package_test.sh`), `scripts/build-release.sh`, `scripts/tag-release.sh` (+ `tag-release_test.sh`), `scripts/linux-packages.Dockerfile`, `scripts/check-linux.sh`, release workflow (tag push → release) `.github/workflows/release.yml`.18 - Tooling: `Makefile`, golangci-lint (`tools/go.mod`), no hosted CI (owner's choice: checks run locally, `make verify`; releases by the local CI `local-ci-*.sh` + `.release.env`/`.ci.cd.token.env`, see RELEASING.md — the old workflow is `.github.bak/`; `make check-linux` runs `make check` in the Linux Docker image), `scripts/agents.sh`, `scripts/install-test-config.sh`, `scripts/check-license-headers.sh`, `scripts/package.sh` (+ `package_test.sh`), `scripts/build-release.sh`, `scripts/tag-release.sh` (+ `tag-release_test.sh`), `scripts/linux-packages.Dockerfile`, `scripts/check-linux.sh`, release workflow (tag push → release) `.github/workflows/release.yml`.
19 19
@@ -24,6 +24,7 @@ What exists:
24 - Conversations, permissions, settings: ADR 0004 (direct conversation per agent, in memory; new session after an agent restart + system message; queue; events `message:updated|delta`, `turn:changed`, `permission:requested|resolved`, `usage:changed`; never-before-reject ordering; stuck banner after 3 failed tool calls; Go validates, the editor only displays; prefs.json).24 - Conversations, permissions, settings: ADR 0004 (direct conversation per agent, in memory; new session after an agent restart + system message; queue; events `message:updated|delta`, `turn:changed`, `permission:requested|resolved`, `usage:changed`; never-before-reject ordering; stuck banner after 3 failed tool calls; Go validates, the editor only displays; prefs.json).
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 - 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.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.
28 - 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).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).
29 - 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/`.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/`.
@@ -38,7 +39,7 @@ What exists:
38 | | |39 | | |
39 | --- | --- |40 | --- | --- |
40 | Before merging (no CI) | `make verify` = `make check` (lint + tests; needs `wails3`, `pnpm`, GTK/WebKit dev packages on Linux) + `make bindings-check` · Linux from the Mac: `make check-linux` |41 | Before merging (no CI) | `make verify` = `make check` (lint + tests; needs `wails3`, `pnpm`, GTK/WebKit dev packages on Linux) + `make bindings-check` · Linux from the Mac: `make check-linux` |
41-| Tests only | `make test` (Go + vitest + shell) · real agents: `make test-real` |42+| Tests only | `make test` (Go + vitest + shell) · real agents: `make test-real` (the creator's: `MM_BIN=<mm ≥ 1.0.9> go test -tags realagents ./internal/creator`, no model server needed) |
42 | Run | `SIDEKICKS_CONFIG="$PWD/examples/test-agents.yaml" make dev` · build `make build` · macOS app `make package` |43 | Run | `SIDEKICKS_CONFIG="$PWD/examples/test-agents.yaml" make dev` · build `make build` · macOS app `make package` |
43 | Release | `make release-build` (Mac: all packages → dist/, Linux in Docker) · `make release-tag` · single systems: `make package-linux` / `package-windows` / `package-macos`; see RELEASING.md |44 | Release | `make release-build` (Mac: all packages → dist/, Linux in Docker) · `make release-tag` · single systems: `make package-linux` / `package-windows` / `package-macos`; see RELEASING.md |
44 | Bindings | `make bindings` after changing a service/event, stage them; `make bindings-check` compares with the index |45 | Bindings | `make bindings` after changing a service/event, stage them; `make bindings-check` compares with the index |
added .tickets/issues/0094-assistant-de-creation-d-agents-mini-me-pour-les.yaml +172 -0
new file mode 100644
@@ -0,0 +1,172 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 94
3+title: "Assistant de création d'agents mini-me pour les utilisateurs non techniques"
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-14T16:32:06.000Z
9+updatedAt: 2026-11-14T17:04:26.000Z
10+labels:
11+ - kind::feature
12+ - area::ui
13+ - area::acp
14+ - citizen-ux
15+ - real-agents
16+ - size::L
17+milestone: "v1.5.0 · Release"
18+epic: Agents
19+body: |
20+ Un nouvel assistant pour **créer** un agent mini-me depuis Sidekicks, pensé pour des utilisateurs non techniques :
21+ aucun fichier à éditer, aucun dossier à choisir, tout se fait par des questions simples. Une fois l'agent créé, il est
22+ ajouté à la liste des agents. Pour le moment, l'assistant ne concerne que mini-me.
23+
24+ ## Principe
25+ - **Un agent = un dossier.** Par défaut, les dossiers des agents sont créés dans le dossier **Documents** de l'OS hôte ;
26+ l'emplacement pourra être changé dans le fichier des settings.
27+ - **Sidekicks est un client ACP de mini-me**, lancé avec **`mm --acp-create --project yes`** (mini-me ≥ **1.0.9**), qui sert le
28+ wizard de `mm init`. Le wizard s'affiche dans Sidekicks avec les possibilités standard du protocole ACP :
29+ Sidekicks annonce la capacité `elicitation.form` et affiche les formulaires `elicitation/create` (défauts
30+ pré-remplis), les messages de l'agent, les commandes disponibles ; sans formulaire, repli sur les questions
31+ numérotées en messages.
32+ - La création démarre avec la commande ACP **`/start`**.
33+ - **Nom du dossier = nom de l'agent**, donné vers la fin du wizard. Le dossier est créé sous le dossier parent des
34+ agents (Documents par défaut). L'utilisateur peut aussi **choisir un emoji** pour l'agent (champ `icon` de la
35+ configuration Sidekicks).
36+ - **Mode `.mm` imposé** : Sidekicks passe `--project yes`, la question « Keep everything in a .mm folder? » n'est donc
37+ pas posée et l'agent est toujours écrit dans `<dossier de l'agent>/.mm/agent.yaml`. (`--project` seul ne suffit
38+ pas : c'est un flag texte qui attend `yes` ou `no`.)
39+ - Une fois l'agent écrit, Sidekicks demande **où il s'exécute** :
40+ - **localement** → l'agent est ajouté directement ;
41+ - **dans docker compose** → Sidekicks envoie `/dockerinit` (écrit `Dockerfile` et `compose.yaml`), puis ajoute l'agent ;
42+ - **dans sbx** → Sidekicks envoie `/sbxinit` (écrit `sbxenv.yaml`), puis ajoute l'agent.
43+ - L'ajout réutilise ce que fait déjà l'assistant d'ajout d'agents (remplissage depuis un `compose.yaml` / `sbxenv.yaml` /
44+ configuration d'agent), sans que l'utilisateur ait à déposer ou choisir un fichier.
45+
46+ ## Références mini-me
47+ - [Create an agent from your editor](../mini-me/docs/en/how-to/create-an-agent-from-an-editor.md) (dépôt mini-me)
48+ - CLI : `mm acp-create`, flags de `mm init` (`--project yes` impose le mode .mm), `/dockerinit`, `/sbxinit`.
49+
50+ ## Messages d'erreur (simples, pour un utilisateur non technique)
51+ - `mm` absent ou version < 1.0.9 : dire quoi installer / mettre à jour ; rien n'est créé.
52+ - Aucun serveur de modèles ne tourne (le wizard liste ses modèles) : dire lequel lancer.
53+ - Un dossier du même nom existe déjà : proposer un autre nom.
54+
55+ ## Dossier temporaire (si besoin)
56+ - mm acp-create écrit dans le `cwd` fixé au `session/new`, avant que le nom de l'agent soit connu. Si c'est
57+ nécessaire, la session travaille dans un dossier temporaire, renommé au nom de l'agent avant `/dockerinit` /
58+ `/sbxinit` (les chemins de `.mm/agent.yaml` sont relatifs au projet) — à vérifier sur un vrai mm 1.0.9.
59+
60+ ## Critères d'acceptation
61+ - Un utilisateur crée un agent mini-me sans éditer de fichier ni choisir de dossier ; le dossier porte le nom de
62+ l'agent et est créé dans Documents (ou l'emplacement des settings) ; l'emoji choisi apparaît dans la liste.
63+ - L'agent est toujours écrit en mode `.mm` (`.mm/agent.yaml`), sans que la question soit posée.
64+ - Les trois modes (local, docker compose, sbx) produisent un agent qui apparaît dans la liste et démarre.
65+ - Les trois messages d'erreur ci-dessus sont affichés dans les cas correspondants.
66+ - Tests unitaires de la logique (hors API Wails), doc EN + FR (how-to + référence du réglage).
67+tasks:
68+ - id: 1
69+ title: "Réglage du dossier parent des agents (défaut : Documents de l'OS hôte)"
70+ state: closed
71+ priority: high
72+ author:
73+ name: k33g
74+ email: ph.charriere@gmail.com
75+ createdAt: 2026-11-14T16:32:06.000Z
76+ updatedAt: 2026-11-14T17:04:26.000Z
77+ closedAt: 2026-11-14T17:04:26.000Z
78+ - id: 2
79+ title: "Détecter mm et sa version (>= 1.0.9), message clair sinon"
80+ state: closed
81+ priority: high
82+ author:
83+ name: k33g
84+ email: ph.charriere@gmail.com
85+ createdAt: 2026-11-14T16:32:06.000Z
86+ updatedAt: 2026-11-14T17:04:26.000Z
87+ closedAt: 2026-11-14T17:04:26.000Z
88+ - id: 3
89+ title: "Client ACP de mm --acp-create : /start, formulaires elicitation/create, messages et commandes ; repli en questions numérotées"
90+ state: closed
91+ priority: high
92+ author:
93+ name: k33g
94+ email: ph.charriere@gmail.com
95+ createdAt: 2026-11-14T16:32:06.000Z
96+ updatedAt: 2026-11-14T17:04:26.000Z
97+ closedAt: 2026-11-14T17:04:26.000Z
98+ - id: 4
99+ title: "Mode .mm imposé (--project yes) ; dossier = nom de l'agent (dossier temporaire si besoin), choix d'un emoji (icon)"
100+ state: closed
101+ priority: medium
102+ author:
103+ name: k33g
104+ email: ph.charriere@gmail.com
105+ createdAt: 2026-11-14T16:32:06.000Z
106+ updatedAt: 2026-11-14T17:04:26.000Z
107+ closedAt: 2026-11-14T17:04:26.000Z
108+ - id: 5
109+ title: "Après l'écriture : choix local / docker compose / sbx ; envoyer /dockerinit ou /sbxinit selon le choix"
110+ state: closed
111+ priority: high
112+ author:
113+ name: k33g
114+ email: ph.charriere@gmail.com
115+ createdAt: 2026-11-14T16:32:06.000Z
116+ updatedAt: 2026-11-14T17:04:26.000Z
117+ closedAt: 2026-11-14T17:04:26.000Z
118+ - id: 6
119+ title: "Ajouter l'agent à la liste à partir des fichiers générés"
120+ state: closed
121+ priority: high
122+ author:
123+ name: k33g
124+ email: ph.charriere@gmail.com
125+ createdAt: 2026-11-14T16:32:06.000Z
126+ updatedAt: 2026-11-14T17:04:26.000Z
127+ closedAt: 2026-11-14T17:04:26.000Z
128+ - id: 7
129+ title: "Tests unitaires, essai avec un vrai mm 1.0.9 (local, compose, sbx)"
130+ state: open
131+ priority: high
132+ author:
133+ name: k33g
134+ email: ph.charriere@gmail.com
135+ createdAt: 2026-11-14T16:32:06.000Z
136+ - id: 8
137+ title: "Documentation EN + FR (how-to, référence du réglage), notes de release v1.5.0"
138+ state: open
139+ priority: medium
140+ author:
141+ name: k33g
142+ email: ph.charriere@gmail.com
143+ createdAt: 2026-11-14T16:32:06.000Z
144+comments:
145+ - id: 1
146+ author:
147+ name: k33g
148+ email: ph.charriere@gmail.com
149+ createdAt: 2026-11-14T17:04:26.000Z
150+ body: |
151+ Implémenté sur la branche `feature/94-mini-me-creator` (pas poussée).
152+
153+ - Client ACP : formulaires d'élicitation (`internal/acp/forms.go`, `Spec.OnForm`, capacité
154+ `elicitation.form` annoncée seulement si quelqu'un répond).
155+ - `internal/creator` : `mm --acp-create --project yes --output .mm/agent.yaml` dans un dossier temporaire
156+ `<agentsFolder>/.sidekicks-new-agent-…`, renommé au nom de l'agent par `Finish` ; `/dockerinit` ou `/sbxinit`
157+ dans un mm relancé dans le dossier final ; version ≥ 1.0.9 vérifiée (`mm --version`).
158+ - `CreatorService` (Start, Answer, Send, Finish, Cancel) ; l'agent est ajouté avec `mm --acp --config
159+ <dossier>/.mm/agent.yaml`, en local, `docker exec -i` ou `sbx exec -i` avec les commandes de cycle de vie du
160+ `compose.yaml` / `sbxenv.yaml`.
161+ - Réglage `agentsFolder` (défaut `~/Documents`).
162+ - Page « Créer un agent mini-me » : formulaires, ← Question précédente (/back), Recommencer (/restart),
163+ dernière étape nom + emoji + local / conteneur / sbx ; messages d'erreur mm absent, trop ancien, pas de
164+ serveur de modèles, nom ou dossier déjà pris.
165+ - Correctif : les commandes de cycle de vie reçoivent `PWD=<dossier>` (le `compose.yaml` de mm monte `${PWD}`).
166+
167+ Vérifié : tests Go + vitest, `make lint-go`, svelte-check ; vrai mm 1.0.9 (compilé depuis mini-me) dans les
168+ trois modes (`go test -tags realagents ./internal/creator`) ; l'application sous Xvfb : création d'un agent
169+ local de bout en bout avec le llmman de l'hôte, Annuler, mm absent, mm 1.0.8.
170+
171+ Reste : tâche 7 — démarrer pour de vrai un agent créé en conteneur et en sbx (sur le Mac) ; tâche 8 — les
172+ notes de release v1.5.0 (avec #93). Doc EN + FR faite.
new file mode 100644
@@ -0,0 +1,172 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 94
3+title: "Assistant de création d'agents mini-me pour les utilisateurs non techniques"
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-14T16:32:06.000Z
9+updatedAt: 2026-11-14T17:04:26.000Z
10+labels:
11+ - kind::feature
12+ - area::ui
13+ - area::acp
14+ - citizen-ux
15+ - real-agents
16+ - size::L
17+milestone: "v1.5.0 · Release"
18+epic: Agents
19+body: |
20+ Un nouvel assistant pour **créer** un agent mini-me depuis Sidekicks, pensé pour des utilisateurs non techniques :
21+ aucun fichier à éditer, aucun dossier à choisir, tout se fait par des questions simples. Une fois l'agent créé, il est
22+ ajouté à la liste des agents. Pour le moment, l'assistant ne concerne que mini-me.
23+
24+ ## Principe
25+ - **Un agent = un dossier.** Par défaut, les dossiers des agents sont créés dans le dossier **Documents** de l'OS hôte ;
26+ l'emplacement pourra être changé dans le fichier des settings.
27+ - **Sidekicks est un client ACP de mini-me**, lancé avec **`mm --acp-create --project yes`** (mini-me ≥ **1.0.9**), qui sert le
28+ wizard de `mm init`. Le wizard s'affiche dans Sidekicks avec les possibilités standard du protocole ACP :
29+ Sidekicks annonce la capacité `elicitation.form` et affiche les formulaires `elicitation/create` (défauts
30+ pré-remplis), les messages de l'agent, les commandes disponibles ; sans formulaire, repli sur les questions
31+ numérotées en messages.
32+ - La création démarre avec la commande ACP **`/start`**.
33+ - **Nom du dossier = nom de l'agent**, donné vers la fin du wizard. Le dossier est créé sous le dossier parent des
34+ agents (Documents par défaut). L'utilisateur peut aussi **choisir un emoji** pour l'agent (champ `icon` de la
35+ configuration Sidekicks).
36+ - **Mode `.mm` imposé** : Sidekicks passe `--project yes`, la question « Keep everything in a .mm folder? » n'est donc
37+ pas posée et l'agent est toujours écrit dans `<dossier de l'agent>/.mm/agent.yaml`. (`--project` seul ne suffit
38+ pas : c'est un flag texte qui attend `yes` ou `no`.)
39+ - Une fois l'agent écrit, Sidekicks demande **où il s'exécute** :
40+ - **localement** → l'agent est ajouté directement ;
41+ - **dans docker compose** → Sidekicks envoie `/dockerinit` (écrit `Dockerfile` et `compose.yaml`), puis ajoute l'agent ;
42+ - **dans sbx** → Sidekicks envoie `/sbxinit` (écrit `sbxenv.yaml`), puis ajoute l'agent.
43+ - L'ajout réutilise ce que fait déjà l'assistant d'ajout d'agents (remplissage depuis un `compose.yaml` / `sbxenv.yaml` /
44+ configuration d'agent), sans que l'utilisateur ait à déposer ou choisir un fichier.
45+
46+ ## Références mini-me
47+ - [Create an agent from your editor](../mini-me/docs/en/how-to/create-an-agent-from-an-editor.md) (dépôt mini-me)
48+ - CLI : `mm acp-create`, flags de `mm init` (`--project yes` impose le mode .mm), `/dockerinit`, `/sbxinit`.
49+
50+ ## Messages d'erreur (simples, pour un utilisateur non technique)
51+ - `mm` absent ou version < 1.0.9 : dire quoi installer / mettre à jour ; rien n'est créé.
52+ - Aucun serveur de modèles ne tourne (le wizard liste ses modèles) : dire lequel lancer.
53+ - Un dossier du même nom existe déjà : proposer un autre nom.
54+
55+ ## Dossier temporaire (si besoin)
56+ - mm acp-create écrit dans le `cwd` fixé au `session/new`, avant que le nom de l'agent soit connu. Si c'est
57+ nécessaire, la session travaille dans un dossier temporaire, renommé au nom de l'agent avant `/dockerinit` /
58+ `/sbxinit` (les chemins de `.mm/agent.yaml` sont relatifs au projet) — à vérifier sur un vrai mm 1.0.9.
59+
60+ ## Critères d'acceptation
61+ - Un utilisateur crée un agent mini-me sans éditer de fichier ni choisir de dossier ; le dossier porte le nom de
62+ l'agent et est créé dans Documents (ou l'emplacement des settings) ; l'emoji choisi apparaît dans la liste.
63+ - L'agent est toujours écrit en mode `.mm` (`.mm/agent.yaml`), sans que la question soit posée.
64+ - Les trois modes (local, docker compose, sbx) produisent un agent qui apparaît dans la liste et démarre.
65+ - Les trois messages d'erreur ci-dessus sont affichés dans les cas correspondants.
66+ - Tests unitaires de la logique (hors API Wails), doc EN + FR (how-to + référence du réglage).
67+tasks:
68+ - id: 1
69+ title: "Réglage du dossier parent des agents (défaut : Documents de l'OS hôte)"
70+ state: closed
71+ priority: high
72+ author:
73+ name: k33g
74+ email: ph.charriere@gmail.com
75+ createdAt: 2026-11-14T16:32:06.000Z
76+ updatedAt: 2026-11-14T17:04:26.000Z
77+ closedAt: 2026-11-14T17:04:26.000Z
78+ - id: 2
79+ title: "Détecter mm et sa version (>= 1.0.9), message clair sinon"
80+ state: closed
81+ priority: high
82+ author:
83+ name: k33g
84+ email: ph.charriere@gmail.com
85+ createdAt: 2026-11-14T16:32:06.000Z
86+ updatedAt: 2026-11-14T17:04:26.000Z
87+ closedAt: 2026-11-14T17:04:26.000Z
88+ - id: 3
89+ title: "Client ACP de mm --acp-create : /start, formulaires elicitation/create, messages et commandes ; repli en questions numérotées"
90+ state: closed
91+ priority: high
92+ author:
93+ name: k33g
94+ email: ph.charriere@gmail.com
95+ createdAt: 2026-11-14T16:32:06.000Z
96+ updatedAt: 2026-11-14T17:04:26.000Z
97+ closedAt: 2026-11-14T17:04:26.000Z
98+ - id: 4
99+ title: "Mode .mm imposé (--project yes) ; dossier = nom de l'agent (dossier temporaire si besoin), choix d'un emoji (icon)"
100+ state: closed
101+ priority: medium
102+ author:
103+ name: k33g
104+ email: ph.charriere@gmail.com
105+ createdAt: 2026-11-14T16:32:06.000Z
106+ updatedAt: 2026-11-14T17:04:26.000Z
107+ closedAt: 2026-11-14T17:04:26.000Z
108+ - id: 5
109+ title: "Après l'écriture : choix local / docker compose / sbx ; envoyer /dockerinit ou /sbxinit selon le choix"
110+ state: closed
111+ priority: high
112+ author:
113+ name: k33g
114+ email: ph.charriere@gmail.com
115+ createdAt: 2026-11-14T16:32:06.000Z
116+ updatedAt: 2026-11-14T17:04:26.000Z
117+ closedAt: 2026-11-14T17:04:26.000Z
118+ - id: 6
119+ title: "Ajouter l'agent à la liste à partir des fichiers générés"
120+ state: closed
121+ priority: high
122+ author:
123+ name: k33g
124+ email: ph.charriere@gmail.com
125+ createdAt: 2026-11-14T16:32:06.000Z
126+ updatedAt: 2026-11-14T17:04:26.000Z
127+ closedAt: 2026-11-14T17:04:26.000Z
128+ - id: 7
129+ title: "Tests unitaires, essai avec un vrai mm 1.0.9 (local, compose, sbx)"
130+ state: open
131+ priority: high
132+ author:
133+ name: k33g
134+ email: ph.charriere@gmail.com
135+ createdAt: 2026-11-14T16:32:06.000Z
136+ - id: 8
137+ title: "Documentation EN + FR (how-to, référence du réglage), notes de release v1.5.0"
138+ state: open
139+ priority: medium
140+ author:
141+ name: k33g
142+ email: ph.charriere@gmail.com
143+ createdAt: 2026-11-14T16:32:06.000Z
144+comments:
145+ - id: 1
146+ author:
147+ name: k33g
148+ email: ph.charriere@gmail.com
149+ createdAt: 2026-11-14T17:04:26.000Z
150+ body: |
151+ Implémenté sur la branche `feature/94-mini-me-creator` (pas poussée).
152+
153+ - Client ACP : formulaires d'élicitation (`internal/acp/forms.go`, `Spec.OnForm`, capacité
154+ `elicitation.form` annoncée seulement si quelqu'un répond).
155+ - `internal/creator` : `mm --acp-create --project yes --output .mm/agent.yaml` dans un dossier temporaire
156+ `<agentsFolder>/.sidekicks-new-agent-…`, renommé au nom de l'agent par `Finish` ; `/dockerinit` ou `/sbxinit`
157+ dans un mm relancé dans le dossier final ; version ≥ 1.0.9 vérifiée (`mm --version`).
158+ - `CreatorService` (Start, Answer, Send, Finish, Cancel) ; l'agent est ajouté avec `mm --acp --config
159+ <dossier>/.mm/agent.yaml`, en local, `docker exec -i` ou `sbx exec -i` avec les commandes de cycle de vie du
160+ `compose.yaml` / `sbxenv.yaml`.
161+ - Réglage `agentsFolder` (défaut `~/Documents`).
162+ - Page « Créer un agent mini-me » : formulaires, ← Question précédente (/back), Recommencer (/restart),
163+ dernière étape nom + emoji + local / conteneur / sbx ; messages d'erreur mm absent, trop ancien, pas de
164+ serveur de modèles, nom ou dossier déjà pris.
165+ - Correctif : les commandes de cycle de vie reçoivent `PWD=<dossier>` (le `compose.yaml` de mm monte `${PWD}`).
166+
167+ Vérifié : tests Go + vitest, `make lint-go`, svelte-check ; vrai mm 1.0.9 (compilé depuis mini-me) dans les
168+ trois modes (`go test -tags realagents ./internal/creator`) ; l'application sous Xvfb : création d'un agent
169+ local de bout en bout avec le llmman de l'hôte, Annuler, mm absent, mm 1.0.8.
170+
171+ Reste : tâche 7 — démarrer pour de vrai un agent créé en conteneur et en sbx (sur le Mac) ; tâche 8 — les
172+ notes de release v1.5.0 (avec #93). Doc EN + FR faite.
modified docs/en/README.md +1 -1
@@ -7,7 +7,7 @@ This documentation follows [Diátaxis](https://diataxis.fr): pick the section th
77 | You want to… | Section | Pages |
88 | --- | --- | --- |
99 | **learn** by doing | Tutorials | [Your first agent, without writing any configuration](tutorials/your-first-agent.md) · [A channel with two agents](tutorials/first-channel.md) · [Your first conversation with an agent](tutorials/first-conversation.md) · [Your first launch of Sidekicks](tutorials/first-launch.md) · [Your first ACP exchange with a test agent](tutorials/first-acp-exchange.md) |
10-| **do** a specific task | How-to guides | [Install Sidekicks](how-to/install-sidekicks.md) · [Add an agent](how-to/add-an-agent.md) · [Work with an agent's files and terminal](how-to/work-with-an-agents-files.md) · [Run an agent in a Docker container](how-to/run-an-agent-in-docker.md) · [Run an agent in an sbx sandbox](how-to/run-an-agent-in-a-sandbox.md) · [Add a Claude agent in an sbx sandbox](how-to/add-a-claude-agent-in-a-sandbox.md) · [Add a Codex agent in an sbx sandbox](how-to/add-a-codex-agent-in-a-sandbox.md) · [Add a Gemini agent in an sbx sandbox](how-to/add-a-gemini-agent-in-a-sandbox.md) · [Join files to a message](how-to/join-files-to-a-message.md) · [Manage channels and their agents](how-to/manage-channels.md) · [Edit or switch the configuration](how-to/edit-or-switch-the-configuration.md) · [Reset Sidekicks](how-to/reset-sidekicks.md) · [Watch the memory pressure](how-to/watch-the-memory-pressure.md) · [Let an agent use Sidekicks' tools](how-to/use-sidekicks-tools-from-an-agent.md) · [Develop the application](how-to/develop-the-application.md) · [Run the tests](how-to/run-the-tests.md) · [Check a change before merging it](how-to/check-before-merging.md) · [Run a test agent](how-to/run-a-test-agent.md) · [Run the end-to-end scenarios (v0.1)](how-to/run-the-end-to-end-scenarios.md) · [Set the version](how-to/set-the-version.md) · [Publish a release](how-to/publish-a-release.md) · [Sign and notarize for macOS](how-to/sign-and-notarize-on-macos.md) · [Test issue #52 on macOS](how-to/test-issue-52-on-macos.md) · [Test issues #49 and #50 on macOS](how-to/test-issues-49-and-50-on-macos.md) · [Test issue #47 on macOS](how-to/test-issue-47-on-macos.md) · [Test milestone M4 on macOS](how-to/test-milestone-m4-on-macos.md) · [Test milestone M3 on macOS](how-to/test-milestone-m3-on-macos.md) · [Test milestone M2 on macOS](how-to/test-milestone-m2-on-macos.md) · [Test milestone M1 on macOS](how-to/test-milestone-m1-on-macos.md) · [Test milestone Initialize on macOS](how-to/test-milestone-initialize-on-macos.md) |
10+| **do** a specific task | How-to guides | [Install Sidekicks](how-to/install-sidekicks.md) · [Create a mini-me agent](how-to/create-a-mini-me-agent.md) · [Add an agent](how-to/add-an-agent.md) · [Work with an agent's files and terminal](how-to/work-with-an-agents-files.md) · [Run an agent in a Docker container](how-to/run-an-agent-in-docker.md) · [Run an agent in an sbx sandbox](how-to/run-an-agent-in-a-sandbox.md) · [Add a Claude agent in an sbx sandbox](how-to/add-a-claude-agent-in-a-sandbox.md) · [Add a Codex agent in an sbx sandbox](how-to/add-a-codex-agent-in-a-sandbox.md) · [Add a Gemini agent in an sbx sandbox](how-to/add-a-gemini-agent-in-a-sandbox.md) · [Join files to a message](how-to/join-files-to-a-message.md) · [Manage channels and their agents](how-to/manage-channels.md) · [Edit or switch the configuration](how-to/edit-or-switch-the-configuration.md) · [Reset Sidekicks](how-to/reset-sidekicks.md) · [Watch the memory pressure](how-to/watch-the-memory-pressure.md) · [Let an agent use Sidekicks' tools](how-to/use-sidekicks-tools-from-an-agent.md) · [Develop the application](how-to/develop-the-application.md) · [Run the tests](how-to/run-the-tests.md) · [Check a change before merging it](how-to/check-before-merging.md) · [Run a test agent](how-to/run-a-test-agent.md) · [Run the end-to-end scenarios (v0.1)](how-to/run-the-end-to-end-scenarios.md) · [Set the version](how-to/set-the-version.md) · [Publish a release](how-to/publish-a-release.md) · [Sign and notarize for macOS](how-to/sign-and-notarize-on-macos.md) · [Test issue #52 on macOS](how-to/test-issue-52-on-macos.md) · [Test issues #49 and #50 on macOS](how-to/test-issues-49-and-50-on-macos.md) · [Test issue #47 on macOS](how-to/test-issue-47-on-macos.md) · [Test milestone M4 on macOS](how-to/test-milestone-m4-on-macos.md) · [Test milestone M3 on macOS](how-to/test-milestone-m3-on-macos.md) · [Test milestone M2 on macOS](how-to/test-milestone-m2-on-macos.md) · [Test milestone M1 on macOS](how-to/test-milestone-m1-on-macos.md) · [Test milestone Initialize on macOS](how-to/test-milestone-initialize-on-macos.md) |
1111 | **look up** an exact detail | Reference | [The configuration file](reference/configuration.md) · [Keyboard shortcuts](reference/keyboard-shortcuts.md) · [Agents, channels and events](reference/agents-and-events.md) · [Commands](reference/commands.md) · [scripts/agents.sh](reference/agents-script.md) |
1212 | **understand** why | Explanation | [Workspaces and terminals](explanation/workspaces-and-terminals.md) · [Channels and what each agent knows](explanation/channels-and-context.md) · [Permissions and trust](explanation/permissions.md) · [Why ACP](explanation/why-acp.md) · [The interface stack](explanation/ui-stack.md) · [Architecture](explanation/architecture.md) · [Memory and local models](explanation/memory-and-local-models.md) |
1313
@@ -7,7 +7,7 @@ This documentation follows [Diátaxis](https://diataxis.fr): pick the section th
7 | You want to… | Section | Pages |7 | You want to… | Section | Pages |
8 | --- | --- | --- |8 | --- | --- | --- |
9 | **learn** by doing | Tutorials | [Your first agent, without writing any configuration](tutorials/your-first-agent.md) · [A channel with two agents](tutorials/first-channel.md) · [Your first conversation with an agent](tutorials/first-conversation.md) · [Your first launch of Sidekicks](tutorials/first-launch.md) · [Your first ACP exchange with a test agent](tutorials/first-acp-exchange.md) |9 | **learn** by doing | Tutorials | [Your first agent, without writing any configuration](tutorials/your-first-agent.md) · [A channel with two agents](tutorials/first-channel.md) · [Your first conversation with an agent](tutorials/first-conversation.md) · [Your first launch of Sidekicks](tutorials/first-launch.md) · [Your first ACP exchange with a test agent](tutorials/first-acp-exchange.md) |
10-| **do** a specific task | How-to guides | [Install Sidekicks](how-to/install-sidekicks.md) · [Add an agent](how-to/add-an-agent.md) · [Work with an agent's files and terminal](how-to/work-with-an-agents-files.md) · [Run an agent in a Docker container](how-to/run-an-agent-in-docker.md) · [Run an agent in an sbx sandbox](how-to/run-an-agent-in-a-sandbox.md) · [Add a Claude agent in an sbx sandbox](how-to/add-a-claude-agent-in-a-sandbox.md) · [Add a Codex agent in an sbx sandbox](how-to/add-a-codex-agent-in-a-sandbox.md) · [Add a Gemini agent in an sbx sandbox](how-to/add-a-gemini-agent-in-a-sandbox.md) · [Join files to a message](how-to/join-files-to-a-message.md) · [Manage channels and their agents](how-to/manage-channels.md) · [Edit or switch the configuration](how-to/edit-or-switch-the-configuration.md) · [Reset Sidekicks](how-to/reset-sidekicks.md) · [Watch the memory pressure](how-to/watch-the-memory-pressure.md) · [Let an agent use Sidekicks' tools](how-to/use-sidekicks-tools-from-an-agent.md) · [Develop the application](how-to/develop-the-application.md) · [Run the tests](how-to/run-the-tests.md) · [Check a change before merging it](how-to/check-before-merging.md) · [Run a test agent](how-to/run-a-test-agent.md) · [Run the end-to-end scenarios (v0.1)](how-to/run-the-end-to-end-scenarios.md) · [Set the version](how-to/set-the-version.md) · [Publish a release](how-to/publish-a-release.md) · [Sign and notarize for macOS](how-to/sign-and-notarize-on-macos.md) · [Test issue #52 on macOS](how-to/test-issue-52-on-macos.md) · [Test issues #49 and #50 on macOS](how-to/test-issues-49-and-50-on-macos.md) · [Test issue #47 on macOS](how-to/test-issue-47-on-macos.md) · [Test milestone M4 on macOS](how-to/test-milestone-m4-on-macos.md) · [Test milestone M3 on macOS](how-to/test-milestone-m3-on-macos.md) · [Test milestone M2 on macOS](how-to/test-milestone-m2-on-macos.md) · [Test milestone M1 on macOS](how-to/test-milestone-m1-on-macos.md) · [Test milestone Initialize on macOS](how-to/test-milestone-initialize-on-macos.md) |10+| **do** a specific task | How-to guides | [Install Sidekicks](how-to/install-sidekicks.md) · [Create a mini-me agent](how-to/create-a-mini-me-agent.md) · [Add an agent](how-to/add-an-agent.md) · [Work with an agent's files and terminal](how-to/work-with-an-agents-files.md) · [Run an agent in a Docker container](how-to/run-an-agent-in-docker.md) · [Run an agent in an sbx sandbox](how-to/run-an-agent-in-a-sandbox.md) · [Add a Claude agent in an sbx sandbox](how-to/add-a-claude-agent-in-a-sandbox.md) · [Add a Codex agent in an sbx sandbox](how-to/add-a-codex-agent-in-a-sandbox.md) · [Add a Gemini agent in an sbx sandbox](how-to/add-a-gemini-agent-in-a-sandbox.md) · [Join files to a message](how-to/join-files-to-a-message.md) · [Manage channels and their agents](how-to/manage-channels.md) · [Edit or switch the configuration](how-to/edit-or-switch-the-configuration.md) · [Reset Sidekicks](how-to/reset-sidekicks.md) · [Watch the memory pressure](how-to/watch-the-memory-pressure.md) · [Let an agent use Sidekicks' tools](how-to/use-sidekicks-tools-from-an-agent.md) · [Develop the application](how-to/develop-the-application.md) · [Run the tests](how-to/run-the-tests.md) · [Check a change before merging it](how-to/check-before-merging.md) · [Run a test agent](how-to/run-a-test-agent.md) · [Run the end-to-end scenarios (v0.1)](how-to/run-the-end-to-end-scenarios.md) · [Set the version](how-to/set-the-version.md) · [Publish a release](how-to/publish-a-release.md) · [Sign and notarize for macOS](how-to/sign-and-notarize-on-macos.md) · [Test issue #52 on macOS](how-to/test-issue-52-on-macos.md) · [Test issues #49 and #50 on macOS](how-to/test-issues-49-and-50-on-macos.md) · [Test issue #47 on macOS](how-to/test-issue-47-on-macos.md) · [Test milestone M4 on macOS](how-to/test-milestone-m4-on-macos.md) · [Test milestone M3 on macOS](how-to/test-milestone-m3-on-macos.md) · [Test milestone M2 on macOS](how-to/test-milestone-m2-on-macos.md) · [Test milestone M1 on macOS](how-to/test-milestone-m1-on-macos.md) · [Test milestone Initialize on macOS](how-to/test-milestone-initialize-on-macos.md) |
11 | **look up** an exact detail | Reference | [The configuration file](reference/configuration.md) · [Keyboard shortcuts](reference/keyboard-shortcuts.md) · [Agents, channels and events](reference/agents-and-events.md) · [Commands](reference/commands.md) · [scripts/agents.sh](reference/agents-script.md) |11 | **look up** an exact detail | Reference | [The configuration file](reference/configuration.md) · [Keyboard shortcuts](reference/keyboard-shortcuts.md) · [Agents, channels and events](reference/agents-and-events.md) · [Commands](reference/commands.md) · [scripts/agents.sh](reference/agents-script.md) |
12 | **understand** why | Explanation | [Workspaces and terminals](explanation/workspaces-and-terminals.md) · [Channels and what each agent knows](explanation/channels-and-context.md) · [Permissions and trust](explanation/permissions.md) · [Why ACP](explanation/why-acp.md) · [The interface stack](explanation/ui-stack.md) · [Architecture](explanation/architecture.md) · [Memory and local models](explanation/memory-and-local-models.md) |12 | **understand** why | Explanation | [Workspaces and terminals](explanation/workspaces-and-terminals.md) · [Channels and what each agent knows](explanation/channels-and-context.md) · [Permissions and trust](explanation/permissions.md) · [Why ACP](explanation/why-acp.md) · [The interface stack](explanation/ui-stack.md) · [Architecture](explanation/architecture.md) · [Memory and local models](explanation/memory-and-local-models.md) |
13 13
modified docs/en/how-to/add-an-agent.md +1 -0
@@ -24,6 +24,7 @@ When the agent cannot be added (a name already used, for instance), the assistan
2424
2525 ## See also
2626
27+- To create a new mini-me agent by answering questions, with no file and no folder to choose: [How to create a mini-me agent](create-a-mini-me-agent.md)
2728 - What the assistant writes: [The configuration file](../reference/configuration.md)
2829 - [How to edit or switch the configuration](edit-or-switch-the-configuration.md)
2930 - [Tutorial: your first agent, without writing any configuration](../tutorials/your-first-agent.md)
@@ -24,6 +24,7 @@ When the agent cannot be added (a name already used, for instance), the assistan
24 24
25 ## See also25 ## See also
26 26
27+- To create a new mini-me agent by answering questions, with no file and no folder to choose: [How to create a mini-me agent](create-a-mini-me-agent.md)
27 - What the assistant writes: [The configuration file](../reference/configuration.md)28 - What the assistant writes: [The configuration file](../reference/configuration.md)
28 - [How to edit or switch the configuration](edit-or-switch-the-configuration.md)29 - [How to edit or switch the configuration](edit-or-switch-the-configuration.md)
29 - [Tutorial: your first agent, without writing any configuration](../tutorials/your-first-agent.md)30 - [Tutorial: your first agent, without writing any configuration](../tutorials/your-first-agent.md)
added docs/en/how-to/create-a-mini-me-agent.md +35 -0
new file mode 100644
@@ -0,0 +1,35 @@
1+# How to create a mini-me agent
2+
3+This guide shows how to create a new [mini-me](https://git.rickub.com/bots-garden/mini-me) agent from the Sidekicks window, by answering questions, without writing a file or choosing a folder. It assumes mini-me (`mm`) **1.0.9 or later** is installed, and that a model server runs (Docker Model Runner, llmman, Ollama…): the questions list its models. To add an agent that already exists, or another program than mini-me, use [How to add an agent](add-an-agent.md) instead.
4+
5+## Steps
6+
7+1. Open the assistant: **✨ Create my first agent** on the welcome screen, **✨ Create a mini-me agent** under the agents list, or **Create a mini-me agent** in the command palette (⌘K, Ctrl+K on Linux and Windows).
8+2. Answer the questions of mini-me, a few at a time: the model server, the model, what the agent is for, which machine runs the model, whether it asks before each command or file change, the agent's name… Each question comes with mini-me's default: **Next →** takes it. **About these choices** explains the options.
9+3. When mini-me has written the agent, give its last details:
10+ - **Name**: what you call it with in a conversation (`@marcel`), and the name of its folder. It starts from the name you gave mini-me; lowercase letters, digits, `-` and `_`, starting with a letter.
11+ - **Emoji**: pick one, or type any emoji.
12+ - **Where does it run?** **On this computer** (the simplest), **In a Docker container** (Docker must be installed) or **In a Docker Sandbox (sbx)** (sbx must be installed).
13+4. Click **Add the agent**. Its direct conversation opens: write to it.
14+
15+The agent's folder is created in your **Documents** folder, named after the agent (`~/Documents/marcel`). Its settings are in `.mm/agent.yaml` there; for a container or a sandbox, mini-me also writes `Dockerfile` and `compose.yaml`, or `sbxenv.yaml`, and Sidekicks creates the container or the sandbox the first time the agent starts.
16+
17+## When something goes wrong
18+
19+- **"mini-me (mm) is not installed on this computer"**: install mini-me, then click **Try again**. If it is installed but Sidekicks was opened from the Finder, quit Sidekicks and open it again: it reads your shell's `PATH` at startup.
20+- **"mini-me 1.0.8 is installed, but this assistant needs mini-me 1.0.9 or later"**: update mini-me, then click **Try again**.
21+- **"No model server answered"**: the model is then asked as text. Start your model server, then click **Start again**; or type the model's name yourself if you know it.
22+- **"A folder with this name already exists"** or **"Another agent already has this name"**: change the **Name** and click **Add the agent** again. An existing folder is never changed.
23+- **The questions stopped** (after **← Previous question**, for instance): click **Continue** to go on where you were, or **Start again**.
24+
25+## Variants
26+
27+- **Go back**: **← Previous question** takes back your last answer and asks it again; **Start again** forgets every answer.
28+- **Give up**: **Cancel**, or opening a channel, closes the assistant; what mini-me had written is removed.
29+- **Another folder than Documents**: set [`agentsFolder`](../reference/configuration.md#top-level) in **Settings**, for example `agentsFolder: ~/agents`. The next agents are created there.
30+
31+## See also
32+
33+- [How to add an agent](add-an-agent.md) — any program, any folder, with every field.
34+- [How to run an agent in a Docker container](run-an-agent-in-docker.md) · [How to run an agent in an sbx sandbox](run-an-agent-in-a-sandbox.md)
35+- How it works: [`CreatorService`](../reference/agents-and-events.md#creatorservice)
new file mode 100644
@@ -0,0 +1,35 @@
1+# How to create a mini-me agent
2+
3+This guide shows how to create a new [mini-me](https://git.rickub.com/bots-garden/mini-me) agent from the Sidekicks window, by answering questions, without writing a file or choosing a folder. It assumes mini-me (`mm`) **1.0.9 or later** is installed, and that a model server runs (Docker Model Runner, llmman, Ollama…): the questions list its models. To add an agent that already exists, or another program than mini-me, use [How to add an agent](add-an-agent.md) instead.
4+
5+## Steps
6+
7+1. Open the assistant: **✨ Create my first agent** on the welcome screen, **✨ Create a mini-me agent** under the agents list, or **Create a mini-me agent** in the command palette (⌘K, Ctrl+K on Linux and Windows).
8+2. Answer the questions of mini-me, a few at a time: the model server, the model, what the agent is for, which machine runs the model, whether it asks before each command or file change, the agent's name… Each question comes with mini-me's default: **Next →** takes it. **About these choices** explains the options.
9+3. When mini-me has written the agent, give its last details:
10+ - **Name**: what you call it with in a conversation (`@marcel`), and the name of its folder. It starts from the name you gave mini-me; lowercase letters, digits, `-` and `_`, starting with a letter.
11+ - **Emoji**: pick one, or type any emoji.
12+ - **Where does it run?** **On this computer** (the simplest), **In a Docker container** (Docker must be installed) or **In a Docker Sandbox (sbx)** (sbx must be installed).
13+4. Click **Add the agent**. Its direct conversation opens: write to it.
14+
15+The agent's folder is created in your **Documents** folder, named after the agent (`~/Documents/marcel`). Its settings are in `.mm/agent.yaml` there; for a container or a sandbox, mini-me also writes `Dockerfile` and `compose.yaml`, or `sbxenv.yaml`, and Sidekicks creates the container or the sandbox the first time the agent starts.
16+
17+## When something goes wrong
18+
19+- **"mini-me (mm) is not installed on this computer"**: install mini-me, then click **Try again**. If it is installed but Sidekicks was opened from the Finder, quit Sidekicks and open it again: it reads your shell's `PATH` at startup.
20+- **"mini-me 1.0.8 is installed, but this assistant needs mini-me 1.0.9 or later"**: update mini-me, then click **Try again**.
21+- **"No model server answered"**: the model is then asked as text. Start your model server, then click **Start again**; or type the model's name yourself if you know it.
22+- **"A folder with this name already exists"** or **"Another agent already has this name"**: change the **Name** and click **Add the agent** again. An existing folder is never changed.
23+- **The questions stopped** (after **← Previous question**, for instance): click **Continue** to go on where you were, or **Start again**.
24+
25+## Variants
26+
27+- **Go back**: **← Previous question** takes back your last answer and asks it again; **Start again** forgets every answer.
28+- **Give up**: **Cancel**, or opening a channel, closes the assistant; what mini-me had written is removed.
29+- **Another folder than Documents**: set [`agentsFolder`](../reference/configuration.md#top-level) in **Settings**, for example `agentsFolder: ~/agents`. The next agents are created there.
30+
31+## See also
32+
33+- [How to add an agent](add-an-agent.md) — any program, any folder, with every field.
34+- [How to run an agent in a Docker container](run-an-agent-in-docker.md) · [How to run an agent in an sbx sandbox](run-an-agent-in-a-sandbox.md)
35+- How it works: [`CreatorService`](../reference/agents-and-events.md#creatorservice)
modified docs/en/reference/agents-and-events.md +14 -0
@@ -235,6 +235,20 @@ A file opened for editing has `path, content, version`; `version` identifies the
235235 | `ChooseCompose()` | The native file dialog, for a Compose file. |
236236 | `Reset(choice)` | The Danger zone: `settings` (default configuration, preferences forgotten), `history` (this configuration's), `allHistory` (every configuration's) or `everything`. Each thing reset is first kept as a dated copy; returns `{copies[]}`. The history is reopened empty and the declared channels created again; then `config:changed` is sent. |
237237
238+## `CreatorService`
239+
240+The assistant that creates a mini-me agent (issue #94, [How to create a mini-me agent](../how-to/create-a-mini-me-agent.md)). Sidekicks is the ACP client of `mm --acp-create --project yes --output .mm/agent.yaml` (mini-me 1.0.9 and later): mm's `mm init` wizard, with the `.mm` layout imposed and neither of those two questions asked. Sidekicks advertises `clientCapabilities.elicitation.form` and shows each `elicitation/create` form of mm (fields in the order of `required`; `string` with `enum` → choice, `boolean`, `array` → several choices, `number`, other `string` → text). The wizard works in a temporary folder `<agentsFolder>/.sidekicks-new-agent-…`, because the agent's name, which names its folder, comes near the end. One wizard at a time.
241+
242+| Method | Effect |
243+| --- | --- |
244+| `Start()` | Runs `mm --version` (`mini-me (mm) is not installed`; `mini-me (mm) 1.0.8 is too old: version 1.0.9 or later is needed`; a version mm cannot tell is accepted), closes a wizard left open, creates the temporary folder (and removes those older than a day), starts mm there and sends `/start`. Returns `{view, agentsFolder, version}`. |
245+| `Answer(answer)` | Answers the form shown: `{action: "accept", content: {name: value…}}`, `decline` or `cancel`. Returns the next `view`. |
246+| `Send(text)` | Sends a message to mm (`/back`, `/restart`, `/start`…); refused while a form waits (decline it first). Returns the next `view`. |
247+| `Finish({name, icon, environment})` | Renames the temporary folder `<agentsFolder>/<name>` (mode 0755), then, for `container` or `sbx`, starts mm again in it and sends `/dockerinit` or `/sbxinit`; adds the agent with `mm --acp --config <folder>/.mm/agent.yaml`, through `docker exec -i <container>` or `sbx exec -i <sandbox>` with the lifecycle commands of the `compose.yaml` or `sbxenv.yaml` (as the "add an agent" assistant does with a dropped file), its title from `acp.title`. Returns `{problem, problems[], name, folder, messages[]}`: `problem` is `nameTaken`, `folderExists` or `invalidName` when nothing was changed and another name can be tried; `problems` are the configuration's. An existing folder is never touched. |
248+| `Cancel()` | Stops mm; before `Finish`, removes the temporary folder. Also done when Sidekicks quits. |
249+
250+A `view` is `{messages[], form, written, name, title}`: mm's messages since the last call (each one whole), the form waiting (`{message, fields[{name, title, description, type, options[], default, required}]}`, `null` when none), and, once `.mm/agent.yaml` exists, `written` with mm's `acp.name` (turned into a valid name) and `acp.title`. The page shows mm's `⚠️` messages and folds the others; a `model` field asked as text means that no model server answered.
251+
238252 ## Tools offered to the agents
239253
240254 Issues #90 and #91. Sidekicks offers every agent six tools, as [`agentTools`](configuration.md#agenttools) allows (all by default), with mini-me's protocol (`org.mini-me/tools`, ACP extension methods). An agent that knows it (`acp.clientTools` in an `mm` file) gives them to its model as `client_<name>`; the others ignore them. Few ACP agents discover a client's tools: among the agents Sidekicks documents, only mini-me does (not Claude, Codex, Gemini nor docker-agent).
@@ -235,6 +235,20 @@ A file opened for editing has `path, content, version`; `version` identifies the
235 | `ChooseCompose()` | The native file dialog, for a Compose file. |235 | `ChooseCompose()` | The native file dialog, for a Compose file. |
236 | `Reset(choice)` | The Danger zone: `settings` (default configuration, preferences forgotten), `history` (this configuration's), `allHistory` (every configuration's) or `everything`. Each thing reset is first kept as a dated copy; returns `{copies[]}`. The history is reopened empty and the declared channels created again; then `config:changed` is sent. |236 | `Reset(choice)` | The Danger zone: `settings` (default configuration, preferences forgotten), `history` (this configuration's), `allHistory` (every configuration's) or `everything`. Each thing reset is first kept as a dated copy; returns `{copies[]}`. The history is reopened empty and the declared channels created again; then `config:changed` is sent. |
237 237
238+## `CreatorService`
239+
240+The assistant that creates a mini-me agent (issue #94, [How to create a mini-me agent](../how-to/create-a-mini-me-agent.md)). Sidekicks is the ACP client of `mm --acp-create --project yes --output .mm/agent.yaml` (mini-me 1.0.9 and later): mm's `mm init` wizard, with the `.mm` layout imposed and neither of those two questions asked. Sidekicks advertises `clientCapabilities.elicitation.form` and shows each `elicitation/create` form of mm (fields in the order of `required`; `string` with `enum` → choice, `boolean`, `array` → several choices, `number`, other `string` → text). The wizard works in a temporary folder `<agentsFolder>/.sidekicks-new-agent-…`, because the agent's name, which names its folder, comes near the end. One wizard at a time.
241+
242+| Method | Effect |
243+| --- | --- |
244+| `Start()` | Runs `mm --version` (`mini-me (mm) is not installed`; `mini-me (mm) 1.0.8 is too old: version 1.0.9 or later is needed`; a version mm cannot tell is accepted), closes a wizard left open, creates the temporary folder (and removes those older than a day), starts mm there and sends `/start`. Returns `{view, agentsFolder, version}`. |
245+| `Answer(answer)` | Answers the form shown: `{action: "accept", content: {name: value…}}`, `decline` or `cancel`. Returns the next `view`. |
246+| `Send(text)` | Sends a message to mm (`/back`, `/restart`, `/start`…); refused while a form waits (decline it first). Returns the next `view`. |
247+| `Finish({name, icon, environment})` | Renames the temporary folder `<agentsFolder>/<name>` (mode 0755), then, for `container` or `sbx`, starts mm again in it and sends `/dockerinit` or `/sbxinit`; adds the agent with `mm --acp --config <folder>/.mm/agent.yaml`, through `docker exec -i <container>` or `sbx exec -i <sandbox>` with the lifecycle commands of the `compose.yaml` or `sbxenv.yaml` (as the "add an agent" assistant does with a dropped file), its title from `acp.title`. Returns `{problem, problems[], name, folder, messages[]}`: `problem` is `nameTaken`, `folderExists` or `invalidName` when nothing was changed and another name can be tried; `problems` are the configuration's. An existing folder is never touched. |
248+| `Cancel()` | Stops mm; before `Finish`, removes the temporary folder. Also done when Sidekicks quits. |
249+
250+A `view` is `{messages[], form, written, name, title}`: mm's messages since the last call (each one whole), the form waiting (`{message, fields[{name, title, description, type, options[], default, required}]}`, `null` when none), and, once `.mm/agent.yaml` exists, `written` with mm's `acp.name` (turned into a valid name) and `acp.title`. The page shows mm's `⚠️` messages and folds the others; a `model` field asked as text means that no model server answered.
251+
238 ## Tools offered to the agents252 ## Tools offered to the agents
239 253
240 Issues #90 and #91. Sidekicks offers every agent six tools, as [`agentTools`](configuration.md#agenttools) allows (all by default), with mini-me's protocol (`org.mini-me/tools`, ACP extension methods). An agent that knows it (`acp.clientTools` in an `mm` file) gives them to its model as `client_<name>`; the others ignore them. Few ACP agents discover a client's tools: among the agents Sidekicks documents, only mini-me does (not Claude, Codex, Gemini nor docker-agent).254 Issues #90 and #91. Sidekicks offers every agent six tools, as [`agentTools`](configuration.md#agenttools) allows (all by default), with mini-me's protocol (`org.mini-me/tools`, ACP extension methods). An agent that knows it (`acp.clientTools` in an `mm` file) gives them to its model as `client_<name>`; the others ignore them. Few ACP agents discover a client's tools: among the agents Sidekicks documents, only mini-me does (not Claude, Codex, Gemini nor docker-agent).
modified docs/en/reference/configuration.md +1 -0
@@ -39,6 +39,7 @@ The file is looked up in this order; the first one that applies wins:
3939 | `ui` | object | no | | Interface preferences. |
4040 | `limits` | object | no | | Resource limits. |
4141 | `agentTools` | object | no | | The tools Sidekicks offers the agents ([below](#agenttools)). |
42+| `agentsFolder` | path | no | `~/Documents` | Where the assistant that creates mini-me agents makes one folder per agent ([How to create a mini-me agent](../how-to/create-a-mini-me-agent.md)): absolute, `~/…`, or relative to this file. Created when missing. |
4243 | `agents` | list of agents | yes | | The agents available with `@name`. May be empty. |
4344 | `channels` | list of channels | no | `[]` | Channels created at startup when they do not exist yet. |
4445
@@ -39,6 +39,7 @@ The file is looked up in this order; the first one that applies wins:
39 | `ui` | object | no | | Interface preferences. |39 | `ui` | object | no | | Interface preferences. |
40 | `limits` | object | no | | Resource limits. |40 | `limits` | object | no | | Resource limits. |
41 | `agentTools` | object | no | | The tools Sidekicks offers the agents ([below](#agenttools)). |41 | `agentTools` | object | no | | The tools Sidekicks offers the agents ([below](#agenttools)). |
42+| `agentsFolder` | path | no | `~/Documents` | Where the assistant that creates mini-me agents makes one folder per agent ([How to create a mini-me agent](../how-to/create-a-mini-me-agent.md)): absolute, `~/…`, or relative to this file. Created when missing. |
42 | `agents` | list of agents | yes | | The agents available with `@name`. May be empty. |43 | `agents` | list of agents | yes | | The agents available with `@name`. May be empty. |
43 | `channels` | list of channels | no | `[]` | Channels created at startup when they do not exist yet. |44 | `channels` | list of channels | no | `[]` | Channels created at startup when they do not exist yet. |
44 45
modified docs/en/reference/keyboard-shortcuts.md +1 -1
@@ -25,7 +25,7 @@ On Linux and Windows, when the cursor is in an agent's terminal, the terminal ke
2525 | Enter | Runs the selection |
2626 | Escape, or a click outside | Closes the palette |
2727
28-The palette lists, in order: the channels, a conversation per agent, the files of each agent, the actions of the table above, and **Open a configuration…**.
28+The palette lists, in order: the channels, a conversation per agent, the files of each agent, the actions of the table above, **Create a mini-me agent** and **Open a configuration…**.
2929
3030 ## Message box
3131
@@ -25,7 +25,7 @@ On Linux and Windows, when the cursor is in an agent's terminal, the terminal ke
25 | Enter | Runs the selection |25 | Enter | Runs the selection |
26 | Escape, or a click outside | Closes the palette |26 | Escape, or a click outside | Closes the palette |
27 27
28-The palette lists, in order: the channels, a conversation per agent, the files of each agent, the actions of the table above, and **Open a configuration…**.28+The palette lists, in order: the channels, a conversation per agent, the files of each agent, the actions of the table above, **Create a mini-me agent** and **Open a configuration…**.
29 29
30 ## Message box30 ## Message box
31 31
modified docs/fr/README.md +1 -1
@@ -7,7 +7,7 @@ Cette documentation suit la méthode [Diátaxis](https://diataxis.fr) : choisiss
77 | Vous voulez… | Section | Pages |
88 | --- | --- | --- |
99 | **apprendre** en pratiquant | Tutoriels | [Votre premier agent, sans écrire de configuration](tutorials/premier-agent.md) · [Un channel avec deux agents](tutorials/premier-channel.md) · [Votre première conversation avec un agent](tutorials/premiere-conversation.md) · [Votre premier lancement de Sidekicks](tutorials/premier-lancement.md) · [Votre premier échange ACP avec un agent de test](tutorials/premier-echange-acp.md) |
10-| **réaliser** une tâche précise | Guides pratiques | [Installer Sidekicks](how-to/installer-sidekicks.md) · [Ajouter un agent](how-to/ajouter-un-agent.md) · [Travailler avec les fichiers et le terminal d'un agent](how-to/fichiers-et-terminal-d-un-agent.md) · [Lancer un agent dans un conteneur Docker](how-to/lancer-un-agent-dans-docker.md) · [Lancer un agent dans une sandbox sbx](how-to/lancer-un-agent-dans-une-sandbox.md) · [Ajouter un agent Claude dans une sandbox sbx](how-to/ajouter-un-agent-claude-dans-une-sandbox.md) · [Ajouter un agent Codex dans une sandbox sbx](how-to/ajouter-un-agent-codex-dans-une-sandbox.md) · [Ajouter un agent Gemini dans une sandbox sbx](how-to/ajouter-un-agent-gemini-dans-une-sandbox.md) · [Joindre des fichiers à un message](how-to/joindre-des-fichiers-a-un-message.md) · [Gérer les channels et leurs agents](how-to/gerer-les-channels.md) · [Modifier ou changer la configuration](how-to/modifier-ou-changer-la-configuration.md) · [Repartir de zéro](how-to/repartir-de-zero.md) · [Surveiller la pression mémoire](how-to/surveiller-la-pression-memoire.md) · [Laisser un agent utiliser les outils de Sidekicks](how-to/utiliser-les-outils-de-sidekicks-depuis-un-agent.md) · [Développer l'application](how-to/developper-l-application.md) · [Lancer les tests](how-to/lancer-les-tests.md) · [Vérifier une modification avant de la fusionner](how-to/verifier-avant-de-fusionner.md) · [Lancer un agent de test](how-to/lancer-un-agent-de-test.md) · [Dérouler les scénarios de bout en bout (v0.1)](how-to/derouler-les-scenarios-de-bout-en-bout.md) · [Définir la version](how-to/definir-la-version.md) · [Tester la CI locale (temporaire)](how-to/tester-la-ci-locale.md) · [Publier une release](how-to/publier-une-release.md) · [Signer et notariser pour macOS](how-to/signer-et-notariser-sous-macos.md) · [Tester l'issue #52 sous macOS](how-to/tester-l-issue-52-sous-macos.md) · [Tester les issues #49 et #50 sous macOS](how-to/tester-les-issues-49-et-50-sous-macos.md) · [Tester l'issue #47 sous macOS](how-to/tester-l-issue-47-sous-macos.md) · [Tester la milestone M4 sous macOS](how-to/tester-la-milestone-m4-sous-macos.md) · [Tester la milestone M3 sous macOS](how-to/tester-la-milestone-m3-sous-macos.md) · [Tester la milestone M2 sous macOS](how-to/tester-la-milestone-m2-sous-macos.md) · [Tester la milestone M1 sous macOS](how-to/tester-la-milestone-m1-sous-macos.md) · [Tester la milestone Initialize sous macOS](how-to/tester-la-milestone-initialize-sous-macos.md) |
10+| **réaliser** une tâche précise | Guides pratiques | [Installer Sidekicks](how-to/installer-sidekicks.md) · [Créer un agent mini-me](how-to/creer-un-agent-mini-me.md) · [Ajouter un agent](how-to/ajouter-un-agent.md) · [Travailler avec les fichiers et le terminal d'un agent](how-to/fichiers-et-terminal-d-un-agent.md) · [Lancer un agent dans un conteneur Docker](how-to/lancer-un-agent-dans-docker.md) · [Lancer un agent dans une sandbox sbx](how-to/lancer-un-agent-dans-une-sandbox.md) · [Ajouter un agent Claude dans une sandbox sbx](how-to/ajouter-un-agent-claude-dans-une-sandbox.md) · [Ajouter un agent Codex dans une sandbox sbx](how-to/ajouter-un-agent-codex-dans-une-sandbox.md) · [Ajouter un agent Gemini dans une sandbox sbx](how-to/ajouter-un-agent-gemini-dans-une-sandbox.md) · [Joindre des fichiers à un message](how-to/joindre-des-fichiers-a-un-message.md) · [Gérer les channels et leurs agents](how-to/gerer-les-channels.md) · [Modifier ou changer la configuration](how-to/modifier-ou-changer-la-configuration.md) · [Repartir de zéro](how-to/repartir-de-zero.md) · [Surveiller la pression mémoire](how-to/surveiller-la-pression-memoire.md) · [Laisser un agent utiliser les outils de Sidekicks](how-to/utiliser-les-outils-de-sidekicks-depuis-un-agent.md) · [Développer l'application](how-to/developper-l-application.md) · [Lancer les tests](how-to/lancer-les-tests.md) · [Vérifier une modification avant de la fusionner](how-to/verifier-avant-de-fusionner.md) · [Lancer un agent de test](how-to/lancer-un-agent-de-test.md) · [Dérouler les scénarios de bout en bout (v0.1)](how-to/derouler-les-scenarios-de-bout-en-bout.md) · [Définir la version](how-to/definir-la-version.md) · [Tester la CI locale (temporaire)](how-to/tester-la-ci-locale.md) · [Publier une release](how-to/publier-une-release.md) · [Signer et notariser pour macOS](how-to/signer-et-notariser-sous-macos.md) · [Tester l'issue #52 sous macOS](how-to/tester-l-issue-52-sous-macos.md) · [Tester les issues #49 et #50 sous macOS](how-to/tester-les-issues-49-et-50-sous-macos.md) · [Tester l'issue #47 sous macOS](how-to/tester-l-issue-47-sous-macos.md) · [Tester la milestone M4 sous macOS](how-to/tester-la-milestone-m4-sous-macos.md) · [Tester la milestone M3 sous macOS](how-to/tester-la-milestone-m3-sous-macos.md) · [Tester la milestone M2 sous macOS](how-to/tester-la-milestone-m2-sous-macos.md) · [Tester la milestone M1 sous macOS](how-to/tester-la-milestone-m1-sous-macos.md) · [Tester la milestone Initialize sous macOS](how-to/tester-la-milestone-initialize-sous-macos.md) |
1111 | **consulter** un détail exact | Référence | [Le fichier de configuration](reference/configuration.md) · [Raccourcis clavier](reference/raccourcis-clavier.md) · [Agents, channels et événements](reference/agents-et-evenements.md) · [Commandes](reference/commandes.md) · [scripts/agents.sh](reference/script-agents.md) |
1212 | **comprendre** le pourquoi | Explications | [Workspaces et terminaux](explanation/workspaces-et-terminaux.md) · [Les channels et ce que sait chaque agent](explanation/channels-et-contexte.md) · [Permissions et confiance](explanation/permissions-et-confiance.md) · [Pourquoi ACP](explanation/pourquoi-acp.md) · [La stack de l'interface](explanation/stack-interface.md) · [Architecture](explanation/architecture.md) · [Mémoire et modèles locaux](explanation/memoire-et-modeles-locaux.md) |
1313
@@ -7,7 +7,7 @@ Cette documentation suit la méthode [Diátaxis](https://diataxis.fr) : choisiss
7 | Vous voulez… | Section | Pages |7 | Vous voulez… | Section | Pages |
8 | --- | --- | --- |8 | --- | --- | --- |
9 | **apprendre** en pratiquant | Tutoriels | [Votre premier agent, sans écrire de configuration](tutorials/premier-agent.md) · [Un channel avec deux agents](tutorials/premier-channel.md) · [Votre première conversation avec un agent](tutorials/premiere-conversation.md) · [Votre premier lancement de Sidekicks](tutorials/premier-lancement.md) · [Votre premier échange ACP avec un agent de test](tutorials/premier-echange-acp.md) |9 | **apprendre** en pratiquant | Tutoriels | [Votre premier agent, sans écrire de configuration](tutorials/premier-agent.md) · [Un channel avec deux agents](tutorials/premier-channel.md) · [Votre première conversation avec un agent](tutorials/premiere-conversation.md) · [Votre premier lancement de Sidekicks](tutorials/premier-lancement.md) · [Votre premier échange ACP avec un agent de test](tutorials/premier-echange-acp.md) |
10-| **réaliser** une tâche précise | Guides pratiques | [Installer Sidekicks](how-to/installer-sidekicks.md) · [Ajouter un agent](how-to/ajouter-un-agent.md) · [Travailler avec les fichiers et le terminal d'un agent](how-to/fichiers-et-terminal-d-un-agent.md) · [Lancer un agent dans un conteneur Docker](how-to/lancer-un-agent-dans-docker.md) · [Lancer un agent dans une sandbox sbx](how-to/lancer-un-agent-dans-une-sandbox.md) · [Ajouter un agent Claude dans une sandbox sbx](how-to/ajouter-un-agent-claude-dans-une-sandbox.md) · [Ajouter un agent Codex dans une sandbox sbx](how-to/ajouter-un-agent-codex-dans-une-sandbox.md) · [Ajouter un agent Gemini dans une sandbox sbx](how-to/ajouter-un-agent-gemini-dans-une-sandbox.md) · [Joindre des fichiers à un message](how-to/joindre-des-fichiers-a-un-message.md) · [Gérer les channels et leurs agents](how-to/gerer-les-channels.md) · [Modifier ou changer la configuration](how-to/modifier-ou-changer-la-configuration.md) · [Repartir de zéro](how-to/repartir-de-zero.md) · [Surveiller la pression mémoire](how-to/surveiller-la-pression-memoire.md) · [Laisser un agent utiliser les outils de Sidekicks](how-to/utiliser-les-outils-de-sidekicks-depuis-un-agent.md) · [Développer l'application](how-to/developper-l-application.md) · [Lancer les tests](how-to/lancer-les-tests.md) · [Vérifier une modification avant de la fusionner](how-to/verifier-avant-de-fusionner.md) · [Lancer un agent de test](how-to/lancer-un-agent-de-test.md) · [Dérouler les scénarios de bout en bout (v0.1)](how-to/derouler-les-scenarios-de-bout-en-bout.md) · [Définir la version](how-to/definir-la-version.md) · [Tester la CI locale (temporaire)](how-to/tester-la-ci-locale.md) · [Publier une release](how-to/publier-une-release.md) · [Signer et notariser pour macOS](how-to/signer-et-notariser-sous-macos.md) · [Tester l'issue #52 sous macOS](how-to/tester-l-issue-52-sous-macos.md) · [Tester les issues #49 et #50 sous macOS](how-to/tester-les-issues-49-et-50-sous-macos.md) · [Tester l'issue #47 sous macOS](how-to/tester-l-issue-47-sous-macos.md) · [Tester la milestone M4 sous macOS](how-to/tester-la-milestone-m4-sous-macos.md) · [Tester la milestone M3 sous macOS](how-to/tester-la-milestone-m3-sous-macos.md) · [Tester la milestone M2 sous macOS](how-to/tester-la-milestone-m2-sous-macos.md) · [Tester la milestone M1 sous macOS](how-to/tester-la-milestone-m1-sous-macos.md) · [Tester la milestone Initialize sous macOS](how-to/tester-la-milestone-initialize-sous-macos.md) |10+| **réaliser** une tâche précise | Guides pratiques | [Installer Sidekicks](how-to/installer-sidekicks.md) · [Créer un agent mini-me](how-to/creer-un-agent-mini-me.md) · [Ajouter un agent](how-to/ajouter-un-agent.md) · [Travailler avec les fichiers et le terminal d'un agent](how-to/fichiers-et-terminal-d-un-agent.md) · [Lancer un agent dans un conteneur Docker](how-to/lancer-un-agent-dans-docker.md) · [Lancer un agent dans une sandbox sbx](how-to/lancer-un-agent-dans-une-sandbox.md) · [Ajouter un agent Claude dans une sandbox sbx](how-to/ajouter-un-agent-claude-dans-une-sandbox.md) · [Ajouter un agent Codex dans une sandbox sbx](how-to/ajouter-un-agent-codex-dans-une-sandbox.md) · [Ajouter un agent Gemini dans une sandbox sbx](how-to/ajouter-un-agent-gemini-dans-une-sandbox.md) · [Joindre des fichiers à un message](how-to/joindre-des-fichiers-a-un-message.md) · [Gérer les channels et leurs agents](how-to/gerer-les-channels.md) · [Modifier ou changer la configuration](how-to/modifier-ou-changer-la-configuration.md) · [Repartir de zéro](how-to/repartir-de-zero.md) · [Surveiller la pression mémoire](how-to/surveiller-la-pression-memoire.md) · [Laisser un agent utiliser les outils de Sidekicks](how-to/utiliser-les-outils-de-sidekicks-depuis-un-agent.md) · [Développer l'application](how-to/developper-l-application.md) · [Lancer les tests](how-to/lancer-les-tests.md) · [Vérifier une modification avant de la fusionner](how-to/verifier-avant-de-fusionner.md) · [Lancer un agent de test](how-to/lancer-un-agent-de-test.md) · [Dérouler les scénarios de bout en bout (v0.1)](how-to/derouler-les-scenarios-de-bout-en-bout.md) · [Définir la version](how-to/definir-la-version.md) · [Tester la CI locale (temporaire)](how-to/tester-la-ci-locale.md) · [Publier une release](how-to/publier-une-release.md) · [Signer et notariser pour macOS](how-to/signer-et-notariser-sous-macos.md) · [Tester l'issue #52 sous macOS](how-to/tester-l-issue-52-sous-macos.md) · [Tester les issues #49 et #50 sous macOS](how-to/tester-les-issues-49-et-50-sous-macos.md) · [Tester l'issue #47 sous macOS](how-to/tester-l-issue-47-sous-macos.md) · [Tester la milestone M4 sous macOS](how-to/tester-la-milestone-m4-sous-macos.md) · [Tester la milestone M3 sous macOS](how-to/tester-la-milestone-m3-sous-macos.md) · [Tester la milestone M2 sous macOS](how-to/tester-la-milestone-m2-sous-macos.md) · [Tester la milestone M1 sous macOS](how-to/tester-la-milestone-m1-sous-macos.md) · [Tester la milestone Initialize sous macOS](how-to/tester-la-milestone-initialize-sous-macos.md) |
11 | **consulter** un détail exact | Référence | [Le fichier de configuration](reference/configuration.md) · [Raccourcis clavier](reference/raccourcis-clavier.md) · [Agents, channels et événements](reference/agents-et-evenements.md) · [Commandes](reference/commandes.md) · [scripts/agents.sh](reference/script-agents.md) |11 | **consulter** un détail exact | Référence | [Le fichier de configuration](reference/configuration.md) · [Raccourcis clavier](reference/raccourcis-clavier.md) · [Agents, channels et événements](reference/agents-et-evenements.md) · [Commandes](reference/commandes.md) · [scripts/agents.sh](reference/script-agents.md) |
12 | **comprendre** le pourquoi | Explications | [Workspaces et terminaux](explanation/workspaces-et-terminaux.md) · [Les channels et ce que sait chaque agent](explanation/channels-et-contexte.md) · [Permissions et confiance](explanation/permissions-et-confiance.md) · [Pourquoi ACP](explanation/pourquoi-acp.md) · [La stack de l'interface](explanation/stack-interface.md) · [Architecture](explanation/architecture.md) · [Mémoire et modèles locaux](explanation/memoire-et-modeles-locaux.md) |12 | **comprendre** le pourquoi | Explications | [Workspaces et terminaux](explanation/workspaces-et-terminaux.md) · [Les channels et ce que sait chaque agent](explanation/channels-et-contexte.md) · [Permissions et confiance](explanation/permissions-et-confiance.md) · [Pourquoi ACP](explanation/pourquoi-acp.md) · [La stack de l'interface](explanation/stack-interface.md) · [Architecture](explanation/architecture.md) · [Mémoire et modèles locaux](explanation/memoire-et-modeles-locaux.md) |
13 13
modified docs/fr/how-to/ajouter-un-agent.md +1 -0
@@ -24,6 +24,7 @@ Quand l'agent ne peut pas être ajouté (un nom déjà pris, par exemple), l'ass
2424
2525 ## Voir aussi
2626
27+- Pour créer un nouvel agent mini-me en répondant à des questions, sans fichier ni dossier à choisir : [Créer un agent mini-me](creer-un-agent-mini-me.md)
2728 - Ce que l'assistant écrit : [Le fichier de configuration](../reference/configuration.md)
2829 - [Modifier ou changer la configuration](modifier-ou-changer-la-configuration.md)
2930 - [Tutoriel : votre premier agent, sans écrire de configuration](../tutorials/premier-agent.md)
@@ -24,6 +24,7 @@ Quand l'agent ne peut pas être ajouté (un nom déjà pris, par exemple), l'ass
24 24
25 ## Voir aussi25 ## Voir aussi
26 26
27+- Pour créer un nouvel agent mini-me en répondant à des questions, sans fichier ni dossier à choisir : [Créer un agent mini-me](creer-un-agent-mini-me.md)
27 - Ce que l'assistant écrit : [Le fichier de configuration](../reference/configuration.md)28 - Ce que l'assistant écrit : [Le fichier de configuration](../reference/configuration.md)
28 - [Modifier ou changer la configuration](modifier-ou-changer-la-configuration.md)29 - [Modifier ou changer la configuration](modifier-ou-changer-la-configuration.md)
29 - [Tutoriel : votre premier agent, sans écrire de configuration](../tutorials/premier-agent.md)30 - [Tutoriel : votre premier agent, sans écrire de configuration](../tutorials/premier-agent.md)
added docs/fr/how-to/creer-un-agent-mini-me.md +35 -0
new file mode 100644
@@ -0,0 +1,35 @@
1+# Créer un agent mini-me
2+
3+Ce guide montre comment créer un nouvel agent [mini-me](https://git.rickub.com/bots-garden/mini-me) depuis la fenêtre de Sidekicks, en répondant à des questions, sans écrire de fichier ni choisir de dossier. Il suppose que mini-me (`mm`) **1.0.9 ou plus récent** est installé, et qu'un serveur de modèles tourne (Docker Model Runner, llmman, Ollama…) : les questions listent ses modèles. Pour ajouter un agent qui existe déjà, ou un autre programme que mini-me, suivez plutôt [Ajouter un agent](ajouter-un-agent.md).
4+
5+## Étapes
6+
7+1. Ouvrez l'assistant : **✨ Créer mon premier agent** sur l'écran d'accueil, **✨ Créer un agent mini-me** sous la liste des agents, ou **Créer un agent mini-me** dans la palette de commandes (⌘K, Ctrl+K sous Linux et Windows).
8+2. Répondez aux questions de mini-me, quelques-unes à la fois : le serveur de modèles, le modèle, à quoi sert l'agent, quelle machine fait tourner le modèle, s'il demande avant chaque commande ou modification de fichier, le nom de l'agent… Chaque question arrive avec la valeur par défaut de mini-me : **Suivant →** la prend. **À propos de ces choix** explique les options. Les questions sont celles de mini-me, en anglais.
9+3. Quand mini-me a écrit l'agent, donnez ses derniers détails :
10+ - **Nom** : ce qui l'appelle dans une conversation (`@marcel`), et le nom de son dossier. Il part du nom donné à mini-me ; minuscules, chiffres, `-` et `_`, en commençant par une lettre.
11+ - **Emoji** : choisissez-en un, ou tapez n'importe quel emoji.
12+ - **Où s'exécute-t-il ?** **Sur cet ordinateur** (le plus simple), **Dans un conteneur Docker** (Docker doit être installé) ou **Dans une Docker Sandbox (sbx)** (sbx doit être installé).
13+4. Cliquez sur **Ajouter l'agent**. Sa conversation directe s'ouvre : écrivez-lui.
14+
15+Le dossier de l'agent est créé dans votre dossier **Documents**, au nom de l'agent (`~/Documents/marcel`). Ses réglages y sont dans `.mm/agent.yaml` ; pour un conteneur ou une sandbox, mini-me écrit aussi `Dockerfile` et `compose.yaml`, ou `sbxenv.yaml`, et Sidekicks crée le conteneur ou la sandbox au premier démarrage de l'agent.
16+
17+## Quand quelque chose ne va pas
18+
19+- **« mini-me (mm) n'est pas installé sur cet ordinateur »** : installez mini-me, puis cliquez sur **Réessayer**. S'il est installé mais que Sidekicks a été ouvert depuis le Finder, quittez Sidekicks et rouvrez-le : il lit le `PATH` de votre shell au démarrage.
20+- **« mini-me 1.0.8 est installé, mais cet assistant a besoin de mini-me 1.0.9 ou plus récent »** : mettez mini-me à jour, puis cliquez sur **Réessayer**.
21+- **« Aucun serveur de modèles n'a répondu »** : le modèle est alors demandé en texte. Démarrez votre serveur de modèles, puis cliquez sur **Recommencer** ; ou tapez vous-même le nom du modèle si vous le connaissez.
22+- **« Un dossier porte déjà ce nom »** ou **« Un autre agent porte déjà ce nom »** : changez le **Nom** et cliquez de nouveau sur **Ajouter l'agent**. Un dossier existant n'est jamais modifié.
23+- **Les questions se sont arrêtées** (après **← Question précédente**, par exemple) : cliquez sur **Continuer** pour reprendre où vous en étiez, ou sur **Recommencer**.
24+
25+## Variantes
26+
27+- **Revenir en arrière** : **← Question précédente** reprend votre dernière réponse et la repose ; **Recommencer** oublie toutes les réponses.
28+- **Abandonner** : **Annuler**, ou ouvrir un channel, ferme l'assistant ; ce que mini-me avait écrit est supprimé.
29+- **Un autre dossier que Documents** : réglez [`agentsFolder`](../reference/configuration.md#racine) dans **Settings**, par exemple `agentsFolder: ~/agents`. Les agents suivants y sont créés.
30+
31+## Voir aussi
32+
33+- [Ajouter un agent](ajouter-un-agent.md) — n'importe quel programme, n'importe quel dossier, avec tous les champs.
34+- [Lancer un agent dans Docker](lancer-un-agent-dans-docker.md) · [Lancer un agent dans une sandbox](lancer-un-agent-dans-une-sandbox.md)
35+- Comment ça marche : [`CreatorService`](../reference/agents-et-evenements.md#creatorservice)
new file mode 100644
@@ -0,0 +1,35 @@
1+# Créer un agent mini-me
2+
3+Ce guide montre comment créer un nouvel agent [mini-me](https://git.rickub.com/bots-garden/mini-me) depuis la fenêtre de Sidekicks, en répondant à des questions, sans écrire de fichier ni choisir de dossier. Il suppose que mini-me (`mm`) **1.0.9 ou plus récent** est installé, et qu'un serveur de modèles tourne (Docker Model Runner, llmman, Ollama…) : les questions listent ses modèles. Pour ajouter un agent qui existe déjà, ou un autre programme que mini-me, suivez plutôt [Ajouter un agent](ajouter-un-agent.md).
4+
5+## Étapes
6+
7+1. Ouvrez l'assistant : **✨ Créer mon premier agent** sur l'écran d'accueil, **✨ Créer un agent mini-me** sous la liste des agents, ou **Créer un agent mini-me** dans la palette de commandes (⌘K, Ctrl+K sous Linux et Windows).
8+2. Répondez aux questions de mini-me, quelques-unes à la fois : le serveur de modèles, le modèle, à quoi sert l'agent, quelle machine fait tourner le modèle, s'il demande avant chaque commande ou modification de fichier, le nom de l'agent… Chaque question arrive avec la valeur par défaut de mini-me : **Suivant →** la prend. **À propos de ces choix** explique les options. Les questions sont celles de mini-me, en anglais.
9+3. Quand mini-me a écrit l'agent, donnez ses derniers détails :
10+ - **Nom** : ce qui l'appelle dans une conversation (`@marcel`), et le nom de son dossier. Il part du nom donné à mini-me ; minuscules, chiffres, `-` et `_`, en commençant par une lettre.
11+ - **Emoji** : choisissez-en un, ou tapez n'importe quel emoji.
12+ - **Où s'exécute-t-il ?** **Sur cet ordinateur** (le plus simple), **Dans un conteneur Docker** (Docker doit être installé) ou **Dans une Docker Sandbox (sbx)** (sbx doit être installé).
13+4. Cliquez sur **Ajouter l'agent**. Sa conversation directe s'ouvre : écrivez-lui.
14+
15+Le dossier de l'agent est créé dans votre dossier **Documents**, au nom de l'agent (`~/Documents/marcel`). Ses réglages y sont dans `.mm/agent.yaml` ; pour un conteneur ou une sandbox, mini-me écrit aussi `Dockerfile` et `compose.yaml`, ou `sbxenv.yaml`, et Sidekicks crée le conteneur ou la sandbox au premier démarrage de l'agent.
16+
17+## Quand quelque chose ne va pas
18+
19+- **« mini-me (mm) n'est pas installé sur cet ordinateur »** : installez mini-me, puis cliquez sur **Réessayer**. S'il est installé mais que Sidekicks a été ouvert depuis le Finder, quittez Sidekicks et rouvrez-le : il lit le `PATH` de votre shell au démarrage.
20+- **« mini-me 1.0.8 est installé, mais cet assistant a besoin de mini-me 1.0.9 ou plus récent »** : mettez mini-me à jour, puis cliquez sur **Réessayer**.
21+- **« Aucun serveur de modèles n'a répondu »** : le modèle est alors demandé en texte. Démarrez votre serveur de modèles, puis cliquez sur **Recommencer** ; ou tapez vous-même le nom du modèle si vous le connaissez.
22+- **« Un dossier porte déjà ce nom »** ou **« Un autre agent porte déjà ce nom »** : changez le **Nom** et cliquez de nouveau sur **Ajouter l'agent**. Un dossier existant n'est jamais modifié.
23+- **Les questions se sont arrêtées** (après **← Question précédente**, par exemple) : cliquez sur **Continuer** pour reprendre où vous en étiez, ou sur **Recommencer**.
24+
25+## Variantes
26+
27+- **Revenir en arrière** : **← Question précédente** reprend votre dernière réponse et la repose ; **Recommencer** oublie toutes les réponses.
28+- **Abandonner** : **Annuler**, ou ouvrir un channel, ferme l'assistant ; ce que mini-me avait écrit est supprimé.
29+- **Un autre dossier que Documents** : réglez [`agentsFolder`](../reference/configuration.md#racine) dans **Settings**, par exemple `agentsFolder: ~/agents`. Les agents suivants y sont créés.
30+
31+## Voir aussi
32+
33+- [Ajouter un agent](ajouter-un-agent.md) — n'importe quel programme, n'importe quel dossier, avec tous les champs.
34+- [Lancer un agent dans Docker](lancer-un-agent-dans-docker.md) · [Lancer un agent dans une sandbox](lancer-un-agent-dans-une-sandbox.md)
35+- Comment ça marche : [`CreatorService`](../reference/agents-et-evenements.md#creatorservice)
modified docs/fr/reference/agents-et-evenements.md +14 -0
@@ -235,6 +235,20 @@ Un fichier ouvert pour modification a `path, content, version` ; `version` ident
235235 | `ChooseCompose()` | Le sélecteur de fichier natif, pour un fichier Compose. |
236236 | `Reset(choice)` | La Danger zone : `settings` (configuration par défaut, préférences oubliées), `history` (celui de cette configuration), `allHistory` (celui de toutes les configurations) ou `everything`. Chaque élément réinitialisé est d'abord gardé en copie datée ; renvoie `{copies[]}`. L'historique est rouvert vide et les channels déclarés sont recréés ; puis `config:changed` est envoyé. |
237237
238+## `CreatorService`
239+
240+L'assistant qui crée un agent mini-me (issue #94, [Créer un agent mini-me](../how-to/creer-un-agent-mini-me.md)). Sidekicks est le client ACP de `mm --acp-create --project yes --output .mm/agent.yaml` (mini-me 1.0.9 et plus récent) : l'assistant `mm init` de mm, avec la disposition `.mm` imposée et sans poser ces deux questions. Sidekicks annonce `clientCapabilities.elicitation.form` et affiche chaque formulaire `elicitation/create` de mm (champs dans l'ordre de `required` ; `string` avec `enum` → choix, `boolean`, `array` → plusieurs choix, `number`, autre `string` → texte). L'assistant travaille dans un dossier temporaire `<agentsFolder>/.sidekicks-new-agent-…`, parce que le nom de l'agent, qui nomme son dossier, arrive vers la fin. Un assistant à la fois.
241+
242+| Méthode | Effet |
243+| --- | --- |
244+| `Start()` | Lance `mm --version` (`mini-me (mm) is not installed` ; `mini-me (mm) 1.0.8 is too old: version 1.0.9 or later is needed` ; une version que mm ne sait pas dire est acceptée), ferme un assistant resté ouvert, crée le dossier temporaire (et supprime ceux de plus d'un jour), y démarre mm et envoie `/start`. Renvoie `{view, agentsFolder, version}`. |
245+| `Answer(answer)` | Répond au formulaire affiché : `{action: "accept", content: {nom: valeur…}}`, `decline` ou `cancel`. Renvoie la `view` suivante. |
246+| `Send(text)` | Envoie un message à mm (`/back`, `/restart`, `/start`…) ; refusé tant qu'un formulaire attend (le refuser d'abord). Renvoie la `view` suivante. |
247+| `Finish({name, icon, environment})` | Renomme le dossier temporaire en `<agentsFolder>/<name>` (mode 0755), puis, pour `container` ou `sbx`, y redémarre mm et envoie `/dockerinit` ou `/sbxinit` ; ajoute l'agent avec `mm --acp --config <dossier>/.mm/agent.yaml`, à travers `docker exec -i <conteneur>` ou `sbx exec -i <sandbox>` avec les commandes de cycle de vie du `compose.yaml` ou du `sbxenv.yaml` (comme l'assistant « ajouter un agent » avec un fichier déposé), son titre venant de `acp.title`. Renvoie `{problem, problems[], name, folder, messages[]}` : `problem` vaut `nameTaken`, `folderExists` ou `invalidName` quand rien n'a été changé et qu'un autre nom peut être essayé ; `problems` sont ceux de la configuration. Un dossier existant n'est jamais touché. |
248+| `Cancel()` | Arrête mm ; avant `Finish`, supprime le dossier temporaire. Fait aussi quand Sidekicks se ferme. |
249+
250+Une `view` vaut `{messages[], form, written, name, title}` : les messages de mm depuis le dernier appel (chacun entier), le formulaire en attente (`{message, fields[{name, title, description, type, options[], default, required}]}`, `null` sinon) et, dès que `.mm/agent.yaml` existe, `written` avec le `acp.name` de mm (transformé en nom valide) et le `acp.title`. La page affiche les messages `⚠️` de mm et replie les autres ; un champ `model` demandé en texte signifie qu'aucun serveur de modèles n'a répondu.
251+
238252 ## Outils proposés aux agents
239253
240254 Tickets #90 et #91. Sidekicks propose six outils à chaque agent, dans la limite de [`agentTools`](configuration.md#agenttools) (tous par défaut), avec le protocole de mini-me (`org.mini-me/tools`, méthodes d'extension ACP). Un agent qui le connaît (`acp.clientTools` dans un fichier `mm`) les donne à son modèle sous le nom `client_<nom>` ; les autres les ignorent. Peu d'agents ACP découvrent les outils d'un client : parmi les agents que documente Sidekicks, seul mini-me le fait (ni Claude, ni Codex, ni Gemini, ni docker-agent).
@@ -235,6 +235,20 @@ Un fichier ouvert pour modification a `path, content, version` ; `version` ident
235 | `ChooseCompose()` | Le sélecteur de fichier natif, pour un fichier Compose. |235 | `ChooseCompose()` | Le sélecteur de fichier natif, pour un fichier Compose. |
236 | `Reset(choice)` | La Danger zone : `settings` (configuration par défaut, préférences oubliées), `history` (celui de cette configuration), `allHistory` (celui de toutes les configurations) ou `everything`. Chaque élément réinitialisé est d'abord gardé en copie datée ; renvoie `{copies[]}`. L'historique est rouvert vide et les channels déclarés sont recréés ; puis `config:changed` est envoyé. |236 | `Reset(choice)` | La Danger zone : `settings` (configuration par défaut, préférences oubliées), `history` (celui de cette configuration), `allHistory` (celui de toutes les configurations) ou `everything`. Chaque élément réinitialisé est d'abord gardé en copie datée ; renvoie `{copies[]}`. L'historique est rouvert vide et les channels déclarés sont recréés ; puis `config:changed` est envoyé. |
237 237
238+## `CreatorService`
239+
240+L'assistant qui crée un agent mini-me (issue #94, [Créer un agent mini-me](../how-to/creer-un-agent-mini-me.md)). Sidekicks est le client ACP de `mm --acp-create --project yes --output .mm/agent.yaml` (mini-me 1.0.9 et plus récent) : l'assistant `mm init` de mm, avec la disposition `.mm` imposée et sans poser ces deux questions. Sidekicks annonce `clientCapabilities.elicitation.form` et affiche chaque formulaire `elicitation/create` de mm (champs dans l'ordre de `required` ; `string` avec `enum` → choix, `boolean`, `array` → plusieurs choix, `number`, autre `string` → texte). L'assistant travaille dans un dossier temporaire `<agentsFolder>/.sidekicks-new-agent-…`, parce que le nom de l'agent, qui nomme son dossier, arrive vers la fin. Un assistant à la fois.
241+
242+| Méthode | Effet |
243+| --- | --- |
244+| `Start()` | Lance `mm --version` (`mini-me (mm) is not installed` ; `mini-me (mm) 1.0.8 is too old: version 1.0.9 or later is needed` ; une version que mm ne sait pas dire est acceptée), ferme un assistant resté ouvert, crée le dossier temporaire (et supprime ceux de plus d'un jour), y démarre mm et envoie `/start`. Renvoie `{view, agentsFolder, version}`. |
245+| `Answer(answer)` | Répond au formulaire affiché : `{action: "accept", content: {nom: valeur…}}`, `decline` ou `cancel`. Renvoie la `view` suivante. |
246+| `Send(text)` | Envoie un message à mm (`/back`, `/restart`, `/start`…) ; refusé tant qu'un formulaire attend (le refuser d'abord). Renvoie la `view` suivante. |
247+| `Finish({name, icon, environment})` | Renomme le dossier temporaire en `<agentsFolder>/<name>` (mode 0755), puis, pour `container` ou `sbx`, y redémarre mm et envoie `/dockerinit` ou `/sbxinit` ; ajoute l'agent avec `mm --acp --config <dossier>/.mm/agent.yaml`, à travers `docker exec -i <conteneur>` ou `sbx exec -i <sandbox>` avec les commandes de cycle de vie du `compose.yaml` ou du `sbxenv.yaml` (comme l'assistant « ajouter un agent » avec un fichier déposé), son titre venant de `acp.title`. Renvoie `{problem, problems[], name, folder, messages[]}` : `problem` vaut `nameTaken`, `folderExists` ou `invalidName` quand rien n'a été changé et qu'un autre nom peut être essayé ; `problems` sont ceux de la configuration. Un dossier existant n'est jamais touché. |
248+| `Cancel()` | Arrête mm ; avant `Finish`, supprime le dossier temporaire. Fait aussi quand Sidekicks se ferme. |
249+
250+Une `view` vaut `{messages[], form, written, name, title}` : les messages de mm depuis le dernier appel (chacun entier), le formulaire en attente (`{message, fields[{name, title, description, type, options[], default, required}]}`, `null` sinon) et, dès que `.mm/agent.yaml` existe, `written` avec le `acp.name` de mm (transformé en nom valide) et le `acp.title`. La page affiche les messages `⚠️` de mm et replie les autres ; un champ `model` demandé en texte signifie qu'aucun serveur de modèles n'a répondu.
251+
238 ## Outils proposés aux agents252 ## Outils proposés aux agents
239 253
240 Tickets #90 et #91. Sidekicks propose six outils à chaque agent, dans la limite de [`agentTools`](configuration.md#agenttools) (tous par défaut), avec le protocole de mini-me (`org.mini-me/tools`, méthodes d'extension ACP). Un agent qui le connaît (`acp.clientTools` dans un fichier `mm`) les donne à son modèle sous le nom `client_<nom>` ; les autres les ignorent. Peu d'agents ACP découvrent les outils d'un client : parmi les agents que documente Sidekicks, seul mini-me le fait (ni Claude, ni Codex, ni Gemini, ni docker-agent).254 Tickets #90 et #91. Sidekicks propose six outils à chaque agent, dans la limite de [`agentTools`](configuration.md#agenttools) (tous par défaut), avec le protocole de mini-me (`org.mini-me/tools`, méthodes d'extension ACP). Un agent qui le connaît (`acp.clientTools` dans un fichier `mm`) les donne à son modèle sous le nom `client_<nom>` ; les autres les ignorent. Peu d'agents ACP découvrent les outils d'un client : parmi les agents que documente Sidekicks, seul mini-me le fait (ni Claude, ni Codex, ni Gemini, ni docker-agent).
modified docs/fr/reference/configuration.md +1 -0
@@ -39,6 +39,7 @@ Le fichier est cherché dans cet ordre ; la première source applicable l'emport
3939 | `ui` | objet | non | | Préférences d'interface. |
4040 | `limits` | objet | non | | Limites de ressources. |
4141 | `agentTools` | objet | non | | Les outils que Sidekicks propose aux agents ([plus bas](#agenttools)). |
42+| `agentsFolder` | chemin | non | `~/Documents` | Où l'assistant qui crée des agents mini-me fait un dossier par agent ([Créer un agent mini-me](../how-to/creer-un-agent-mini-me.md)) : absolu, `~/…`, ou relatif à ce fichier. Créé s'il manque. |
4243 | `agents` | liste d'agents | oui | | Les agents disponibles avec `@nom`. Peut être vide. |
4344 | `channels` | liste de channels | non | `[]` | Channels créés au démarrage s'ils n'existent pas encore. |
4445
@@ -39,6 +39,7 @@ Le fichier est cherché dans cet ordre ; la première source applicable l'emport
39 | `ui` | objet | non | | Préférences d'interface. |39 | `ui` | objet | non | | Préférences d'interface. |
40 | `limits` | objet | non | | Limites de ressources. |40 | `limits` | objet | non | | Limites de ressources. |
41 | `agentTools` | objet | non | | Les outils que Sidekicks propose aux agents ([plus bas](#agenttools)). |41 | `agentTools` | objet | non | | Les outils que Sidekicks propose aux agents ([plus bas](#agenttools)). |
42+| `agentsFolder` | chemin | non | `~/Documents` | Où l'assistant qui crée des agents mini-me fait un dossier par agent ([Créer un agent mini-me](../how-to/creer-un-agent-mini-me.md)) : absolu, `~/…`, ou relatif à ce fichier. Créé s'il manque. |
42 | `agents` | liste d'agents | oui | | Les agents disponibles avec `@nom`. Peut être vide. |43 | `agents` | liste d'agents | oui | | Les agents disponibles avec `@nom`. Peut être vide. |
43 | `channels` | liste de channels | non | `[]` | Channels créés au démarrage s'ils n'existent pas encore. |44 | `channels` | liste de channels | non | `[]` | Channels créés au démarrage s'ils n'existent pas encore. |
44 45
modified docs/fr/reference/raccourcis-clavier.md +1 -1
@@ -25,7 +25,7 @@ Sous Linux et Windows, quand le curseur est dans le terminal d'un agent, le term
2525 | Entrée | Lance la sélection |
2626 | Échap, ou un clic à côté | Ferme la palette |
2727
28-La palette liste, dans l'ordre : les channels, une conversation par agent, les fichiers de chaque agent, les actions du tableau ci-dessus, et **Ouvrir une configuration…**.
28+La palette liste, dans l'ordre : les channels, une conversation par agent, les fichiers de chaque agent, les actions du tableau ci-dessus, **Créer un agent mini-me** et **Ouvrir une configuration…**.
2929
3030 ## Zone de message
3131
@@ -25,7 +25,7 @@ Sous Linux et Windows, quand le curseur est dans le terminal d'un agent, le term
25 | Entrée | Lance la sélection |25 | Entrée | Lance la sélection |
26 | Échap, ou un clic à côté | Ferme la palette |26 | Échap, ou un clic à côté | Ferme la palette |
27 27
28-La palette liste, dans l'ordre : les channels, une conversation par agent, les fichiers de chaque agent, les actions du tableau ci-dessus, et **Ouvrir une configuration…**.28+La palette liste, dans l'ordre : les channels, une conversation par agent, les fichiers de chaque agent, les actions du tableau ci-dessus, **Créer un agent mini-me** et **Ouvrir une configuration…**.
29 29
30 ## Zone de message30 ## Zone de message
31 31
modified frontend/bindings/git.rickub.com/bots-garden/sidekicks/internal/acp/index.ts +3 -0
@@ -4,6 +4,9 @@
44 export type {
55 Command,
66 Diff,
7+ Form,
8+ FormAnswer,
9+ FormField,
710 PermissionOption,
811 PlanEntry,
912 ToolCall,
@@ -4,6 +4,9 @@
4 export type {4 export type {
5 Command,5 Command,
6 Diff,6 Diff,
7+ Form,
8+ FormAnswer,
9+ FormField,
7 PermissionOption,10 PermissionOption,
8 PlanEntry,11 PlanEntry,
9 ToolCall,12 ToolCall,
modified frontend/bindings/git.rickub.com/bots-garden/sidekicks/internal/acp/models.ts +49 -0
@@ -24,6 +24,55 @@ export interface Diff {
2424 "newFile": boolean;
2525 }
2626
27+/**
28+ * Form is what an agent asks the user to fill in.
29+ */
30+export interface Form {
31+ /**
32+ * Message says what the form is for (Markdown or plain text).
33+ */
34+ "message": string;
35+ "fields": FormField[] | null;
36+}
37+
38+/**
39+ * FormAnswer is the user's answer: Action is accept, decline or cancel;
40+ * Content holds the values by field name when the form is accepted.
41+ */
42+export interface FormAnswer {
43+ "action": string;
44+ "content": { [_ in string]?: any } | null;
45+}
46+
47+/**
48+ * FormField is one question of a Form.
49+ */
50+export interface FormField {
51+ /**
52+ * Name is the key of the answer in FormAnswer.Content.
53+ */
54+ "name": string;
55+ "title": string;
56+
57+ /**
58+ * Description is optional help shown under the title.
59+ */
60+ "description": string;
61+
62+ /**
63+ * Type is one of the Field… constants.
64+ */
65+ "type": string;
66+ "options": string[] | null;
67+
68+ /**
69+ * Default is a string, a boolean, a number or a list of strings
70+ * (FieldMulti), as the agent gave it; nil when there is none.
71+ */
72+ "default": any;
73+ "required": boolean;
74+}
75+
2776 /**
2877 * PermissionOption is one possible answer, as proposed by the agent.
2978 */
@@ -24,6 +24,55 @@ export interface Diff {
24 "newFile": boolean;24 "newFile": boolean;
25 }25 }
26 26
27+/**
28+ * Form is what an agent asks the user to fill in.
29+ */
30+export interface Form {
31+ /**
32+ * Message says what the form is for (Markdown or plain text).
33+ */
34+ "message": string;
35+ "fields": FormField[] | null;
36+}
37+
38+/**
39+ * FormAnswer is the user's answer: Action is accept, decline or cancel;
40+ * Content holds the values by field name when the form is accepted.
41+ */
42+export interface FormAnswer {
43+ "action": string;
44+ "content": { [_ in string]?: any } | null;
45+}
46+
47+/**
48+ * FormField is one question of a Form.
49+ */
50+export interface FormField {
51+ /**
52+ * Name is the key of the answer in FormAnswer.Content.
53+ */
54+ "name": string;
55+ "title": string;
56+
57+ /**
58+ * Description is optional help shown under the title.
59+ */
60+ "description": string;
61+
62+ /**
63+ * Type is one of the Field… constants.
64+ */
65+ "type": string;
66+ "options": string[] | null;
67+
68+ /**
69+ * Default is a string, a boolean, a number or a list of strings
70+ * (FieldMulti), as the agent gave it; nil when there is none.
71+ */
72+ "default": any;
73+ "required": boolean;
74+}
75+
27 /**76 /**
28 * PermissionOption is one possible answer, as proposed by the agent.77 * PermissionOption is one possible answer, as proposed by the agent.
29 */78 */
added frontend/bindings/git.rickub.com/bots-garden/sidekicks/internal/app/creatorservice.ts +71 -0
new file mode 100644
@@ -0,0 +1,71 @@
1+// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
2+// This file is automatically generated. DO NOT EDIT
3+
4+/**
5+ * CreatorService is the assistant that creates a mini-me agent for people
6+ * who do not write files (issue #94): Sidekicks drives mm's wizard
7+ * (mm --acp-create) and shows its questions as forms, then adds the agent
8+ * to the configuration. One wizard at a time.
9+ *
10+ * view, err := service.Start(ctx) // the first form
11+ * view, err = service.Answer(ctx, answer) // … until view.Written
12+ * result, err := service.Finish(ctx, CreatorFinish{Name: view.Name, Icon: "🤖", Environment: "local"})
13+ * @module
14+ */
15+
16+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
17+// @ts-ignore: Unused imports
18+import { Call as $Call, CancellablePromise as $CancellablePromise } from "@wailsio/runtime";
19+
20+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
21+// @ts-ignore: Unused imports
22+import * as acp$0 from "../acp/models.js";
23+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
24+// @ts-ignore: Unused imports
25+import * as creator$0 from "../creator/models.js";
26+
27+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
28+// @ts-ignore: Unused imports
29+import * as $models from "./models.js";
30+
31+/**
32+ * Answer answers the form shown (action accept, decline or cancel) and
33+ * returns the next step.
34+ */
35+export function Answer(answer: acp$0.FormAnswer): $CancellablePromise<creator$0.View> {
36+ return $Call.ByID(4016253217, answer);
37+}
38+
39+/**
40+ * Cancel closes the wizard. Before Finish, what it wrote is removed.
41+ */
42+export function Cancel(): $CancellablePromise<void> {
43+ return $Call.ByID(4106769953);
44+}
45+
46+/**
47+ * Finish gives the agent its folder, named after it in the agents' folder,
48+ * writes the files of its container or sandbox, and adds it to the
49+ * configuration. A name already used, by an agent or by a folder, is a
50+ * Problem: nothing is changed and another name can be tried.
51+ */
52+export function Finish(form: $models.CreatorFinish): $CancellablePromise<$models.CreatorResult> {
53+ return $Call.ByID(599336288, form);
54+}
55+
56+/**
57+ * Send sends a message to the wizard, such as /back or /restart, and
58+ * returns the next step.
59+ */
60+export function Send(text: string): $CancellablePromise<creator$0.View> {
61+ return $Call.ByID(815611089, text);
62+}
63+
64+/**
65+ * Start checks that mm 1.0.9 or later is installed, then starts its wizard
66+ * and returns its first step. A wizard already open is closed first, and
67+ * what it wrote is removed.
68+ */
69+export function Start(): $CancellablePromise<$models.CreatorStart> {
70+ return $Call.ByID(1360837005);
71+}
new file mode 100644
@@ -0,0 +1,71 @@
1+// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
2+// This file is automatically generated. DO NOT EDIT
3+
4+/**
5+ * CreatorService is the assistant that creates a mini-me agent for people
6+ * who do not write files (issue #94): Sidekicks drives mm's wizard
7+ * (mm --acp-create) and shows its questions as forms, then adds the agent
8+ * to the configuration. One wizard at a time.
9+ *
10+ * view, err := service.Start(ctx) // the first form
11+ * view, err = service.Answer(ctx, answer) // … until view.Written
12+ * result, err := service.Finish(ctx, CreatorFinish{Name: view.Name, Icon: "🤖", Environment: "local"})
13+ * @module
14+ */
15+
16+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
17+// @ts-ignore: Unused imports
18+import { Call as $Call, CancellablePromise as $CancellablePromise } from "@wailsio/runtime";
19+
20+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
21+// @ts-ignore: Unused imports
22+import * as acp$0 from "../acp/models.js";
23+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
24+// @ts-ignore: Unused imports
25+import * as creator$0 from "../creator/models.js";
26+
27+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
28+// @ts-ignore: Unused imports
29+import * as $models from "./models.js";
30+
31+/**
32+ * Answer answers the form shown (action accept, decline or cancel) and
33+ * returns the next step.
34+ */
35+export function Answer(answer: acp$0.FormAnswer): $CancellablePromise<creator$0.View> {
36+ return $Call.ByID(4016253217, answer);
37+}
38+
39+/**
40+ * Cancel closes the wizard. Before Finish, what it wrote is removed.
41+ */
42+export function Cancel(): $CancellablePromise<void> {
43+ return $Call.ByID(4106769953);
44+}
45+
46+/**
47+ * Finish gives the agent its folder, named after it in the agents' folder,
48+ * writes the files of its container or sandbox, and adds it to the
49+ * configuration. A name already used, by an agent or by a folder, is a
50+ * Problem: nothing is changed and another name can be tried.
51+ */
52+export function Finish(form: $models.CreatorFinish): $CancellablePromise<$models.CreatorResult> {
53+ return $Call.ByID(599336288, form);
54+}
55+
56+/**
57+ * Send sends a message to the wizard, such as /back or /restart, and
58+ * returns the next step.
59+ */
60+export function Send(text: string): $CancellablePromise<creator$0.View> {
61+ return $Call.ByID(815611089, text);
62+}
63+
64+/**
65+ * Start checks that mm 1.0.9 or later is installed, then starts its wizard
66+ * and returns its first step. A wizard already open is closed first, and
67+ * what it wrote is removed.
68+ */
69+export function Start(): $CancellablePromise<$models.CreatorStart> {
70+ return $Call.ByID(1360837005);
71+}
modified frontend/bindings/git.rickub.com/bots-garden/sidekicks/internal/app/index.ts +5 -0
@@ -4,6 +4,7 @@
44 import * as AgentService from "./agentservice.js";
55 import * as ChannelService from "./channelservice.js";
66 import * as ConfigService from "./configservice.js";
7+import * as CreatorService from "./creatorservice.js";
78 import * as SystemService from "./systemservice.js";
89 import * as TerminalService from "./terminalservice.js";
910 import * as WorkspaceService from "./workspaceservice.js";
@@ -11,6 +12,7 @@ export {
1112 AgentService,
1213 ChannelService,
1314 ConfigService,
15+ CreatorService,
1416 SystemService,
1517 TerminalService,
1618 WorkspaceService
@@ -21,6 +23,9 @@ export type {
2123 ComposeServiceView,
2224 ComposeView,
2325 ConfigView,
26+ CreatorFinish,
27+ CreatorResult,
28+ CreatorStart,
2429 LinkedFile,
2530 OlderView,
2631 ProblemView,
@@ -4,6 +4,7 @@
4 import * as AgentService from "./agentservice.js";4 import * as AgentService from "./agentservice.js";
5 import * as ChannelService from "./channelservice.js";5 import * as ChannelService from "./channelservice.js";
6 import * as ConfigService from "./configservice.js";6 import * as ConfigService from "./configservice.js";
7+import * as CreatorService from "./creatorservice.js";
7 import * as SystemService from "./systemservice.js";8 import * as SystemService from "./systemservice.js";
8 import * as TerminalService from "./terminalservice.js";9 import * as TerminalService from "./terminalservice.js";
9 import * as WorkspaceService from "./workspaceservice.js";10 import * as WorkspaceService from "./workspaceservice.js";
@@ -11,6 +12,7 @@ export {
11 AgentService,12 AgentService,
12 ChannelService,13 ChannelService,
13 ConfigService,14 ConfigService,
15+ CreatorService,
14 SystemService,16 SystemService,
15 TerminalService,17 TerminalService,
16 WorkspaceService18 WorkspaceService
@@ -21,6 +23,9 @@ export type {
21 ComposeServiceView,23 ComposeServiceView,
22 ComposeView,24 ComposeView,
23 ConfigView,25 ConfigView,
26+ CreatorFinish,
27+ CreatorResult,
28+ CreatorStart,
24 LinkedFile,29 LinkedFile,
25 OlderView,30 OlderView,
26 ProblemView,31 ProblemView,
modified frontend/bindings/git.rickub.com/bots-garden/sidekicks/internal/app/models.ts +49 -0
@@ -6,6 +6,9 @@
66 import * as channels$0 from "../channels/models.js";
77 // eslint-disable-next-line @typescript-eslint/ban-ts-comment
88 // @ts-ignore: Unused imports
9+import * as creator$0 from "../creator/models.js";
10+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
11+// @ts-ignore: Unused imports
912 import * as workspace$0 from "../workspace/models.js";
1013
1114 /**
@@ -110,6 +113,52 @@ export interface ConfigView {
110113 "historyProblem": string;
111114 }
112115
116+/**
117+ * CreatorFinish is the last step: the agent's name (its folder's too), its
118+ * emoji, and where it runs: local, container or sbx.
119+ */
120+export interface CreatorFinish {
121+ "name": string;
122+ "icon": string;
123+ "environment": string;
124+}
125+
126+/**
127+ * CreatorResult is how Finish ended: Problem (one of the Creator…
128+ * constants) or Problems (from the configuration) when the agent was not
129+ * added, else the agent's name and folder.
130+ */
131+export interface CreatorResult {
132+ "problem": string;
133+ "problems": string[] | null;
134+ "name": string;
135+ "folder": string;
136+
137+ /**
138+ * Messages are what mm said while writing the container's or the
139+ * sandbox's files.
140+ */
141+ "messages": string[] | null;
142+}
143+
144+/**
145+ * CreatorStart is what Start returns: the wizard's first step, and where
146+ * the agent's folder will be.
147+ */
148+export interface CreatorStart {
149+ "view": creator$0.View;
150+
151+ /**
152+ * AgentsFolder is the folder that receives the agent's folder.
153+ */
154+ "agentsFolder": string;
155+
156+ /**
157+ * Version is what mm --version said.
158+ */
159+ "version": string;
160+}
161+
113162 /**
114163 * LinkedFile is the file of an agent's folder a link of its answer leads to
115164 * (issue #65).
@@ -6,6 +6,9 @@
6 import * as channels$0 from "../channels/models.js";6 import * as channels$0 from "../channels/models.js";
7 // eslint-disable-next-line @typescript-eslint/ban-ts-comment7 // eslint-disable-next-line @typescript-eslint/ban-ts-comment
8 // @ts-ignore: Unused imports8 // @ts-ignore: Unused imports
9+import * as creator$0 from "../creator/models.js";
10+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
11+// @ts-ignore: Unused imports
9 import * as workspace$0 from "../workspace/models.js";12 import * as workspace$0 from "../workspace/models.js";
10 13
11 /**14 /**
@@ -110,6 +113,52 @@ export interface ConfigView {
110 "historyProblem": string;113 "historyProblem": string;
111 }114 }
112 115
116+/**
117+ * CreatorFinish is the last step: the agent's name (its folder's too), its
118+ * emoji, and where it runs: local, container or sbx.
119+ */
120+export interface CreatorFinish {
121+ "name": string;
122+ "icon": string;
123+ "environment": string;
124+}
125+
126+/**
127+ * CreatorResult is how Finish ended: Problem (one of the Creator…
128+ * constants) or Problems (from the configuration) when the agent was not
129+ * added, else the agent's name and folder.
130+ */
131+export interface CreatorResult {
132+ "problem": string;
133+ "problems": string[] | null;
134+ "name": string;
135+ "folder": string;
136+
137+ /**
138+ * Messages are what mm said while writing the container's or the
139+ * sandbox's files.
140+ */
141+ "messages": string[] | null;
142+}
143+
144+/**
145+ * CreatorStart is what Start returns: the wizard's first step, and where
146+ * the agent's folder will be.
147+ */
148+export interface CreatorStart {
149+ "view": creator$0.View;
150+
151+ /**
152+ * AgentsFolder is the folder that receives the agent's folder.
153+ */
154+ "agentsFolder": string;
155+
156+ /**
157+ * Version is what mm --version said.
158+ */
159+ "version": string;
160+}
161+
113 /**162 /**
114 * LinkedFile is the file of an agent's folder a link of its answer leads to163 * LinkedFile is the file of an agent's folder a link of its answer leads to
115 * (issue #65).164 * (issue #65).
added frontend/bindings/git.rickub.com/bots-garden/sidekicks/internal/creator/index.ts +6 -0
new file mode 100644
@@ -0,0 +1,6 @@
1+// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
2+// This file is automatically generated. DO NOT EDIT
3+
4+export type {
5+ View
6+} from "./models.js";
new file mode 100644
@@ -0,0 +1,6 @@
1+// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
2+// This file is automatically generated. DO NOT EDIT
3+
4+export type {
5+ View
6+} from "./models.js";
added frontend/bindings/git.rickub.com/bots-garden/sidekicks/internal/creator/models.ts +23 -0
new file mode 100644
@@ -0,0 +1,23 @@
1+// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
2+// This file is automatically generated. DO NOT EDIT
3+
4+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
5+// @ts-ignore: Unused imports
6+import * as acp$0 from "../acp/models.js";
7+
8+/**
9+ * View is what the interface shows after each step: the messages mm sent
10+ * since the last step, the form waiting for an answer (nil when none), and
11+ * the agent once it is written.
12+ */
13+export interface View {
14+ "messages": string[] | null;
15+ "form": acp$0.Form | null;
16+
17+ /**
18+ * Written: .mm/agent.yaml exists; Name and Title are mm's.
19+ */
20+ "written": boolean;
21+ "name": string;
22+ "title": string;
23+}
new file mode 100644
@@ -0,0 +1,23 @@
1+// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
2+// This file is automatically generated. DO NOT EDIT
3+
4+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
5+// @ts-ignore: Unused imports
6+import * as acp$0 from "../acp/models.js";
7+
8+/**
9+ * View is what the interface shows after each step: the messages mm sent
10+ * since the last step, the form waiting for an answer (nil when none), and
11+ * the agent once it is written.
12+ */
13+export interface View {
14+ "messages": string[] | null;
15+ "form": acp$0.Form | null;
16+
17+ /**
18+ * Written: .mm/agent.yaml exists; Name and Title are mm's.
19+ */
20+ "written": boolean;
21+ "name": string;
22+ "title": string;
23+}
added frontend/src/lib/agent/CreateMiniMeAgent.svelte +352 -0
new file mode 100644
@@ -0,0 +1,352 @@
1+<!-- Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE -->
2+<script lang="ts">
3+ // The assistant that creates a mini-me agent (issue #94), for people who
4+ // never write a file: Go runs mm's wizard (mm --acp-create, mini-me 1.0.9
5+ // and later) and sends its questions as forms, shown here one after the
6+ // other. Once mm has written the agent, the user gives its name (its
7+ // folder's too), an emoji and where it runs; CreatorService.Finish then
8+ // adds it to the configuration and its conversation opens.
9+ import { onDestroy } from 'svelte'
10+ import { t, type MessageKey } from '../i18n/index.svelte'
11+ import { CreatorService } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/app'
12+ import { agentAdded, appState } from '../state.svelte'
13+ import { agentFolder, contentOf, environments, iconChoices, initialValues, missingFields, noModelServer, problemKey, splitMessages, startProblem, validName, type Environment, type Form, type Value } from '../creator'
14+ import AgentAvatar from './AgentAvatar.svelte'
15+ import ErrorText from '../chat/ErrorText.svelte'
16+ import Markdown from '../chat/Markdown.svelte'
17+ import Spinner from '../chat/Spinner.svelte'
18+
19+ type Step = 'starting' | 'questions' | 'stopped' | 'ready' | 'failed'
20+
21+ let step = $state<Step>('starting')
22+ let busy = $state(false)
23+ let agentsFolder = $state('')
24+ // Why Start failed: mm missing or too old, or another error.
25+ let failure = $state('')
26+ let form = $state<Form | null>(null)
27+ let values = $state<Record<string, Value>>({})
28+ let tried = $state(false)
29+ let warnings = $state<string[]>([])
30+ let details = $state<string[]>([])
31+ // The last step.
32+ let name = $state('')
33+ let title = $state('')
34+ let icon = $state('🤖')
35+ let environment = $state<Environment>('local')
36+ let problem = $state('')
37+ let refused = $state<string[]>([])
38+ let error = $state('')
39+ let finished = false
40+
41+ const missing = $derived(form && tried ? missingFields(form, values) : [])
42+ const startIssue = $derived(startProblem(failure))
43+ const nameOk = $derived(validName(name))
44+
45+ interface ViewLike {
46+ messages: string[] | null
47+ form: Form | null
48+ written: boolean
49+ name: string
50+ title: string
51+ }
52+
53+ // show takes the step Go returned: a form to fill in, the agent written,
54+ // or the questions stopped (a form declined, mm's answer over).
55+ function show(view: ViewLike) {
56+ const said = splitMessages(view.messages)
57+ warnings = said.warnings
58+ details = [...details, ...said.details].slice(-20)
59+ tried = false
60+ if (view.form) {
61+ form = view.form
62+ values = initialValues(view.form)
63+ step = 'questions'
64+ } else if (view.written) {
65+ form = null
66+ name = name || view.name
67+ title = view.title
68+ step = 'ready'
69+ } else {
70+ form = null
71+ step = 'stopped'
72+ }
73+ }
74+
75+ async function run(action: () => Promise<ViewLike>) {
76+ busy = true
77+ error = ''
78+ try {
79+ show(await action())
80+ } catch (caught) {
81+ error = caught instanceof Error ? caught.message : String(caught)
82+ } finally {
83+ busy = false
84+ }
85+ }
86+
87+ async function start() {
88+ step = 'starting'
89+ failure = ''
90+ details = []
91+ try {
92+ const started = await CreatorService.Start()
93+ agentsFolder = started.agentsFolder
94+ show(started.view)
95+ } catch (caught) {
96+ failure = caught instanceof Error ? caught.message : String(caught)
97+ step = 'failed'
98+ }
99+ }
100+
101+ function next(event: SubmitEvent) {
102+ event.preventDefault()
103+ if (!form) return
104+ tried = true
105+ if (missingFields(form, values).length > 0) return
106+ const answer = { action: 'accept', content: contentOf(form, values) }
107+ void run(() => CreatorService.Answer(answer))
108+ }
109+
110+ // A form waits for its answer: it is declined first, then mm gets the
111+ // command (/back takes back the last answer, /restart forgets them all).
112+ async function command(text: string) {
113+ await run(async () => {
114+ if (form) await CreatorService.Answer({ action: 'decline', content: {} })
115+ return CreatorService.Send(text)
116+ })
117+ }
118+
119+ async function finish(event: SubmitEvent) {
120+ event.preventDefault()
121+ problem = ''
122+ refused = []
123+ error = ''
124+ if (!nameOk) {
125+ problem = 'invalidName'
126+ return
127+ }
128+ busy = true
129+ try {
130+ const result = await CreatorService.Finish({ name, icon: icon.trim(), environment })
131+ if (result.problem) problem = result.problem
132+ else if (result.problems && result.problems.length > 0) refused = result.problems
133+ else {
134+ finished = true
135+ agentAdded(name)
136+ }
137+ } catch (caught) {
138+ error = caught instanceof Error ? caught.message : String(caught)
139+ } finally {
140+ busy = false
141+ }
142+ }
143+
144+ function close() {
145+ appState.creator = false
146+ }
147+
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.
154+ onDestroy(() => {
155+ if (!finished) void CreatorService.Cancel()
156+ })
157+
158+ void start()
159+</script>
160+
161+<div class="creator">
162+ <h1>{t('creator.title')}</h1>
163+ {#if agentsFolder}<p class="intro">{t('creator.intro', { folder: agentsFolder })}</p>{/if}
164+
165+ {#if step === 'starting'}
166+ <p class="status" role="status"><Spinner /> {t('creator.starting')}</p>
167+ {:else if step === 'failed'}
168+ <div class="problem" role="alert">
169+ {#if startIssue}{t(startIssue.key, { found: startIssue.found })}{:else}<ErrorText raw={failure} />{/if}
170+ </div>
171+ <div class="actions">
172+ <button type="button" onclick={close}>{t('creator.cancel')}</button>
173+ <button type="button" class="primary" onclick={start}>{t('creator.retry')}</button>
174+ </div>
175+ {:else}
176+ {#each warnings as warning, index (index)}
177+ <div class="warning" role="alert"><Markdown text={warning} /></div>
178+ {/each}
179+
180+ {#if step === 'questions' && form}
181+ {#if noModelServer(form)}
182+ <div class="warning" role="alert">{t('creator.noModelServer')}</div>
183+ {/if}
184+ <form class="questions" onsubmit={next} novalidate>
185+ <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}
239+ </fieldset>
240+ {#if form.message.includes('\n')}
241+ <details class="about">
242+ <summary>{t('creator.about')}</summary>
243+ <pre>{form.message}</pre>
244+ </details>
245+ {/if}
246+ <div class="actions">
247+ <button type="button" onclick={close} disabled={busy}>{t('creator.cancel')}</button>
248+ <span class="grow"></span>
249+ <button type="button" onclick={() => command('/restart')} disabled={busy}>{t('creator.restart')}</button>
250+ <button type="button" onclick={() => command('/back')} disabled={busy}>{t('creator.back')}</button>
251+ <button type="submit" class="primary" disabled={busy}>{#if busy}<Spinner /> {/if}{t('creator.next')}</button>
252+ </div>
253+ </form>
254+ {:else if step === 'stopped'}
255+ <p>{t('creator.stopped')}</p>
256+ <div class="actions">
257+ <button type="button" onclick={close} disabled={busy}>{t('creator.cancel')}</button>
258+ <span class="grow"></span>
259+ <button type="button" onclick={() => command('/restart')} disabled={busy}>{t('creator.restart')}</button>
260+ <button type="button" class="primary" onclick={() => command('/start')} disabled={busy}>{t('creator.continue')}</button>
261+ </div>
262+ {:else if step === 'ready'}
263+ <form class="questions" onsubmit={finish} novalidate>
264+ <p>{t('creator.ready')}</p>
265+ <fieldset disabled={busy}>
266+ <div class="row">
267+ <span class="preview"><AgentAvatar icon={icon} title={title || name} name={name} size={34} /></span>
268+ <label class="grow">
269+ {t('creator.name')}
270+ <input bind:value={name} oninput={() => (problem = '')} aria-invalid={problem !== ''} aria-describedby="creator-name-hint" spellcheck="false" autocapitalize="off" />
271+ </label>
272+ </div>
273+ <small id="creator-name-hint" class:problem-text={problem !== ''} role={problem ? 'alert' : undefined}>
274+ {problem ? t(problemKey(problem)) : t('creator.nameHint', { name, folder: agentFolder(agentsFolder, name) })}
275+ </small>
276+ <div class="group" aria-label={t('creator.icon')}>
277+ <span class="label">{t('creator.icon')}</span>
278+ <div class="icons">
279+ {#each iconChoices as choice (choice)}
280+ <button type="button" class="icon" class:chosen={icon === choice} onclick={() => (icon = choice)} aria-label={choice} aria-pressed={icon === choice}>{choice}</button>
281+ {/each}
282+ <input class="custom" bind:value={icon} maxlength="8" aria-label={t('creator.icon')} />
283+ </div>
284+ <small>{t('creator.iconHint')}</small>
285+ </div>
286+ <div class="group" role="radiogroup" aria-label={t('creator.where')}>
287+ <span class="label">{t('creator.where')}</span>
288+ {#each environments as choice (choice)}
289+ <label class="choice wide" class:chosen={environment === choice}>
290+ <input type="radio" name="environment" value={choice} bind:group={environment} />
291+ <span><strong>{t(`creator.env.${choice}` as MessageKey)}</strong><br /><small>{t(`creator.env.${choice}Hint` as MessageKey)}</small></span>
292+ </label>
293+ {/each}
294+ </div>
295+ </fieldset>
296+ {#if refused.length > 0}
297+ <div class="problem" role="alert">
298+ <strong>{t('creator.refused')}</strong>
299+ <ul>{#each refused as reason, index (index)}<li>{reason}</li>{/each}</ul>
300+ </div>
301+ {/if}
302+ <div class="actions">
303+ <button type="button" onclick={close} disabled={busy}>{t('creator.cancel')}</button>
304+ <span class="grow"></span>
305+ <button type="submit" class="primary" disabled={busy}>{#if busy}<Spinner /> {t('creator.creating')}{:else}{t('creator.create')}{/if}</button>
306+ </div>
307+ </form>
308+ {/if}
309+
310+ {#if busy && step !== 'ready'}<p class="status" role="status"><Spinner /> {t('creator.waiting')}</p>{/if}
311+ {#if error}<div class="problem" role="alert"><ErrorText raw={error} /></div>{/if}
312+ {#if details.length > 0}
313+ <details class="said">
314+ <summary>{t('creator.details')}</summary>
315+ {#each details as message, index (index)}<Markdown text={message} />{/each}
316+ </details>
317+ {/if}
318+ {/if}
319+</div>
320+
321+<style>
322+ .creator { max-width: 620px; width: 100%; margin: 0 auto; padding: 24px 24px 32px; overflow-y: auto; display: flex; flex-direction: column; gap: 14px; box-sizing: border-box; }
323+ h1 { font-size: 20px; margin: 0; }
324+ .intro, .status { color: var(--muted); margin: 0; }
325+ .status { display: flex; align-items: center; gap: 8px; }
326+ .questions { display: flex; flex-direction: column; gap: 12px; }
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; }
328+ label, .group { display: flex; flex-direction: column; gap: 4px; font-size: 13px; }
329+ .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); }
332+ input[aria-invalid='true'] { border-color: var(--danger); }
333+ small { color: var(--muted); font-size: 12px; }
334+ .problem-text { color: var(--danger); }
335+ .choices, .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; }
337+ .choice.wide { align-items: flex-start; }
338+ .choice.wide input { margin-top: 3px; }
339+ .choice.chosen, .icon.chosen { border-color: var(--accent); }
340+ .icon { font-size: 20px; width: 38px; height: 38px; padding: 0; border: 1px solid var(--border); border-radius: 8px; background: var(--bg); }
341+ .custom { width: 64px; text-align: center; }
342+ .row { display: flex; gap: 10px; align-items: flex-end; }
343+ .preview { display: flex; align-items: center; justify-content: center; width: 38px; height: 34px; }
344+ .grow { flex: 1; min-width: 0; }
345+ .actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
346+ .warning { border: 1px solid var(--warn); border-radius: var(--radius); color: var(--warn); padding: 8px 12px; font-size: 13px; }
347+ .problem { border: 1px solid var(--danger); border-radius: var(--radius); color: var(--danger); padding: 8px 12px; font-size: 13px; }
348+ .problem ul { margin: 4px 0 0; padding-left: 18px; }
349+ .about pre { white-space: pre-wrap; font-size: 12px; color: var(--muted); margin: 6px 0 0; }
350+ .said { font-size: 12px; color: var(--muted); }
351+ .primary { background: var(--accent); border-color: var(--accent); color: #fff; font-weight: 600; }
352+</style>
new file mode 100644
@@ -0,0 +1,352 @@
1+<!-- Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE -->
2+<script lang="ts">
3+ // The assistant that creates a mini-me agent (issue #94), for people who
4+ // never write a file: Go runs mm's wizard (mm --acp-create, mini-me 1.0.9
5+ // and later) and sends its questions as forms, shown here one after the
6+ // other. Once mm has written the agent, the user gives its name (its
7+ // folder's too), an emoji and where it runs; CreatorService.Finish then
8+ // adds it to the configuration and its conversation opens.
9+ import { onDestroy } from 'svelte'
10+ import { t, type MessageKey } from '../i18n/index.svelte'
11+ import { CreatorService } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/app'
12+ import { agentAdded, appState } from '../state.svelte'
13+ import { agentFolder, contentOf, environments, iconChoices, initialValues, missingFields, noModelServer, problemKey, splitMessages, startProblem, validName, type Environment, type Form, type Value } from '../creator'
14+ import AgentAvatar from './AgentAvatar.svelte'
15+ import ErrorText from '../chat/ErrorText.svelte'
16+ import Markdown from '../chat/Markdown.svelte'
17+ import Spinner from '../chat/Spinner.svelte'
18+
19+ type Step = 'starting' | 'questions' | 'stopped' | 'ready' | 'failed'
20+
21+ let step = $state<Step>('starting')
22+ let busy = $state(false)
23+ let agentsFolder = $state('')
24+ // Why Start failed: mm missing or too old, or another error.
25+ let failure = $state('')
26+ let form = $state<Form | null>(null)
27+ let values = $state<Record<string, Value>>({})
28+ let tried = $state(false)
29+ let warnings = $state<string[]>([])
30+ let details = $state<string[]>([])
31+ // The last step.
32+ let name = $state('')
33+ let title = $state('')
34+ let icon = $state('🤖')
35+ let environment = $state<Environment>('local')
36+ let problem = $state('')
37+ let refused = $state<string[]>([])
38+ let error = $state('')
39+ let finished = false
40+
41+ const missing = $derived(form && tried ? missingFields(form, values) : [])
42+ const startIssue = $derived(startProblem(failure))
43+ const nameOk = $derived(validName(name))
44+
45+ interface ViewLike {
46+ messages: string[] | null
47+ form: Form | null
48+ written: boolean
49+ name: string
50+ title: string
51+ }
52+
53+ // show takes the step Go returned: a form to fill in, the agent written,
54+ // or the questions stopped (a form declined, mm's answer over).
55+ function show(view: ViewLike) {
56+ const said = splitMessages(view.messages)
57+ warnings = said.warnings
58+ details = [...details, ...said.details].slice(-20)
59+ tried = false
60+ if (view.form) {
61+ form = view.form
62+ values = initialValues(view.form)
63+ step = 'questions'
64+ } else if (view.written) {
65+ form = null
66+ name = name || view.name
67+ title = view.title
68+ step = 'ready'
69+ } else {
70+ form = null
71+ step = 'stopped'
72+ }
73+ }
74+
75+ async function run(action: () => Promise<ViewLike>) {
76+ busy = true
77+ error = ''
78+ try {
79+ show(await action())
80+ } catch (caught) {
81+ error = caught instanceof Error ? caught.message : String(caught)
82+ } finally {
83+ busy = false
84+ }
85+ }
86+
87+ async function start() {
88+ step = 'starting'
89+ failure = ''
90+ details = []
91+ try {
92+ const started = await CreatorService.Start()
93+ agentsFolder = started.agentsFolder
94+ show(started.view)
95+ } catch (caught) {
96+ failure = caught instanceof Error ? caught.message : String(caught)
97+ step = 'failed'
98+ }
99+ }
100+
101+ function next(event: SubmitEvent) {
102+ event.preventDefault()
103+ if (!form) return
104+ tried = true
105+ if (missingFields(form, values).length > 0) return
106+ const answer = { action: 'accept', content: contentOf(form, values) }
107+ void run(() => CreatorService.Answer(answer))
108+ }
109+
110+ // A form waits for its answer: it is declined first, then mm gets the
111+ // command (/back takes back the last answer, /restart forgets them all).
112+ async function command(text: string) {
113+ await run(async () => {
114+ if (form) await CreatorService.Answer({ action: 'decline', content: {} })
115+ return CreatorService.Send(text)
116+ })
117+ }
118+
119+ async function finish(event: SubmitEvent) {
120+ event.preventDefault()
121+ problem = ''
122+ refused = []
123+ error = ''
124+ if (!nameOk) {
125+ problem = 'invalidName'
126+ return
127+ }
128+ busy = true
129+ try {
130+ const result = await CreatorService.Finish({ name, icon: icon.trim(), environment })
131+ if (result.problem) problem = result.problem
132+ else if (result.problems && result.problems.length > 0) refused = result.problems
133+ else {
134+ finished = true
135+ agentAdded(name)
136+ }
137+ } catch (caught) {
138+ error = caught instanceof Error ? caught.message : String(caught)
139+ } finally {
140+ busy = false
141+ }
142+ }
143+
144+ function close() {
145+ appState.creator = false
146+ }
147+
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.
154+ onDestroy(() => {
155+ if (!finished) void CreatorService.Cancel()
156+ })
157+
158+ void start()
159+</script>
160+
161+<div class="creator">
162+ <h1>{t('creator.title')}</h1>
163+ {#if agentsFolder}<p class="intro">{t('creator.intro', { folder: agentsFolder })}</p>{/if}
164+
165+ {#if step === 'starting'}
166+ <p class="status" role="status"><Spinner /> {t('creator.starting')}</p>
167+ {:else if step === 'failed'}
168+ <div class="problem" role="alert">
169+ {#if startIssue}{t(startIssue.key, { found: startIssue.found })}{:else}<ErrorText raw={failure} />{/if}
170+ </div>
171+ <div class="actions">
172+ <button type="button" onclick={close}>{t('creator.cancel')}</button>
173+ <button type="button" class="primary" onclick={start}>{t('creator.retry')}</button>
174+ </div>
175+ {:else}
176+ {#each warnings as warning, index (index)}
177+ <div class="warning" role="alert"><Markdown text={warning} /></div>
178+ {/each}
179+
180+ {#if step === 'questions' && form}
181+ {#if noModelServer(form)}
182+ <div class="warning" role="alert">{t('creator.noModelServer')}</div>
183+ {/if}
184+ <form class="questions" onsubmit={next} novalidate>
185+ <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}
239+ </fieldset>
240+ {#if form.message.includes('\n')}
241+ <details class="about">
242+ <summary>{t('creator.about')}</summary>
243+ <pre>{form.message}</pre>
244+ </details>
245+ {/if}
246+ <div class="actions">
247+ <button type="button" onclick={close} disabled={busy}>{t('creator.cancel')}</button>
248+ <span class="grow"></span>
249+ <button type="button" onclick={() => command('/restart')} disabled={busy}>{t('creator.restart')}</button>
250+ <button type="button" onclick={() => command('/back')} disabled={busy}>{t('creator.back')}</button>
251+ <button type="submit" class="primary" disabled={busy}>{#if busy}<Spinner /> {/if}{t('creator.next')}</button>
252+ </div>
253+ </form>
254+ {:else if step === 'stopped'}
255+ <p>{t('creator.stopped')}</p>
256+ <div class="actions">
257+ <button type="button" onclick={close} disabled={busy}>{t('creator.cancel')}</button>
258+ <span class="grow"></span>
259+ <button type="button" onclick={() => command('/restart')} disabled={busy}>{t('creator.restart')}</button>
260+ <button type="button" class="primary" onclick={() => command('/start')} disabled={busy}>{t('creator.continue')}</button>
261+ </div>
262+ {:else if step === 'ready'}
263+ <form class="questions" onsubmit={finish} novalidate>
264+ <p>{t('creator.ready')}</p>
265+ <fieldset disabled={busy}>
266+ <div class="row">
267+ <span class="preview"><AgentAvatar icon={icon} title={title || name} name={name} size={34} /></span>
268+ <label class="grow">
269+ {t('creator.name')}
270+ <input bind:value={name} oninput={() => (problem = '')} aria-invalid={problem !== ''} aria-describedby="creator-name-hint" spellcheck="false" autocapitalize="off" />
271+ </label>
272+ </div>
273+ <small id="creator-name-hint" class:problem-text={problem !== ''} role={problem ? 'alert' : undefined}>
274+ {problem ? t(problemKey(problem)) : t('creator.nameHint', { name, folder: agentFolder(agentsFolder, name) })}
275+ </small>
276+ <div class="group" aria-label={t('creator.icon')}>
277+ <span class="label">{t('creator.icon')}</span>
278+ <div class="icons">
279+ {#each iconChoices as choice (choice)}
280+ <button type="button" class="icon" class:chosen={icon === choice} onclick={() => (icon = choice)} aria-label={choice} aria-pressed={icon === choice}>{choice}</button>
281+ {/each}
282+ <input class="custom" bind:value={icon} maxlength="8" aria-label={t('creator.icon')} />
283+ </div>
284+ <small>{t('creator.iconHint')}</small>
285+ </div>
286+ <div class="group" role="radiogroup" aria-label={t('creator.where')}>
287+ <span class="label">{t('creator.where')}</span>
288+ {#each environments as choice (choice)}
289+ <label class="choice wide" class:chosen={environment === choice}>
290+ <input type="radio" name="environment" value={choice} bind:group={environment} />
291+ <span><strong>{t(`creator.env.${choice}` as MessageKey)}</strong><br /><small>{t(`creator.env.${choice}Hint` as MessageKey)}</small></span>
292+ </label>
293+ {/each}
294+ </div>
295+ </fieldset>
296+ {#if refused.length > 0}
297+ <div class="problem" role="alert">
298+ <strong>{t('creator.refused')}</strong>
299+ <ul>{#each refused as reason, index (index)}<li>{reason}</li>{/each}</ul>
300+ </div>
301+ {/if}
302+ <div class="actions">
303+ <button type="button" onclick={close} disabled={busy}>{t('creator.cancel')}</button>
304+ <span class="grow"></span>
305+ <button type="submit" class="primary" disabled={busy}>{#if busy}<Spinner /> {t('creator.creating')}{:else}{t('creator.create')}{/if}</button>
306+ </div>
307+ </form>
308+ {/if}
309+
310+ {#if busy && step !== 'ready'}<p class="status" role="status"><Spinner /> {t('creator.waiting')}</p>{/if}
311+ {#if error}<div class="problem" role="alert"><ErrorText raw={error} /></div>{/if}
312+ {#if details.length > 0}
313+ <details class="said">
314+ <summary>{t('creator.details')}</summary>
315+ {#each details as message, index (index)}<Markdown text={message} />{/each}
316+ </details>
317+ {/if}
318+ {/if}
319+</div>
320+
321+<style>
322+ .creator { max-width: 620px; width: 100%; margin: 0 auto; padding: 24px 24px 32px; overflow-y: auto; display: flex; flex-direction: column; gap: 14px; box-sizing: border-box; }
323+ h1 { font-size: 20px; margin: 0; }
324+ .intro, .status { color: var(--muted); margin: 0; }
325+ .status { display: flex; align-items: center; gap: 8px; }
326+ .questions { display: flex; flex-direction: column; gap: 12px; }
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; }
328+ label, .group { display: flex; flex-direction: column; gap: 4px; font-size: 13px; }
329+ .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); }
332+ input[aria-invalid='true'] { border-color: var(--danger); }
333+ small { color: var(--muted); font-size: 12px; }
334+ .problem-text { color: var(--danger); }
335+ .choices, .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; }
337+ .choice.wide { align-items: flex-start; }
338+ .choice.wide input { margin-top: 3px; }
339+ .choice.chosen, .icon.chosen { border-color: var(--accent); }
340+ .icon { font-size: 20px; width: 38px; height: 38px; padding: 0; border: 1px solid var(--border); border-radius: 8px; background: var(--bg); }
341+ .custom { width: 64px; text-align: center; }
342+ .row { display: flex; gap: 10px; align-items: flex-end; }
343+ .preview { display: flex; align-items: center; justify-content: center; width: 38px; height: 34px; }
344+ .grow { flex: 1; min-width: 0; }
345+ .actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
346+ .warning { border: 1px solid var(--warn); border-radius: var(--radius); color: var(--warn); padding: 8px 12px; font-size: 13px; }
347+ .problem { border: 1px solid var(--danger); border-radius: var(--radius); color: var(--danger); padding: 8px 12px; font-size: 13px; }
348+ .problem ul { margin: 4px 0 0; padding-left: 18px; }
349+ .about pre { white-space: pre-wrap; font-size: 12px; color: var(--muted); margin: 6px 0 0; }
350+ .said { font-size: 12px; color: var(--muted); }
351+ .primary { background: var(--accent); border-color: var(--accent); color: #fff; font-weight: 600; }
352+</style>
added frontend/src/lib/creator.test.ts +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+
3+import { describe, expect, it } from 'vitest'
4+import { agentFolder, contentOf, initialValues, missingFields, noModelServer, problemKey, splitMessages, startProblem, validName, type Field, type Form } from './creator'
5+
6+function field(name: string, type: string, extra: Partial<Field> = {}): Field {
7+ return { name, title: name, description: '', type, options: null, default: null, required: true, ...extra }
8+}
9+
10+const form: Form = {
11+ message: 'mm init — create an agent',
12+ fields: [
13+ field('provider', 'choice', { options: ['llmman', 'ollama'], default: 'ollama' }),
14+ field('usage', 'choice', { options: ['developer', 'writer'] }),
15+ field('yolo', 'boolean', { default: true }),
16+ field('skills', 'multi', { options: ['a', 'b'], default: ['b'] }),
17+ field('name', 'text', { default: 'developer' }),
18+ field('model', 'text'),
19+ field('size', 'number', { required: false }),
20+ ],
21+}
22+
23+describe('initialValues', () => {
24+ it('starts from the defaults, the first option of a choice without one', () => {
25+ expect(initialValues(form)).toEqual({ provider: 'ollama', usage: 'developer', yolo: true, skills: ['b'], name: 'developer', model: '', size: '' })
26+ })
27+ it('reads a yes/no default given as text', () => {
28+ expect(initialValues({ message: '', fields: [field('yolo', 'boolean', { default: 'yes' })] })).toEqual({ yolo: true })
29+ })
30+ it('accepts a form without fields', () => {
31+ expect(initialValues({ message: '', fields: null })).toEqual({})
32+ })
33+})
34+
35+describe('contentOf', () => {
36+ it('trims text and sends numbers as numbers', () => {
37+ const values = { ...initialValues(form), name: ' Bob ', size: ' 12 ', yolo: false }
38+ expect(contentOf(form, values)).toEqual({ provider: 'ollama', usage: 'developer', yolo: false, skills: ['b'], name: 'Bob', model: '', size: 12 })
39+ })
40+ it('keeps a number field that is not a number as text, for mm to refuse', () => {
41+ expect(contentOf({ message: '', fields: [field('size', 'number')] }, { size: 'big' })).toEqual({ size: 'big' })
42+ })
43+})
44+
45+describe('missingFields', () => {
46+ it('lists the required text fields left empty', () => {
47+ expect(missingFields(form, initialValues(form))).toEqual(['model'])
48+ expect(missingFields(form, { ...initialValues(form), model: 'qwen' })).toEqual([])
49+ })
50+})
51+
52+describe('noModelServer', () => {
53+ it('is true when mm asks the model as text', () => {
54+ expect(noModelServer(form)).toBe(true)
55+ expect(noModelServer({ message: '', fields: [field('model', 'choice', { options: ['qwen'] })] })).toBe(false)
56+ expect(noModelServer(null)).toBe(false)
57+ })
58+})
59+
60+describe('splitMessages', () => {
61+ it('shows the warnings and folds the rest', () => {
62+ expect(splitMessages(['**mm init** — let us start', '⚠️ unknown provider "x"', ' ⚠️ again'])).toEqual({
63+ warnings: ['⚠️ unknown provider "x"', ' ⚠️ again'],
64+ details: ['**mm init** — let us start'],
65+ })
66+ expect(splitMessages(null)).toEqual({ warnings: [], details: [] })
67+ })
68+})
69+
70+describe('names and folders', () => {
71+ it('accepts the names of the configuration', () => {
72+ expect(validName('bob')).toBe(true)
73+ expect(validName('bob-2_x')).toBe(true)
74+ expect(validName('Bob')).toBe(false)
75+ expect(validName('2bob')).toBe(false)
76+ expect(validName('')).toBe(false)
77+ expect(validName('a'.repeat(33))).toBe(false)
78+ })
79+ it('joins the folder with its own separator', () => {
80+ expect(agentFolder('/Users/me/Documents', 'bob')).toBe('/Users/me/Documents/bob')
81+ expect(agentFolder('/Users/me/Documents/', 'bob')).toBe('/Users/me/Documents/bob')
82+ expect(agentFolder('C:\\Users\\me\\Documents', 'bob')).toBe('C:\\Users\\me\\Documents\\bob')
83+ })
84+})
85+
86+describe('problems', () => {
87+ it('explains the problems of Finish', () => {
88+ expect(problemKey('nameTaken')).toBe('creator.problem.nameTaken')
89+ expect(problemKey('folderExists')).toBe('creator.problem.folderExists')
90+ expect(problemKey('invalidName')).toBe('creator.problem.invalidName')
91+ })
92+ it('recognises a missing or old mm', () => {
93+ expect(startProblem('mini-me (mm) is not installed')).toEqual({ key: 'creator.mmMissing', found: '' })
94+ expect(startProblem('mini-me (mm) 1.0.8 is too old: version 1.0.9 or later is needed')).toEqual({ key: 'creator.mmTooOld', found: '1.0.8' })
95+ expect(startProblem('connection refused')).toBeNull()
96+ })
97+})
new file mode 100644
@@ -0,0 +1,97 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+import { describe, expect, it } from 'vitest'
4+import { agentFolder, contentOf, initialValues, missingFields, noModelServer, problemKey, splitMessages, startProblem, validName, type Field, type Form } from './creator'
5+
6+function field(name: string, type: string, extra: Partial<Field> = {}): Field {
7+ return { name, title: name, description: '', type, options: null, default: null, required: true, ...extra }
8+}
9+
10+const form: Form = {
11+ message: 'mm init — create an agent',
12+ fields: [
13+ field('provider', 'choice', { options: ['llmman', 'ollama'], default: 'ollama' }),
14+ field('usage', 'choice', { options: ['developer', 'writer'] }),
15+ field('yolo', 'boolean', { default: true }),
16+ field('skills', 'multi', { options: ['a', 'b'], default: ['b'] }),
17+ field('name', 'text', { default: 'developer' }),
18+ field('model', 'text'),
19+ field('size', 'number', { required: false }),
20+ ],
21+}
22+
23+describe('initialValues', () => {
24+ it('starts from the defaults, the first option of a choice without one', () => {
25+ expect(initialValues(form)).toEqual({ provider: 'ollama', usage: 'developer', yolo: true, skills: ['b'], name: 'developer', model: '', size: '' })
26+ })
27+ it('reads a yes/no default given as text', () => {
28+ expect(initialValues({ message: '', fields: [field('yolo', 'boolean', { default: 'yes' })] })).toEqual({ yolo: true })
29+ })
30+ it('accepts a form without fields', () => {
31+ expect(initialValues({ message: '', fields: null })).toEqual({})
32+ })
33+})
34+
35+describe('contentOf', () => {
36+ it('trims text and sends numbers as numbers', () => {
37+ const values = { ...initialValues(form), name: ' Bob ', size: ' 12 ', yolo: false }
38+ expect(contentOf(form, values)).toEqual({ provider: 'ollama', usage: 'developer', yolo: false, skills: ['b'], name: 'Bob', model: '', size: 12 })
39+ })
40+ it('keeps a number field that is not a number as text, for mm to refuse', () => {
41+ expect(contentOf({ message: '', fields: [field('size', 'number')] }, { size: 'big' })).toEqual({ size: 'big' })
42+ })
43+})
44+
45+describe('missingFields', () => {
46+ it('lists the required text fields left empty', () => {
47+ expect(missingFields(form, initialValues(form))).toEqual(['model'])
48+ expect(missingFields(form, { ...initialValues(form), model: 'qwen' })).toEqual([])
49+ })
50+})
51+
52+describe('noModelServer', () => {
53+ it('is true when mm asks the model as text', () => {
54+ expect(noModelServer(form)).toBe(true)
55+ expect(noModelServer({ message: '', fields: [field('model', 'choice', { options: ['qwen'] })] })).toBe(false)
56+ expect(noModelServer(null)).toBe(false)
57+ })
58+})
59+
60+describe('splitMessages', () => {
61+ it('shows the warnings and folds the rest', () => {
62+ expect(splitMessages(['**mm init** — let us start', '⚠️ unknown provider "x"', ' ⚠️ again'])).toEqual({
63+ warnings: ['⚠️ unknown provider "x"', ' ⚠️ again'],
64+ details: ['**mm init** — let us start'],
65+ })
66+ expect(splitMessages(null)).toEqual({ warnings: [], details: [] })
67+ })
68+})
69+
70+describe('names and folders', () => {
71+ it('accepts the names of the configuration', () => {
72+ expect(validName('bob')).toBe(true)
73+ expect(validName('bob-2_x')).toBe(true)
74+ expect(validName('Bob')).toBe(false)
75+ expect(validName('2bob')).toBe(false)
76+ expect(validName('')).toBe(false)
77+ expect(validName('a'.repeat(33))).toBe(false)
78+ })
79+ it('joins the folder with its own separator', () => {
80+ expect(agentFolder('/Users/me/Documents', 'bob')).toBe('/Users/me/Documents/bob')
81+ expect(agentFolder('/Users/me/Documents/', 'bob')).toBe('/Users/me/Documents/bob')
82+ expect(agentFolder('C:\\Users\\me\\Documents', 'bob')).toBe('C:\\Users\\me\\Documents\\bob')
83+ })
84+})
85+
86+describe('problems', () => {
87+ it('explains the problems of Finish', () => {
88+ expect(problemKey('nameTaken')).toBe('creator.problem.nameTaken')
89+ expect(problemKey('folderExists')).toBe('creator.problem.folderExists')
90+ expect(problemKey('invalidName')).toBe('creator.problem.invalidName')
91+ })
92+ it('recognises a missing or old mm', () => {
93+ expect(startProblem('mini-me (mm) is not installed')).toEqual({ key: 'creator.mmMissing', found: '' })
94+ expect(startProblem('mini-me (mm) 1.0.8 is too old: version 1.0.9 or later is needed')).toEqual({ key: 'creator.mmTooOld', found: '1.0.8' })
95+ expect(startProblem('connection refused')).toBeNull()
96+ })
97+})
added frontend/src/lib/creator.ts +155 -0
new file mode 100644
@@ -0,0 +1,155 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+// The assistant that creates a mini-me agent (issue #94): Go drives mm's
4+// wizard (CreatorService) and sends its questions as forms; this module
5+// turns a form into values the page edits, and those values back into the
6+// answer mm expects. No Svelte here, so that vitest can test it.
7+
8+import type { MessageKey } from './i18n/index.svelte'
9+
10+/** A question of a form, as acp.FormField gives it. */
11+export interface Field {
12+ name: string
13+ title: string
14+ description: string
15+ /** text, choice, multi, boolean or number. */
16+ type: string
17+ options: string[] | null
18+ default: unknown
19+ required: boolean
20+}
21+
22+export interface Form {
23+ message: string
24+ fields: Field[] | null
25+}
26+
27+export type Value = string | boolean | string[]
28+
29+/** Where the agent runs, as CreatorService.Finish takes it. */
30+export type Environment = 'local' | 'container' | 'sbx'
31+export const environments: Environment[] = ['local', 'container', 'sbx']
32+
33+/** A few emojis to pick from; any other can be typed. */
34+export const iconChoices = ['🤖', '🦊', '🐱', '🐼', '🦉', '🐙', '🧙', '👩‍🔬', '👨‍🍳', '🧑‍🚀', '🎨', '📚']
35+
36+/**
37+ * The values a form starts with: the defaults mm gives, else nothing (the
38+ * first option for a choice, which a select shows anyway).
39+ *
40+ * @example
41+ * initialValues({ message: '', fields: [{ name: 'yolo', type: 'boolean', default: true, … }] }) // { yolo: true }
42+ */
43+export function initialValues(form: Form): Record<string, Value> {
44+ const values: Record<string, Value> = {}
45+ for (const field of form.fields ?? []) {
46+ const value = field.default
47+ switch (field.type) {
48+ case 'boolean':
49+ values[field.name] = value === true || value === 'yes' || value === 'true'
50+ break
51+ case 'multi':
52+ values[field.name] = Array.isArray(value) ? value.map(String) : []
53+ break
54+ case 'choice':
55+ values[field.name] = value !== undefined && value !== null ? String(value) : (field.options?.[0] ?? '')
56+ break
57+ default:
58+ values[field.name] = value !== undefined && value !== null ? String(value) : ''
59+ }
60+ }
61+ return values
62+}
63+
64+/**
65+ * The content of an accepted form: each value with the type its field
66+ * asks for (a number field sends a number when the text is one).
67+ *
68+ * @example
69+ * contentOf(form, { name: ' bob ', yolo: false }) // { name: 'bob', yolo: false }
70+ */
71+export function contentOf(form: Form, values: Record<string, Value>): Record<string, unknown> {
72+ const content: Record<string, unknown> = {}
73+ for (const field of form.fields ?? []) {
74+ const value = values[field.name]
75+ if (typeof value === 'string') {
76+ const text = value.trim()
77+ content[field.name] = field.type === 'number' && text !== '' && !Number.isNaN(Number(text)) ? Number(text) : text
78+ } else {
79+ content[field.name] = value
80+ }
81+ }
82+ return content
83+}
84+
85+/** The required text fields still empty, by name: the form cannot be sent. */
86+export function missingFields(form: Form, values: Record<string, Value>): string[] {
87+ return (form.fields ?? [])
88+ .filter((field) => field.required && (field.type === 'text' || field.type === 'number' || field.type === 'choice'))
89+ .filter((field) => String(values[field.name] ?? '').trim() === '')
90+ .map((field) => field.name)
91+}
92+
93+/**
94+ * True when mm asks the model as plain text: no model server answered, so
95+ * it could not list the models (mm's "model" question has choices otherwise).
96+ */
97+export function noModelServer(form: Form | null | undefined): boolean {
98+ return (form?.fields ?? []).some((field) => field.name === 'model' && field.type === 'text')
99+}
100+
101+/**
102+ * mm's messages, split: its warnings (⚠️) are shown, the rest — meant for a
103+ * developer — stays folded.
104+ */
105+export function splitMessages(messages: string[] | null | undefined): { warnings: string[]; details: string[] } {
106+ const warnings: string[] = []
107+ const details: string[] = []
108+ for (const message of messages ?? []) {
109+ ;(message.trimStart().startsWith('⚠️') ? warnings : details).push(message)
110+ }
111+ return { warnings, details }
112+}
113+
114+/** An agent name Sidekicks accepts, which is also its folder's name. */
115+export function validName(name: string): boolean {
116+ return /^[a-z][a-z0-9_-]{0,31}$/.test(name)
117+}
118+
119+/**
120+ * The agent's folder: name in the agents' folder, with that folder's separator.
121+ *
122+ * @example
123+ * agentFolder('/Users/me/Documents', 'bob') // '/Users/me/Documents/bob'
124+ * agentFolder('C:\\Users\\me\\Documents', 'bob') // 'C:\\Users\\me\\Documents\\bob'
125+ */
126+export function agentFolder(folder: string, name: string): string {
127+ const separator = folder.includes('\\') && !folder.includes('/') ? '\\' : '/'
128+ return folder.endsWith(separator) ? folder + name : folder + separator + name
129+}
130+
131+/** The message key explaining a Problem of CreatorService.Finish. */
132+export function problemKey(problem: string): MessageKey {
133+ switch (problem) {
134+ case 'nameTaken':
135+ return 'creator.problem.nameTaken'
136+ case 'folderExists':
137+ return 'creator.problem.folderExists'
138+ default:
139+ return 'creator.problem.invalidName'
140+ }
141+}
142+
143+/**
144+ * What a Start error means for the user: mm missing, too old, or another
145+ * problem (shown with ErrorText).
146+ *
147+ * @example
148+ * startProblem('mini-me (mm) 1.0.8 is too old: version 1.0.9 or later is needed') // { key: 'creator.mmTooOld', found: '1.0.8' }
149+ */
150+export function startProblem(raw: string): { key: MessageKey; found: string } | null {
151+ if (/mini-me \(mm\) is not installed/.test(raw)) return { key: 'creator.mmMissing', found: '' }
152+ const old = /mini-me \(mm\) (\S+) is too old/.exec(raw)
153+ if (old) return { key: 'creator.mmTooOld', found: old[1] }
154+ return null
155+}
new file mode 100644
@@ -0,0 +1,155 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+// The assistant that creates a mini-me agent (issue #94): Go drives mm's
4+// wizard (CreatorService) and sends its questions as forms; this module
5+// turns a form into values the page edits, and those values back into the
6+// answer mm expects. No Svelte here, so that vitest can test it.
7+
8+import type { MessageKey } from './i18n/index.svelte'
9+
10+/** A question of a form, as acp.FormField gives it. */
11+export interface Field {
12+ name: string
13+ title: string
14+ description: string
15+ /** text, choice, multi, boolean or number. */
16+ type: string
17+ options: string[] | null
18+ default: unknown
19+ required: boolean
20+}
21+
22+export interface Form {
23+ message: string
24+ fields: Field[] | null
25+}
26+
27+export type Value = string | boolean | string[]
28+
29+/** Where the agent runs, as CreatorService.Finish takes it. */
30+export type Environment = 'local' | 'container' | 'sbx'
31+export const environments: Environment[] = ['local', 'container', 'sbx']
32+
33+/** A few emojis to pick from; any other can be typed. */
34+export const iconChoices = ['🤖', '🦊', '🐱', '🐼', '🦉', '🐙', '🧙', '👩‍🔬', '👨‍🍳', '🧑‍🚀', '🎨', '📚']
35+
36+/**
37+ * The values a form starts with: the defaults mm gives, else nothing (the
38+ * first option for a choice, which a select shows anyway).
39+ *
40+ * @example
41+ * initialValues({ message: '', fields: [{ name: 'yolo', type: 'boolean', default: true, … }] }) // { yolo: true }
42+ */
43+export function initialValues(form: Form): Record<string, Value> {
44+ const values: Record<string, Value> = {}
45+ for (const field of form.fields ?? []) {
46+ const value = field.default
47+ switch (field.type) {
48+ case 'boolean':
49+ values[field.name] = value === true || value === 'yes' || value === 'true'
50+ break
51+ case 'multi':
52+ values[field.name] = Array.isArray(value) ? value.map(String) : []
53+ break
54+ case 'choice':
55+ values[field.name] = value !== undefined && value !== null ? String(value) : (field.options?.[0] ?? '')
56+ break
57+ default:
58+ values[field.name] = value !== undefined && value !== null ? String(value) : ''
59+ }
60+ }
61+ return values
62+}
63+
64+/**
65+ * The content of an accepted form: each value with the type its field
66+ * asks for (a number field sends a number when the text is one).
67+ *
68+ * @example
69+ * contentOf(form, { name: ' bob ', yolo: false }) // { name: 'bob', yolo: false }
70+ */
71+export function contentOf(form: Form, values: Record<string, Value>): Record<string, unknown> {
72+ const content: Record<string, unknown> = {}
73+ for (const field of form.fields ?? []) {
74+ const value = values[field.name]
75+ if (typeof value === 'string') {
76+ const text = value.trim()
77+ content[field.name] = field.type === 'number' && text !== '' && !Number.isNaN(Number(text)) ? Number(text) : text
78+ } else {
79+ content[field.name] = value
80+ }
81+ }
82+ return content
83+}
84+
85+/** The required text fields still empty, by name: the form cannot be sent. */
86+export function missingFields(form: Form, values: Record<string, Value>): string[] {
87+ return (form.fields ?? [])
88+ .filter((field) => field.required && (field.type === 'text' || field.type === 'number' || field.type === 'choice'))
89+ .filter((field) => String(values[field.name] ?? '').trim() === '')
90+ .map((field) => field.name)
91+}
92+
93+/**
94+ * True when mm asks the model as plain text: no model server answered, so
95+ * it could not list the models (mm's "model" question has choices otherwise).
96+ */
97+export function noModelServer(form: Form | null | undefined): boolean {
98+ return (form?.fields ?? []).some((field) => field.name === 'model' && field.type === 'text')
99+}
100+
101+/**
102+ * mm's messages, split: its warnings (⚠️) are shown, the rest — meant for a
103+ * developer — stays folded.
104+ */
105+export function splitMessages(messages: string[] | null | undefined): { warnings: string[]; details: string[] } {
106+ const warnings: string[] = []
107+ const details: string[] = []
108+ for (const message of messages ?? []) {
109+ ;(message.trimStart().startsWith('⚠️') ? warnings : details).push(message)
110+ }
111+ return { warnings, details }
112+}
113+
114+/** An agent name Sidekicks accepts, which is also its folder's name. */
115+export function validName(name: string): boolean {
116+ return /^[a-z][a-z0-9_-]{0,31}$/.test(name)
117+}
118+
119+/**
120+ * The agent's folder: name in the agents' folder, with that folder's separator.
121+ *
122+ * @example
123+ * agentFolder('/Users/me/Documents', 'bob') // '/Users/me/Documents/bob'
124+ * agentFolder('C:\\Users\\me\\Documents', 'bob') // 'C:\\Users\\me\\Documents\\bob'
125+ */
126+export function agentFolder(folder: string, name: string): string {
127+ const separator = folder.includes('\\') && !folder.includes('/') ? '\\' : '/'
128+ return folder.endsWith(separator) ? folder + name : folder + separator + name
129+}
130+
131+/** The message key explaining a Problem of CreatorService.Finish. */
132+export function problemKey(problem: string): MessageKey {
133+ switch (problem) {
134+ case 'nameTaken':
135+ return 'creator.problem.nameTaken'
136+ case 'folderExists':
137+ return 'creator.problem.folderExists'
138+ default:
139+ return 'creator.problem.invalidName'
140+ }
141+}
142+
143+/**
144+ * What a Start error means for the user: mm missing, too old, or another
145+ * problem (shown with ErrorText).
146+ *
147+ * @example
148+ * startProblem('mini-me (mm) 1.0.8 is too old: version 1.0.9 or later is needed') // { key: 'creator.mmTooOld', found: '1.0.8' }
149+ */
150+export function startProblem(raw: string): { key: MessageKey; found: string } | null {
151+ if (/mini-me \(mm\) is not installed/.test(raw)) return { key: 'creator.mmMissing', found: '' }
152+ const old = /mini-me \(mm\) (\S+) is too old/.exec(raw)
153+ if (old) return { key: 'creator.mmTooOld', found: old[1] }
154+ return null
155+}
modified frontend/src/lib/i18n/messages.ts +76 -0
@@ -323,6 +323,44 @@ export const en = {
323323 'welcome.configAt': 'Configuration: {path}',
324324 'welcome.pick': 'Pick a channel, or click an agent to talk with it directly.',
325325 'agents.add': '+ Add an agent',
326+ 'agents.create': '✨ Create a mini-me agent',
327+ 'welcome.createFirst': '✨ Create my first agent',
328+ 'action.createAgent': 'Create a mini-me agent',
329+ 'creator.title': 'Create a mini-me agent',
330+ 'creator.intro': 'Answer a few questions: mini-me prepares the agent, then Sidekicks adds it to your agents. Its folder will be in {folder}.',
331+ 'creator.starting': 'Starting mini-me…',
332+ 'creator.waiting': 'mini-me is working…',
333+ 'creator.mmMissing': 'mini-me (mm) is not installed on this computer. Install it, then try again.',
334+ 'creator.mmTooOld': 'mini-me {found} is installed, but this assistant needs mini-me 1.0.9 or later. Update it, then try again.',
335+ 'creator.retry': 'Try again',
336+ 'creator.cancel': 'Cancel',
337+ 'creator.back': '← Previous question',
338+ 'creator.restart': 'Start again',
339+ 'creator.next': 'Next →',
340+ 'creator.about': 'About these choices',
341+ 'creator.details': 'What mini-me said',
342+ 'creator.missing': 'Please fill this in.',
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.',
344+ 'creator.stopped': 'The questions stopped: nothing was written yet.',
345+ 'creator.continue': 'Continue',
346+ 'creator.ready': 'Your agent is ready. Last details:',
347+ 'creator.name': 'Name',
348+ 'creator.nameHint': 'Used to call it with @{name}, and as the name of its folder: {folder}',
349+ 'creator.icon': 'Emoji',
350+ 'creator.iconHint': 'Pick one, or type any emoji.',
351+ 'creator.where': 'Where does it run?',
352+ 'creator.env.local': 'On this computer',
353+ 'creator.env.localHint': 'The simplest: mini-me runs directly on your computer.',
354+ 'creator.env.container': 'In a Docker container',
355+ 'creator.env.containerHint': 'mini-me prepares a Docker container; Docker must be installed.',
356+ 'creator.env.sbx': 'In a Docker Sandbox (sbx)',
357+ 'creator.env.sbxHint': 'mini-me prepares a sandbox, isolated from your computer; sbx must be installed.',
358+ 'creator.create': 'Add the agent',
359+ 'creator.creating': 'Adding…',
360+ 'creator.problem.nameTaken': 'Another agent already has this name: choose another one.',
361+ 'creator.problem.folderExists': 'A folder with this name already exists: choose another name.',
362+ 'creator.problem.invalidName': 'Use lowercase letters, digits, - or _, starting with a letter (32 characters at most).',
363+ 'creator.refused': 'The agent could not be added:',
326364 'palette.label': 'Command palette',
327365 'palette.placeholder': 'Go to a channel or an agent, or run an action…',
328366 'palette.none': 'Nothing matches.',
@@ -717,6 +755,44 @@ export const fr: Record<MessageKey, string> = {
717755 'welcome.configAt': 'Configuration : {path}',
718756 'welcome.pick': 'Choisissez un channel, ou cliquez sur un agent pour lui parler directement.',
719757 'agents.add': '+ Ajouter un agent',
758+ 'agents.create': '✨ Créer un agent mini-me',
759+ 'welcome.createFirst': '✨ Créer mon premier agent',
760+ 'action.createAgent': 'Créer un agent mini-me',
761+ 'creator.title': 'Créer un agent mini-me',
762+ 'creator.intro': "Répondez à quelques questions : mini-me prépare l'agent, puis Sidekicks l'ajoute à vos agents. Son dossier sera dans {folder}.",
763+ 'creator.starting': 'Démarrage de mini-me…',
764+ 'creator.waiting': 'mini-me travaille…',
765+ 'creator.mmMissing': "mini-me (mm) n'est pas installé sur cet ordinateur. Installez-le, puis réessayez.",
766+ 'creator.mmTooOld': 'mini-me {found} est installé, mais cet assistant a besoin de mini-me 1.0.9 ou plus récent. Mettez-le à jour, puis réessayez.',
767+ 'creator.retry': 'Réessayer',
768+ 'creator.cancel': 'Annuler',
769+ 'creator.back': '← Question précédente',
770+ 'creator.restart': 'Recommencer',
771+ 'creator.next': 'Suivant →',
772+ 'creator.about': 'À propos de ces choix',
773+ 'creator.details': 'Ce que mini-me a dit',
774+ 'creator.missing': 'Merci de remplir ce champ.',
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.",
776+ 'creator.stopped': "Les questions se sont arrêtées : rien n'est encore écrit.",
777+ 'creator.continue': 'Continuer',
778+ 'creator.ready': 'Votre agent est prêt. Derniers détails :',
779+ 'creator.name': 'Nom',
780+ 'creator.nameHint': "Pour l'appeler avec @{name}, et comme nom de son dossier : {folder}",
781+ 'creator.icon': 'Emoji',
782+ 'creator.iconHint': "Choisissez-en un, ou tapez n'importe quel emoji.",
783+ 'creator.where': "Où s'exécute-t-il ?",
784+ 'creator.env.local': 'Sur cet ordinateur',
785+ 'creator.env.localHint': 'Le plus simple : mini-me tourne directement sur votre ordinateur.',
786+ 'creator.env.container': 'Dans un conteneur Docker',
787+ 'creator.env.containerHint': 'mini-me prépare un conteneur Docker ; Docker doit être installé.',
788+ 'creator.env.sbx': 'Dans une Docker Sandbox (sbx)',
789+ 'creator.env.sbxHint': 'mini-me prépare une sandbox, isolée de votre ordinateur ; sbx doit être installé.',
790+ 'creator.create': "Ajouter l'agent",
791+ 'creator.creating': 'Ajout…',
792+ 'creator.problem.nameTaken': 'Un autre agent porte déjà ce nom : choisissez-en un autre.',
793+ 'creator.problem.folderExists': 'Un dossier porte déjà ce nom : choisissez un autre nom.',
794+ 'creator.problem.invalidName': 'Utilisez des minuscules, des chiffres, - ou _, en commençant par une lettre (32 caractères au plus).',
795+ 'creator.refused': "L'agent n'a pas pu être ajouté :",
720796 'palette.label': 'Palette de commandes',
721797 'palette.placeholder': 'Aller à un channel ou un agent, ou lancer une action…',
722798 'palette.none': 'Aucun résultat.',
@@ -323,6 +323,44 @@ export const en = {
323 'welcome.configAt': 'Configuration: {path}',323 'welcome.configAt': 'Configuration: {path}',
324 'welcome.pick': 'Pick a channel, or click an agent to talk with it directly.',324 'welcome.pick': 'Pick a channel, or click an agent to talk with it directly.',
325 'agents.add': '+ Add an agent',325 'agents.add': '+ Add an agent',
326+ 'agents.create': '✨ Create a mini-me agent',
327+ 'welcome.createFirst': '✨ Create my first agent',
328+ 'action.createAgent': 'Create a mini-me agent',
329+ 'creator.title': 'Create a mini-me agent',
330+ 'creator.intro': 'Answer a few questions: mini-me prepares the agent, then Sidekicks adds it to your agents. Its folder will be in {folder}.',
331+ 'creator.starting': 'Starting mini-me…',
332+ 'creator.waiting': 'mini-me is working…',
333+ 'creator.mmMissing': 'mini-me (mm) is not installed on this computer. Install it, then try again.',
334+ 'creator.mmTooOld': 'mini-me {found} is installed, but this assistant needs mini-me 1.0.9 or later. Update it, then try again.',
335+ 'creator.retry': 'Try again',
336+ 'creator.cancel': 'Cancel',
337+ 'creator.back': '← Previous question',
338+ 'creator.restart': 'Start again',
339+ 'creator.next': 'Next →',
340+ 'creator.about': 'About these choices',
341+ 'creator.details': 'What mini-me said',
342+ 'creator.missing': 'Please fill this in.',
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.',
344+ 'creator.stopped': 'The questions stopped: nothing was written yet.',
345+ 'creator.continue': 'Continue',
346+ 'creator.ready': 'Your agent is ready. Last details:',
347+ 'creator.name': 'Name',
348+ 'creator.nameHint': 'Used to call it with @{name}, and as the name of its folder: {folder}',
349+ 'creator.icon': 'Emoji',
350+ 'creator.iconHint': 'Pick one, or type any emoji.',
351+ 'creator.where': 'Where does it run?',
352+ 'creator.env.local': 'On this computer',
353+ 'creator.env.localHint': 'The simplest: mini-me runs directly on your computer.',
354+ 'creator.env.container': 'In a Docker container',
355+ 'creator.env.containerHint': 'mini-me prepares a Docker container; Docker must be installed.',
356+ 'creator.env.sbx': 'In a Docker Sandbox (sbx)',
357+ 'creator.env.sbxHint': 'mini-me prepares a sandbox, isolated from your computer; sbx must be installed.',
358+ 'creator.create': 'Add the agent',
359+ 'creator.creating': 'Adding…',
360+ 'creator.problem.nameTaken': 'Another agent already has this name: choose another one.',
361+ 'creator.problem.folderExists': 'A folder with this name already exists: choose another name.',
362+ 'creator.problem.invalidName': 'Use lowercase letters, digits, - or _, starting with a letter (32 characters at most).',
363+ 'creator.refused': 'The agent could not be added:',
326 'palette.label': 'Command palette',364 'palette.label': 'Command palette',
327 'palette.placeholder': 'Go to a channel or an agent, or run an action…',365 'palette.placeholder': 'Go to a channel or an agent, or run an action…',
328 'palette.none': 'Nothing matches.',366 'palette.none': 'Nothing matches.',
@@ -717,6 +755,44 @@ export const fr: Record<MessageKey, string> = {
717 'welcome.configAt': 'Configuration : {path}',755 'welcome.configAt': 'Configuration : {path}',
718 'welcome.pick': 'Choisissez un channel, ou cliquez sur un agent pour lui parler directement.',756 'welcome.pick': 'Choisissez un channel, ou cliquez sur un agent pour lui parler directement.',
719 'agents.add': '+ Ajouter un agent',757 'agents.add': '+ Ajouter un agent',
758+ 'agents.create': '✨ Créer un agent mini-me',
759+ 'welcome.createFirst': '✨ Créer mon premier agent',
760+ 'action.createAgent': 'Créer un agent mini-me',
761+ 'creator.title': 'Créer un agent mini-me',
762+ 'creator.intro': "Répondez à quelques questions : mini-me prépare l'agent, puis Sidekicks l'ajoute à vos agents. Son dossier sera dans {folder}.",
763+ 'creator.starting': 'Démarrage de mini-me…',
764+ 'creator.waiting': 'mini-me travaille…',
765+ 'creator.mmMissing': "mini-me (mm) n'est pas installé sur cet ordinateur. Installez-le, puis réessayez.",
766+ 'creator.mmTooOld': 'mini-me {found} est installé, mais cet assistant a besoin de mini-me 1.0.9 ou plus récent. Mettez-le à jour, puis réessayez.',
767+ 'creator.retry': 'Réessayer',
768+ 'creator.cancel': 'Annuler',
769+ 'creator.back': '← Question précédente',
770+ 'creator.restart': 'Recommencer',
771+ 'creator.next': 'Suivant →',
772+ 'creator.about': 'À propos de ces choix',
773+ 'creator.details': 'Ce que mini-me a dit',
774+ 'creator.missing': 'Merci de remplir ce champ.',
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.",
776+ 'creator.stopped': "Les questions se sont arrêtées : rien n'est encore écrit.",
777+ 'creator.continue': 'Continuer',
778+ 'creator.ready': 'Votre agent est prêt. Derniers détails :',
779+ 'creator.name': 'Nom',
780+ 'creator.nameHint': "Pour l'appeler avec @{name}, et comme nom de son dossier : {folder}",
781+ 'creator.icon': 'Emoji',
782+ 'creator.iconHint': "Choisissez-en un, ou tapez n'importe quel emoji.",
783+ 'creator.where': "Où s'exécute-t-il ?",
784+ 'creator.env.local': 'Sur cet ordinateur',
785+ 'creator.env.localHint': 'Le plus simple : mini-me tourne directement sur votre ordinateur.',
786+ 'creator.env.container': 'Dans un conteneur Docker',
787+ 'creator.env.containerHint': 'mini-me prépare un conteneur Docker ; Docker doit être installé.',
788+ 'creator.env.sbx': 'Dans une Docker Sandbox (sbx)',
789+ 'creator.env.sbxHint': 'mini-me prépare une sandbox, isolée de votre ordinateur ; sbx doit être installé.',
790+ 'creator.create': "Ajouter l'agent",
791+ 'creator.creating': 'Ajout…',
792+ 'creator.problem.nameTaken': 'Un autre agent porte déjà ce nom : choisissez-en un autre.',
793+ 'creator.problem.folderExists': 'Un dossier porte déjà ce nom : choisissez un autre nom.',
794+ 'creator.problem.invalidName': 'Utilisez des minuscules, des chiffres, - ou _, en commençant par une lettre (32 caractères au plus).',
795+ 'creator.refused': "L'agent n'a pas pu être ajouté :",
720 'palette.label': 'Palette de commandes',796 'palette.label': 'Palette de commandes',
721 'palette.placeholder': 'Aller à un channel ou un agent, ou lancer une action…',797 'palette.placeholder': 'Aller à un channel ou un agent, ou lancer une action…',
722 'palette.none': 'Aucun résultat.',798 'palette.none': 'Aucun résultat.',
modified frontend/src/lib/layout/CommandPalette.svelte +2 -1
@@ -6,7 +6,7 @@
66 import { t } from '../i18n/index.svelte'
77 import { textIcon } from '../avatar'
88 import { filterEntries, isMac, shortcutLabel, type Action, type PaletteEntry } from '../shortcuts'
9- import { act, appState, openDirect, openWorkspace, selectChannel } from '../state.svelte'
9+ import { act, appState, openCreator, openDirect, openWorkspace, selectChannel } from '../state.svelte'
1010 import { ConfigService } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/app'
1111
1212 let { run }: { run: (action: Action) => void } = $props()
@@ -31,6 +31,7 @@
3131 id: `files:${agent.name}`, label: t('palette.filesOf', { agent: agent.title }), hint: t('palette.files'), run: () => openWorkspace(agent.name),
3232 })),
3333 ...actions.map((action) => ({ id: `action:${action}`, label: t(`action.${action}`), hint: shortcutLabel(action, mac), run: () => run(action) })),
34+ { id: 'action:createAgent', label: t('action.createAgent'), hint: '', run: openCreator },
3435 { id: 'action:openConfig', label: t('action.openConfig'), hint: '', run: () => void act(() => ConfigService.Choose()) },
3536 ]
3637 })
@@ -6,7 +6,7 @@
6 import { t } from '../i18n/index.svelte'6 import { t } from '../i18n/index.svelte'
7 import { textIcon } from '../avatar'7 import { textIcon } from '../avatar'
8 import { filterEntries, isMac, shortcutLabel, type Action, type PaletteEntry } from '../shortcuts'8 import { filterEntries, isMac, shortcutLabel, type Action, type PaletteEntry } from '../shortcuts'
9- import { act, appState, openDirect, openWorkspace, selectChannel } from '../state.svelte'9+ import { act, appState, openCreator, openDirect, openWorkspace, selectChannel } from '../state.svelte'
10 import { ConfigService } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/app'10 import { ConfigService } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/app'
11 11
12 let { run }: { run: (action: Action) => void } = $props()12 let { run }: { run: (action: Action) => void } = $props()
@@ -31,6 +31,7 @@
31 id: `files:${agent.name}`, label: t('palette.filesOf', { agent: agent.title }), hint: t('palette.files'), run: () => openWorkspace(agent.name),31 id: `files:${agent.name}`, label: t('palette.filesOf', { agent: agent.title }), hint: t('palette.files'), run: () => openWorkspace(agent.name),
32 })),32 })),
33 ...actions.map((action) => ({ id: `action:${action}`, label: t(`action.${action}`), hint: shortcutLabel(action, mac), run: () => run(action) })),33 ...actions.map((action) => ({ id: `action:${action}`, label: t(`action.${action}`), hint: shortcutLabel(action, mac), run: () => run(action) })),
34+ { id: 'action:createAgent', label: t('action.createAgent'), hint: '', run: openCreator },
34 { id: 'action:openConfig', label: t('action.openConfig'), hint: '', run: () => void act(() => ConfigService.Choose()) },35 { id: 'action:openConfig', label: t('action.openConfig'), hint: '', run: () => void act(() => ConfigService.Choose()) },
35 ]36 ]
36 })37 })
modified frontend/src/lib/panels/AgentsPanel.svelte +2 -1
@@ -6,7 +6,7 @@
66 import ErrorText from '../chat/ErrorText.svelte'
77 import AgentAvatar from '../agent/AgentAvatar.svelte'
88 import { AgentService } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/app'
9- import { act, appState, channelOf, loadCommands, openAssistant, openDirect, openWorkspace } from '../state.svelte'
9+ import { act, appState, channelOf, loadCommands, openAssistant, openCreator, openDirect, openWorkspace } from '../state.svelte'
1010 import { directOf } from '../conversation'
1111 import { canUnload, unloadReady } from '../unload'
1212
@@ -60,6 +60,7 @@
6060 {/each}
6161 </ul>
6262 {/if}
63+<button class="add" onclick={openCreator}>{t('agents.create')}</button>
6364 <button class="add" onclick={openAssistant}>{t('agents.add')}</button>
6465 <ActionError />
6566
@@ -6,7 +6,7 @@
6 import ErrorText from '../chat/ErrorText.svelte'6 import ErrorText from '../chat/ErrorText.svelte'
7 import AgentAvatar from '../agent/AgentAvatar.svelte'7 import AgentAvatar from '../agent/AgentAvatar.svelte'
8 import { AgentService } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/app'8 import { AgentService } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/app'
9- import { act, appState, channelOf, loadCommands, openAssistant, openDirect, openWorkspace } from '../state.svelte'9+ import { act, appState, channelOf, loadCommands, openAssistant, openCreator, openDirect, openWorkspace } from '../state.svelte'
10 import { directOf } from '../conversation'10 import { directOf } from '../conversation'
11 import { canUnload, unloadReady } from '../unload'11 import { canUnload, unloadReady } from '../unload'
12 12
@@ -60,6 +60,7 @@
60 {/each}60 {/each}
61 </ul>61 </ul>
62 {/if}62 {/if}
63+<button class="add" onclick={openCreator}>{t('agents.create')}</button>
63 <button class="add" onclick={openAssistant}>{t('agents.add')}</button>64 <button class="add" onclick={openAssistant}>{t('agents.add')}</button>
64 <ActionError />65 <ActionError />
65 66
modified frontend/src/lib/panels/ConversationPanel.svelte +7 -3
@@ -10,13 +10,14 @@
1010 import LinkedFilePanel from '../agent/LinkedFilePanel.svelte'
1111 import { Pane, PaneGroup, PaneResizer } from 'paneforge'
1212 import AddAgentForm from '../agent/AddAgentForm.svelte'
13+ import CreateMiniMeAgent from '../agent/CreateMiniMeAgent.svelte'
1314 import AgentAvatar from '../agent/AgentAvatar.svelte'
1415 import { textIcon } from '../avatar'
1516 import ActionError from '../chat/ActionError.svelte'
1617 import Logo from '../layout/Logo.svelte'
1718 import { drafts, isNearBottom, type Trigger } from '../composer'
1819 import { notStreaming, usagePercent } from '../conversation'
19- import { act, addMember, agentTitle, appState, cancel, channelOf, clearHistory, loadOlder, openAssistant, prepareCommands, removeMember, send } from '../state.svelte'
20+ import { act, addMember, agentTitle, appState, cancel, channelOf, clearHistory, loadOlder, openAssistant, openCreator, prepareCommands, removeMember, send } from '../state.svelte'
2021 import { ConfigService, WorkspaceService } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/app'
2122 import type { FilesDroppedPayload } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/events'
2223 import { FilesDropped } from '../../../bindings/events'
@@ -203,7 +204,9 @@
203204 <div class="banner warning" role="alert">{t('conversation.historyProblem', { problem: appState.config.historyProblem })}</div>
204205 {/if}
205206
206- {#if appState.assistant}
207+ {#if appState.creator}
208+ <CreateMiniMeAgent />
209+ {:else if appState.assistant}
207210 <AddAgentForm />
208211 {:else if appState.workspaceAgent}
209212 {#key appState.workspaceAgent}
@@ -337,7 +340,8 @@
337340 {/each}
338341 </ol>
339342 <div class="buttons">
340- <button class="primary" onclick={openAssistant}>{t('welcome.addFirst')}</button>
343+ <button class="primary" onclick={openCreator}>{t('welcome.createFirst')}</button>
344+ <button onclick={openAssistant}>{t('welcome.addFirst')}</button>
341345 <button onclick={() => act(() => ConfigService.Choose())}>{t('welcome.openConfig')}</button>
342346 </div>
343347 {#if appState.config?.path}
@@ -10,13 +10,14 @@
10 import LinkedFilePanel from '../agent/LinkedFilePanel.svelte'10 import LinkedFilePanel from '../agent/LinkedFilePanel.svelte'
11 import { Pane, PaneGroup, PaneResizer } from 'paneforge'11 import { Pane, PaneGroup, PaneResizer } from 'paneforge'
12 import AddAgentForm from '../agent/AddAgentForm.svelte'12 import AddAgentForm from '../agent/AddAgentForm.svelte'
13+ import CreateMiniMeAgent from '../agent/CreateMiniMeAgent.svelte'
13 import AgentAvatar from '../agent/AgentAvatar.svelte'14 import AgentAvatar from '../agent/AgentAvatar.svelte'
14 import { textIcon } from '../avatar'15 import { textIcon } from '../avatar'
15 import ActionError from '../chat/ActionError.svelte'16 import ActionError from '../chat/ActionError.svelte'
16 import Logo from '../layout/Logo.svelte'17 import Logo from '../layout/Logo.svelte'
17 import { drafts, isNearBottom, type Trigger } from '../composer'18 import { drafts, isNearBottom, type Trigger } from '../composer'
18 import { notStreaming, usagePercent } from '../conversation'19 import { notStreaming, usagePercent } from '../conversation'
19- import { act, addMember, agentTitle, appState, cancel, channelOf, clearHistory, loadOlder, openAssistant, prepareCommands, removeMember, send } from '../state.svelte'20+ import { act, addMember, agentTitle, appState, cancel, channelOf, clearHistory, loadOlder, openAssistant, openCreator, prepareCommands, removeMember, send } from '../state.svelte'
20 import { ConfigService, WorkspaceService } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/app'21 import { ConfigService, WorkspaceService } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/app'
21 import type { FilesDroppedPayload } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/events'22 import type { FilesDroppedPayload } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/events'
22 import { FilesDropped } from '../../../bindings/events'23 import { FilesDropped } from '../../../bindings/events'
@@ -203,7 +204,9 @@
203 <div class="banner warning" role="alert">{t('conversation.historyProblem', { problem: appState.config.historyProblem })}</div>204 <div class="banner warning" role="alert">{t('conversation.historyProblem', { problem: appState.config.historyProblem })}</div>
204 {/if}205 {/if}
205 206
206- {#if appState.assistant}207+ {#if appState.creator}
208+ <CreateMiniMeAgent />
209+ {:else if appState.assistant}
207 <AddAgentForm />210 <AddAgentForm />
208 {:else if appState.workspaceAgent}211 {:else if appState.workspaceAgent}
209 {#key appState.workspaceAgent}212 {#key appState.workspaceAgent}
@@ -337,7 +340,8 @@
337 {/each}340 {/each}
338 </ol>341 </ol>
339 <div class="buttons">342 <div class="buttons">
340- <button class="primary" onclick={openAssistant}>{t('welcome.addFirst')}</button>343+ <button class="primary" onclick={openCreator}>{t('welcome.createFirst')}</button>
344+ <button onclick={openAssistant}>{t('welcome.addFirst')}</button>
341 <button onclick={() => act(() => ConfigService.Choose())}>{t('welcome.openConfig')}</button>345 <button onclick={() => act(() => ConfigService.Choose())}>{t('welcome.openConfig')}</button>
342 </div>346 </div>
343 {#if appState.config?.path}347 {#if appState.config?.path}
modified frontend/src/lib/state.svelte.ts +13 -0
@@ -93,6 +93,8 @@ export const appState = $state({
9393 actionError: '',
9494 /** The "add an agent" assistant is shown in the centre. */
9595 assistant: false,
96+ /** The assistant that creates a mini-me agent (issue #94) is shown in the centre. */
97+ creator: false,
9698 /** An agent just added with the assistant: its conversation opens once it is loaded. */
9799 pendingAgent: '',
98100 /** The command palette (⌘K) is open. */
@@ -172,6 +174,7 @@ export async function selectChannel(id: string) {
172174 conversationOf(id) // shown empty until loaded
173175 appState.workspaceAgent = ''
174176 appState.assistant = false
177+ appState.creator = false
175178 appState.selectedChannel = id
176179 appState.unread[id] = 0
177180 const channel = channelOf(id)
@@ -205,6 +208,7 @@ export function closeLinkedFile(channel: string) {
205208 /** Shows the workspace of agent (files, terminal, log) in the centre. */
206209 export function openWorkspace(agent: string, file = '') {
207210 appState.assistant = false
211+ appState.creator = false
208212 appState.workspaceAgent = agent
209213 appState.workspaceFile = file
210214 }
@@ -212,9 +216,17 @@ export function openWorkspace(agent: string, file = '') {
212216 /** Shows the "add an agent" assistant in the centre. */
213217 export function openAssistant() {
214218 appState.workspaceAgent = ''
219+ appState.creator = false
215220 appState.assistant = true
216221 }
217222
223+/** Shows the assistant that creates a mini-me agent (issue #94) in the centre. */
224+export function openCreator() {
225+ appState.workspaceAgent = ''
226+ appState.assistant = false
227+ appState.creator = true
228+}
229+
218230 /**
219231 * Called once the assistant has written the agent to the configuration:
220232 * its direct conversation opens when the reloaded configuration lists it.
@@ -236,6 +248,7 @@ export async function historyReset() {
236248
237249 export function agentAdded(name: string) {
238250 appState.assistant = false
251+ appState.creator = false
239252 appState.pendingAgent = name
240253 if (appState.agents.some((agent) => agent.name === name)) void refreshAgents()
241254 }
@@ -93,6 +93,8 @@ export const appState = $state({
93 actionError: '',93 actionError: '',
94 /** The "add an agent" assistant is shown in the centre. */94 /** The "add an agent" assistant is shown in the centre. */
95 assistant: false,95 assistant: false,
96+ /** The assistant that creates a mini-me agent (issue #94) is shown in the centre. */
97+ creator: false,
96 /** An agent just added with the assistant: its conversation opens once it is loaded. */98 /** An agent just added with the assistant: its conversation opens once it is loaded. */
97 pendingAgent: '',99 pendingAgent: '',
98 /** The command palette (⌘K) is open. */100 /** The command palette (⌘K) is open. */
@@ -172,6 +174,7 @@ export async function selectChannel(id: string) {
172 conversationOf(id) // shown empty until loaded174 conversationOf(id) // shown empty until loaded
173 appState.workspaceAgent = ''175 appState.workspaceAgent = ''
174 appState.assistant = false176 appState.assistant = false
177+ appState.creator = false
175 appState.selectedChannel = id178 appState.selectedChannel = id
176 appState.unread[id] = 0179 appState.unread[id] = 0
177 const channel = channelOf(id)180 const channel = channelOf(id)
@@ -205,6 +208,7 @@ export function closeLinkedFile(channel: string) {
205 /** Shows the workspace of agent (files, terminal, log) in the centre. */208 /** Shows the workspace of agent (files, terminal, log) in the centre. */
206 export function openWorkspace(agent: string, file = '') {209 export function openWorkspace(agent: string, file = '') {
207 appState.assistant = false210 appState.assistant = false
211+ appState.creator = false
208 appState.workspaceAgent = agent212 appState.workspaceAgent = agent
209 appState.workspaceFile = file213 appState.workspaceFile = file
210 }214 }
@@ -212,9 +216,17 @@ export function openWorkspace(agent: string, file = '') {
212 /** Shows the "add an agent" assistant in the centre. */216 /** Shows the "add an agent" assistant in the centre. */
213 export function openAssistant() {217 export function openAssistant() {
214 appState.workspaceAgent = ''218 appState.workspaceAgent = ''
219+ appState.creator = false
215 appState.assistant = true220 appState.assistant = true
216 }221 }
217 222
223+/** Shows the assistant that creates a mini-me agent (issue #94) in the centre. */
224+export function openCreator() {
225+ appState.workspaceAgent = ''
226+ appState.assistant = false
227+ appState.creator = true
228+}
229+
218 /**230 /**
219 * Called once the assistant has written the agent to the configuration:231 * Called once the assistant has written the agent to the configuration:
220 * its direct conversation opens when the reloaded configuration lists it.232 * its direct conversation opens when the reloaded configuration lists it.
@@ -236,6 +248,7 @@ export async function historyReset() {
236 248
237 export function agentAdded(name: string) {249 export function agentAdded(name: string) {
238 appState.assistant = false250 appState.assistant = false
251+ appState.creator = false
239 appState.pendingAgent = name252 appState.pendingAgent = name
240 if (appState.agents.some((agent) => agent.name === name)) void refreshAgents()253 if (appState.agents.some((agent) => agent.name === name)) void refreshAgents()
241 }254 }
modified frontend/src/lib/yamlSchema.test.ts +1 -1
@@ -11,7 +11,7 @@ const labels = (suggestions: Array<{ label: string }>) => suggestions.map((sugge
1111
1212 describe('createSchemaIndex', () => {
1313 it('lists the keys of the schema, following $ref and list items', () => {
14- expect(labels(schema.keysAt([]))).toEqual(['version', 'ui', 'limits', 'agentTools', 'agents', 'channels'])
14+ expect(labels(schema.keysAt([]))).toEqual(['version', 'ui', 'limits', 'agentTools', 'agentsFolder', 'agents', 'channels'])
1515 expect(labels(schema.keysAt(['agentTools']))).toEqual(['enabled', 'offer'])
1616 expect(labels(schema.keysAt(['agents', item]))).toContain('workspace')
1717 expect(labels(schema.keysAt(['agents', item, 'runtime']))).toEqual(['type', 'container', 'sandbox', 'workspacePath', 'lifecycle'])
@@ -11,7 +11,7 @@ const labels = (suggestions: Array<{ label: string }>) => suggestions.map((sugge
11 11
12 describe('createSchemaIndex', () => {12 describe('createSchemaIndex', () => {
13 it('lists the keys of the schema, following $ref and list items', () => {13 it('lists the keys of the schema, following $ref and list items', () => {
14- expect(labels(schema.keysAt([]))).toEqual(['version', 'ui', 'limits', 'agentTools', 'agents', 'channels'])14+ expect(labels(schema.keysAt([]))).toEqual(['version', 'ui', 'limits', 'agentTools', 'agentsFolder', 'agents', 'channels'])
15 expect(labels(schema.keysAt(['agentTools']))).toEqual(['enabled', 'offer'])15 expect(labels(schema.keysAt(['agentTools']))).toEqual(['enabled', 'offer'])
16 expect(labels(schema.keysAt(['agents', item]))).toContain('workspace')16 expect(labels(schema.keysAt(['agents', item]))).toContain('workspace')
17 expect(labels(schema.keysAt(['agents', item, 'runtime']))).toEqual(['type', 'container', 'sandbox', 'workspacePath', 'lifecycle'])17 expect(labels(schema.keysAt(['agents', item, 'runtime']))).toEqual(['type', 'container', 'sandbox', 'workspacePath', 'lifecycle'])
modified internal/acp/client.go +3 -1
@@ -10,11 +10,13 @@ import (
1010
1111 // client answers the requests an agent sends to Sidekicks: session updates
1212 // and permission requests go to the handler of their session; the tools
13-// Sidekicks offers are answered (tools.go); file and terminal access — which
13+// Sidekicks offers are answered (tools.go), and so are forms when
14+// Spec.OnForm is set (forms.go); file and terminal access — which
1415 // Sidekicks does not advertise (ADR 0001, decision 5) — is refused.
1516 type client struct {
1617 sessions *sessions
1718 tools []Tool
19+ onForm FormHandler
1820 }
1921
2022 func (c *client) SessionUpdate(_ context.Context, notification sdk.SessionNotification) error {
@@ -10,11 +10,13 @@ import (
10 10
11 // client answers the requests an agent sends to Sidekicks: session updates11 // client answers the requests an agent sends to Sidekicks: session updates
12 // and permission requests go to the handler of their session; the tools12 // and permission requests go to the handler of their session; the tools
13-// Sidekicks offers are answered (tools.go); file and terminal access — which13+// Sidekicks offers are answered (tools.go), and so are forms when
14+// Spec.OnForm is set (forms.go); file and terminal access — which
14 // Sidekicks does not advertise (ADR 0001, decision 5) — is refused.15 // Sidekicks does not advertise (ADR 0001, decision 5) — is refused.
15 type client struct {16 type client struct {
16 sessions *sessions17 sessions *sessions
17 tools []Tool18 tools []Tool
19+ onForm FormHandler
18 }20 }
19 21
20 func (c *client) SessionUpdate(_ context.Context, notification sdk.SessionNotification) error {22 func (c *client) SessionUpdate(_ context.Context, notification sdk.SessionNotification) error {
modified internal/acp/conn.go +5 -2
@@ -64,6 +64,9 @@ type Spec struct {
6464 ToolDiscovery string
6565 // ClientVersion is Sidekicks' version, told in initialize.
6666 ClientVersion string
67+ // OnForm answers the forms the agent asks the user to fill in (ACP
68+ // elicitation, issue #94); nil advertises no form support.
69+ OnForm FormHandler
6770 }
6871
6972 // Options tunes Start. The zero value is usable.
@@ -159,7 +162,7 @@ func (c *Conn) launch(onStderr func(string)) error {
159162 stderrDone := make(chan struct{})
160163 go c.readStderr(stderr, onStderr, stderrDone)
161164 go c.wait(stderrDone)
162- c.connection = sdk.NewClientSideConnection(&client{sessions: c.sessions, tools: c.spec.Tools}, stdin, stdout)
165+ c.connection = sdk.NewClientSideConnection(&client{sessions: c.sessions, tools: c.spec.Tools, onForm: c.spec.OnForm}, stdin, stdout)
163166 // The SDK logs its own diagnostics ("connection closed"…); the agent's
164167 // stderr already tells what matters.
165168 c.connection.SetLogger(slog.New(slog.NewTextHandler(io.Discard, nil)))
@@ -207,7 +210,7 @@ func (c *Conn) initialize(ctx context.Context) error {
207210 go func() {
208211 response, err := c.connection.Initialize(ctx, sdk.InitializeRequest{
209212 ProtocolVersion: sdk.ProtocolVersion(ProtocolVersion),
210- ClientCapabilities: sdk.ClientCapabilities{Meta: toolsMeta(c.spec.Tools, c.spec.ToolDiscovery)},
213+ ClientCapabilities: sdk.ClientCapabilities{Meta: toolsMeta(c.spec.Tools, c.spec.ToolDiscovery), Elicitation: elicitationCapabilities(c.spec.OnForm)},
211214 ClientInfo: &sdk.Implementation{Name: "sidekicks", Version: clientVersion(c.spec.ClientVersion)},
212215 })
213216 answer <- result{response, err}
@@ -64,6 +64,9 @@ type Spec struct {
64 ToolDiscovery string64 ToolDiscovery string
65 // ClientVersion is Sidekicks' version, told in initialize.65 // ClientVersion is Sidekicks' version, told in initialize.
66 ClientVersion string66 ClientVersion string
67+ // OnForm answers the forms the agent asks the user to fill in (ACP
68+ // elicitation, issue #94); nil advertises no form support.
69+ OnForm FormHandler
67 }70 }
68 71
69 // Options tunes Start. The zero value is usable.72 // Options tunes Start. The zero value is usable.
@@ -159,7 +162,7 @@ func (c *Conn) launch(onStderr func(string)) error {
159 stderrDone := make(chan struct{})162 stderrDone := make(chan struct{})
160 go c.readStderr(stderr, onStderr, stderrDone)163 go c.readStderr(stderr, onStderr, stderrDone)
161 go c.wait(stderrDone)164 go c.wait(stderrDone)
162- c.connection = sdk.NewClientSideConnection(&client{sessions: c.sessions, tools: c.spec.Tools}, stdin, stdout)165+ c.connection = sdk.NewClientSideConnection(&client{sessions: c.sessions, tools: c.spec.Tools, onForm: c.spec.OnForm}, stdin, stdout)
163 // The SDK logs its own diagnostics ("connection closed"…); the agent's166 // The SDK logs its own diagnostics ("connection closed"…); the agent's
164 // stderr already tells what matters.167 // stderr already tells what matters.
165 c.connection.SetLogger(slog.New(slog.NewTextHandler(io.Discard, nil)))168 c.connection.SetLogger(slog.New(slog.NewTextHandler(io.Discard, nil)))
@@ -207,7 +210,7 @@ func (c *Conn) initialize(ctx context.Context) error {
207 go func() {210 go func() {
208 response, err := c.connection.Initialize(ctx, sdk.InitializeRequest{211 response, err := c.connection.Initialize(ctx, sdk.InitializeRequest{
209 ProtocolVersion: sdk.ProtocolVersion(ProtocolVersion),212 ProtocolVersion: sdk.ProtocolVersion(ProtocolVersion),
210- ClientCapabilities: sdk.ClientCapabilities{Meta: toolsMeta(c.spec.Tools, c.spec.ToolDiscovery)},213+ ClientCapabilities: sdk.ClientCapabilities{Meta: toolsMeta(c.spec.Tools, c.spec.ToolDiscovery), Elicitation: elicitationCapabilities(c.spec.OnForm)},
211 ClientInfo: &sdk.Implementation{Name: "sidekicks", Version: clientVersion(c.spec.ClientVersion)},214 ClientInfo: &sdk.Implementation{Name: "sidekicks", Version: clientVersion(c.spec.ClientVersion)},
212 })215 })
213 answer <- result{response, err}216 answer <- result{response, err}
modified internal/acp/conn_test.go +31 -0
@@ -340,6 +340,9 @@ func (a *fakeAgent) Prompt(ctx context.Context, request sdk.PromptRequest) (sdk.
340340 _, err = a.conn.CallExtension(ctx, "_test/missing", nil)
341341 send(sdk.UpdateAgentMessageText(fmt.Sprintf("missing=%v", err)))
342342 return sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn}, nil
343+ case "form":
344+ send(sdk.UpdateAgentMessageText(a.askForm(ctx)))
345+ return sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn}, nil
343346 case "long":
344347 for {
345348 select {
@@ -353,6 +356,34 @@ func (a *fakeAgent) Prompt(ctx context.Context, request sdk.PromptRequest) (sdk.
353356 return sdk.PromptResponse{}, sdk.NewInternalError(map[string]any{"error": "exceeded maximum tool call iterations (40)"})
354357 }
355358
359+// askForm plays mm acp-create: it asks a form and tells what came back and
360+// whether initialize advertised forms.
361+func (a *fakeAgent) askForm(ctx context.Context) string {
362+ advertised := a.client.ClientCapabilities.Elicitation != nil && a.client.ClientCapabilities.Elicitation.Form != nil
363+ req := sdk.NewUnstableCreateElicitationRequestForm(sdk.UnstableElicitationSchema{
364+ Type: sdk.UnstableElicitationSchemaTypeObject,
365+ Properties: map[string]any{
366+ "provider": map[string]any{"type": "string", "title": "Model server?", "enum": []any{"llmman", "ollama"}, "default": "llmman"},
367+ "yolo": map[string]any{"type": "boolean", "title": "Ask first?", "default": true},
368+ "name": map[string]any{"type": "string", "title": "Agent name?"},
369+ },
370+ Required: []string{"provider", "yolo", "name"},
371+ })
372+ req.Form.Message = "mm init — create an agent"
373+ resp, err := a.conn.UnstableCreateElicitation(ctx, req)
374+ switch {
375+ case err != nil:
376+ return fmt.Sprintf("advertised=%v error=%v", advertised, err)
377+ case resp.Accept != nil:
378+ content, _ := json.Marshal(resp.Accept.Content)
379+ return fmt.Sprintf("advertised=%v accept=%s", advertised, content)
380+ case resp.Decline != nil:
381+ return fmt.Sprintf("advertised=%v decline", advertised)
382+ default:
383+ return fmt.Sprintf("advertised=%v cancel", advertised)
384+ }
385+}
386+
356387 // LoadSession resumes "s-1" and, as ACP requires, replays its history before
357388 // answering; any other id is unknown.
358389 func (a *fakeAgent) LoadSession(ctx context.Context, request sdk.LoadSessionRequest) (sdk.LoadSessionResponse, error) {
@@ -340,6 +340,9 @@ func (a *fakeAgent) Prompt(ctx context.Context, request sdk.PromptRequest) (sdk.
340 _, err = a.conn.CallExtension(ctx, "_test/missing", nil)340 _, err = a.conn.CallExtension(ctx, "_test/missing", nil)
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}, nil342 return sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn}, nil
343+ case "form":
344+ send(sdk.UpdateAgentMessageText(a.askForm(ctx)))
345+ return sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn}, nil
343 case "long":346 case "long":
344 for {347 for {
345 select {348 select {
@@ -353,6 +356,34 @@ func (a *fakeAgent) Prompt(ctx context.Context, request sdk.PromptRequest) (sdk.
353 return sdk.PromptResponse{}, sdk.NewInternalError(map[string]any{"error": "exceeded maximum tool call iterations (40)"})356 return sdk.PromptResponse{}, sdk.NewInternalError(map[string]any{"error": "exceeded maximum tool call iterations (40)"})
354 }357 }
355 358
359+// askForm plays mm acp-create: it asks a form and tells what came back and
360+// whether initialize advertised forms.
361+func (a *fakeAgent) askForm(ctx context.Context) string {
362+ advertised := a.client.ClientCapabilities.Elicitation != nil && a.client.ClientCapabilities.Elicitation.Form != nil
363+ req := sdk.NewUnstableCreateElicitationRequestForm(sdk.UnstableElicitationSchema{
364+ Type: sdk.UnstableElicitationSchemaTypeObject,
365+ Properties: map[string]any{
366+ "provider": map[string]any{"type": "string", "title": "Model server?", "enum": []any{"llmman", "ollama"}, "default": "llmman"},
367+ "yolo": map[string]any{"type": "boolean", "title": "Ask first?", "default": true},
368+ "name": map[string]any{"type": "string", "title": "Agent name?"},
369+ },
370+ Required: []string{"provider", "yolo", "name"},
371+ })
372+ req.Form.Message = "mm init — create an agent"
373+ resp, err := a.conn.UnstableCreateElicitation(ctx, req)
374+ switch {
375+ case err != nil:
376+ return fmt.Sprintf("advertised=%v error=%v", advertised, err)
377+ case resp.Accept != nil:
378+ content, _ := json.Marshal(resp.Accept.Content)
379+ return fmt.Sprintf("advertised=%v accept=%s", advertised, content)
380+ case resp.Decline != nil:
381+ return fmt.Sprintf("advertised=%v decline", advertised)
382+ default:
383+ return fmt.Sprintf("advertised=%v cancel", advertised)
384+ }
385+}
386+
356 // LoadSession resumes "s-1" and, as ACP requires, replays its history before387 // LoadSession resumes "s-1" and, as ACP requires, replays its history before
357 // answering; any other id is unknown.388 // answering; any other id is unknown.
358 func (a *fakeAgent) LoadSession(ctx context.Context, request sdk.LoadSessionRequest) (sdk.LoadSessionResponse, error) {389 func (a *fakeAgent) LoadSession(ctx context.Context, request sdk.LoadSessionRequest) (sdk.LoadSessionResponse, error) {
added internal/acp/forms.go +196 -0
new file mode 100644
@@ -0,0 +1,196 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+package acp
4+
5+import (
6+ "context"
7+ "fmt"
8+ "slices"
9+ "sort"
10+
11+ sdk "github.com/coder/acp-go-sdk"
12+)
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.
19+
20+// Field types of a Form, from the JSON Schema of the request.
21+const (
22+ FieldText = "text" // a string without choices
23+ FieldChoice = "choice" // a string among Options
24+ FieldMulti = "multi" // several strings among Options
25+ FieldBoolean = "boolean" // yes or no
26+ FieldNumber = "number" // a number, typed as text
27+)
28+
29+// The actions that end a form.
30+const (
31+ FormAccept = "accept"
32+ FormDecline = "decline"
33+ FormCancel = "cancel"
34+)
35+
36+// Form is what an agent asks the user to fill in.
37+type Form struct {
38+ // Message says what the form is for (Markdown or plain text).
39+ Message string `json:"message"`
40+ Fields []FormField `json:"fields"`
41+}
42+
43+// FormField is one question of a Form.
44+type FormField struct {
45+ // Name is the key of the answer in FormAnswer.Content.
46+ Name string `json:"name"`
47+ Title string `json:"title"`
48+ // Description is optional help shown under the title.
49+ Description string `json:"description"`
50+ // Type is one of the Field… constants.
51+ Type string `json:"type"`
52+ Options []string `json:"options"`
53+ // Default is a string, a boolean, a number or a list of strings
54+ // (FieldMulti), as the agent gave it; nil when there is none.
55+ Default any `json:"default"`
56+ Required bool `json:"required"`
57+}
58+
59+// FormAnswer is the user's answer: Action is accept, decline or cancel;
60+// Content holds the values by field name when the form is accepted.
61+type FormAnswer struct {
62+ Action string `json:"action"`
63+ Content map[string]any `json:"content"`
64+}
65+
66+// FormHandler answers a form. It may block until the user answers, and
67+// must return a cancel answer once ctx is done.
68+type FormHandler func(ctx context.Context, form Form) FormAnswer
69+
70+// formFrom reads the JSON Schema of a form request into a Form. Its fields
71+// come in the order of `required` (mm lists every field there, in order:
72+// a JSON object has no order of its own), then the others by name.
73+func formFrom(request sdk.UnstableCreateElicitationForm) Form {
74+ schema := request.RequestedSchema
75+ form := Form{Message: request.Message, Fields: []FormField{}}
76+ names := make([]string, 0, len(schema.Properties))
77+ for name := range schema.Properties {
78+ names = append(names, name)
79+ }
80+ sort.Strings(names)
81+ sort.SliceStable(names, func(i, j int) bool {
82+ return rank(schema.Required, names[i], len(names)) < rank(schema.Required, names[j], len(names))
83+ })
84+ for _, name := range names {
85+ property, _ := schema.Properties[name].(map[string]any)
86+ if property == nil {
87+ continue
88+ }
89+ form.Fields = append(form.Fields, fieldFrom(name, property, slices.Contains(schema.Required, name)))
90+ }
91+ return form
92+}
93+
94+// rank is the place of name in required, or after them all (then by name,
95+// as names was sorted before).
96+func rank(required []string, name string, others int) int {
97+ if index := slices.Index(required, name); index >= 0 {
98+ return index
99+ }
100+ return len(required) + others
101+}
102+
103+func fieldFrom(name string, property map[string]any, required bool) FormField {
104+ field := FormField{
105+ Name: name, Title: text(property["title"]), Description: text(property["description"]),
106+ Type: FieldText, Default: property["default"], Required: required,
107+ }
108+ if field.Title == "" {
109+ field.Title = name
110+ }
111+ switch text(property["type"]) {
112+ case "boolean":
113+ field.Type = FieldBoolean
114+ case "number", "integer":
115+ field.Type = FieldNumber
116+ case "array":
117+ field.Type = FieldMulti
118+ items, _ := property["items"].(map[string]any)
119+ field.Options = choices(items)
120+ default:
121+ if field.Options = choices(property); len(field.Options) > 0 {
122+ field.Type = FieldChoice
123+ }
124+ }
125+ return field
126+}
127+
128+// choices reads the values of an `enum`, or of a titled `oneOf`/`anyOf`
129+// (`const` of each), as the elicitation schema allows.
130+func choices(property map[string]any) []string {
131+ if property == nil {
132+ return nil
133+ }
134+ var values []string
135+ if list, ok := property["enum"].([]any); ok {
136+ for _, value := range list {
137+ values = append(values, fmt.Sprint(value))
138+ }
139+ return values
140+ }
141+ for _, key := range []string{"oneOf", "anyOf"} {
142+ list, _ := property[key].([]any)
143+ for _, item := range list {
144+ if option, ok := item.(map[string]any); ok && option["const"] != nil {
145+ values = append(values, fmt.Sprint(option["const"]))
146+ }
147+ }
148+ }
149+ return values
150+}
151+
152+func text(value any) string {
153+ if s, ok := value.(string); ok {
154+ return s
155+ }
156+ return ""
157+}
158+
159+// elicitationResponse turns the user's answer into the protocol's.
160+func elicitationResponse(answer FormAnswer) sdk.UnstableCreateElicitationResponse {
161+ switch answer.Action {
162+ case FormAccept:
163+ content := answer.Content
164+ if content == nil {
165+ content = map[string]any{}
166+ }
167+ return sdk.UnstableCreateElicitationResponse{Accept: &sdk.UnstableCreateElicitationAccept{Action: FormAccept, Content: content}}
168+ case FormDecline:
169+ return sdk.UnstableCreateElicitationResponse{Decline: &sdk.UnstableCreateElicitationDecline{Action: FormDecline}}
170+ }
171+ return sdk.UnstableCreateElicitationResponse{Cancel: &sdk.UnstableCreateElicitationCancel{Action: FormCancel}}
172+}
173+
174+// elicitationCapabilities is what initialize advertises: forms only, and
175+// only when someone answers them.
176+func elicitationCapabilities(onForm FormHandler) *sdk.ElicitationCapabilities {
177+ if onForm == nil {
178+ return nil
179+ }
180+ return &sdk.ElicitationCapabilities{Form: &sdk.ElicitationFormCapabilities{}}
181+}
182+
183+// UnstableCreateElicitation answers an agent's elicitation/create request
184+// (the SDK finds it by this name).
185+func (c *client) UnstableCreateElicitation(ctx context.Context, request sdk.UnstableCreateElicitationRequest) (sdk.UnstableCreateElicitationResponse, error) {
186+ if c.onForm == nil || request.Form == nil {
187+ return elicitationResponse(FormAnswer{Action: FormCancel}), nil
188+ }
189+ return elicitationResponse(c.onForm(ctx, formFrom(*request.Form))), nil
190+}
191+
192+// UnstableCompleteElicitation is the end of a "url" elicitation: nothing
193+// to do, Sidekicks never starts one.
194+func (*client) UnstableCompleteElicitation(context.Context, sdk.UnstableCompleteElicitationNotification) error {
195+ return nil
196+}
new file mode 100644
@@ -0,0 +1,196 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+package acp
4+
5+import (
6+ "context"
7+ "fmt"
8+ "slices"
9+ "sort"
10+
11+ sdk "github.com/coder/acp-go-sdk"
12+)
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.
19+
20+// Field types of a Form, from the JSON Schema of the request.
21+const (
22+ FieldText = "text" // a string without choices
23+ FieldChoice = "choice" // a string among Options
24+ FieldMulti = "multi" // several strings among Options
25+ FieldBoolean = "boolean" // yes or no
26+ FieldNumber = "number" // a number, typed as text
27+)
28+
29+// The actions that end a form.
30+const (
31+ FormAccept = "accept"
32+ FormDecline = "decline"
33+ FormCancel = "cancel"
34+)
35+
36+// Form is what an agent asks the user to fill in.
37+type Form struct {
38+ // Message says what the form is for (Markdown or plain text).
39+ Message string `json:"message"`
40+ Fields []FormField `json:"fields"`
41+}
42+
43+// FormField is one question of a Form.
44+type FormField struct {
45+ // Name is the key of the answer in FormAnswer.Content.
46+ Name string `json:"name"`
47+ Title string `json:"title"`
48+ // Description is optional help shown under the title.
49+ Description string `json:"description"`
50+ // Type is one of the Field… constants.
51+ Type string `json:"type"`
52+ Options []string `json:"options"`
53+ // Default is a string, a boolean, a number or a list of strings
54+ // (FieldMulti), as the agent gave it; nil when there is none.
55+ Default any `json:"default"`
56+ Required bool `json:"required"`
57+}
58+
59+// FormAnswer is the user's answer: Action is accept, decline or cancel;
60+// Content holds the values by field name when the form is accepted.
61+type FormAnswer struct {
62+ Action string `json:"action"`
63+ Content map[string]any `json:"content"`
64+}
65+
66+// FormHandler answers a form. It may block until the user answers, and
67+// must return a cancel answer once ctx is done.
68+type FormHandler func(ctx context.Context, form Form) FormAnswer
69+
70+// formFrom reads the JSON Schema of a form request into a Form. Its fields
71+// come in the order of `required` (mm lists every field there, in order:
72+// a JSON object has no order of its own), then the others by name.
73+func formFrom(request sdk.UnstableCreateElicitationForm) Form {
74+ schema := request.RequestedSchema
75+ form := Form{Message: request.Message, Fields: []FormField{}}
76+ names := make([]string, 0, len(schema.Properties))
77+ for name := range schema.Properties {
78+ names = append(names, name)
79+ }
80+ sort.Strings(names)
81+ sort.SliceStable(names, func(i, j int) bool {
82+ return rank(schema.Required, names[i], len(names)) < rank(schema.Required, names[j], len(names))
83+ })
84+ for _, name := range names {
85+ property, _ := schema.Properties[name].(map[string]any)
86+ if property == nil {
87+ continue
88+ }
89+ form.Fields = append(form.Fields, fieldFrom(name, property, slices.Contains(schema.Required, name)))
90+ }
91+ return form
92+}
93+
94+// rank is the place of name in required, or after them all (then by name,
95+// as names was sorted before).
96+func rank(required []string, name string, others int) int {
97+ if index := slices.Index(required, name); index >= 0 {
98+ return index
99+ }
100+ return len(required) + others
101+}
102+
103+func fieldFrom(name string, property map[string]any, required bool) FormField {
104+ field := FormField{
105+ Name: name, Title: text(property["title"]), Description: text(property["description"]),
106+ Type: FieldText, Default: property["default"], Required: required,
107+ }
108+ if field.Title == "" {
109+ field.Title = name
110+ }
111+ switch text(property["type"]) {
112+ case "boolean":
113+ field.Type = FieldBoolean
114+ case "number", "integer":
115+ field.Type = FieldNumber
116+ case "array":
117+ field.Type = FieldMulti
118+ items, _ := property["items"].(map[string]any)
119+ field.Options = choices(items)
120+ default:
121+ if field.Options = choices(property); len(field.Options) > 0 {
122+ field.Type = FieldChoice
123+ }
124+ }
125+ return field
126+}
127+
128+// choices reads the values of an `enum`, or of a titled `oneOf`/`anyOf`
129+// (`const` of each), as the elicitation schema allows.
130+func choices(property map[string]any) []string {
131+ if property == nil {
132+ return nil
133+ }
134+ var values []string
135+ if list, ok := property["enum"].([]any); ok {
136+ for _, value := range list {
137+ values = append(values, fmt.Sprint(value))
138+ }
139+ return values
140+ }
141+ for _, key := range []string{"oneOf", "anyOf"} {
142+ list, _ := property[key].([]any)
143+ for _, item := range list {
144+ if option, ok := item.(map[string]any); ok && option["const"] != nil {
145+ values = append(values, fmt.Sprint(option["const"]))
146+ }
147+ }
148+ }
149+ return values
150+}
151+
152+func text(value any) string {
153+ if s, ok := value.(string); ok {
154+ return s
155+ }
156+ return ""
157+}
158+
159+// elicitationResponse turns the user's answer into the protocol's.
160+func elicitationResponse(answer FormAnswer) sdk.UnstableCreateElicitationResponse {
161+ switch answer.Action {
162+ case FormAccept:
163+ content := answer.Content
164+ if content == nil {
165+ content = map[string]any{}
166+ }
167+ return sdk.UnstableCreateElicitationResponse{Accept: &sdk.UnstableCreateElicitationAccept{Action: FormAccept, Content: content}}
168+ case FormDecline:
169+ return sdk.UnstableCreateElicitationResponse{Decline: &sdk.UnstableCreateElicitationDecline{Action: FormDecline}}
170+ }
171+ return sdk.UnstableCreateElicitationResponse{Cancel: &sdk.UnstableCreateElicitationCancel{Action: FormCancel}}
172+}
173+
174+// elicitationCapabilities is what initialize advertises: forms only, and
175+// only when someone answers them.
176+func elicitationCapabilities(onForm FormHandler) *sdk.ElicitationCapabilities {
177+ if onForm == nil {
178+ return nil
179+ }
180+ return &sdk.ElicitationCapabilities{Form: &sdk.ElicitationFormCapabilities{}}
181+}
182+
183+// UnstableCreateElicitation answers an agent's elicitation/create request
184+// (the SDK finds it by this name).
185+func (c *client) UnstableCreateElicitation(ctx context.Context, request sdk.UnstableCreateElicitationRequest) (sdk.UnstableCreateElicitationResponse, error) {
186+ if c.onForm == nil || request.Form == nil {
187+ return elicitationResponse(FormAnswer{Action: FormCancel}), nil
188+ }
189+ return elicitationResponse(c.onForm(ctx, formFrom(*request.Form))), nil
190+}
191+
192+// UnstableCompleteElicitation is the end of a "url" elicitation: nothing
193+// to do, Sidekicks never starts one.
194+func (*client) UnstableCompleteElicitation(context.Context, sdk.UnstableCompleteElicitationNotification) error {
195+ return nil
196+}
added internal/acp/forms_test.go +82 -0
new file mode 100644
@@ -0,0 +1,82 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+package acp_test
4+
5+import (
6+ "context"
7+ "reflect"
8+ "strings"
9+ "testing"
10+
11+ "git.rickub.com/bots-garden/sidekicks/internal/acp"
12+)
13+
14+// formSession opens a session on the fake agent with onForm answering its forms.
15+func formSession(t *testing.T, onForm acp.FormHandler) (*acp.Conn, string, *recordingHandler) {
16+ t.Helper()
17+ spec := fakeSpec(t, "ready")
18+ spec.OnForm = onForm
19+ conn, err := acp.Start(context.Background(), spec, acp.Options{})
20+ if err != nil {
21+ t.Fatal(err)
22+ }
23+ t.Cleanup(func() { _ = conn.Close(context.Background()) })
24+ handler := &recordingHandler{}
25+ id, err := conn.NewSession(context.Background(), t.TempDir(), handler)
26+ if err != nil {
27+ t.Fatal(err)
28+ }
29+ return conn, id, handler
30+}
31+
32+func answerText(t *testing.T, conn *acp.Conn, id string, handler *recordingHandler) string {
33+ t.Helper()
34+ if _, err := conn.Prompt(context.Background(), id, "form"); err != nil {
35+ t.Fatal(err)
36+ }
37+ var text strings.Builder
38+ for _, update := range handler.ofKind(acp.UpdateMessage) {
39+ text.WriteString(update.Text)
40+ }
41+ return text.String()
42+}
43+
44+func TestAFormIsReadInOrderAndAnswered(t *testing.T) {
45+ var got acp.Form
46+ conn, id, handler := formSession(t, func(_ context.Context, form acp.Form) acp.FormAnswer {
47+ got = form
48+ return acp.FormAnswer{Action: acp.FormAccept, Content: map[string]any{"provider": "ollama", "yolo": false, "name": "bob"}}
49+ })
50+ text := answerText(t, conn, id, handler)
51+ if text != `advertised=true accept={"name":"bob","provider":"ollama","yolo":false}` {
52+ t.Fatalf("answer: %s", text)
53+ }
54+ if got.Message != "mm init — create an agent" {
55+ t.Fatalf("message: %q", got.Message)
56+ }
57+ want := []acp.FormField{
58+ {Name: "provider", Title: "Model server?", Type: acp.FieldChoice, Options: []string{"llmman", "ollama"}, Default: "llmman", Required: true},
59+ {Name: "yolo", Title: "Ask first?", Type: acp.FieldBoolean, Default: true, Required: true},
60+ {Name: "name", Title: "Agent name?", Type: acp.FieldText, Required: true},
61+ }
62+ if !reflect.DeepEqual(got.Fields, want) {
63+ t.Fatalf("fields:\n got %+v\nwant %+v", got.Fields, want)
64+ }
65+}
66+
67+func TestADeclinedFormIsDeclined(t *testing.T) {
68+ conn, id, handler := formSession(t, func(context.Context, acp.Form) acp.FormAnswer {
69+ return acp.FormAnswer{Action: acp.FormDecline}
70+ })
71+ if text := answerText(t, conn, id, handler); text != "advertised=true decline" {
72+ t.Fatalf("answer: %s", text)
73+ }
74+}
75+
76+func TestWithoutOnFormNoFormIsAdvertisedAndFormsAreCancelled(t *testing.T) {
77+ handler := &recordingHandler{}
78+ conn, id := openSession(t, handler)
79+ if text := answerText(t, conn, id, handler); text != "advertised=false cancel" {
80+ t.Fatalf("answer: %s", text)
81+ }
82+}
new file mode 100644
@@ -0,0 +1,82 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+package acp_test
4+
5+import (
6+ "context"
7+ "reflect"
8+ "strings"
9+ "testing"
10+
11+ "git.rickub.com/bots-garden/sidekicks/internal/acp"
12+)
13+
14+// formSession opens a session on the fake agent with onForm answering its forms.
15+func formSession(t *testing.T, onForm acp.FormHandler) (*acp.Conn, string, *recordingHandler) {
16+ t.Helper()
17+ spec := fakeSpec(t, "ready")
18+ spec.OnForm = onForm
19+ conn, err := acp.Start(context.Background(), spec, acp.Options{})
20+ if err != nil {
21+ t.Fatal(err)
22+ }
23+ t.Cleanup(func() { _ = conn.Close(context.Background()) })
24+ handler := &recordingHandler{}
25+ id, err := conn.NewSession(context.Background(), t.TempDir(), handler)
26+ if err != nil {
27+ t.Fatal(err)
28+ }
29+ return conn, id, handler
30+}
31+
32+func answerText(t *testing.T, conn *acp.Conn, id string, handler *recordingHandler) string {
33+ t.Helper()
34+ if _, err := conn.Prompt(context.Background(), id, "form"); err != nil {
35+ t.Fatal(err)
36+ }
37+ var text strings.Builder
38+ for _, update := range handler.ofKind(acp.UpdateMessage) {
39+ text.WriteString(update.Text)
40+ }
41+ return text.String()
42+}
43+
44+func TestAFormIsReadInOrderAndAnswered(t *testing.T) {
45+ var got acp.Form
46+ conn, id, handler := formSession(t, func(_ context.Context, form acp.Form) acp.FormAnswer {
47+ got = form
48+ return acp.FormAnswer{Action: acp.FormAccept, Content: map[string]any{"provider": "ollama", "yolo": false, "name": "bob"}}
49+ })
50+ text := answerText(t, conn, id, handler)
51+ if text != `advertised=true accept={"name":"bob","provider":"ollama","yolo":false}` {
52+ t.Fatalf("answer: %s", text)
53+ }
54+ if got.Message != "mm init — create an agent" {
55+ t.Fatalf("message: %q", got.Message)
56+ }
57+ want := []acp.FormField{
58+ {Name: "provider", Title: "Model server?", Type: acp.FieldChoice, Options: []string{"llmman", "ollama"}, Default: "llmman", Required: true},
59+ {Name: "yolo", Title: "Ask first?", Type: acp.FieldBoolean, Default: true, Required: true},
60+ {Name: "name", Title: "Agent name?", Type: acp.FieldText, Required: true},
61+ }
62+ if !reflect.DeepEqual(got.Fields, want) {
63+ t.Fatalf("fields:\n got %+v\nwant %+v", got.Fields, want)
64+ }
65+}
66+
67+func TestADeclinedFormIsDeclined(t *testing.T) {
68+ conn, id, handler := formSession(t, func(context.Context, acp.Form) acp.FormAnswer {
69+ return acp.FormAnswer{Action: acp.FormDecline}
70+ })
71+ if text := answerText(t, conn, id, handler); text != "advertised=true decline" {
72+ t.Fatalf("answer: %s", text)
73+ }
74+}
75+
76+func TestWithoutOnFormNoFormIsAdvertisedAndFormsAreCancelled(t *testing.T) {
77+ handler := &recordingHandler{}
78+ conn, id := openSession(t, handler)
79+ if text := answerText(t, conn, id, handler); text != "advertised=false cancel" {
80+ t.Fatalf("answer: %s", text)
81+ }
82+}
modified internal/app/app.go +9 -1
@@ -61,6 +61,11 @@ type Options struct {
6161 // OpenStore opens the history of the configuration file at path; nil
6262 // opens it in the user's configuration folder (store.DirFor).
6363 OpenStore func(configPath string) (*store.Store, error)
64+ // MiniMe is mm's program for the assistant that creates mini-me agents
65+ // (issue #94); "" looks mm up in PATH. MiniMeEnv is added to its
66+ // environment. Tests pass a fake.
67+ MiniMe string
68+ MiniMeEnv map[string]string
6469 }
6570
6671 // Core holds the loaded configuration, the agent manager, and the channels
@@ -84,6 +89,8 @@ type Core struct {
8489 historyProblem string
8590 runCtx context.Context
8691 stopWait context.CancelFunc
92+ // creator is the mini-me creation assistant's wizard (issue #94).
93+ creator *creation
8794 }
8895
8996 // New loads the configuration at location — creating the default file first
@@ -283,9 +290,10 @@ func (c *Core) Open(ctx context.Context, path string) error {
283290 return nil
284291 }
285292
286-// Shutdown cancels the answers, closes the terminals, stops every agent and
293+// Shutdown closes the creation assistant, cancels the answers, closes the terminals, stops every agent and
287294 // closes the history.
288295 func (c *Core) Shutdown(ctx context.Context) {
296+ (&CreatorService{Core: c}).Cancel()
289297 c.closeChannels()
290298 c.stopWorkspaces()
291299 c.manager.StopAll(ctx)
@@ -61,6 +61,11 @@ type Options struct {
61 // OpenStore opens the history of the configuration file at path; nil61 // OpenStore opens the history of the configuration file at path; nil
62 // opens it in the user's configuration folder (store.DirFor).62 // opens it in the user's configuration folder (store.DirFor).
63 OpenStore func(configPath string) (*store.Store, error)63 OpenStore func(configPath string) (*store.Store, error)
64+ // MiniMe is mm's program for the assistant that creates mini-me agents
65+ // (issue #94); "" looks mm up in PATH. MiniMeEnv is added to its
66+ // environment. Tests pass a fake.
67+ MiniMe string
68+ MiniMeEnv map[string]string
64 }69 }
65 70
66 // Core holds the loaded configuration, the agent manager, and the channels71 // Core holds the loaded configuration, the agent manager, and the channels
@@ -84,6 +89,8 @@ type Core struct {
84 historyProblem string89 historyProblem string
85 runCtx context.Context90 runCtx context.Context
86 stopWait context.CancelFunc91 stopWait context.CancelFunc
92+ // creator is the mini-me creation assistant's wizard (issue #94).
93+ creator *creation
87 }94 }
88 95
89 // New loads the configuration at location — creating the default file first96 // New loads the configuration at location — creating the default file first
@@ -283,9 +290,10 @@ func (c *Core) Open(ctx context.Context, path string) error {
283 return nil290 return nil
284 }291 }
285 292
286-// Shutdown cancels the answers, closes the terminals, stops every agent and293+// Shutdown closes the creation assistant, cancels the answers, closes the terminals, stops every agent and
287 // closes the history.294 // closes the history.
288 func (c *Core) Shutdown(ctx context.Context) {295 func (c *Core) Shutdown(ctx context.Context) {
296+ (&CreatorService{Core: c}).Cancel()
289 c.closeChannels()297 c.closeChannels()
290 c.stopWorkspaces()298 c.stopWorkspaces()
291 c.manager.StopAll(ctx)299 c.manager.StopAll(ctx)
modified internal/app/app_test.go +2 -0
@@ -15,6 +15,7 @@ import (
1515 "git.rickub.com/bots-garden/sidekicks/internal/app"
1616 "git.rickub.com/bots-garden/sidekicks/internal/channels"
1717 "git.rickub.com/bots-garden/sidekicks/internal/config"
18+ "git.rickub.com/bots-garden/sidekicks/internal/creator/creatortest"
1819 "git.rickub.com/bots-garden/sidekicks/internal/events"
1920 "git.rickub.com/bots-garden/sidekicks/internal/prefs"
2021 "git.rickub.com/bots-garden/sidekicks/internal/workspace"
@@ -23,6 +24,7 @@ import (
2324 // TestMain points the user's configuration folder, where the history is
2425 // kept, to a temporary folder: tests never touch the real one.
2526 func TestMain(m *testing.M) {
27+ creatortest.RunIfFake()
2628 home, err := os.MkdirTemp("", "sidekicks-app-test")
2729 if err != nil {
2830 panic(err)
@@ -15,6 +15,7 @@ import (
15 "git.rickub.com/bots-garden/sidekicks/internal/app"15 "git.rickub.com/bots-garden/sidekicks/internal/app"
16 "git.rickub.com/bots-garden/sidekicks/internal/channels"16 "git.rickub.com/bots-garden/sidekicks/internal/channels"
17 "git.rickub.com/bots-garden/sidekicks/internal/config"17 "git.rickub.com/bots-garden/sidekicks/internal/config"
18+ "git.rickub.com/bots-garden/sidekicks/internal/creator/creatortest"
18 "git.rickub.com/bots-garden/sidekicks/internal/events"19 "git.rickub.com/bots-garden/sidekicks/internal/events"
19 "git.rickub.com/bots-garden/sidekicks/internal/prefs"20 "git.rickub.com/bots-garden/sidekicks/internal/prefs"
20 "git.rickub.com/bots-garden/sidekicks/internal/workspace"21 "git.rickub.com/bots-garden/sidekicks/internal/workspace"
@@ -23,6 +24,7 @@ import (
23 // TestMain points the user's configuration folder, where the history is24 // TestMain points the user's configuration folder, where the history is
24 // kept, to a temporary folder: tests never touch the real one.25 // kept, to a temporary folder: tests never touch the real one.
25 func TestMain(m *testing.M) {26 func TestMain(m *testing.M) {
27+ creatortest.RunIfFake()
26 home, err := os.MkdirTemp("", "sidekicks-app-test")28 home, err := os.MkdirTemp("", "sidekicks-app-test")
27 if err != nil {29 if err != nil {
28 panic(err)30 panic(err)
added internal/app/creator.go +233 -0
new file mode 100644
@@ -0,0 +1,233 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+package app
4+
5+import (
6+ "context"
7+ "errors"
8+ "fmt"
9+ "path/filepath"
10+ "sync"
11+
12+ "git.rickub.com/bots-garden/sidekicks/internal/acp"
13+ "git.rickub.com/bots-garden/sidekicks/internal/creator"
14+ "git.rickub.com/bots-garden/sidekicks/internal/lifecycle"
15+)
16+
17+// CreatorService is the assistant that creates a mini-me agent for people
18+// who do not write files (issue #94): Sidekicks drives mm's wizard
19+// (mm --acp-create) and shows its questions as forms, then adds the agent
20+// to the configuration. One wizard at a time.
21+//
22+// view, err := service.Start(ctx) // the first form
23+// view, err = service.Answer(ctx, answer) // … until view.Written
24+// result, err := service.Finish(ctx, CreatorFinish{Name: view.Name, Icon: "🤖", Environment: "local"})
25+type CreatorService struct {
26+ Core *Core
27+}
28+
29+// Problems Finish reports instead of an error, for the user to fix: the
30+// interface explains each one.
31+const (
32+ CreatorNameTaken = "nameTaken" // an agent already has this name
33+ CreatorFolderExists = "folderExists" // the agents' folder already has one with this name
34+ CreatorInvalidName = "invalidName" // not a name Sidekicks accepts
35+)
36+
37+// CreatorStart is what Start returns: the wizard's first step, and where
38+// the agent's folder will be.
39+type CreatorStart struct {
40+ View creator.View `json:"view"`
41+ // AgentsFolder is the folder that receives the agent's folder.
42+ AgentsFolder string `json:"agentsFolder"`
43+ // Version is what mm --version said.
44+ Version string `json:"version"`
45+}
46+
47+// CreatorFinish is the last step: the agent's name (its folder's too), its
48+// emoji, and where it runs: local, container or sbx.
49+type CreatorFinish struct {
50+ Name string `json:"name"`
51+ Icon string `json:"icon"`
52+ Environment string `json:"environment"`
53+}
54+
55+// CreatorResult is how Finish ended: Problem (one of the Creator…
56+// constants) or Problems (from the configuration) when the agent was not
57+// added, else the agent's name and folder.
58+type CreatorResult struct {
59+ Problem string `json:"problem"`
60+ Problems []string `json:"problems"`
61+ Name string `json:"name"`
62+ Folder string `json:"folder"`
63+ // Messages are what mm said while writing the container's or the
64+ // sandbox's files.
65+ Messages []string `json:"messages"`
66+}
67+
68+// creation holds the wizard in progress.
69+type creation struct {
70+ mu sync.Mutex
71+ session *creator.Session
72+}
73+
74+func (c *Core) creation() *creation {
75+ c.mu.Lock()
76+ defer c.mu.Unlock()
77+ if c.creator == nil {
78+ c.creator = &creation{}
79+ }
80+ return c.creator
81+}
82+
83+func (c *Core) agentsFolder() string {
84+ c.mu.Lock()
85+ defer c.mu.Unlock()
86+ return c.cfg.AgentsFolder
87+}
88+
89+func (c *Core) creatorOptions() creator.Options {
90+ return creator.Options{Command: c.options.MiniMe, AgentsFolder: c.agentsFolder(), Env: c.options.MiniMeEnv}
91+}
92+
93+// Start checks that mm 1.0.9 or later is installed, then starts its wizard
94+// and returns its first step. A wizard already open is closed first, and
95+// what it wrote is removed.
96+func (s *CreatorService) Start(ctx context.Context) (CreatorStart, error) {
97+ options := s.Core.creatorOptions()
98+ version, err := creator.Version(ctx, options)
99+ if err != nil {
100+ return CreatorStart{}, err
101+ }
102+ creation := s.Core.creation()
103+ creation.mu.Lock()
104+ defer creation.mu.Unlock()
105+ if creation.session != nil {
106+ creation.session.Close()
107+ creation.session = nil
108+ }
109+ session, err := creator.Start(ctx, options)
110+ if err != nil {
111+ return CreatorStart{}, err
112+ }
113+ creation.session = session
114+ view, err := session.Begin(ctx)
115+ return CreatorStart{View: view, AgentsFolder: options.AgentsFolder, Version: version}, err
116+}
117+
118+// session is the wizard in progress, or ErrClosed.
119+func (s *CreatorService) session() (*creator.Session, error) {
120+ creation := s.Core.creation()
121+ creation.mu.Lock()
122+ defer creation.mu.Unlock()
123+ if creation.session == nil {
124+ return nil, creator.ErrClosed
125+ }
126+ return creation.session, nil
127+}
128+
129+// Answer answers the form shown (action accept, decline or cancel) and
130+// returns the next step.
131+func (s *CreatorService) Answer(ctx context.Context, answer acp.FormAnswer) (creator.View, error) {
132+ session, err := s.session()
133+ if err != nil {
134+ return creator.View{}, err
135+ }
136+ return session.Answer(ctx, answer)
137+}
138+
139+// Send sends a message to the wizard, such as /back or /restart, and
140+// returns the next step.
141+func (s *CreatorService) Send(ctx context.Context, text string) (creator.View, error) {
142+ session, err := s.session()
143+ if err != nil {
144+ return creator.View{}, err
145+ }
146+ return session.Send(ctx, text)
147+}
148+
149+// Finish gives the agent its folder, named after it in the agents' folder,
150+// writes the files of its container or sandbox, and adds it to the
151+// configuration. A name already used, by an agent or by a folder, is a
152+// Problem: nothing is changed and another name can be tried.
153+func (s *CreatorService) Finish(ctx context.Context, form CreatorFinish) (CreatorResult, error) {
154+ session, err := s.session()
155+ if err != nil {
156+ return CreatorResult{}, err
157+ }
158+ if !creator.ValidName(form.Name) {
159+ return CreatorResult{Problem: CreatorInvalidName}, nil
160+ }
161+ if s.Core.hasAgent(form.Name) {
162+ return CreatorResult{Problem: CreatorNameTaken}, nil
163+ }
164+ result, err := session.Finish(ctx, form.Name, form.Environment)
165+ if errors.Is(err, creator.ErrFolderExists) {
166+ return CreatorResult{Problem: CreatorFolderExists}, nil
167+ }
168+ if err != nil {
169+ return CreatorResult{Messages: result.Messages}, err
170+ }
171+ agent, err := agentFormOf(form, result)
172+ if err != nil {
173+ return CreatorResult{Messages: result.Messages}, err
174+ }
175+ problems, err := (&ConfigService{Core: s.Core}).AddAgent(agent)
176+ if err != nil || len(problems) > 0 {
177+ return CreatorResult{Problems: problems, Messages: result.Messages}, err
178+ }
179+ s.Cancel()
180+ return CreatorResult{Problems: []string{}, Name: form.Name, Folder: result.Folder, Messages: result.Messages}, nil
181+}
182+
183+// Cancel closes the wizard. Before Finish, what it wrote is removed.
184+func (s *CreatorService) Cancel() {
185+ creation := s.Core.creation()
186+ creation.mu.Lock()
187+ defer creation.mu.Unlock()
188+ if creation.session != nil {
189+ creation.session.Close()
190+ creation.session = nil
191+ }
192+}
193+
194+func (c *Core) hasAgent(name string) bool {
195+ c.mu.Lock()
196+ defer c.mu.Unlock()
197+ _, ok := c.cfg.Agent(name)
198+ return ok
199+}
200+
201+// agentFormOf is the configuration entry of a created agent: mm started
202+// with its .mm/agent.yaml, on this computer, with docker exec in the
203+// container of its compose.yaml, or with sbx exec in the sandbox of its
204+// sbxenv.yaml. Both mount the agent's folder at the same path, so the
205+// agent file's path is the same inside.
206+func agentFormOf(form CreatorFinish, result creator.Result) (AgentForm, error) {
207+ agent := AgentForm{
208+ Name: form.Name, Title: result.Title, Icon: form.Icon, Environment: result.Environment,
209+ Program: "mm", Arguments: joinArguments([]string{"--acp", "--config", result.AgentFile}), Workspace: result.Folder,
210+ }
211+ switch result.Environment {
212+ case creator.Container:
213+ compose, err := lifecycle.ReadCompose(filepath.Join(result.Folder, "compose.yaml"))
214+ if err != nil {
215+ return AgentForm{}, err
216+ }
217+ if len(compose.Services) == 0 {
218+ return AgentForm{}, fmt.Errorf("no service in %s", filepath.Join(result.Folder, "compose.yaml"))
219+ }
220+ service := compose.Services[0]
221+ create, stop, remove := compose.Commands(service.Name)
222+ agent.Box, agent.SandboxFolder = service.Container, compose.Folder
223+ agent.CreateCommand, agent.StopCommand, agent.RemoveCommand = joinArguments(create), joinArguments(stop), joinArguments(remove)
224+ case creator.Sandbox:
225+ env, err := lifecycle.ReadSbxEnv(filepath.Join(result.Folder, "sbxenv.yaml"))
226+ if err != nil {
227+ return AgentForm{}, err
228+ }
229+ agent.Box, agent.SandboxFolder = env.Name, env.Folder
230+ agent.CreateCommand, agent.StopCommand, agent.RemoveCommand = joinArguments(env.Create), joinArguments(env.Stop), joinArguments(env.Remove)
231+ }
232+ return agent, nil
233+}
new file mode 100644
@@ -0,0 +1,233 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+package app
4+
5+import (
6+ "context"
7+ "errors"
8+ "fmt"
9+ "path/filepath"
10+ "sync"
11+
12+ "git.rickub.com/bots-garden/sidekicks/internal/acp"
13+ "git.rickub.com/bots-garden/sidekicks/internal/creator"
14+ "git.rickub.com/bots-garden/sidekicks/internal/lifecycle"
15+)
16+
17+// CreatorService is the assistant that creates a mini-me agent for people
18+// who do not write files (issue #94): Sidekicks drives mm's wizard
19+// (mm --acp-create) and shows its questions as forms, then adds the agent
20+// to the configuration. One wizard at a time.
21+//
22+// view, err := service.Start(ctx) // the first form
23+// view, err = service.Answer(ctx, answer) // … until view.Written
24+// result, err := service.Finish(ctx, CreatorFinish{Name: view.Name, Icon: "🤖", Environment: "local"})
25+type CreatorService struct {
26+ Core *Core
27+}
28+
29+// Problems Finish reports instead of an error, for the user to fix: the
30+// interface explains each one.
31+const (
32+ CreatorNameTaken = "nameTaken" // an agent already has this name
33+ CreatorFolderExists = "folderExists" // the agents' folder already has one with this name
34+ CreatorInvalidName = "invalidName" // not a name Sidekicks accepts
35+)
36+
37+// CreatorStart is what Start returns: the wizard's first step, and where
38+// the agent's folder will be.
39+type CreatorStart struct {
40+ View creator.View `json:"view"`
41+ // AgentsFolder is the folder that receives the agent's folder.
42+ AgentsFolder string `json:"agentsFolder"`
43+ // Version is what mm --version said.
44+ Version string `json:"version"`
45+}
46+
47+// CreatorFinish is the last step: the agent's name (its folder's too), its
48+// emoji, and where it runs: local, container or sbx.
49+type CreatorFinish struct {
50+ Name string `json:"name"`
51+ Icon string `json:"icon"`
52+ Environment string `json:"environment"`
53+}
54+
55+// CreatorResult is how Finish ended: Problem (one of the Creator…
56+// constants) or Problems (from the configuration) when the agent was not
57+// added, else the agent's name and folder.
58+type CreatorResult struct {
59+ Problem string `json:"problem"`
60+ Problems []string `json:"problems"`
61+ Name string `json:"name"`
62+ Folder string `json:"folder"`
63+ // Messages are what mm said while writing the container's or the
64+ // sandbox's files.
65+ Messages []string `json:"messages"`
66+}
67+
68+// creation holds the wizard in progress.
69+type creation struct {
70+ mu sync.Mutex
71+ session *creator.Session
72+}
73+
74+func (c *Core) creation() *creation {
75+ c.mu.Lock()
76+ defer c.mu.Unlock()
77+ if c.creator == nil {
78+ c.creator = &creation{}
79+ }
80+ return c.creator
81+}
82+
83+func (c *Core) agentsFolder() string {
84+ c.mu.Lock()
85+ defer c.mu.Unlock()
86+ return c.cfg.AgentsFolder
87+}
88+
89+func (c *Core) creatorOptions() creator.Options {
90+ return creator.Options{Command: c.options.MiniMe, AgentsFolder: c.agentsFolder(), Env: c.options.MiniMeEnv}
91+}
92+
93+// Start checks that mm 1.0.9 or later is installed, then starts its wizard
94+// and returns its first step. A wizard already open is closed first, and
95+// what it wrote is removed.
96+func (s *CreatorService) Start(ctx context.Context) (CreatorStart, error) {
97+ options := s.Core.creatorOptions()
98+ version, err := creator.Version(ctx, options)
99+ if err != nil {
100+ return CreatorStart{}, err
101+ }
102+ creation := s.Core.creation()
103+ creation.mu.Lock()
104+ defer creation.mu.Unlock()
105+ if creation.session != nil {
106+ creation.session.Close()
107+ creation.session = nil
108+ }
109+ session, err := creator.Start(ctx, options)
110+ if err != nil {
111+ return CreatorStart{}, err
112+ }
113+ creation.session = session
114+ view, err := session.Begin(ctx)
115+ return CreatorStart{View: view, AgentsFolder: options.AgentsFolder, Version: version}, err
116+}
117+
118+// session is the wizard in progress, or ErrClosed.
119+func (s *CreatorService) session() (*creator.Session, error) {
120+ creation := s.Core.creation()
121+ creation.mu.Lock()
122+ defer creation.mu.Unlock()
123+ if creation.session == nil {
124+ return nil, creator.ErrClosed
125+ }
126+ return creation.session, nil
127+}
128+
129+// Answer answers the form shown (action accept, decline or cancel) and
130+// returns the next step.
131+func (s *CreatorService) Answer(ctx context.Context, answer acp.FormAnswer) (creator.View, error) {
132+ session, err := s.session()
133+ if err != nil {
134+ return creator.View{}, err
135+ }
136+ return session.Answer(ctx, answer)
137+}
138+
139+// Send sends a message to the wizard, such as /back or /restart, and
140+// returns the next step.
141+func (s *CreatorService) Send(ctx context.Context, text string) (creator.View, error) {
142+ session, err := s.session()
143+ if err != nil {
144+ return creator.View{}, err
145+ }
146+ return session.Send(ctx, text)
147+}
148+
149+// Finish gives the agent its folder, named after it in the agents' folder,
150+// writes the files of its container or sandbox, and adds it to the
151+// configuration. A name already used, by an agent or by a folder, is a
152+// Problem: nothing is changed and another name can be tried.
153+func (s *CreatorService) Finish(ctx context.Context, form CreatorFinish) (CreatorResult, error) {
154+ session, err := s.session()
155+ if err != nil {
156+ return CreatorResult{}, err
157+ }
158+ if !creator.ValidName(form.Name) {
159+ return CreatorResult{Problem: CreatorInvalidName}, nil
160+ }
161+ if s.Core.hasAgent(form.Name) {
162+ return CreatorResult{Problem: CreatorNameTaken}, nil
163+ }
164+ result, err := session.Finish(ctx, form.Name, form.Environment)
165+ if errors.Is(err, creator.ErrFolderExists) {
166+ return CreatorResult{Problem: CreatorFolderExists}, nil
167+ }
168+ if err != nil {
169+ return CreatorResult{Messages: result.Messages}, err
170+ }
171+ agent, err := agentFormOf(form, result)
172+ if err != nil {
173+ return CreatorResult{Messages: result.Messages}, err
174+ }
175+ problems, err := (&ConfigService{Core: s.Core}).AddAgent(agent)
176+ if err != nil || len(problems) > 0 {
177+ return CreatorResult{Problems: problems, Messages: result.Messages}, err
178+ }
179+ s.Cancel()
180+ return CreatorResult{Problems: []string{}, Name: form.Name, Folder: result.Folder, Messages: result.Messages}, nil
181+}
182+
183+// Cancel closes the wizard. Before Finish, what it wrote is removed.
184+func (s *CreatorService) Cancel() {
185+ creation := s.Core.creation()
186+ creation.mu.Lock()
187+ defer creation.mu.Unlock()
188+ if creation.session != nil {
189+ creation.session.Close()
190+ creation.session = nil
191+ }
192+}
193+
194+func (c *Core) hasAgent(name string) bool {
195+ c.mu.Lock()
196+ defer c.mu.Unlock()
197+ _, ok := c.cfg.Agent(name)
198+ return ok
199+}
200+
201+// agentFormOf is the configuration entry of a created agent: mm started
202+// with its .mm/agent.yaml, on this computer, with docker exec in the
203+// container of its compose.yaml, or with sbx exec in the sandbox of its
204+// sbxenv.yaml. Both mount the agent's folder at the same path, so the
205+// agent file's path is the same inside.
206+func agentFormOf(form CreatorFinish, result creator.Result) (AgentForm, error) {
207+ agent := AgentForm{
208+ Name: form.Name, Title: result.Title, Icon: form.Icon, Environment: result.Environment,
209+ Program: "mm", Arguments: joinArguments([]string{"--acp", "--config", result.AgentFile}), Workspace: result.Folder,
210+ }
211+ switch result.Environment {
212+ case creator.Container:
213+ compose, err := lifecycle.ReadCompose(filepath.Join(result.Folder, "compose.yaml"))
214+ if err != nil {
215+ return AgentForm{}, err
216+ }
217+ if len(compose.Services) == 0 {
218+ return AgentForm{}, fmt.Errorf("no service in %s", filepath.Join(result.Folder, "compose.yaml"))
219+ }
220+ service := compose.Services[0]
221+ create, stop, remove := compose.Commands(service.Name)
222+ agent.Box, agent.SandboxFolder = service.Container, compose.Folder
223+ agent.CreateCommand, agent.StopCommand, agent.RemoveCommand = joinArguments(create), joinArguments(stop), joinArguments(remove)
224+ case creator.Sandbox:
225+ env, err := lifecycle.ReadSbxEnv(filepath.Join(result.Folder, "sbxenv.yaml"))
226+ if err != nil {
227+ return AgentForm{}, err
228+ }
229+ agent.Box, agent.SandboxFolder = env.Name, env.Folder
230+ agent.CreateCommand, agent.StopCommand, agent.RemoveCommand = joinArguments(env.Create), joinArguments(env.Stop), joinArguments(env.Remove)
231+ }
232+ return agent, nil
233+}
added internal/app/creator_test.go +141 -0
new file mode 100644
@@ -0,0 +1,141 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+package app_test
4+
5+import (
6+ "context"
7+ "errors"
8+ "os"
9+ "path/filepath"
10+ "slices"
11+ "testing"
12+
13+ "git.rickub.com/bots-garden/sidekicks/internal/acp"
14+ "git.rickub.com/bots-garden/sidekicks/internal/app"
15+ "git.rickub.com/bots-garden/sidekicks/internal/config"
16+ "git.rickub.com/bots-garden/sidekicks/internal/creator"
17+ "git.rickub.com/bots-garden/sidekicks/internal/creator/creatortest"
18+)
19+
20+// creatorFixture is a configuration whose agents' folder is a temporary
21+// one, and the creation assistant with the fake mm of creatortest.
22+func creatorFixture(t *testing.T, version string) (*app.CreatorService, string, string) {
23+ t.Helper()
24+ dir := t.TempDir()
25+ folder := filepath.Join(dir, "Documents")
26+ path := filepath.Join(dir, "config.yaml")
27+ write(t, path, "version: 1\nagentsFolder: "+folder+"\nagents:\n - name: alice\n command: sh\n")
28+ command, env := creatortest.Fake(t, version)
29+ core := app.New(config.Location{Path: path, Source: config.SourceFlag}, app.Options{Starter: starter, MiniMe: command, MiniMeEnv: env})
30+ t.Cleanup(func() { core.Shutdown(context.Background()) })
31+ return &app.CreatorService{Core: core}, path, folder
32+}
33+
34+// written runs the wizard of the fake mm up to the agent file.
35+func written(t *testing.T, service *app.CreatorService, name string) {
36+ t.Helper()
37+ start, err := service.Start(context.Background())
38+ if err != nil {
39+ t.Fatal(err)
40+ }
41+ if start.View.Form == nil || start.Version != "mm v1.0.9" {
42+ t.Fatalf("start: %+v", start)
43+ }
44+ view, err := service.Answer(context.Background(), acp.FormAnswer{Action: acp.FormAccept, Content: map[string]any{"provider": "llmman", "name": name}})
45+ if err != nil || !view.Written {
46+ t.Fatalf("answer: %+v %v", view, err)
47+ }
48+}
49+
50+func TestTheCreatedAgentIsAddedToTheConfiguration(t *testing.T) {
51+ service, path, folder := creatorFixture(t, "mm v1.0.9")
52+ written(t, service, "Bob")
53+ result, err := service.Finish(context.Background(), app.CreatorFinish{Name: "bob", Icon: "🦊", Environment: creator.Local})
54+ if err != nil || result.Problem != "" || len(result.Problems) != 0 || result.Name != "bob" {
55+ t.Fatalf("finish: %+v %v", result, err)
56+ }
57+ cfg, err := config.Load(path)
58+ if err != nil {
59+ t.Fatal(err)
60+ }
61+ bob, ok := cfg.Agent("bob")
62+ agentFile := filepath.Join(folder, "bob", ".mm", "agent.yaml")
63+ if !ok || bob.Icon != "🦊" || bob.Title != "Bob (developer)" || bob.Workspace != filepath.Join(folder, "bob") ||
64+ !slices.Equal(bob.Args, []string{"--acp", "--config", agentFile}) || filepath.Base(bob.Command) != "mm" {
65+ t.Fatalf("bob: %+v", bob)
66+ }
67+ if _, err := service.Send(context.Background(), "/start"); !errors.Is(err, creator.ErrClosed) {
68+ t.Fatalf("the wizard should be closed after Finish: %v", err)
69+ }
70+}
71+
72+func TestACreatedAgentInAContainerOrASandboxGetsItsRuntime(t *testing.T) {
73+ for _, environment := range []string{creator.Container, creator.Sandbox} {
74+ service, path, folder := creatorFixture(t, "mm v1.0.9")
75+ written(t, service, "bob")
76+ if _, err := service.Finish(context.Background(), app.CreatorFinish{Name: "bob", Environment: environment}); err != nil {
77+ t.Fatalf("%s: %v", environment, err)
78+ }
79+ cfg, err := config.Load(path)
80+ if err != nil {
81+ t.Fatal(err)
82+ }
83+ bob, _ := cfg.Agent("bob")
84+ agentFile := filepath.Join(folder, "bob", ".mm", "agent.yaml")
85+ runtime := bob.Runtime
86+ switch environment {
87+ case creator.Container:
88+ if runtime.Type != "container" || runtime.Container != "bob-box" || !slices.Equal(bob.Args, []string{"exec", "-i", "bob-box", "mm", "--acp", "--config", agentFile}) ||
89+ !slices.Equal(runtime.Lifecycle.Create[1:], []string{"compose", "-f", "compose.yaml", "up", "-d", "--wait", "bob"}) {
90+ t.Fatalf("container: %+v", bob)
91+ }
92+ case creator.Sandbox:
93+ if runtime.Type != "sbx" || runtime.Sandbox != "bob-sbx" || !slices.Equal(bob.Args, []string{"exec", "-i", "bob-sbx", "mm", "--acp", "--config", agentFile}) ||
94+ len(runtime.Lifecycle.Create) == 0 || runtime.Lifecycle.Folder != filepath.Join(folder, "bob") {
95+ t.Fatalf("sbx: %+v", bob)
96+ }
97+ }
98+ }
99+}
100+
101+func TestANameAlreadyUsedIsAProblemToFix(t *testing.T) {
102+ service, _, folder := creatorFixture(t, "mm v1.0.9")
103+ written(t, service, "alice")
104+ cases := []struct{ name, problem string }{
105+ {"alice", app.CreatorNameTaken},
106+ {"Not A Name", app.CreatorInvalidName},
107+ }
108+ for _, c := range cases {
109+ result, err := service.Finish(context.Background(), app.CreatorFinish{Name: c.name, Environment: creator.Local})
110+ if err != nil || result.Problem != c.problem {
111+ t.Fatalf("%s: %+v %v", c.name, result, err)
112+ }
113+ }
114+ if err := os.MkdirAll(filepath.Join(folder, "alice-2"), 0o755); err != nil {
115+ t.Fatal(err)
116+ }
117+ result, err := service.Finish(context.Background(), app.CreatorFinish{Name: "alice-2", Environment: creator.Local})
118+ if err != nil || result.Problem != app.CreatorFolderExists {
119+ t.Fatalf("existing folder: %+v %v", result, err)
120+ }
121+ result, err = service.Finish(context.Background(), app.CreatorFinish{Name: "alice-3", Environment: creator.Local})
122+ if err != nil || result.Problem != "" || result.Name != "alice-3" {
123+ t.Fatalf("a free name: %+v %v", result, err)
124+ }
125+}
126+
127+func TestAnOldMMIsRefusedAndCancelRemovesTheWizardsFolder(t *testing.T) {
128+ old, _, _ := creatorFixture(t, "mm v1.0.8")
129+ var tooOld *creator.TooOldError
130+ if _, err := old.Start(context.Background()); !errors.As(err, &tooOld) || tooOld.Found != "1.0.8" {
131+ t.Fatalf("an old mm: %v", err)
132+ }
133+ service, _, folder := creatorFixture(t, "mm v1.0.9")
134+ if _, err := service.Start(context.Background()); err != nil {
135+ t.Fatal(err)
136+ }
137+ service.Cancel()
138+ if entries, _ := os.ReadDir(folder); len(entries) != 0 {
139+ t.Fatalf("the agents' folder should be left empty: %v", entries)
140+ }
141+}
new file mode 100644
@@ -0,0 +1,141 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+package app_test
4+
5+import (
6+ "context"
7+ "errors"
8+ "os"
9+ "path/filepath"
10+ "slices"
11+ "testing"
12+
13+ "git.rickub.com/bots-garden/sidekicks/internal/acp"
14+ "git.rickub.com/bots-garden/sidekicks/internal/app"
15+ "git.rickub.com/bots-garden/sidekicks/internal/config"
16+ "git.rickub.com/bots-garden/sidekicks/internal/creator"
17+ "git.rickub.com/bots-garden/sidekicks/internal/creator/creatortest"
18+)
19+
20+// creatorFixture is a configuration whose agents' folder is a temporary
21+// one, and the creation assistant with the fake mm of creatortest.
22+func creatorFixture(t *testing.T, version string) (*app.CreatorService, string, string) {
23+ t.Helper()
24+ dir := t.TempDir()
25+ folder := filepath.Join(dir, "Documents")
26+ path := filepath.Join(dir, "config.yaml")
27+ write(t, path, "version: 1\nagentsFolder: "+folder+"\nagents:\n - name: alice\n command: sh\n")
28+ command, env := creatortest.Fake(t, version)
29+ core := app.New(config.Location{Path: path, Source: config.SourceFlag}, app.Options{Starter: starter, MiniMe: command, MiniMeEnv: env})
30+ t.Cleanup(func() { core.Shutdown(context.Background()) })
31+ return &app.CreatorService{Core: core}, path, folder
32+}
33+
34+// written runs the wizard of the fake mm up to the agent file.
35+func written(t *testing.T, service *app.CreatorService, name string) {
36+ t.Helper()
37+ start, err := service.Start(context.Background())
38+ if err != nil {
39+ t.Fatal(err)
40+ }
41+ if start.View.Form == nil || start.Version != "mm v1.0.9" {
42+ t.Fatalf("start: %+v", start)
43+ }
44+ view, err := service.Answer(context.Background(), acp.FormAnswer{Action: acp.FormAccept, Content: map[string]any{"provider": "llmman", "name": name}})
45+ if err != nil || !view.Written {
46+ t.Fatalf("answer: %+v %v", view, err)
47+ }
48+}
49+
50+func TestTheCreatedAgentIsAddedToTheConfiguration(t *testing.T) {
51+ service, path, folder := creatorFixture(t, "mm v1.0.9")
52+ written(t, service, "Bob")
53+ result, err := service.Finish(context.Background(), app.CreatorFinish{Name: "bob", Icon: "🦊", Environment: creator.Local})
54+ if err != nil || result.Problem != "" || len(result.Problems) != 0 || result.Name != "bob" {
55+ t.Fatalf("finish: %+v %v", result, err)
56+ }
57+ cfg, err := config.Load(path)
58+ if err != nil {
59+ t.Fatal(err)
60+ }
61+ bob, ok := cfg.Agent("bob")
62+ agentFile := filepath.Join(folder, "bob", ".mm", "agent.yaml")
63+ if !ok || bob.Icon != "🦊" || bob.Title != "Bob (developer)" || bob.Workspace != filepath.Join(folder, "bob") ||
64+ !slices.Equal(bob.Args, []string{"--acp", "--config", agentFile}) || filepath.Base(bob.Command) != "mm" {
65+ t.Fatalf("bob: %+v", bob)
66+ }
67+ if _, err := service.Send(context.Background(), "/start"); !errors.Is(err, creator.ErrClosed) {
68+ t.Fatalf("the wizard should be closed after Finish: %v", err)
69+ }
70+}
71+
72+func TestACreatedAgentInAContainerOrASandboxGetsItsRuntime(t *testing.T) {
73+ for _, environment := range []string{creator.Container, creator.Sandbox} {
74+ service, path, folder := creatorFixture(t, "mm v1.0.9")
75+ written(t, service, "bob")
76+ if _, err := service.Finish(context.Background(), app.CreatorFinish{Name: "bob", Environment: environment}); err != nil {
77+ t.Fatalf("%s: %v", environment, err)
78+ }
79+ cfg, err := config.Load(path)
80+ if err != nil {
81+ t.Fatal(err)
82+ }
83+ bob, _ := cfg.Agent("bob")
84+ agentFile := filepath.Join(folder, "bob", ".mm", "agent.yaml")
85+ runtime := bob.Runtime
86+ switch environment {
87+ case creator.Container:
88+ if runtime.Type != "container" || runtime.Container != "bob-box" || !slices.Equal(bob.Args, []string{"exec", "-i", "bob-box", "mm", "--acp", "--config", agentFile}) ||
89+ !slices.Equal(runtime.Lifecycle.Create[1:], []string{"compose", "-f", "compose.yaml", "up", "-d", "--wait", "bob"}) {
90+ t.Fatalf("container: %+v", bob)
91+ }
92+ case creator.Sandbox:
93+ if runtime.Type != "sbx" || runtime.Sandbox != "bob-sbx" || !slices.Equal(bob.Args, []string{"exec", "-i", "bob-sbx", "mm", "--acp", "--config", agentFile}) ||
94+ len(runtime.Lifecycle.Create) == 0 || runtime.Lifecycle.Folder != filepath.Join(folder, "bob") {
95+ t.Fatalf("sbx: %+v", bob)
96+ }
97+ }
98+ }
99+}
100+
101+func TestANameAlreadyUsedIsAProblemToFix(t *testing.T) {
102+ service, _, folder := creatorFixture(t, "mm v1.0.9")
103+ written(t, service, "alice")
104+ cases := []struct{ name, problem string }{
105+ {"alice", app.CreatorNameTaken},
106+ {"Not A Name", app.CreatorInvalidName},
107+ }
108+ for _, c := range cases {
109+ result, err := service.Finish(context.Background(), app.CreatorFinish{Name: c.name, Environment: creator.Local})
110+ if err != nil || result.Problem != c.problem {
111+ t.Fatalf("%s: %+v %v", c.name, result, err)
112+ }
113+ }
114+ if err := os.MkdirAll(filepath.Join(folder, "alice-2"), 0o755); err != nil {
115+ t.Fatal(err)
116+ }
117+ result, err := service.Finish(context.Background(), app.CreatorFinish{Name: "alice-2", Environment: creator.Local})
118+ if err != nil || result.Problem != app.CreatorFolderExists {
119+ t.Fatalf("existing folder: %+v %v", result, err)
120+ }
121+ result, err = service.Finish(context.Background(), app.CreatorFinish{Name: "alice-3", Environment: creator.Local})
122+ if err != nil || result.Problem != "" || result.Name != "alice-3" {
123+ t.Fatalf("a free name: %+v %v", result, err)
124+ }
125+}
126+
127+func TestAnOldMMIsRefusedAndCancelRemovesTheWizardsFolder(t *testing.T) {
128+ old, _, _ := creatorFixture(t, "mm v1.0.8")
129+ var tooOld *creator.TooOldError
130+ if _, err := old.Start(context.Background()); !errors.As(err, &tooOld) || tooOld.Found != "1.0.8" {
131+ t.Fatalf("an old mm: %v", err)
132+ }
133+ service, _, folder := creatorFixture(t, "mm v1.0.9")
134+ if _, err := service.Start(context.Background()); err != nil {
135+ t.Fatal(err)
136+ }
137+ service.Cancel()
138+ if entries, _ := os.ReadDir(folder); len(entries) != 0 {
139+ t.Fatalf("the agents' folder should be left empty: %v", entries)
140+ }
141+}
modified internal/config/config.go +11 -3
@@ -37,6 +37,9 @@ const (
3737 DefaultStopIdleAgentsAfter = 10 * time.Minute
3838 DefaultMaxAgentHandoffs = 3
3939 RuntimeLocal = "local"
40+ // DefaultAgentsFolder is where the mini-me creation assistant puts the
41+ // agents' folders (issue #94): the Documents folder of the user.
42+ DefaultAgentsFolder = "~/Documents"
4043 )
4144
4245 // Config is a loaded configuration: defaults applied and paths absolute.
@@ -48,8 +51,11 @@ type Config struct {
4851 Limits Limits
4952 // AgentTools says which tools Sidekicks offers the agents (issues #90 and #91).
5053 AgentTools AgentTools
51- Agents []Agent
52- Channels []Channel
54+ // AgentsFolder is the absolute folder where the mini-me creation
55+ // assistant creates one folder per agent (issue #94).
56+ AgentsFolder string
57+ Agents []Agent
58+ Channels []Channel
5359 // Warnings are problems that do not prevent using the configuration,
5460 // such as an agent command that cannot be found yet.
5561 Warnings []Problem
@@ -359,7 +365,8 @@ type rawConfig struct {
359365 Enabled *bool `yaml:"enabled"`
360366 Offer *[]string `yaml:"offer"`
361367 } `yaml:"agentTools"`
362- Agents []struct {
368+ AgentsFolder string `yaml:"agentsFolder"`
369+ Agents []struct {
363370 Name string `yaml:"name"`
364371 Title string `yaml:"title"`
365372 Icon string `yaml:"icon"`
@@ -400,6 +407,7 @@ func (raw *rawConfig) toConfig(baseDir string) *Config {
400407 MaxAgentHandoffs: DefaultMaxAgentHandoffs,
401408 },
402409 }
410+ cfg.AgentsFolder = resolvePath(orDefault(raw.AgentsFolder, DefaultAgentsFolder), baseDir)
403411 cfg.AgentTools.Enabled = raw.AgentTools.Enabled == nil || *raw.AgentTools.Enabled
404412 if raw.AgentTools.Offer != nil {
405413 cfg.AgentTools.Offer = append([]string{}, *raw.AgentTools.Offer...)
@@ -37,6 +37,9 @@ const (
37 DefaultStopIdleAgentsAfter = 10 * time.Minute37 DefaultStopIdleAgentsAfter = 10 * time.Minute
38 DefaultMaxAgentHandoffs = 338 DefaultMaxAgentHandoffs = 3
39 RuntimeLocal = "local"39 RuntimeLocal = "local"
40+ // DefaultAgentsFolder is where the mini-me creation assistant puts the
41+ // agents' folders (issue #94): the Documents folder of the user.
42+ DefaultAgentsFolder = "~/Documents"
40 )43 )
41 44
42 // Config is a loaded configuration: defaults applied and paths absolute.45 // Config is a loaded configuration: defaults applied and paths absolute.
@@ -48,8 +51,11 @@ type Config struct {
48 Limits Limits51 Limits Limits
49 // AgentTools says which tools Sidekicks offers the agents (issues #90 and #91).52 // AgentTools says which tools Sidekicks offers the agents (issues #90 and #91).
50 AgentTools AgentTools53 AgentTools AgentTools
51- Agents []Agent54+ // AgentsFolder is the absolute folder where the mini-me creation
52- Channels []Channel55+ // assistant creates one folder per agent (issue #94).
56+ AgentsFolder string
57+ Agents []Agent
58+ Channels []Channel
53 // Warnings are problems that do not prevent using the configuration,59 // Warnings are problems that do not prevent using the configuration,
54 // such as an agent command that cannot be found yet.60 // such as an agent command that cannot be found yet.
55 Warnings []Problem61 Warnings []Problem
@@ -359,7 +365,8 @@ type rawConfig struct {
359 Enabled *bool `yaml:"enabled"`365 Enabled *bool `yaml:"enabled"`
360 Offer *[]string `yaml:"offer"`366 Offer *[]string `yaml:"offer"`
361 } `yaml:"agentTools"`367 } `yaml:"agentTools"`
362- Agents []struct {368+ AgentsFolder string `yaml:"agentsFolder"`
369+ Agents []struct {
363 Name string `yaml:"name"`370 Name string `yaml:"name"`
364 Title string `yaml:"title"`371 Title string `yaml:"title"`
365 Icon string `yaml:"icon"`372 Icon string `yaml:"icon"`
@@ -400,6 +407,7 @@ func (raw *rawConfig) toConfig(baseDir string) *Config {
400 MaxAgentHandoffs: DefaultMaxAgentHandoffs,407 MaxAgentHandoffs: DefaultMaxAgentHandoffs,
401 },408 },
402 }409 }
410+ cfg.AgentsFolder = resolvePath(orDefault(raw.AgentsFolder, DefaultAgentsFolder), baseDir)
403 cfg.AgentTools.Enabled = raw.AgentTools.Enabled == nil || *raw.AgentTools.Enabled411 cfg.AgentTools.Enabled = raw.AgentTools.Enabled == nil || *raw.AgentTools.Enabled
404 if raw.AgentTools.Offer != nil {412 if raw.AgentTools.Offer != nil {
405 cfg.AgentTools.Offer = append([]string{}, *raw.AgentTools.Offer...)413 cfg.AgentTools.Offer = append([]string{}, *raw.AgentTools.Offer...)
modified internal/config/config_test.go +22 -0
@@ -613,3 +613,25 @@ func TestAnUnknownToolIsOnlyAWarning(t *testing.T) {
613613 t.Fatal("enabled is a boolean")
614614 }
615615 }
616+
617+func TestTheAgentsFolderIsTheDocumentsFolderByDefault(t *testing.T) {
618+ home, _ := os.UserHomeDir()
619+ cases := []struct{ yaml, want string }{
620+ {"", filepath.Join(home, "Documents")},
621+ {"agentsFolder: ~/agents\n", filepath.Join(home, "agents")},
622+ {"agentsFolder: /srv/agents\n", "/srv/agents"},
623+ {"agentsFolder: ../agents\n", "/home/me/agents"},
624+ }
625+ for _, c := range cases {
626+ cfg, err := parse(t, "version: 1\n"+c.yaml+"agents: []\n")
627+ if err != nil {
628+ t.Fatalf("%q: %v", c.yaml, err)
629+ }
630+ if cfg.AgentsFolder != c.want {
631+ t.Errorf("%q: agents folder %q, want %q", c.yaml, cfg.AgentsFolder, c.want)
632+ }
633+ }
634+ if _, err := parse(t, "version: 1\nagentsFolder: \"\"\nagents: []\n"); err == nil {
635+ t.Error("an empty agentsFolder must be refused")
636+ }
637+}
@@ -613,3 +613,25 @@ func TestAnUnknownToolIsOnlyAWarning(t *testing.T) {
613 t.Fatal("enabled is a boolean")613 t.Fatal("enabled is a boolean")
614 }614 }
615 }615 }
616+
617+func TestTheAgentsFolderIsTheDocumentsFolderByDefault(t *testing.T) {
618+ home, _ := os.UserHomeDir()
619+ cases := []struct{ yaml, want string }{
620+ {"", filepath.Join(home, "Documents")},
621+ {"agentsFolder: ~/agents\n", filepath.Join(home, "agents")},
622+ {"agentsFolder: /srv/agents\n", "/srv/agents"},
623+ {"agentsFolder: ../agents\n", "/home/me/agents"},
624+ }
625+ for _, c := range cases {
626+ cfg, err := parse(t, "version: 1\n"+c.yaml+"agents: []\n")
627+ if err != nil {
628+ t.Fatalf("%q: %v", c.yaml, err)
629+ }
630+ if cfg.AgentsFolder != c.want {
631+ t.Errorf("%q: agents folder %q, want %q", c.yaml, cfg.AgentsFolder, c.want)
632+ }
633+ }
634+ if _, err := parse(t, "version: 1\nagentsFolder: \"\"\nagents: []\n"); err == nil {
635+ t.Error("an empty agentsFolder must be refused")
636+ }
637+}
modified internal/config/default.go +4 -0
@@ -36,6 +36,10 @@ limits:
3636 agentTools:
3737 enabled: true
3838
39+# Where the "Create a mini-me agent" assistant makes one folder per agent.
40+# Default: your Documents folder.
41+# agentsFolder: ~/Documents
42+
3943 # The agents: call them in a conversation by clicking their name.
4044 # The simplest way to add one is the "Add an agent" button of Sidekicks.
4145 agents: []
@@ -36,6 +36,10 @@ limits:
36 agentTools:36 agentTools:
37 enabled: true37 enabled: true
38 38
39+# Where the "Create a mini-me agent" assistant makes one folder per agent.
40+# Default: your Documents folder.
41+# agentsFolder: ~/Documents
42+
39 # The agents: call them in a conversation by clicking their name.43 # The agents: call them in a conversation by clicking their name.
40 # The simplest way to add one is the "Add an agent" button of Sidekicks.44 # The simplest way to add one is the "Add an agent" button of Sidekicks.
41 agents: []45 agents: []
modified internal/config/problems.go +1 -1
@@ -290,7 +290,7 @@ func allowedKeys(path []string) []string {
290290 parent := path[:len(path)-1]
291291 switch {
292292 case len(parent) == 0:
293- return []string{"version", "ui", "limits", "agents", "channels"}
293+ return []string{"version", "ui", "limits", "agentTools", "agentsFolder", "agents", "channels"}
294294 case parent[0] == "ui":
295295 return []string{"theme", "language"}
296296 case parent[0] == "limits":
@@ -290,7 +290,7 @@ func allowedKeys(path []string) []string {
290 parent := path[:len(path)-1]290 parent := path[:len(path)-1]
291 switch {291 switch {
292 case len(parent) == 0:292 case len(parent) == 0:
293- return []string{"version", "ui", "limits", "agents", "channels"}293+ return []string{"version", "ui", "limits", "agentTools", "agentsFolder", "agents", "channels"}
294 case parent[0] == "ui":294 case parent[0] == "ui":
295 return []string{"theme", "language"}295 return []string{"theme", "language"}
296 case parent[0] == "limits":296 case parent[0] == "limits":
added internal/creator/creator.go +555 -0
new file mode 100644
@@ -0,0 +1,555 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+// Package creator creates a mini-me agent without a terminal (issue #94):
4+// Sidekicks is the ACP client of `mm --acp-create --project yes`, the wizard
5+// of `mm init` served over ACP (mini-me 1.0.9 and later), and shows its
6+// questions as forms (ACP elicitation).
7+//
8+// An agent is a folder. Its name is only known near the end of the wizard,
9+// so the wizard works in a temporary folder of the agents' folder, renamed
10+// after the agent by Finish; Finish then asks mm for the files of a
11+// container (/dockerinit) or of a Docker Sandbox (/sbxinit) when the agent
12+// runs in one.
13+//
14+// session, err := creator.Start(ctx, creator.Options{AgentsFolder: "/Users/me/Documents"})
15+// view, err := session.Begin(ctx) // the first form
16+// view, err = session.Answer(ctx, answer) // … until view.Written
17+// result, err := session.Finish(ctx, "bob", creator.Local)
18+package creator
19+
20+import (
21+ "context"
22+ "errors"
23+ "fmt"
24+ "os"
25+ "os/exec"
26+ "path/filepath"
27+ "regexp"
28+ "strconv"
29+ "strings"
30+ "sync"
31+ "time"
32+
33+ "git.rickub.com/bots-garden/sidekicks/internal/acp"
34+ "go.yaml.in/yaml/v3"
35+)
36+
37+// MinVersion is the first mini-me with `mm --acp-create`.
38+var MinVersion = [3]int{1, 0, 9}
39+
40+// Where the created agent runs.
41+const (
42+ Local = "local"
43+ Container = "container"
44+ Sandbox = "sbx"
45+)
46+
47+// AgentFile is where mm writes the agent in its folder: the .mm layout is
48+// imposed (--project yes).
49+var AgentFile = filepath.Join(".mm", "agent.yaml")
50+
51+// wizardArguments start mm's wizard with the .mm layout imposed and its
52+// file fixed: neither question is asked.
53+var wizardArguments = []string{"--acp-create", "--project", "yes", "--output", AgentFile}
54+
55+// tempPrefix starts the name of the temporary folder of a wizard.
56+const tempPrefix = ".sidekicks-new-agent-"
57+
58+var (
59+ // ErrMiniMeMissing is returned when mm is not installed (not found in PATH).
60+ ErrMiniMeMissing = errors.New("mini-me (mm) is not installed")
61+ // ErrFolderExists is returned when a folder already has the agent's name.
62+ ErrFolderExists = errors.New("a folder with this name already exists")
63+ // ErrBusy is returned while a question waits for its answer.
64+ ErrBusy = errors.New("the assistant is waiting for an answer")
65+ // ErrNotWritten is returned by Finish before the wizard wrote the agent.
66+ ErrNotWritten = errors.New("the agent is not written yet")
67+ // ErrInvalidName is returned for a name that cannot be both a folder and an agent name.
68+ ErrInvalidName = errors.New("invalid agent name")
69+ // ErrClosed is returned once the session is closed.
70+ ErrClosed = errors.New("the assistant is closed")
71+)
72+
73+// TooOldError is returned when the installed mm has no --acp-create.
74+type TooOldError struct {
75+ Found string
76+}
77+
78+func (e *TooOldError) Error() string {
79+ return fmt.Sprintf("mini-me (mm) %s is too old: version %d.%d.%d or later is needed", e.Found, MinVersion[0], MinVersion[1], MinVersion[2])
80+}
81+
82+// Options tunes Start.
83+type Options struct {
84+ // Command is mm's program; "" looks mm up in PATH.
85+ Command string
86+ // AgentsFolder is the folder where the agent's folder is created; it is
87+ // created when missing.
88+ AgentsFolder string
89+ // OnStderr receives what mm writes on its standard error.
90+ OnStderr func(line string)
91+ // Env is added to mm's environment (the tests' fake mm).
92+ Env map[string]string
93+}
94+
95+// View is what the interface shows after each step: the messages mm sent
96+// since the last step, the form waiting for an answer (nil when none), and
97+// the agent once it is written.
98+type View struct {
99+ Messages []string `json:"messages"`
100+ Form *acp.Form `json:"form"`
101+ // Written: .mm/agent.yaml exists; Name and Title are mm's.
102+ Written bool `json:"written"`
103+ Name string `json:"name"`
104+ Title string `json:"title"`
105+}
106+
107+// Result is a created agent, ready to be added to the configuration.
108+type Result struct {
109+ // Folder is the agent's folder, AgentFile its .mm/agent.yaml (absolute).
110+ Folder string
111+ AgentFile string
112+ Title string
113+ // Environment is Local, Container or Sandbox; the compose.yaml or the
114+ // sbxenv.yaml mm wrote for the last two is in Folder.
115+ Environment string
116+ // Messages are what mm said while writing those files.
117+ Messages []string
118+}
119+
120+// Version runs `mm --version` (options.Command, options.Env) and checks that it is MinVersion or later. A
121+// version mm cannot tell ("unknown", a development build) is accepted: only
122+// a known old version is refused.
123+func Version(ctx context.Context, options Options) (string, error) {
124+ program, err := program(options.Command)
125+ if err != nil {
126+ return "", err
127+ }
128+ ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
129+ defer cancel()
130+ command := exec.CommandContext(ctx, program, "--version")
131+ command.Env = os.Environ()
132+ for key, value := range options.Env {
133+ command.Env = append(command.Env, key+"="+value)
134+ }
135+ output, err := command.Output()
136+ if err != nil {
137+ return "", fmt.Errorf("mm --version: %w", err)
138+ }
139+ found := strings.TrimSpace(string(output))
140+ version, ok := parseVersion(found)
141+ if !ok {
142+ return found, nil
143+ }
144+ if older(version, MinVersion) {
145+ return found, &TooOldError{Found: fmt.Sprintf("%d.%d.%d", version[0], version[1], version[2])}
146+ }
147+ return found, nil
148+}
149+
150+func program(command string) (string, error) {
151+ if command == "" {
152+ command = "mm"
153+ }
154+ path, err := exec.LookPath(command)
155+ if err != nil {
156+ return "", ErrMiniMeMissing
157+ }
158+ return path, nil
159+}
160+
161+var versionPattern = regexp.MustCompile(`(\d+)\.(\d+)\.(\d+)`)
162+
163+// parseVersion reads the first x.y.z of `mm --version` ("mm v1.0.9 (go1.27…)").
164+func parseVersion(text string) ([3]int, bool) {
165+ match := versionPattern.FindStringSubmatch(text)
166+ if match == nil {
167+ return [3]int{}, false
168+ }
169+ var version [3]int
170+ for index := range version {
171+ version[index], _ = strconv.Atoi(match[index+1])
172+ }
173+ return version, true
174+}
175+
176+func older(version, than [3]int) bool {
177+ for index := range version {
178+ if version[index] != than[index] {
179+ return version[index] < than[index]
180+ }
181+ }
182+ return false
183+}
184+
185+// namePattern is the agent names of the configuration, which are folder
186+// names too.
187+var namePattern = regexp.MustCompile(`^[a-z][a-z0-9_-]{0,31}$`)
188+
189+// NameOf turns mm's agent name into a name Sidekicks accepts: lowercase,
190+// letters, digits, '-' and '_', starting with a letter, 32 characters at
191+// most; "" when nothing is left.
192+//
193+// NameOf("Bob the Builder") // "bob-the-builder"
194+func NameOf(text string) string {
195+ var b strings.Builder
196+ dash := false
197+ for _, r := range strings.ToLower(strings.TrimSpace(text)) {
198+ switch {
199+ case r >= 'a' && r <= 'z', r >= '0' && r <= '9', r == '_':
200+ b.WriteRune(r)
201+ dash = false
202+ case b.Len() > 0 && !dash:
203+ b.WriteRune('-')
204+ dash = true
205+ }
206+ }
207+ name := strings.TrimLeft(strings.Trim(b.String(), "-"), "0123456789_-")
208+ if len(name) > 32 {
209+ name = strings.TrimRight(name[:32], "-")
210+ }
211+ return name
212+}
213+
214+// ValidName reports whether name is an agent name Sidekicks accepts.
215+func ValidName(name string) bool { return namePattern.MatchString(name) }
216+
217+// Session is one wizard: mm --acp-create running in a temporary folder.
218+type Session struct {
219+ options Options
220+ program string
221+ folder string // the agents' folder
222+ dir string // the temporary folder, then the agent's folder
223+ conn *acp.Conn
224+ id string
225+
226+ mu sync.Mutex
227+ messages []string
228+ pending *pendingForm
229+ turn chan error // the end of the turn in flight; nil when none
230+ forms chan struct{}
231+ finished bool
232+ closed bool
233+}
234+
235+type pendingForm struct {
236+ form acp.Form
237+ reply chan acp.FormAnswer
238+}
239+
240+// Start checks mm, creates the temporary folder in the agents' folder and
241+// starts mm --acp-create --project yes --output .mm/agent.yaml there, with a session open.
242+func Start(ctx context.Context, options Options) (*Session, error) {
243+ program, err := program(options.Command)
244+ if err != nil {
245+ return nil, err
246+ }
247+ if options.AgentsFolder == "" {
248+ return nil, errors.New("no agents folder")
249+ }
250+ if err := os.MkdirAll(options.AgentsFolder, 0o755); err != nil {
251+ return nil, err
252+ }
253+ removeStale(options.AgentsFolder, time.Now().Add(-24*time.Hour))
254+ dir, err := os.MkdirTemp(options.AgentsFolder, tempPrefix)
255+ if err != nil {
256+ return nil, err
257+ }
258+ s := &Session{options: options, program: program, folder: options.AgentsFolder, dir: dir, forms: make(chan struct{}, 1)}
259+ if err := s.open(ctx, wizardArguments); err != nil {
260+ _ = os.RemoveAll(dir)
261+ return nil, err
262+ }
263+ return s, nil
264+}
265+
266+// removeStale removes the temporary folders of wizards older than before:
267+// those of a Sidekicks that stopped in the middle of one.
268+func removeStale(folder string, before time.Time) {
269+ entries, _ := os.ReadDir(folder)
270+ for _, entry := range entries {
271+ if !entry.IsDir() || !strings.HasPrefix(entry.Name(), tempPrefix) {
272+ continue
273+ }
274+ if info, err := entry.Info(); err == nil && info.ModTime().Before(before) {
275+ _ = os.RemoveAll(filepath.Join(folder, entry.Name()))
276+ }
277+ }
278+}
279+
280+// open starts mm in s.dir with arguments and opens a session there.
281+func (s *Session) open(ctx context.Context, arguments []string) error {
282+ conn, err := acp.Start(ctx, acp.Spec{
283+ Name: "mm-acp-create", Command: s.program, Args: arguments, Dir: s.dir, Env: s.options.Env, OnForm: s.onForm,
284+ }, acp.Options{OnStderr: s.options.OnStderr})
285+ if err != nil {
286+ return err
287+ }
288+ id, err := conn.NewSession(ctx, s.dir, handler{s})
289+ if err != nil {
290+ _ = conn.Close(context.Background())
291+ return err
292+ }
293+ s.mu.Lock()
294+ s.conn, s.id = conn, id
295+ s.mu.Unlock()
296+ return nil
297+}
298+
299+// Begin sends /start: the wizard asks its first questions.
300+func (s *Session) Begin(ctx context.Context) (View, error) { return s.Send(ctx, "/start") }
301+
302+// Send sends text as a message (an answer when mm asks without a form, or
303+// one of its commands: /back, /restart…) and waits for the next form or
304+// for the end of mm's answer.
305+func (s *Session) Send(ctx context.Context, text string) (View, error) {
306+ s.mu.Lock()
307+ finished := s.finished
308+ s.mu.Unlock()
309+ if finished {
310+ return View{}, ErrClosed
311+ }
312+ return s.send(ctx, text)
313+}
314+
315+// send starts a turn with text and waits like Send.
316+func (s *Session) send(ctx context.Context, text string) (View, error) {
317+ s.mu.Lock()
318+ switch {
319+ case s.closed:
320+ s.mu.Unlock()
321+ return View{}, ErrClosed
322+ case s.turn != nil:
323+ s.mu.Unlock()
324+ return View{}, ErrBusy
325+ }
326+ turn := make(chan error, 1)
327+ s.turn = turn
328+ conn, id := s.conn, s.id
329+ s.mu.Unlock()
330+ go func() {
331+ _, err := conn.Prompt(context.WithoutCancel(ctx), id, text)
332+ turn <- err
333+ }()
334+ return s.wait(ctx)
335+}
336+
337+// Answer answers the form waiting (accept with values, decline or cancel)
338+// and waits for the next form or for the end of mm's answer.
339+func (s *Session) Answer(ctx context.Context, answer acp.FormAnswer) (View, error) {
340+ s.mu.Lock()
341+ pending := s.pending
342+ s.pending = nil
343+ s.mu.Unlock()
344+ if pending == nil {
345+ return s.View(), nil
346+ }
347+ pending.reply <- answer
348+ return s.wait(ctx)
349+}
350+
351+// wait returns once a form waits for an answer, the turn is over, or mm
352+// stopped.
353+func (s *Session) wait(ctx context.Context) (View, error) {
354+ s.mu.Lock()
355+ turn, conn := s.turn, s.conn
356+ s.mu.Unlock()
357+ if turn == nil {
358+ return s.View(), nil
359+ }
360+ select {
361+ case <-s.forms:
362+ return s.View(), nil
363+ case err := <-turn:
364+ s.mu.Lock()
365+ s.turn = nil
366+ s.mu.Unlock()
367+ return s.View(), err
368+ case <-conn.Done():
369+ return s.View(), conn.Err()
370+ case <-ctx.Done():
371+ return s.View(), ctx.Err()
372+ }
373+}
374+
375+// View is the state now: the messages not shown yet, the form waiting,
376+// and the agent if it is written.
377+func (s *Session) View() View {
378+ s.mu.Lock()
379+ view := View{Messages: s.messages}
380+ s.messages = nil
381+ if s.pending != nil {
382+ form := s.pending.form
383+ view.Form = &form
384+ }
385+ dir := s.dir
386+ s.mu.Unlock()
387+ if view.Messages == nil {
388+ view.Messages = []string{}
389+ }
390+ if name, title, ok := readAgent(filepath.Join(dir, AgentFile)); ok {
391+ view.Written, view.Name, view.Title = true, NameOf(name), title
392+ }
393+ return view
394+}
395+
396+// onForm is called by acp for each form mm asks: it waits for Answer.
397+func (s *Session) onForm(ctx context.Context, form acp.Form) acp.FormAnswer {
398+ pending := &pendingForm{form: form, reply: make(chan acp.FormAnswer, 1)}
399+ s.mu.Lock()
400+ if s.closed {
401+ s.mu.Unlock()
402+ return acp.FormAnswer{Action: acp.FormCancel}
403+ }
404+ s.pending = pending
405+ s.mu.Unlock()
406+ select {
407+ case s.forms <- struct{}{}:
408+ default:
409+ }
410+ select {
411+ case answer := <-pending.reply:
412+ return answer
413+ case <-ctx.Done():
414+ return acp.FormAnswer{Action: acp.FormCancel}
415+ }
416+}
417+
418+// handler keeps what mm says. Each message of mm's wizard comes whole, in
419+// one chunk.
420+type handler struct{ s *Session }
421+
422+func (h handler) Update(update acp.Update) {
423+ if update.Kind != acp.UpdateMessage || strings.TrimSpace(update.Text) == "" {
424+ return
425+ }
426+ h.s.mu.Lock()
427+ h.s.messages = append(h.s.messages, update.Text)
428+ h.s.mu.Unlock()
429+}
430+
431+func (handler) RequestPermission(context.Context, acp.PermissionRequest) acp.PermissionAnswer {
432+ return acp.PermissionAnswer{}
433+}
434+
435+// readAgent reads acp.name and acp.title of the agent file mm wrote.
436+func readAgent(path string) (name, title string, ok bool) {
437+ content, err := os.ReadFile(path)
438+ if err != nil {
439+ return "", "", false
440+ }
441+ var file struct {
442+ ACP struct {
443+ Name string `yaml:"name"`
444+ Title string `yaml:"title"`
445+ } `yaml:"acp"`
446+ }
447+ _ = yaml.Unmarshal(content, &file)
448+ return file.ACP.Name, file.ACP.Title, true
449+}
450+
451+// Finish ends the wizard: the temporary folder becomes the agent's folder,
452+// named name in the agents' folder, then, for a container or a sandbox, mm
453+// writes its compose.yaml (/dockerinit) or its sbxenv.yaml (/sbxinit) there.
454+// A folder that already has this name is never touched: ErrFolderExists,
455+// and another name can be tried.
456+func (s *Session) Finish(ctx context.Context, name, environment string) (Result, error) {
457+ if !ValidName(name) {
458+ return Result{}, ErrInvalidName
459+ }
460+ view := s.View()
461+ if !view.Written {
462+ return Result{}, ErrNotWritten
463+ }
464+ target := filepath.Join(s.folder, name)
465+ if _, err := os.Lstat(target); err == nil {
466+ return Result{}, ErrFolderExists
467+ }
468+ s.mu.Lock()
469+ if s.closed || s.finished {
470+ s.mu.Unlock()
471+ return Result{}, ErrClosed
472+ }
473+ if s.turn != nil {
474+ s.mu.Unlock()
475+ return Result{}, ErrBusy
476+ }
477+ s.finished = true
478+ conn := s.conn
479+ s.mu.Unlock()
480+ _ = conn.Close(ctx)
481+ if err := os.Rename(s.dir, target); err != nil {
482+ s.mu.Lock()
483+ s.finished = false
484+ s.mu.Unlock()
485+ _ = s.open(ctx, wizardArguments)
486+ return Result{}, err
487+ }
488+ // MkdirTemp made it private (0700): an agent's folder is an ordinary one.
489+ _ = os.Chmod(target, 0o755)
490+ s.mu.Lock()
491+ s.dir = target
492+ s.mu.Unlock()
493+ result := Result{Folder: target, AgentFile: filepath.Join(target, AgentFile), Title: view.Title, Environment: environment}
494+ switch environment {
495+ case Local:
496+ return result, nil
497+ case Container:
498+ return s.scaffold(ctx, result, "/dockerinit", "compose.yaml")
499+ case Sandbox:
500+ return s.scaffold(ctx, result, "/sbxinit", "sbxenv.yaml")
501+ }
502+ return result, fmt.Errorf("unknown environment %q", environment)
503+}
504+
505+// scaffold asks mm, started again in the agent's folder, for command, and
506+// checks that it wrote file.
507+func (s *Session) scaffold(ctx context.Context, result Result, command, file string) (Result, error) {
508+ if err := s.open(ctx, []string{"--acp-create"}); err != nil {
509+ return result, err
510+ }
511+ defer func() { _ = s.conn.Close(context.Background()) }()
512+ view, err := s.send(ctx, command)
513+ // Only the command's report: mm's welcome may come before it.
514+ if len(view.Messages) > 0 {
515+ result.Messages = view.Messages[len(view.Messages)-1:]
516+ }
517+ if err != nil {
518+ return result, err
519+ }
520+ if _, err := os.Stat(filepath.Join(result.Folder, file)); err != nil {
521+ return result, fmt.Errorf("mm did not write %s: %s", file, strings.Join(view.Messages, "\n"))
522+ }
523+ return result, nil
524+}
525+
526+// Close stops mm. Before Finish, the temporary folder is removed with what
527+// the wizard wrote in it.
528+func (s *Session) Close() {
529+ s.mu.Lock()
530+ if s.closed {
531+ s.mu.Unlock()
532+ return
533+ }
534+ s.closed = true
535+ pending, conn, finished, dir := s.pending, s.conn, s.finished, s.dir
536+ s.pending = nil
537+ s.mu.Unlock()
538+ if pending != nil {
539+ pending.reply <- acp.FormAnswer{Action: acp.FormCancel}
540+ }
541+ if conn != nil {
542+ _ = conn.Close(context.Background())
543+ }
544+ if !finished && strings.HasPrefix(filepath.Base(dir), tempPrefix) {
545+ _ = os.RemoveAll(dir)
546+ }
547+}
548+
549+// Folder is the folder the wizard writes in: the temporary one, then the
550+// agent's.
551+func (s *Session) Folder() string {
552+ s.mu.Lock()
553+ defer s.mu.Unlock()
554+ return s.dir
555+}
new file mode 100644
@@ -0,0 +1,555 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+// Package creator creates a mini-me agent without a terminal (issue #94):
4+// Sidekicks is the ACP client of `mm --acp-create --project yes`, the wizard
5+// of `mm init` served over ACP (mini-me 1.0.9 and later), and shows its
6+// questions as forms (ACP elicitation).
7+//
8+// An agent is a folder. Its name is only known near the end of the wizard,
9+// so the wizard works in a temporary folder of the agents' folder, renamed
10+// after the agent by Finish; Finish then asks mm for the files of a
11+// container (/dockerinit) or of a Docker Sandbox (/sbxinit) when the agent
12+// runs in one.
13+//
14+// session, err := creator.Start(ctx, creator.Options{AgentsFolder: "/Users/me/Documents"})
15+// view, err := session.Begin(ctx) // the first form
16+// view, err = session.Answer(ctx, answer) // … until view.Written
17+// result, err := session.Finish(ctx, "bob", creator.Local)
18+package creator
19+
20+import (
21+ "context"
22+ "errors"
23+ "fmt"
24+ "os"
25+ "os/exec"
26+ "path/filepath"
27+ "regexp"
28+ "strconv"
29+ "strings"
30+ "sync"
31+ "time"
32+
33+ "git.rickub.com/bots-garden/sidekicks/internal/acp"
34+ "go.yaml.in/yaml/v3"
35+)
36+
37+// MinVersion is the first mini-me with `mm --acp-create`.
38+var MinVersion = [3]int{1, 0, 9}
39+
40+// Where the created agent runs.
41+const (
42+ Local = "local"
43+ Container = "container"
44+ Sandbox = "sbx"
45+)
46+
47+// AgentFile is where mm writes the agent in its folder: the .mm layout is
48+// imposed (--project yes).
49+var AgentFile = filepath.Join(".mm", "agent.yaml")
50+
51+// wizardArguments start mm's wizard with the .mm layout imposed and its
52+// file fixed: neither question is asked.
53+var wizardArguments = []string{"--acp-create", "--project", "yes", "--output", AgentFile}
54+
55+// tempPrefix starts the name of the temporary folder of a wizard.
56+const tempPrefix = ".sidekicks-new-agent-"
57+
58+var (
59+ // ErrMiniMeMissing is returned when mm is not installed (not found in PATH).
60+ ErrMiniMeMissing = errors.New("mini-me (mm) is not installed")
61+ // ErrFolderExists is returned when a folder already has the agent's name.
62+ ErrFolderExists = errors.New("a folder with this name already exists")
63+ // ErrBusy is returned while a question waits for its answer.
64+ ErrBusy = errors.New("the assistant is waiting for an answer")
65+ // ErrNotWritten is returned by Finish before the wizard wrote the agent.
66+ ErrNotWritten = errors.New("the agent is not written yet")
67+ // ErrInvalidName is returned for a name that cannot be both a folder and an agent name.
68+ ErrInvalidName = errors.New("invalid agent name")
69+ // ErrClosed is returned once the session is closed.
70+ ErrClosed = errors.New("the assistant is closed")
71+)
72+
73+// TooOldError is returned when the installed mm has no --acp-create.
74+type TooOldError struct {
75+ Found string
76+}
77+
78+func (e *TooOldError) Error() string {
79+ return fmt.Sprintf("mini-me (mm) %s is too old: version %d.%d.%d or later is needed", e.Found, MinVersion[0], MinVersion[1], MinVersion[2])
80+}
81+
82+// Options tunes Start.
83+type Options struct {
84+ // Command is mm's program; "" looks mm up in PATH.
85+ Command string
86+ // AgentsFolder is the folder where the agent's folder is created; it is
87+ // created when missing.
88+ AgentsFolder string
89+ // OnStderr receives what mm writes on its standard error.
90+ OnStderr func(line string)
91+ // Env is added to mm's environment (the tests' fake mm).
92+ Env map[string]string
93+}
94+
95+// View is what the interface shows after each step: the messages mm sent
96+// since the last step, the form waiting for an answer (nil when none), and
97+// the agent once it is written.
98+type View struct {
99+ Messages []string `json:"messages"`
100+ Form *acp.Form `json:"form"`
101+ // Written: .mm/agent.yaml exists; Name and Title are mm's.
102+ Written bool `json:"written"`
103+ Name string `json:"name"`
104+ Title string `json:"title"`
105+}
106+
107+// Result is a created agent, ready to be added to the configuration.
108+type Result struct {
109+ // Folder is the agent's folder, AgentFile its .mm/agent.yaml (absolute).
110+ Folder string
111+ AgentFile string
112+ Title string
113+ // Environment is Local, Container or Sandbox; the compose.yaml or the
114+ // sbxenv.yaml mm wrote for the last two is in Folder.
115+ Environment string
116+ // Messages are what mm said while writing those files.
117+ Messages []string
118+}
119+
120+// Version runs `mm --version` (options.Command, options.Env) and checks that it is MinVersion or later. A
121+// version mm cannot tell ("unknown", a development build) is accepted: only
122+// a known old version is refused.
123+func Version(ctx context.Context, options Options) (string, error) {
124+ program, err := program(options.Command)
125+ if err != nil {
126+ return "", err
127+ }
128+ ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
129+ defer cancel()
130+ command := exec.CommandContext(ctx, program, "--version")
131+ command.Env = os.Environ()
132+ for key, value := range options.Env {
133+ command.Env = append(command.Env, key+"="+value)
134+ }
135+ output, err := command.Output()
136+ if err != nil {
137+ return "", fmt.Errorf("mm --version: %w", err)
138+ }
139+ found := strings.TrimSpace(string(output))
140+ version, ok := parseVersion(found)
141+ if !ok {
142+ return found, nil
143+ }
144+ if older(version, MinVersion) {
145+ return found, &TooOldError{Found: fmt.Sprintf("%d.%d.%d", version[0], version[1], version[2])}
146+ }
147+ return found, nil
148+}
149+
150+func program(command string) (string, error) {
151+ if command == "" {
152+ command = "mm"
153+ }
154+ path, err := exec.LookPath(command)
155+ if err != nil {
156+ return "", ErrMiniMeMissing
157+ }
158+ return path, nil
159+}
160+
161+var versionPattern = regexp.MustCompile(`(\d+)\.(\d+)\.(\d+)`)
162+
163+// parseVersion reads the first x.y.z of `mm --version` ("mm v1.0.9 (go1.27…)").
164+func parseVersion(text string) ([3]int, bool) {
165+ match := versionPattern.FindStringSubmatch(text)
166+ if match == nil {
167+ return [3]int{}, false
168+ }
169+ var version [3]int
170+ for index := range version {
171+ version[index], _ = strconv.Atoi(match[index+1])
172+ }
173+ return version, true
174+}
175+
176+func older(version, than [3]int) bool {
177+ for index := range version {
178+ if version[index] != than[index] {
179+ return version[index] < than[index]
180+ }
181+ }
182+ return false
183+}
184+
185+// namePattern is the agent names of the configuration, which are folder
186+// names too.
187+var namePattern = regexp.MustCompile(`^[a-z][a-z0-9_-]{0,31}$`)
188+
189+// NameOf turns mm's agent name into a name Sidekicks accepts: lowercase,
190+// letters, digits, '-' and '_', starting with a letter, 32 characters at
191+// most; "" when nothing is left.
192+//
193+// NameOf("Bob the Builder") // "bob-the-builder"
194+func NameOf(text string) string {
195+ var b strings.Builder
196+ dash := false
197+ for _, r := range strings.ToLower(strings.TrimSpace(text)) {
198+ switch {
199+ case r >= 'a' && r <= 'z', r >= '0' && r <= '9', r == '_':
200+ b.WriteRune(r)
201+ dash = false
202+ case b.Len() > 0 && !dash:
203+ b.WriteRune('-')
204+ dash = true
205+ }
206+ }
207+ name := strings.TrimLeft(strings.Trim(b.String(), "-"), "0123456789_-")
208+ if len(name) > 32 {
209+ name = strings.TrimRight(name[:32], "-")
210+ }
211+ return name
212+}
213+
214+// ValidName reports whether name is an agent name Sidekicks accepts.
215+func ValidName(name string) bool { return namePattern.MatchString(name) }
216+
217+// Session is one wizard: mm --acp-create running in a temporary folder.
218+type Session struct {
219+ options Options
220+ program string
221+ folder string // the agents' folder
222+ dir string // the temporary folder, then the agent's folder
223+ conn *acp.Conn
224+ id string
225+
226+ mu sync.Mutex
227+ messages []string
228+ pending *pendingForm
229+ turn chan error // the end of the turn in flight; nil when none
230+ forms chan struct{}
231+ finished bool
232+ closed bool
233+}
234+
235+type pendingForm struct {
236+ form acp.Form
237+ reply chan acp.FormAnswer
238+}
239+
240+// Start checks mm, creates the temporary folder in the agents' folder and
241+// starts mm --acp-create --project yes --output .mm/agent.yaml there, with a session open.
242+func Start(ctx context.Context, options Options) (*Session, error) {
243+ program, err := program(options.Command)
244+ if err != nil {
245+ return nil, err
246+ }
247+ if options.AgentsFolder == "" {
248+ return nil, errors.New("no agents folder")
249+ }
250+ if err := os.MkdirAll(options.AgentsFolder, 0o755); err != nil {
251+ return nil, err
252+ }
253+ removeStale(options.AgentsFolder, time.Now().Add(-24*time.Hour))
254+ dir, err := os.MkdirTemp(options.AgentsFolder, tempPrefix)
255+ if err != nil {
256+ return nil, err
257+ }
258+ s := &Session{options: options, program: program, folder: options.AgentsFolder, dir: dir, forms: make(chan struct{}, 1)}
259+ if err := s.open(ctx, wizardArguments); err != nil {
260+ _ = os.RemoveAll(dir)
261+ return nil, err
262+ }
263+ return s, nil
264+}
265+
266+// removeStale removes the temporary folders of wizards older than before:
267+// those of a Sidekicks that stopped in the middle of one.
268+func removeStale(folder string, before time.Time) {
269+ entries, _ := os.ReadDir(folder)
270+ for _, entry := range entries {
271+ if !entry.IsDir() || !strings.HasPrefix(entry.Name(), tempPrefix) {
272+ continue
273+ }
274+ if info, err := entry.Info(); err == nil && info.ModTime().Before(before) {
275+ _ = os.RemoveAll(filepath.Join(folder, entry.Name()))
276+ }
277+ }
278+}
279+
280+// open starts mm in s.dir with arguments and opens a session there.
281+func (s *Session) open(ctx context.Context, arguments []string) error {
282+ conn, err := acp.Start(ctx, acp.Spec{
283+ Name: "mm-acp-create", Command: s.program, Args: arguments, Dir: s.dir, Env: s.options.Env, OnForm: s.onForm,
284+ }, acp.Options{OnStderr: s.options.OnStderr})
285+ if err != nil {
286+ return err
287+ }
288+ id, err := conn.NewSession(ctx, s.dir, handler{s})
289+ if err != nil {
290+ _ = conn.Close(context.Background())
291+ return err
292+ }
293+ s.mu.Lock()
294+ s.conn, s.id = conn, id
295+ s.mu.Unlock()
296+ return nil
297+}
298+
299+// Begin sends /start: the wizard asks its first questions.
300+func (s *Session) Begin(ctx context.Context) (View, error) { return s.Send(ctx, "/start") }
301+
302+// Send sends text as a message (an answer when mm asks without a form, or
303+// one of its commands: /back, /restart…) and waits for the next form or
304+// for the end of mm's answer.
305+func (s *Session) Send(ctx context.Context, text string) (View, error) {
306+ s.mu.Lock()
307+ finished := s.finished
308+ s.mu.Unlock()
309+ if finished {
310+ return View{}, ErrClosed
311+ }
312+ return s.send(ctx, text)
313+}
314+
315+// send starts a turn with text and waits like Send.
316+func (s *Session) send(ctx context.Context, text string) (View, error) {
317+ s.mu.Lock()
318+ switch {
319+ case s.closed:
320+ s.mu.Unlock()
321+ return View{}, ErrClosed
322+ case s.turn != nil:
323+ s.mu.Unlock()
324+ return View{}, ErrBusy
325+ }
326+ turn := make(chan error, 1)
327+ s.turn = turn
328+ conn, id := s.conn, s.id
329+ s.mu.Unlock()
330+ go func() {
331+ _, err := conn.Prompt(context.WithoutCancel(ctx), id, text)
332+ turn <- err
333+ }()
334+ return s.wait(ctx)
335+}
336+
337+// Answer answers the form waiting (accept with values, decline or cancel)
338+// and waits for the next form or for the end of mm's answer.
339+func (s *Session) Answer(ctx context.Context, answer acp.FormAnswer) (View, error) {
340+ s.mu.Lock()
341+ pending := s.pending
342+ s.pending = nil
343+ s.mu.Unlock()
344+ if pending == nil {
345+ return s.View(), nil
346+ }
347+ pending.reply <- answer
348+ return s.wait(ctx)
349+}
350+
351+// wait returns once a form waits for an answer, the turn is over, or mm
352+// stopped.
353+func (s *Session) wait(ctx context.Context) (View, error) {
354+ s.mu.Lock()
355+ turn, conn := s.turn, s.conn
356+ s.mu.Unlock()
357+ if turn == nil {
358+ return s.View(), nil
359+ }
360+ select {
361+ case <-s.forms:
362+ return s.View(), nil
363+ case err := <-turn:
364+ s.mu.Lock()
365+ s.turn = nil
366+ s.mu.Unlock()
367+ return s.View(), err
368+ case <-conn.Done():
369+ return s.View(), conn.Err()
370+ case <-ctx.Done():
371+ return s.View(), ctx.Err()
372+ }
373+}
374+
375+// View is the state now: the messages not shown yet, the form waiting,
376+// and the agent if it is written.
377+func (s *Session) View() View {
378+ s.mu.Lock()
379+ view := View{Messages: s.messages}
380+ s.messages = nil
381+ if s.pending != nil {
382+ form := s.pending.form
383+ view.Form = &form
384+ }
385+ dir := s.dir
386+ s.mu.Unlock()
387+ if view.Messages == nil {
388+ view.Messages = []string{}
389+ }
390+ if name, title, ok := readAgent(filepath.Join(dir, AgentFile)); ok {
391+ view.Written, view.Name, view.Title = true, NameOf(name), title
392+ }
393+ return view
394+}
395+
396+// onForm is called by acp for each form mm asks: it waits for Answer.
397+func (s *Session) onForm(ctx context.Context, form acp.Form) acp.FormAnswer {
398+ pending := &pendingForm{form: form, reply: make(chan acp.FormAnswer, 1)}
399+ s.mu.Lock()
400+ if s.closed {
401+ s.mu.Unlock()
402+ return acp.FormAnswer{Action: acp.FormCancel}
403+ }
404+ s.pending = pending
405+ s.mu.Unlock()
406+ select {
407+ case s.forms <- struct{}{}:
408+ default:
409+ }
410+ select {
411+ case answer := <-pending.reply:
412+ return answer
413+ case <-ctx.Done():
414+ return acp.FormAnswer{Action: acp.FormCancel}
415+ }
416+}
417+
418+// handler keeps what mm says. Each message of mm's wizard comes whole, in
419+// one chunk.
420+type handler struct{ s *Session }
421+
422+func (h handler) Update(update acp.Update) {
423+ if update.Kind != acp.UpdateMessage || strings.TrimSpace(update.Text) == "" {
424+ return
425+ }
426+ h.s.mu.Lock()
427+ h.s.messages = append(h.s.messages, update.Text)
428+ h.s.mu.Unlock()
429+}
430+
431+func (handler) RequestPermission(context.Context, acp.PermissionRequest) acp.PermissionAnswer {
432+ return acp.PermissionAnswer{}
433+}
434+
435+// readAgent reads acp.name and acp.title of the agent file mm wrote.
436+func readAgent(path string) (name, title string, ok bool) {
437+ content, err := os.ReadFile(path)
438+ if err != nil {
439+ return "", "", false
440+ }
441+ var file struct {
442+ ACP struct {
443+ Name string `yaml:"name"`
444+ Title string `yaml:"title"`
445+ } `yaml:"acp"`
446+ }
447+ _ = yaml.Unmarshal(content, &file)
448+ return file.ACP.Name, file.ACP.Title, true
449+}
450+
451+// Finish ends the wizard: the temporary folder becomes the agent's folder,
452+// named name in the agents' folder, then, for a container or a sandbox, mm
453+// writes its compose.yaml (/dockerinit) or its sbxenv.yaml (/sbxinit) there.
454+// A folder that already has this name is never touched: ErrFolderExists,
455+// and another name can be tried.
456+func (s *Session) Finish(ctx context.Context, name, environment string) (Result, error) {
457+ if !ValidName(name) {
458+ return Result{}, ErrInvalidName
459+ }
460+ view := s.View()
461+ if !view.Written {
462+ return Result{}, ErrNotWritten
463+ }
464+ target := filepath.Join(s.folder, name)
465+ if _, err := os.Lstat(target); err == nil {
466+ return Result{}, ErrFolderExists
467+ }
468+ s.mu.Lock()
469+ if s.closed || s.finished {
470+ s.mu.Unlock()
471+ return Result{}, ErrClosed
472+ }
473+ if s.turn != nil {
474+ s.mu.Unlock()
475+ return Result{}, ErrBusy
476+ }
477+ s.finished = true
478+ conn := s.conn
479+ s.mu.Unlock()
480+ _ = conn.Close(ctx)
481+ if err := os.Rename(s.dir, target); err != nil {
482+ s.mu.Lock()
483+ s.finished = false
484+ s.mu.Unlock()
485+ _ = s.open(ctx, wizardArguments)
486+ return Result{}, err
487+ }
488+ // MkdirTemp made it private (0700): an agent's folder is an ordinary one.
489+ _ = os.Chmod(target, 0o755)
490+ s.mu.Lock()
491+ s.dir = target
492+ s.mu.Unlock()
493+ result := Result{Folder: target, AgentFile: filepath.Join(target, AgentFile), Title: view.Title, Environment: environment}
494+ switch environment {
495+ case Local:
496+ return result, nil
497+ case Container:
498+ return s.scaffold(ctx, result, "/dockerinit", "compose.yaml")
499+ case Sandbox:
500+ return s.scaffold(ctx, result, "/sbxinit", "sbxenv.yaml")
501+ }
502+ return result, fmt.Errorf("unknown environment %q", environment)
503+}
504+
505+// scaffold asks mm, started again in the agent's folder, for command, and
506+// checks that it wrote file.
507+func (s *Session) scaffold(ctx context.Context, result Result, command, file string) (Result, error) {
508+ if err := s.open(ctx, []string{"--acp-create"}); err != nil {
509+ return result, err
510+ }
511+ defer func() { _ = s.conn.Close(context.Background()) }()
512+ view, err := s.send(ctx, command)
513+ // Only the command's report: mm's welcome may come before it.
514+ if len(view.Messages) > 0 {
515+ result.Messages = view.Messages[len(view.Messages)-1:]
516+ }
517+ if err != nil {
518+ return result, err
519+ }
520+ if _, err := os.Stat(filepath.Join(result.Folder, file)); err != nil {
521+ return result, fmt.Errorf("mm did not write %s: %s", file, strings.Join(view.Messages, "\n"))
522+ }
523+ return result, nil
524+}
525+
526+// Close stops mm. Before Finish, the temporary folder is removed with what
527+// the wizard wrote in it.
528+func (s *Session) Close() {
529+ s.mu.Lock()
530+ if s.closed {
531+ s.mu.Unlock()
532+ return
533+ }
534+ s.closed = true
535+ pending, conn, finished, dir := s.pending, s.conn, s.finished, s.dir
536+ s.pending = nil
537+ s.mu.Unlock()
538+ if pending != nil {
539+ pending.reply <- acp.FormAnswer{Action: acp.FormCancel}
540+ }
541+ if conn != nil {
542+ _ = conn.Close(context.Background())
543+ }
544+ if !finished && strings.HasPrefix(filepath.Base(dir), tempPrefix) {
545+ _ = os.RemoveAll(dir)
546+ }
547+}
548+
549+// Folder is the folder the wizard writes in: the temporary one, then the
550+// agent's.
551+func (s *Session) Folder() string {
552+ s.mu.Lock()
553+ defer s.mu.Unlock()
554+ return s.dir
555+}
added internal/creator/creator_realagents_test.go +87 -0
new file mode 100644
@@ -0,0 +1,87 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+//go:build realagents
4+
5+package creator_test
6+
7+import (
8+ "context"
9+ "os"
10+ "path/filepath"
11+ "strings"
12+ "testing"
13+ "time"
14+
15+ "git.rickub.com/bots-garden/sidekicks/internal/acp"
16+ "git.rickub.com/bots-garden/sidekicks/internal/creator"
17+)
18+
19+// The real mm (MM_BIN, else mm in PATH), 1.0.9 or later. No model server is
20+// needed: without one, mm asks the model as text and the test types one.
21+func realOptions(t *testing.T) creator.Options {
22+ t.Helper()
23+ options := creator.Options{Command: os.Getenv("MM_BIN"), AgentsFolder: filepath.Join(t.TempDir(), "Documents")}
24+ if _, err := creator.Version(context.Background(), options); err != nil {
25+ t.Skip("mm 1.0.9 or later is needed:", err)
26+ }
27+ return options
28+}
29+
30+// fillIn answers a form the way a user taking every default would; a text
31+// field without a default gets a value of its own (the model, the name).
32+func fillIn(form *acp.Form, name string) acp.FormAnswer {
33+ content := map[string]any{}
34+ for _, field := range form.Fields {
35+ switch {
36+ case field.Name == "name":
37+ content[field.Name] = name
38+ case field.Default != nil:
39+ content[field.Name] = field.Default
40+ case field.Type == acp.FieldBoolean:
41+ content[field.Name] = false
42+ case len(field.Options) > 0:
43+ content[field.Name] = field.Options[0]
44+ default:
45+ content[field.Name] = "test-model"
46+ }
47+ }
48+ return acp.FormAnswer{Action: acp.FormAccept, Content: content}
49+}
50+
51+func TestRealMMCreatesAnAgentInEachEnvironment(t *testing.T) {
52+ for _, environment := range []string{creator.Local, creator.Container, creator.Sandbox} {
53+ options := realOptions(t)
54+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
55+ session, err := creator.Start(ctx, options)
56+ if err != nil {
57+ t.Fatal(err)
58+ }
59+ view, err := session.Begin(ctx)
60+ var asked []string
61+ for err == nil && view.Form != nil {
62+ for _, field := range view.Form.Fields {
63+ asked = append(asked, field.Name)
64+ }
65+ view, err = session.Answer(ctx, fillIn(view.Form, "Scout"))
66+ }
67+ if err != nil || !view.Written {
68+ t.Fatalf("%s: not written (%v): %q", environment, err, view.Messages)
69+ }
70+ if strings.Contains(" "+strings.Join(asked, " ")+" ", " project ") || strings.Contains(" "+strings.Join(asked, " ")+" ", " file ") {
71+ t.Fatalf("the .mm and file questions must not be asked: %v", asked)
72+ }
73+ if view.Name != "scout" {
74+ t.Fatalf("name %q, title %q", view.Name, view.Title)
75+ }
76+ result, err := session.Finish(ctx, view.Name, environment)
77+ if err != nil {
78+ t.Fatalf("%s: %v %q", environment, err, result.Messages)
79+ }
80+ if _, err := os.Stat(result.AgentFile); err != nil || result.AgentFile != filepath.Join(options.AgentsFolder, "scout", ".mm", "agent.yaml") {
81+ t.Fatalf("%s: %+v", environment, result)
82+ }
83+ t.Logf("%s: asked %v, title %q, messages %q", environment, asked, result.Title, result.Messages)
84+ session.Close()
85+ cancel()
86+ }
87+}
new file mode 100644
@@ -0,0 +1,87 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+//go:build realagents
4+
5+package creator_test
6+
7+import (
8+ "context"
9+ "os"
10+ "path/filepath"
11+ "strings"
12+ "testing"
13+ "time"
14+
15+ "git.rickub.com/bots-garden/sidekicks/internal/acp"
16+ "git.rickub.com/bots-garden/sidekicks/internal/creator"
17+)
18+
19+// The real mm (MM_BIN, else mm in PATH), 1.0.9 or later. No model server is
20+// needed: without one, mm asks the model as text and the test types one.
21+func realOptions(t *testing.T) creator.Options {
22+ t.Helper()
23+ options := creator.Options{Command: os.Getenv("MM_BIN"), AgentsFolder: filepath.Join(t.TempDir(), "Documents")}
24+ if _, err := creator.Version(context.Background(), options); err != nil {
25+ t.Skip("mm 1.0.9 or later is needed:", err)
26+ }
27+ return options
28+}
29+
30+// fillIn answers a form the way a user taking every default would; a text
31+// field without a default gets a value of its own (the model, the name).
32+func fillIn(form *acp.Form, name string) acp.FormAnswer {
33+ content := map[string]any{}
34+ for _, field := range form.Fields {
35+ switch {
36+ case field.Name == "name":
37+ content[field.Name] = name
38+ case field.Default != nil:
39+ content[field.Name] = field.Default
40+ case field.Type == acp.FieldBoolean:
41+ content[field.Name] = false
42+ case len(field.Options) > 0:
43+ content[field.Name] = field.Options[0]
44+ default:
45+ content[field.Name] = "test-model"
46+ }
47+ }
48+ return acp.FormAnswer{Action: acp.FormAccept, Content: content}
49+}
50+
51+func TestRealMMCreatesAnAgentInEachEnvironment(t *testing.T) {
52+ for _, environment := range []string{creator.Local, creator.Container, creator.Sandbox} {
53+ options := realOptions(t)
54+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
55+ session, err := creator.Start(ctx, options)
56+ if err != nil {
57+ t.Fatal(err)
58+ }
59+ view, err := session.Begin(ctx)
60+ var asked []string
61+ for err == nil && view.Form != nil {
62+ for _, field := range view.Form.Fields {
63+ asked = append(asked, field.Name)
64+ }
65+ view, err = session.Answer(ctx, fillIn(view.Form, "Scout"))
66+ }
67+ if err != nil || !view.Written {
68+ t.Fatalf("%s: not written (%v): %q", environment, err, view.Messages)
69+ }
70+ if strings.Contains(" "+strings.Join(asked, " ")+" ", " project ") || strings.Contains(" "+strings.Join(asked, " ")+" ", " file ") {
71+ t.Fatalf("the .mm and file questions must not be asked: %v", asked)
72+ }
73+ if view.Name != "scout" {
74+ t.Fatalf("name %q, title %q", view.Name, view.Title)
75+ }
76+ result, err := session.Finish(ctx, view.Name, environment)
77+ if err != nil {
78+ t.Fatalf("%s: %v %q", environment, err, result.Messages)
79+ }
80+ if _, err := os.Stat(result.AgentFile); err != nil || result.AgentFile != filepath.Join(options.AgentsFolder, "scout", ".mm", "agent.yaml") {
81+ t.Fatalf("%s: %+v", environment, result)
82+ }
83+ t.Logf("%s: asked %v, title %q, messages %q", environment, asked, result.Title, result.Messages)
84+ session.Close()
85+ cancel()
86+ }
87+}
added internal/creator/creator_test.go +246 -0
new file mode 100644
@@ -0,0 +1,246 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+package creator_test
4+
5+import (
6+ "context"
7+ "errors"
8+ "os"
9+ "path/filepath"
10+ "strings"
11+ "testing"
12+ "time"
13+
14+ "git.rickub.com/bots-garden/sidekicks/internal/acp"
15+ "git.rickub.com/bots-garden/sidekicks/internal/creator"
16+ "git.rickub.com/bots-garden/sidekicks/internal/creator/creatortest"
17+)
18+
19+// The test binary doubles as a fake mm (creatortest).
20+func TestMain(m *testing.M) {
21+ creatortest.RunIfFake()
22+ os.Exit(m.Run())
23+}
24+
25+func fakeMM(t *testing.T, version string) creator.Options {
26+ t.Helper()
27+ command, env := creatortest.Fake(t, version)
28+ return creator.Options{Command: command, AgentsFolder: filepath.Join(t.TempDir(), "Documents"), Env: env}
29+}
30+
31+func TestTheVersionMustBe109OrLater(t *testing.T) {
32+ cases := []struct {
33+ version string
34+ tooOld bool
35+ }{
36+ {"mm v1.0.9 (go1.27.2, darwin/arm64)", false},
37+ {"mm v1.2.0 (go1.27.2, darwin/arm64)", false},
38+ {"mm v2.0.0", false},
39+ {"mm 1.0.8 (go1.27.2, darwin/arm64)", true},
40+ {"mm v0.9.12", true},
41+ {"mm unknown (go1.27.2, linux/arm64)", false},
42+ }
43+ for _, c := range cases {
44+ options := fakeMM(t, c.version)
45+ found, err := creator.Version(context.Background(), options)
46+ var tooOld *creator.TooOldError
47+ if errors.As(err, &tooOld) != c.tooOld {
48+ t.Errorf("%q: error %v", c.version, err)
49+ }
50+ if found != c.version {
51+ t.Errorf("%q: found %q", c.version, found)
52+ }
53+ }
54+}
55+
56+func TestAMissingMMIsReported(t *testing.T) {
57+ if _, err := creator.Version(context.Background(), creator.Options{Command: "mm-that-does-not-exist"}); !errors.Is(err, creator.ErrMiniMeMissing) {
58+ t.Fatalf("Version: %v", err)
59+ }
60+ if _, err := creator.Start(context.Background(), creator.Options{Command: "mm-that-does-not-exist", AgentsFolder: t.TempDir()}); !errors.Is(err, creator.ErrMiniMeMissing) {
61+ t.Fatalf("Start: %v", err)
62+ }
63+}
64+
65+func TestNameOf(t *testing.T) {
66+ cases := map[string]string{
67+ "bob": "bob", "Bob the Builder": "bob-the-builder", " Élise ": "lise", "42 robots": "robots",
68+ "a_b-c": "a_b-c", "!!!": "", strings.Repeat("x", 40): strings.Repeat("x", 32),
69+ }
70+ for text, want := range cases {
71+ if got := creator.NameOf(text); got != want {
72+ t.Errorf("NameOf(%q) = %q, want %q", text, got, want)
73+ }
74+ }
75+}
76+
77+// begin starts a wizard and answers its form with name.
78+func begin(t *testing.T, options creator.Options, name string) *creator.Session {
79+ t.Helper()
80+ session, err := creator.Start(context.Background(), options)
81+ if err != nil {
82+ t.Fatal(err)
83+ }
84+ t.Cleanup(session.Close)
85+ view, err := session.Begin(context.Background())
86+ if err != nil {
87+ t.Fatal(err)
88+ }
89+ if view.Form == nil || len(view.Form.Fields) != 2 || view.Form.Fields[0].Name != "provider" || view.Form.Fields[1].Name != "name" {
90+ t.Fatalf("first view: %+v", view)
91+ }
92+ if len(view.Messages) == 0 || !strings.Contains(strings.Join(view.Messages, "\n"), "args=--acp-create --project yes --output .mm/agent.yaml") {
93+ t.Fatalf("messages: %q", view.Messages)
94+ }
95+ view, err = session.Answer(context.Background(), acp.FormAnswer{Action: acp.FormAccept, Content: map[string]any{"provider": "llmman", "name": name}})
96+ if err != nil {
97+ t.Fatal(err)
98+ }
99+ if !view.Written || view.Form != nil {
100+ t.Fatalf("after the form: %+v", view)
101+ }
102+ return session
103+}
104+
105+func TestTheWizardWritesInATemporaryFolderThenFinishRenamesIt(t *testing.T) {
106+ options := fakeMM(t, "mm v1.0.9")
107+ session := begin(t, options, "Bob")
108+ temporary := session.Folder()
109+ if filepath.Dir(temporary) != options.AgentsFolder || !strings.HasPrefix(filepath.Base(temporary), ".sidekicks-new-agent-") {
110+ t.Fatalf("temporary folder %s", temporary)
111+ }
112+ view := session.View()
113+ if view.Name != "bob" || view.Title != "Bob (developer)" {
114+ t.Fatalf("agent: %+v", view)
115+ }
116+ result, err := session.Finish(context.Background(), "bob", creator.Local)
117+ if err != nil {
118+ t.Fatal(err)
119+ }
120+ folder := filepath.Join(options.AgentsFolder, "bob")
121+ if result.Folder != folder || result.AgentFile != filepath.Join(folder, ".mm", "agent.yaml") || result.Title != "Bob (developer)" {
122+ t.Fatalf("result: %+v", result)
123+ }
124+ if _, err := os.Stat(result.AgentFile); err != nil {
125+ t.Fatal(err)
126+ }
127+ if info, err := os.Stat(folder); err != nil || info.Mode().Perm() != 0o755 {
128+ t.Fatalf("the agent's folder should be an ordinary one (0755): %v %v", info.Mode(), err)
129+ }
130+ if _, err := os.Stat(temporary); !os.IsNotExist(err) {
131+ t.Fatalf("the temporary folder is still there: %v", err)
132+ }
133+ session.Close()
134+ if _, err := os.Stat(result.AgentFile); err != nil {
135+ t.Fatal("Close after Finish must keep the agent")
136+ }
137+}
138+
139+func TestAnExistingFolderIsNeverTouched(t *testing.T) {
140+ options := fakeMM(t, "mm v1.0.9")
141+ session := begin(t, options, "bob")
142+ taken := filepath.Join(options.AgentsFolder, "bob")
143+ if err := os.MkdirAll(taken, 0o755); err != nil {
144+ t.Fatal(err)
145+ }
146+ if _, err := session.Finish(context.Background(), "bob", creator.Local); !errors.Is(err, creator.ErrFolderExists) {
147+ t.Fatalf("Finish: %v", err)
148+ }
149+ if entries, _ := os.ReadDir(taken); len(entries) != 0 {
150+ t.Fatal("the existing folder was changed")
151+ }
152+ if _, err := session.Finish(context.Background(), "Bob Two", creator.Local); !errors.Is(err, creator.ErrInvalidName) {
153+ t.Fatalf("an invalid name: %v", err)
154+ }
155+ result, err := session.Finish(context.Background(), "bob-2", creator.Local)
156+ if err != nil || result.Folder != filepath.Join(options.AgentsFolder, "bob-2") {
157+ t.Fatalf("another name: %+v %v", result, err)
158+ }
159+}
160+
161+func TestAContainerOrASandboxGetsItsFilesFromMM(t *testing.T) {
162+ for environment, file := range map[string]string{creator.Container: "compose.yaml", creator.Sandbox: "sbxenv.yaml"} {
163+ options := fakeMM(t, "mm v1.0.9")
164+ session := begin(t, options, "bob")
165+ result, err := session.Finish(context.Background(), "bob", environment)
166+ if err != nil {
167+ t.Fatalf("%s: %v", environment, err)
168+ }
169+ if _, err := os.Stat(filepath.Join(result.Folder, file)); err != nil {
170+ t.Fatalf("%s: %v", environment, err)
171+ }
172+ if result.Environment != environment || len(result.Messages) != 1 || !strings.Contains(result.Messages[0], "wrote "+file) {
173+ t.Fatalf("%s: %+v", environment, result)
174+ }
175+ }
176+}
177+
178+func TestCloseBeforeFinishRemovesTheTemporaryFolder(t *testing.T) {
179+ options := fakeMM(t, "mm v1.0.9")
180+ session, err := creator.Start(context.Background(), options)
181+ if err != nil {
182+ t.Fatal(err)
183+ }
184+ if _, err := session.Begin(context.Background()); err != nil {
185+ t.Fatal(err)
186+ }
187+ // A form is waiting: Close cancels it and stops mm.
188+ temporary := session.Folder()
189+ session.Close()
190+ if _, err := os.Stat(temporary); !os.IsNotExist(err) {
191+ t.Fatalf("the temporary folder is still there: %v", err)
192+ }
193+ if _, err := session.Send(context.Background(), "hello"); !errors.Is(err, creator.ErrClosed) {
194+ t.Fatalf("Send after Close: %v", err)
195+ }
196+}
197+
198+func TestADeclinedFormEndsTheTurnWithMMsMessage(t *testing.T) {
199+ session, err := creator.Start(context.Background(), fakeMM(t, "mm v1.0.9"))
200+ if err != nil {
201+ t.Fatal(err)
202+ }
203+ defer session.Close()
204+ if _, err := session.Begin(context.Background()); err != nil {
205+ t.Fatal(err)
206+ }
207+ if _, err := session.Send(context.Background(), "/back"); !errors.Is(err, creator.ErrBusy) {
208+ t.Fatalf("Send while a form waits: %v", err)
209+ }
210+ view, err := session.Answer(context.Background(), acp.FormAnswer{Action: acp.FormDecline})
211+ if err != nil {
212+ t.Fatal(err)
213+ }
214+ if view.Form != nil || view.Written || len(view.Messages) != 1 || !strings.HasPrefix(view.Messages[0], "Stopped") {
215+ t.Fatalf("view: %+v", view)
216+ }
217+ if _, err := session.Finish(context.Background(), "bob", creator.Local); !errors.Is(err, creator.ErrNotWritten) {
218+ t.Fatalf("Finish before the agent is written: %v", err)
219+ }
220+}
221+
222+func TestStaleTemporaryFoldersAreRemoved(t *testing.T) {
223+ options := fakeMM(t, "mm v1.0.9")
224+ stale := filepath.Join(options.AgentsFolder, ".sidekicks-new-agent-old")
225+ recent := filepath.Join(options.AgentsFolder, ".sidekicks-new-agent-recent")
226+ for _, folder := range []string{stale, recent} {
227+ if err := os.MkdirAll(folder, 0o755); err != nil {
228+ t.Fatal(err)
229+ }
230+ }
231+ old := time.Now().Add(-48 * time.Hour)
232+ if err := os.Chtimes(stale, old, old); err != nil {
233+ t.Fatal(err)
234+ }
235+ session, err := creator.Start(context.Background(), options)
236+ if err != nil {
237+ t.Fatal(err)
238+ }
239+ defer session.Close()
240+ if _, err := os.Stat(stale); !os.IsNotExist(err) {
241+ t.Fatal("a folder left two days ago should be removed")
242+ }
243+ if _, err := os.Stat(recent); err != nil {
244+ t.Fatal("a recent folder may belong to another window: it stays")
245+ }
246+}
new file mode 100644
@@ -0,0 +1,246 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+package creator_test
4+
5+import (
6+ "context"
7+ "errors"
8+ "os"
9+ "path/filepath"
10+ "strings"
11+ "testing"
12+ "time"
13+
14+ "git.rickub.com/bots-garden/sidekicks/internal/acp"
15+ "git.rickub.com/bots-garden/sidekicks/internal/creator"
16+ "git.rickub.com/bots-garden/sidekicks/internal/creator/creatortest"
17+)
18+
19+// The test binary doubles as a fake mm (creatortest).
20+func TestMain(m *testing.M) {
21+ creatortest.RunIfFake()
22+ os.Exit(m.Run())
23+}
24+
25+func fakeMM(t *testing.T, version string) creator.Options {
26+ t.Helper()
27+ command, env := creatortest.Fake(t, version)
28+ return creator.Options{Command: command, AgentsFolder: filepath.Join(t.TempDir(), "Documents"), Env: env}
29+}
30+
31+func TestTheVersionMustBe109OrLater(t *testing.T) {
32+ cases := []struct {
33+ version string
34+ tooOld bool
35+ }{
36+ {"mm v1.0.9 (go1.27.2, darwin/arm64)", false},
37+ {"mm v1.2.0 (go1.27.2, darwin/arm64)", false},
38+ {"mm v2.0.0", false},
39+ {"mm 1.0.8 (go1.27.2, darwin/arm64)", true},
40+ {"mm v0.9.12", true},
41+ {"mm unknown (go1.27.2, linux/arm64)", false},
42+ }
43+ for _, c := range cases {
44+ options := fakeMM(t, c.version)
45+ found, err := creator.Version(context.Background(), options)
46+ var tooOld *creator.TooOldError
47+ if errors.As(err, &tooOld) != c.tooOld {
48+ t.Errorf("%q: error %v", c.version, err)
49+ }
50+ if found != c.version {
51+ t.Errorf("%q: found %q", c.version, found)
52+ }
53+ }
54+}
55+
56+func TestAMissingMMIsReported(t *testing.T) {
57+ if _, err := creator.Version(context.Background(), creator.Options{Command: "mm-that-does-not-exist"}); !errors.Is(err, creator.ErrMiniMeMissing) {
58+ t.Fatalf("Version: %v", err)
59+ }
60+ if _, err := creator.Start(context.Background(), creator.Options{Command: "mm-that-does-not-exist", AgentsFolder: t.TempDir()}); !errors.Is(err, creator.ErrMiniMeMissing) {
61+ t.Fatalf("Start: %v", err)
62+ }
63+}
64+
65+func TestNameOf(t *testing.T) {
66+ cases := map[string]string{
67+ "bob": "bob", "Bob the Builder": "bob-the-builder", " Élise ": "lise", "42 robots": "robots",
68+ "a_b-c": "a_b-c", "!!!": "", strings.Repeat("x", 40): strings.Repeat("x", 32),
69+ }
70+ for text, want := range cases {
71+ if got := creator.NameOf(text); got != want {
72+ t.Errorf("NameOf(%q) = %q, want %q", text, got, want)
73+ }
74+ }
75+}
76+
77+// begin starts a wizard and answers its form with name.
78+func begin(t *testing.T, options creator.Options, name string) *creator.Session {
79+ t.Helper()
80+ session, err := creator.Start(context.Background(), options)
81+ if err != nil {
82+ t.Fatal(err)
83+ }
84+ t.Cleanup(session.Close)
85+ view, err := session.Begin(context.Background())
86+ if err != nil {
87+ t.Fatal(err)
88+ }
89+ if view.Form == nil || len(view.Form.Fields) != 2 || view.Form.Fields[0].Name != "provider" || view.Form.Fields[1].Name != "name" {
90+ t.Fatalf("first view: %+v", view)
91+ }
92+ if len(view.Messages) == 0 || !strings.Contains(strings.Join(view.Messages, "\n"), "args=--acp-create --project yes --output .mm/agent.yaml") {
93+ t.Fatalf("messages: %q", view.Messages)
94+ }
95+ view, err = session.Answer(context.Background(), acp.FormAnswer{Action: acp.FormAccept, Content: map[string]any{"provider": "llmman", "name": name}})
96+ if err != nil {
97+ t.Fatal(err)
98+ }
99+ if !view.Written || view.Form != nil {
100+ t.Fatalf("after the form: %+v", view)
101+ }
102+ return session
103+}
104+
105+func TestTheWizardWritesInATemporaryFolderThenFinishRenamesIt(t *testing.T) {
106+ options := fakeMM(t, "mm v1.0.9")
107+ session := begin(t, options, "Bob")
108+ temporary := session.Folder()
109+ if filepath.Dir(temporary) != options.AgentsFolder || !strings.HasPrefix(filepath.Base(temporary), ".sidekicks-new-agent-") {
110+ t.Fatalf("temporary folder %s", temporary)
111+ }
112+ view := session.View()
113+ if view.Name != "bob" || view.Title != "Bob (developer)" {
114+ t.Fatalf("agent: %+v", view)
115+ }
116+ result, err := session.Finish(context.Background(), "bob", creator.Local)
117+ if err != nil {
118+ t.Fatal(err)
119+ }
120+ folder := filepath.Join(options.AgentsFolder, "bob")
121+ if result.Folder != folder || result.AgentFile != filepath.Join(folder, ".mm", "agent.yaml") || result.Title != "Bob (developer)" {
122+ t.Fatalf("result: %+v", result)
123+ }
124+ if _, err := os.Stat(result.AgentFile); err != nil {
125+ t.Fatal(err)
126+ }
127+ if info, err := os.Stat(folder); err != nil || info.Mode().Perm() != 0o755 {
128+ t.Fatalf("the agent's folder should be an ordinary one (0755): %v %v", info.Mode(), err)
129+ }
130+ if _, err := os.Stat(temporary); !os.IsNotExist(err) {
131+ t.Fatalf("the temporary folder is still there: %v", err)
132+ }
133+ session.Close()
134+ if _, err := os.Stat(result.AgentFile); err != nil {
135+ t.Fatal("Close after Finish must keep the agent")
136+ }
137+}
138+
139+func TestAnExistingFolderIsNeverTouched(t *testing.T) {
140+ options := fakeMM(t, "mm v1.0.9")
141+ session := begin(t, options, "bob")
142+ taken := filepath.Join(options.AgentsFolder, "bob")
143+ if err := os.MkdirAll(taken, 0o755); err != nil {
144+ t.Fatal(err)
145+ }
146+ if _, err := session.Finish(context.Background(), "bob", creator.Local); !errors.Is(err, creator.ErrFolderExists) {
147+ t.Fatalf("Finish: %v", err)
148+ }
149+ if entries, _ := os.ReadDir(taken); len(entries) != 0 {
150+ t.Fatal("the existing folder was changed")
151+ }
152+ if _, err := session.Finish(context.Background(), "Bob Two", creator.Local); !errors.Is(err, creator.ErrInvalidName) {
153+ t.Fatalf("an invalid name: %v", err)
154+ }
155+ result, err := session.Finish(context.Background(), "bob-2", creator.Local)
156+ if err != nil || result.Folder != filepath.Join(options.AgentsFolder, "bob-2") {
157+ t.Fatalf("another name: %+v %v", result, err)
158+ }
159+}
160+
161+func TestAContainerOrASandboxGetsItsFilesFromMM(t *testing.T) {
162+ for environment, file := range map[string]string{creator.Container: "compose.yaml", creator.Sandbox: "sbxenv.yaml"} {
163+ options := fakeMM(t, "mm v1.0.9")
164+ session := begin(t, options, "bob")
165+ result, err := session.Finish(context.Background(), "bob", environment)
166+ if err != nil {
167+ t.Fatalf("%s: %v", environment, err)
168+ }
169+ if _, err := os.Stat(filepath.Join(result.Folder, file)); err != nil {
170+ t.Fatalf("%s: %v", environment, err)
171+ }
172+ if result.Environment != environment || len(result.Messages) != 1 || !strings.Contains(result.Messages[0], "wrote "+file) {
173+ t.Fatalf("%s: %+v", environment, result)
174+ }
175+ }
176+}
177+
178+func TestCloseBeforeFinishRemovesTheTemporaryFolder(t *testing.T) {
179+ options := fakeMM(t, "mm v1.0.9")
180+ session, err := creator.Start(context.Background(), options)
181+ if err != nil {
182+ t.Fatal(err)
183+ }
184+ if _, err := session.Begin(context.Background()); err != nil {
185+ t.Fatal(err)
186+ }
187+ // A form is waiting: Close cancels it and stops mm.
188+ temporary := session.Folder()
189+ session.Close()
190+ if _, err := os.Stat(temporary); !os.IsNotExist(err) {
191+ t.Fatalf("the temporary folder is still there: %v", err)
192+ }
193+ if _, err := session.Send(context.Background(), "hello"); !errors.Is(err, creator.ErrClosed) {
194+ t.Fatalf("Send after Close: %v", err)
195+ }
196+}
197+
198+func TestADeclinedFormEndsTheTurnWithMMsMessage(t *testing.T) {
199+ session, err := creator.Start(context.Background(), fakeMM(t, "mm v1.0.9"))
200+ if err != nil {
201+ t.Fatal(err)
202+ }
203+ defer session.Close()
204+ if _, err := session.Begin(context.Background()); err != nil {
205+ t.Fatal(err)
206+ }
207+ if _, err := session.Send(context.Background(), "/back"); !errors.Is(err, creator.ErrBusy) {
208+ t.Fatalf("Send while a form waits: %v", err)
209+ }
210+ view, err := session.Answer(context.Background(), acp.FormAnswer{Action: acp.FormDecline})
211+ if err != nil {
212+ t.Fatal(err)
213+ }
214+ if view.Form != nil || view.Written || len(view.Messages) != 1 || !strings.HasPrefix(view.Messages[0], "Stopped") {
215+ t.Fatalf("view: %+v", view)
216+ }
217+ if _, err := session.Finish(context.Background(), "bob", creator.Local); !errors.Is(err, creator.ErrNotWritten) {
218+ t.Fatalf("Finish before the agent is written: %v", err)
219+ }
220+}
221+
222+func TestStaleTemporaryFoldersAreRemoved(t *testing.T) {
223+ options := fakeMM(t, "mm v1.0.9")
224+ stale := filepath.Join(options.AgentsFolder, ".sidekicks-new-agent-old")
225+ recent := filepath.Join(options.AgentsFolder, ".sidekicks-new-agent-recent")
226+ for _, folder := range []string{stale, recent} {
227+ if err := os.MkdirAll(folder, 0o755); err != nil {
228+ t.Fatal(err)
229+ }
230+ }
231+ old := time.Now().Add(-48 * time.Hour)
232+ if err := os.Chtimes(stale, old, old); err != nil {
233+ t.Fatal(err)
234+ }
235+ session, err := creator.Start(context.Background(), options)
236+ if err != nil {
237+ t.Fatal(err)
238+ }
239+ defer session.Close()
240+ if _, err := os.Stat(stale); !os.IsNotExist(err) {
241+ t.Fatal("a folder left two days ago should be removed")
242+ }
243+ if _, err := os.Stat(recent); err != nil {
244+ t.Fatal("a recent folder may belong to another window: it stays")
245+ }
246+}
added internal/creator/creatortest/creatortest.go +144 -0
new file mode 100644
@@ -0,0 +1,144 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+// Package creatortest is a fake mm for the tests of the mini-me creation
4+// assistant (issue #94): a test binary that calls RunIfFake in its TestMain
5+// becomes, when Fake started it, an mm that answers --version and serves a
6+// short --acp-create wizard: one form (provider, name), then
7+// .mm/agent.yaml; /dockerinit and /sbxinit write their file.
8+package creatortest
9+
10+import (
11+ "context"
12+ "fmt"
13+ "os"
14+ "path/filepath"
15+ "strings"
16+ "testing"
17+
18+ sdk "github.com/coder/acp-go-sdk"
19+)
20+
21+const variable = "SIDEKICKS_FAKE_MM"
22+
23+// RunIfFake turns the test binary into the fake mm when Fake started it,
24+// and exits; otherwise it returns at once.
25+func RunIfFake() {
26+ if version := os.Getenv(variable); version != "" {
27+ runFakeMM(version, os.Args[1:])
28+ os.Exit(0)
29+ }
30+}
31+
32+// Fake copies the test binary to a folder of its own under the name mm, so
33+// that it is found by name like the real one, and returns its path and the
34+// environment that makes it the fake mm answering version to --version.
35+func Fake(t *testing.T, version string) (string, map[string]string) {
36+ t.Helper()
37+ self, err := os.Executable()
38+ if err != nil {
39+ t.Fatal(err)
40+ }
41+ content, err := os.ReadFile(self)
42+ if err != nil {
43+ t.Fatal(err)
44+ }
45+ command := filepath.Join(t.TempDir(), "mm")
46+ if err := os.WriteFile(command, content, 0o755); err != nil {
47+ t.Fatal(err)
48+ }
49+ return command, map[string]string{variable: version}
50+}
51+
52+func runFakeMM(version string, args []string) {
53+ if len(args) > 0 && args[0] == "--version" {
54+ fmt.Println(version)
55+ return
56+ }
57+ agent := &fakeAgent{args: strings.Join(args, " ")}
58+ agent.conn = sdk.NewAgentSideConnection(agent, os.Stdout, os.Stdin)
59+ <-agent.conn.Done()
60+}
61+
62+type fakeAgent struct {
63+ args string
64+ conn *sdk.AgentSideConnection
65+ cwd string
66+}
67+
68+func (*fakeAgent) Initialize(context.Context, sdk.InitializeRequest) (sdk.InitializeResponse, error) {
69+ return sdk.InitializeResponse{ProtocolVersion: 1, AgentInfo: &sdk.Implementation{Name: "mm-acp-create", Version: "1.0.9"}, AuthMethods: []sdk.AuthMethod{}}, nil
70+}
71+
72+func (a *fakeAgent) NewSession(_ context.Context, request sdk.NewSessionRequest) (sdk.NewSessionResponse, error) {
73+ a.cwd = request.Cwd
74+ return sdk.NewSessionResponse{SessionId: "create-1"}, nil
75+}
76+
77+// Prompt plays mm acp-create in short: /start asks one form (provider and
78+// name) and writes .mm/agent.yaml; /dockerinit and /sbxinit write their file.
79+func (a *fakeAgent) Prompt(ctx context.Context, request sdk.PromptRequest) (sdk.PromptResponse, error) {
80+ say := func(text string) {
81+ _ = a.conn.SessionUpdate(ctx, sdk.SessionNotification{SessionId: request.SessionId, Update: sdk.UpdateAgentMessageText(text)})
82+ }
83+ done := sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn}
84+ switch text := request.Prompt[0].Text.Text; text {
85+ case "/dockerinit", "/sbxinit":
86+ file := map[string]string{"/dockerinit": "compose.yaml", "/sbxinit": "sbxenv.yaml"}[text]
87+ content := map[string]string{
88+ "/dockerinit": "services:\n bob:\n container_name: bob-box\n",
89+ "/sbxinit": "schemaVersion: \"1\"\nname: bob-sbx\nagent: mini-me-kit\nworkspace: .\n",
90+ }[text]
91+ _ = os.WriteFile(filepath.Join(a.cwd, file), []byte(content), 0o644)
92+ say("✅ wrote " + file)
93+ return done, nil
94+ }
95+ say("**mm init** — args=" + a.args)
96+ req := sdk.NewUnstableCreateElicitationRequestForm(sdk.UnstableElicitationSchema{
97+ Type: sdk.UnstableElicitationSchemaTypeObject,
98+ Properties: map[string]any{
99+ "provider": map[string]any{"type": "string", "title": "Model server?", "enum": []any{"llmman", "ollama"}, "default": "llmman"},
100+ "name": map[string]any{"type": "string", "title": "Agent name?", "default": "developer"},
101+ },
102+ Required: []string{"provider", "name"},
103+ })
104+ resp, err := a.conn.UnstableCreateElicitation(ctx, req)
105+ switch {
106+ case err != nil || resp.Cancel != nil:
107+ say("The form was closed: nothing written.")
108+ case resp.Decline != nil:
109+ say("Stopped: nothing written.")
110+ default:
111+ name := fmt.Sprint(resp.Accept.Content["name"])
112+ _ = os.MkdirAll(filepath.Join(a.cwd, ".mm"), 0o755)
113+ content := fmt.Sprintf("acp:\n name: %s\n title: %q\n", strings.ToLower(name), name+" (developer)")
114+ _ = os.WriteFile(filepath.Join(a.cwd, ".mm", "agent.yaml"), []byte(content), 0o644)
115+ say("✅ wrote .mm/agent.yaml")
116+ }
117+ return done, nil
118+}
119+
120+func (*fakeAgent) Authenticate(context.Context, sdk.AuthenticateRequest) (sdk.AuthenticateResponse, error) {
121+ return sdk.AuthenticateResponse{}, nil
122+}
123+func (*fakeAgent) Logout(context.Context, sdk.LogoutRequest) (sdk.LogoutResponse, error) {
124+ return sdk.LogoutResponse{}, nil
125+}
126+func (*fakeAgent) Cancel(context.Context, sdk.CancelNotification) error { return nil }
127+func (*fakeAgent) CloseSession(context.Context, sdk.CloseSessionRequest) (sdk.CloseSessionResponse, error) {
128+ return sdk.CloseSessionResponse{}, nil
129+}
130+func (*fakeAgent) ListSessions(context.Context, sdk.ListSessionsRequest) (sdk.ListSessionsResponse, error) {
131+ return sdk.ListSessionsResponse{}, sdk.NewMethodNotFound("session/list")
132+}
133+func (*fakeAgent) LoadSession(context.Context, sdk.LoadSessionRequest) (sdk.LoadSessionResponse, error) {
134+ return sdk.LoadSessionResponse{}, sdk.NewMethodNotFound("session/load")
135+}
136+func (*fakeAgent) ResumeSession(context.Context, sdk.ResumeSessionRequest) (sdk.ResumeSessionResponse, error) {
137+ return sdk.ResumeSessionResponse{}, sdk.NewMethodNotFound("session/resume")
138+}
139+func (*fakeAgent) SetSessionConfigOption(context.Context, sdk.SetSessionConfigOptionRequest) (sdk.SetSessionConfigOptionResponse, error) {
140+ return sdk.SetSessionConfigOptionResponse{}, sdk.NewMethodNotFound("session/set_config_option")
141+}
142+func (*fakeAgent) SetSessionMode(context.Context, sdk.SetSessionModeRequest) (sdk.SetSessionModeResponse, error) {
143+ return sdk.SetSessionModeResponse{}, sdk.NewMethodNotFound("session/set_mode")
144+}
new file mode 100644
@@ -0,0 +1,144 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+// Package creatortest is a fake mm for the tests of the mini-me creation
4+// assistant (issue #94): a test binary that calls RunIfFake in its TestMain
5+// becomes, when Fake started it, an mm that answers --version and serves a
6+// short --acp-create wizard: one form (provider, name), then
7+// .mm/agent.yaml; /dockerinit and /sbxinit write their file.
8+package creatortest
9+
10+import (
11+ "context"
12+ "fmt"
13+ "os"
14+ "path/filepath"
15+ "strings"
16+ "testing"
17+
18+ sdk "github.com/coder/acp-go-sdk"
19+)
20+
21+const variable = "SIDEKICKS_FAKE_MM"
22+
23+// RunIfFake turns the test binary into the fake mm when Fake started it,
24+// and exits; otherwise it returns at once.
25+func RunIfFake() {
26+ if version := os.Getenv(variable); version != "" {
27+ runFakeMM(version, os.Args[1:])
28+ os.Exit(0)
29+ }
30+}
31+
32+// Fake copies the test binary to a folder of its own under the name mm, so
33+// that it is found by name like the real one, and returns its path and the
34+// environment that makes it the fake mm answering version to --version.
35+func Fake(t *testing.T, version string) (string, map[string]string) {
36+ t.Helper()
37+ self, err := os.Executable()
38+ if err != nil {
39+ t.Fatal(err)
40+ }
41+ content, err := os.ReadFile(self)
42+ if err != nil {
43+ t.Fatal(err)
44+ }
45+ command := filepath.Join(t.TempDir(), "mm")
46+ if err := os.WriteFile(command, content, 0o755); err != nil {
47+ t.Fatal(err)
48+ }
49+ return command, map[string]string{variable: version}
50+}
51+
52+func runFakeMM(version string, args []string) {
53+ if len(args) > 0 && args[0] == "--version" {
54+ fmt.Println(version)
55+ return
56+ }
57+ agent := &fakeAgent{args: strings.Join(args, " ")}
58+ agent.conn = sdk.NewAgentSideConnection(agent, os.Stdout, os.Stdin)
59+ <-agent.conn.Done()
60+}
61+
62+type fakeAgent struct {
63+ args string
64+ conn *sdk.AgentSideConnection
65+ cwd string
66+}
67+
68+func (*fakeAgent) Initialize(context.Context, sdk.InitializeRequest) (sdk.InitializeResponse, error) {
69+ return sdk.InitializeResponse{ProtocolVersion: 1, AgentInfo: &sdk.Implementation{Name: "mm-acp-create", Version: "1.0.9"}, AuthMethods: []sdk.AuthMethod{}}, nil
70+}
71+
72+func (a *fakeAgent) NewSession(_ context.Context, request sdk.NewSessionRequest) (sdk.NewSessionResponse, error) {
73+ a.cwd = request.Cwd
74+ return sdk.NewSessionResponse{SessionId: "create-1"}, nil
75+}
76+
77+// Prompt plays mm acp-create in short: /start asks one form (provider and
78+// name) and writes .mm/agent.yaml; /dockerinit and /sbxinit write their file.
79+func (a *fakeAgent) Prompt(ctx context.Context, request sdk.PromptRequest) (sdk.PromptResponse, error) {
80+ say := func(text string) {
81+ _ = a.conn.SessionUpdate(ctx, sdk.SessionNotification{SessionId: request.SessionId, Update: sdk.UpdateAgentMessageText(text)})
82+ }
83+ done := sdk.PromptResponse{StopReason: sdk.StopReasonEndTurn}
84+ switch text := request.Prompt[0].Text.Text; text {
85+ case "/dockerinit", "/sbxinit":
86+ file := map[string]string{"/dockerinit": "compose.yaml", "/sbxinit": "sbxenv.yaml"}[text]
87+ content := map[string]string{
88+ "/dockerinit": "services:\n bob:\n container_name: bob-box\n",
89+ "/sbxinit": "schemaVersion: \"1\"\nname: bob-sbx\nagent: mini-me-kit\nworkspace: .\n",
90+ }[text]
91+ _ = os.WriteFile(filepath.Join(a.cwd, file), []byte(content), 0o644)
92+ say("✅ wrote " + file)
93+ return done, nil
94+ }
95+ say("**mm init** — args=" + a.args)
96+ req := sdk.NewUnstableCreateElicitationRequestForm(sdk.UnstableElicitationSchema{
97+ Type: sdk.UnstableElicitationSchemaTypeObject,
98+ Properties: map[string]any{
99+ "provider": map[string]any{"type": "string", "title": "Model server?", "enum": []any{"llmman", "ollama"}, "default": "llmman"},
100+ "name": map[string]any{"type": "string", "title": "Agent name?", "default": "developer"},
101+ },
102+ Required: []string{"provider", "name"},
103+ })
104+ resp, err := a.conn.UnstableCreateElicitation(ctx, req)
105+ switch {
106+ case err != nil || resp.Cancel != nil:
107+ say("The form was closed: nothing written.")
108+ case resp.Decline != nil:
109+ say("Stopped: nothing written.")
110+ default:
111+ name := fmt.Sprint(resp.Accept.Content["name"])
112+ _ = os.MkdirAll(filepath.Join(a.cwd, ".mm"), 0o755)
113+ content := fmt.Sprintf("acp:\n name: %s\n title: %q\n", strings.ToLower(name), name+" (developer)")
114+ _ = os.WriteFile(filepath.Join(a.cwd, ".mm", "agent.yaml"), []byte(content), 0o644)
115+ say("✅ wrote .mm/agent.yaml")
116+ }
117+ return done, nil
118+}
119+
120+func (*fakeAgent) Authenticate(context.Context, sdk.AuthenticateRequest) (sdk.AuthenticateResponse, error) {
121+ return sdk.AuthenticateResponse{}, nil
122+}
123+func (*fakeAgent) Logout(context.Context, sdk.LogoutRequest) (sdk.LogoutResponse, error) {
124+ return sdk.LogoutResponse{}, nil
125+}
126+func (*fakeAgent) Cancel(context.Context, sdk.CancelNotification) error { return nil }
127+func (*fakeAgent) CloseSession(context.Context, sdk.CloseSessionRequest) (sdk.CloseSessionResponse, error) {
128+ return sdk.CloseSessionResponse{}, nil
129+}
130+func (*fakeAgent) ListSessions(context.Context, sdk.ListSessionsRequest) (sdk.ListSessionsResponse, error) {
131+ return sdk.ListSessionsResponse{}, sdk.NewMethodNotFound("session/list")
132+}
133+func (*fakeAgent) LoadSession(context.Context, sdk.LoadSessionRequest) (sdk.LoadSessionResponse, error) {
134+ return sdk.LoadSessionResponse{}, sdk.NewMethodNotFound("session/load")
135+}
136+func (*fakeAgent) ResumeSession(context.Context, sdk.ResumeSessionRequest) (sdk.ResumeSessionResponse, error) {
137+ return sdk.ResumeSessionResponse{}, sdk.NewMethodNotFound("session/resume")
138+}
139+func (*fakeAgent) SetSessionConfigOption(context.Context, sdk.SetSessionConfigOptionRequest) (sdk.SetSessionConfigOptionResponse, error) {
140+ return sdk.SetSessionConfigOptionResponse{}, sdk.NewMethodNotFound("session/set_config_option")
141+}
142+func (*fakeAgent) SetSessionMode(context.Context, sdk.SetSessionModeRequest) (sdk.SetSessionModeResponse, error) {
143+ return sdk.SetSessionModeResponse{}, sdk.NewMethodNotFound("session/set_mode")
144+}
modified internal/lifecycle/lifecycle.go +6 -0
@@ -219,6 +219,12 @@ func (r Runner) command(ctx context.Context, agent config.Agent, command []strin
219219 process := exec.CommandContext(ctx, program, command[1:]...)
220220 process.Dir = agent.Runtime.Lifecycle.Folder
221221 process.Env = os.Environ()
222+ if process.Dir != "" {
223+ // PWD is the folder, as in a terminal: the compose.yaml of mm
224+ // dockerinit mounts ${PWD}, and Sidekicks' own PWD is wherever it
225+ // was started from ("/" from the Finder).
226+ process.Env = append(process.Env, "PWD="+process.Dir)
227+ }
222228 for key, value := range agent.Env {
223229 process.Env = append(process.Env, key+"="+value)
224230 }
@@ -219,6 +219,12 @@ func (r Runner) command(ctx context.Context, agent config.Agent, command []strin
219 process := exec.CommandContext(ctx, program, command[1:]...)219 process := exec.CommandContext(ctx, program, command[1:]...)
220 process.Dir = agent.Runtime.Lifecycle.Folder220 process.Dir = agent.Runtime.Lifecycle.Folder
221 process.Env = os.Environ()221 process.Env = os.Environ()
222+ if process.Dir != "" {
223+ // PWD is the folder, as in a terminal: the compose.yaml of mm
224+ // dockerinit mounts ${PWD}, and Sidekicks' own PWD is wherever it
225+ // was started from ("/" from the Finder).
226+ process.Env = append(process.Env, "PWD="+process.Dir)
227+ }
222 for key, value := range agent.Env {228 for key, value := range agent.Env {
223 process.Env = append(process.Env, key+"="+value)229 process.Env = append(process.Env, key+"="+value)
224 }230 }
modified internal/lifecycle/lifecycle_test.go +15 -0
@@ -170,3 +170,18 @@ func TestRunReportsAFailingCommand(t *testing.T) {
170170 t.Fatalf("want the command error, got %v", err)
171171 }
172172 }
173+
174+// A command sees PWD set to its folder, like in a terminal (issue #94: the
175+// compose.yaml of mm dockerinit mounts ${PWD}).
176+func TestACommandRunsWithPWDSetToItsFolder(t *testing.T) {
177+ f := setup(t)
178+ folder := t.TempDir()
179+ agent := milo(folder)
180+ agent.Runtime.Lifecycle.Stop = []string{"env"}
181+ if err := f.runner.Run(ctx, agent, lifecycle.Stop, f.log); err != nil {
182+ t.Fatal(err)
183+ }
184+ if !slices.Contains(f.logs, "PWD="+folder) {
185+ t.Fatalf("PWD should be %s: %q", folder, f.logs)
186+ }
187+}
@@ -170,3 +170,18 @@ func TestRunReportsAFailingCommand(t *testing.T) {
170 t.Fatalf("want the command error, got %v", err)170 t.Fatalf("want the command error, got %v", err)
171 }171 }
172 }172 }
173+
174+// A command sees PWD set to its folder, like in a terminal (issue #94: the
175+// compose.yaml of mm dockerinit mounts ${PWD}).
176+func TestACommandRunsWithPWDSetToItsFolder(t *testing.T) {
177+ f := setup(t)
178+ folder := t.TempDir()
179+ agent := milo(folder)
180+ agent.Runtime.Lifecycle.Stop = []string{"env"}
181+ if err := f.runner.Run(ctx, agent, lifecycle.Stop, f.log); err != nil {
182+ t.Fatal(err)
183+ }
184+ if !slices.Contains(f.logs, "PWD="+folder) {
185+ t.Fatalf("PWD should be %s: %q", folder, f.logs)
186+ }
187+}
modified main.go +1 -0
@@ -139,6 +139,7 @@ func main() {
139139 application.NewService(&app.ChannelService{Core: core}),
140140 application.NewService(&app.WorkspaceService{Core: core}),
141141 application.NewService(&app.TerminalService{Core: core}),
142+ application.NewService(&app.CreatorService{Core: core}),
142143 application.NewService(&app.SystemService{}),
143144 },
144145 Assets: application.AssetOptions{Handler: application.AssetFileServerFS(assets)},
@@ -139,6 +139,7 @@ func main() {
139 application.NewService(&app.ChannelService{Core: core}),139 application.NewService(&app.ChannelService{Core: core}),
140 application.NewService(&app.WorkspaceService{Core: core}),140 application.NewService(&app.WorkspaceService{Core: core}),
141 application.NewService(&app.TerminalService{Core: core}),141 application.NewService(&app.TerminalService{Core: core}),
142+ application.NewService(&app.CreatorService{Core: core}),
142 application.NewService(&app.SystemService{}),143 application.NewService(&app.SystemService{}),
143 },144 },
144 Assets: application.AssetOptions{Handler: application.AssetFileServerFS(assets)},145 Assets: application.AssetOptions{Handler: application.AssetFileServerFS(assets)},
modified schema/config.schema.json +6 -0
@@ -23,6 +23,12 @@
2323 "agentTools": {
2424 "$ref": "#/$defs/agentTools"
2525 },
26+ "agentsFolder": {
27+ "description": "Where the assistant that creates mini-me agents makes one folder per agent: an absolute path, ~/… (your home folder) or a path relative to this file. Default: your Documents folder.",
28+ "type": "string",
29+ "minLength": 1,
30+ "default": "~/Documents"
31+ },
2632 "agents": {
2733 "description": "The agents available with @name. Names must be unique.",
2834 "type": "array",
@@ -23,6 +23,12 @@
23 "agentTools": {23 "agentTools": {
24 "$ref": "#/$defs/agentTools"24 "$ref": "#/$defs/agentTools"
25 },25 },
26+ "agentsFolder": {
27+ "description": "Where the assistant that creates mini-me agents makes one folder per agent: an absolute path, ~/… (your home folder) or a path relative to this file. Default: your Documents folder.",
28+ "type": "string",
29+ "minLength": 1,
30+ "default": "~/Documents"
31+ },
26 "agents": {32 "agents": {
27 "description": "The agents available with @name. Names must be unique.",33 "description": "The agents available with @name. Names must be unique.",
28 "type": "array",34 "type": "array",