Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(agents): create agents from starters, a blank sheet or an imported template (#902)
Ruben Lütke07f63627fd67
diff --git a/dodaios/society/starters.py b/dodaios/society/starters.pynew file mode 100644index 0000000000..5e3b05fbd4--- /dev/null+++ b/dodaios/society/starters.py@@ -0,0 +1,294 @@+"""Job-shaped starter agents for the New-agent dialog.++A starter is an agent template (``agent_template``) plus what the dialog+needs to offer it: the area it belongs to, a one-line outcome, the tools it+suggests, the first message it proposes and, optionally, one routine. The+catalogue is our own data under ``starters/*.json`` (one file per area) and+every template in it passes ``agent_template.validate_template`` — the same+stranger-safety rules a marketplace template meets. So a starter carries no+seat (the installer's provider and runtime decide), names no machine, and+never widens approvals: ``require_approval`` can only add confirmations.++Pure functions over the files and the capability catalog; the routes in+``dodaios/ui/web/society_routes.py`` serve them.+"""++from __future__ import annotations++import copy+import json+import logging+import re+from collections.abc import Iterable, Mapping+from dataclasses import dataclass, field+from functools import lru_cache+from pathlib import Path+from typing import Any, Final++from .agent_template import validate_template++log = logging.getLogger(__name__)++__all__ = [+ "AREAS",+ "ROUTINE_SCHEDULES",+ "Starter",+ "StarterError",+ "load_starters",+ "preview_payload",+ "routine_schedule",+ "starter_by_id",+ "starter_payload",+ "starter_template",+ "template_summary",+ "validate_starter",+]++#: Display order of the gallery's areas.+AREAS: Final[tuple[str, ...]] = ("coding", "research", "inbox", "writing", "ops", "personal")++#: The routine times a starter may propose, as cron in the person's own zone.+#: Named slots keep the gallery's schedule sentence translatable.+ROUTINE_SCHEDULES: Final[dict[str, str]] = {+ "weekday_morning": "0 8 * * 1-5",+ "daily_morning": "0 8 * * *",+ "daily_evening": "0 18 * * *",+ "weekly_monday": "0 9 * * 1",+ "weekly_friday": "0 16 * * 5",+}++_DATA_DIR: Final[Path] = Path(__file__).with_name("starters")+_ID_RE: Final[re.Pattern[str]] = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$")+_ICON_RE: Final[re.Pattern[str]] = re.compile(r"^[a-z0-9-]{1,40}$")+_CAPABILITY_RE: Final[re.Pattern[str]] = re.compile(r"^[a-z]+:[A-Za-z0-9_.:-]{1,80}$")+_MAX_TOOLS: Final[int] = 8+_MAX_OUTCOME: Final[int] = 140+_MAX_FIRST_MESSAGE: Final[int] = 400+_BULLET_RE: Final[re.Pattern[str]] = re.compile(r"^\s*[-*]\s+\S", re.MULTILINE)+++class StarterError(ValueError):+ """A starter file or a starter request is not usable; user-facing message."""+++@dataclass(frozen=True, slots=True)+class Starter:+ id: str+ area: str+ icon: str+ outcome: str+ tools: tuple[str, ...]+ first_message: str+ template: Mapping[str, Any]+ routine: Mapping[str, str] | None = None+ extra: Mapping[str, Any] = field(default_factory=dict)+++def validate_starter(raw: Any, area: str) -> list[str]:+ """Every problem with one starter entry, as sentences (empty = usable)."""+ if not isinstance(raw, dict):+ return ["a starter is a JSON object"]+ errors: list[str] = []+ sid = raw.get("id")+ label = sid if isinstance(sid, str) else "?"+ if not isinstance(sid, str) or not _ID_RE.fullmatch(sid):+ errors.append(f"{label}: id must be 1-40 characters of a-z 0-9 -")+ if area not in AREAS:+ errors.append(f"{label}: area {area!r} is not one of {', '.join(AREAS)}")+ if not isinstance(raw.get("icon"), str) or not _ICON_RE.fullmatch(raw["icon"]):+ errors.append(f"{label}: icon must be a lowercase icon name")+ outcome = raw.get("outcome")+ if not isinstance(outcome, str) or not outcome.strip() or len(outcome) > _MAX_OUTCOME:+ errors.append(f"{label}: outcome must be one line of at most {_MAX_OUTCOME} characters")+ first = raw.get("first_message")+ if not isinstance(first, str) or not first.strip() or len(first) > _MAX_FIRST_MESSAGE:+ errors.append(f"{label}: first_message must be at most {_MAX_FIRST_MESSAGE} characters")+ tools = raw.get("tools", [])+ if (+ not isinstance(tools, list)+ or len(tools) > _MAX_TOOLS+ or not all(isinstance(t, str) and _CAPABILITY_RE.fullmatch(t) for t in tools)+ ):+ errors.append(f"{label}: tools must be at most {_MAX_TOOLS} capability ids")+ routine = raw.get("routine")+ if routine is not None:+ if not isinstance(routine, dict):+ errors.append(f"{label}: routine must be an object")+ else:+ if routine.get("when") not in ROUTINE_SCHEDULES:+ errors.append(f"{label}: routine.when must be one of {sorted(ROUTINE_SCHEDULES)}")+ for key, limit in (("title", 200), ("prompt", 2_000)):+ value = routine.get(key)+ if not isinstance(value, str) or not value.strip() or len(value) > limit:+ errors.append(f"{label}: routine.{key} is missing or too long")+ template = raw.get("template")+ errors += [f"{label}: {problem}" for problem in validate_template(template)]+ if isinstance(template, dict) and template.get("focus"):+ errors.append(f"{label}: the template's focus comes from tools, leave it out")+ return errors+++def _from_file(path: Path) -> list[Starter]:+ data = json.loads(path.read_text(encoding="utf-8"))+ area = str(data.get("area") or "")+ out: list[Starter] = []+ for raw in data.get("starters") or []:+ problems = validate_starter(raw, area)+ if problems:+ # A broken entry is a bug in our own data; the rest of the gallery stays.+ log.error("starters: %s skipped: %s", path.name, "; ".join(problems))+ continue+ out.append(+ Starter(+ id=raw["id"],+ area=area,+ icon=raw["icon"],+ outcome=" ".join(raw["outcome"].split()),+ tools=tuple(dict.fromkeys(raw.get("tools") or [])),+ first_message=raw["first_message"],+ template=raw["template"],+ routine=dict(raw["routine"]) if raw.get("routine") else None,+ )+ )+ return out+++@lru_cache(maxsize=1)+def load_starters(directory: Path | None = None) -> tuple[Starter, ...]:+ """Every usable starter, in area order and then file order; ids are unique."""+ folder = directory or _DATA_DIR+ found: list[Starter] = []+ seen: set[str] = set()+ for path in sorted(folder.glob("*.json")):+ try:+ entries = _from_file(path)+ except (OSError, ValueError):+ log.exception("starters: unreadable file %s", path)+ continue+ for entry in entries:+ if entry.id in seen:+ log.error("starters: duplicate id %s in %s skipped", entry.id, path.name)+ continue+ seen.add(entry.id)+ found.append(entry)+ order = {area: index for index, area in enumerate(AREAS)}+ return tuple(sorted(found, key=lambda s: order.get(s.area, len(AREAS))))+++def starter_by_id(starter_id: str) -> Starter:+ for starter in load_starters():+ if starter.id == starter_id:+ return starter+ raise StarterError(f"There is no starter called {starter_id!r}")+++def routine_schedule(starter: Starter, timezone: str) -> dict[str, Any] | None:+ """The routine's schedule for ``RoutineBody`` in the person's zone, or ``None``."""+ if starter.routine is None:+ return None+ return {+ "kind": "cron",+ "expression": ROUTINE_SCHEDULES[starter.routine["when"]],+ "timezone": timezone,+ }+++def starter_template(+ starter: Starter, *, name: str | None = None, tools: Iterable[str] | None = None+) -> dict[str, Any]:+ """The starter's template with the picked name and tools applied.++ ``tools`` narrows the suggestion: only ids the starter suggests can be+ picked, so a request can never hand the agent a focus the gallery did not+ show. ``None`` keeps every suggested tool.+ """+ template = copy.deepcopy(dict(starter.template))+ if name is not None and name.strip():+ template["name"] = " ".join(name.split())+ picked = starter.tools if tools is None else tuple(t for t in starter.tools if t in set(tools))+ if picked:+ template["focus"] = list(picked)+ return template+++def template_summary(+ template: Mapping[str, Any], *, routines: int = 0, tools: Iterable[str] | None = None+) -> dict[str, Any]:+ """What a template brings, counted the same way for starters and imports."""+ instructions = str(template.get("instructions") or "")+ skills = template.get("skills")+ tool_ids = list(tools) if tools is not None else list(template.get("focus") or [])+ return {+ "instructions_words": len(instructions.split()),+ "instructions_rules": len(_BULLET_RE.findall(instructions)),+ # ``None`` = the template does not narrow skills: every skill on the box.+ "skills": len(skills) if isinstance(skills, list) else None,+ "routines": routines,+ "tools": len(tool_ids),+ "asks_before": len(template.get("require_approval") or []),+ "limited_tools": template.get("grant_mode") == "allowlist",+ }+++def _tool_rows(tool_ids: Iterable[str], catalog: Iterable[Any]) -> list[dict[str, Any]]:+ rows = {getattr(row, "id", ""): row for row in catalog}+ out: list[dict[str, Any]] = []+ for cap_id in tool_ids:+ row = rows.get(cap_id)+ out.append(+ {+ "id": cap_id,+ "label": getattr(row, "label", "") or cap_id.split(":", 1)[-1],+ "available": row is not None,+ "connected": bool(row is not None and getattr(row, "connected", False)),+ }+ )+ return out+++def starter_payload(starter: Starter, catalog: Iterable[Any]) -> dict[str, Any]:+ """One gallery entry: the starter, its tools on THIS box, and its counts."""+ template = dict(starter.template)+ return {+ "id": starter.id,+ "area": starter.area,+ "icon": starter.icon,+ "name": template["name"],+ "title": template.get("title", ""),+ "outcome": starter.outcome,+ "instructions": template["instructions"],+ "first_message": starter.first_message,+ "tools": _tool_rows(starter.tools, catalog),+ "routine": (+ {+ "title": starter.routine["title"],+ "when": starter.routine["when"],+ "cron": ROUTINE_SCHEDULES[starter.routine["when"]],+ }+ if starter.routine+ else None+ ),+ "summary": template_summary(+ template, routines=1 if starter.routine else 0, tools=starter.tools+ ),+ }+++def preview_payload(template: Any, catalog: Iterable[Any]) -> dict[str, Any]:+ """An imported template, checked and counted before anything is created."""+ errors = validate_template(template)+ if not isinstance(template, dict):+ return {"ok": False, "errors": errors, "template": None, "summary": None, "tools": []}+ focus = [t for t in template.get("focus") or [] if isinstance(t, str)]+ return {+ "ok": not errors,+ "errors": errors,+ "template": {+ "name": template.get("name", ""),+ "title": template.get("title", ""),+ "instructions": template.get("instructions", ""),+ "require_approval": list(template.get("require_approval") or []),+ },+ "summary": template_summary(template),+ "tools": _tool_rows(focus, catalog),+ }diff --git a/dodaios/society/starters/coding.json b/dodaios/society/starters/coding.jsonnew file mode 100644index 0000000000..a31df2f184--- /dev/null+++ b/dodaios/society/starters/coding.json@@ -0,0 +1,67 @@+{+ "area": "coding",+ "starters": [+ {+ "id": "code-reviewer",+ "icon": "git-pull-request",+ "outcome": "Reads a branch before you merge and lists what to fix, riskiest first.",+ "tools": ["core:coding-session", "cli:git", "cli:gh"],+ "first_message": "Review the changes on my current branch and tell me what to fix before I merge.",+ "template": {+ "schema": 1,+ "name": "Code Reviewer",+ "title": "Reviews changes before they merge",+ "instructions": "You review code changes before they are merged.\n\n## How you work\n- Read the whole diff and the code it touches before you judge it.\n- Rank findings by risk: correctness, security, data loss, then style.\n- Name the file and line for every finding and suggest the smallest fix.\n\n## Boundaries\n- You never merge or close anything yourself.",+ "tier": "specialist",+ "require_approval": ["cli:gh:merge", "cli:gh:close"]+ }+ },+ {+ "id": "bug-hunter",+ "icon": "bug",+ "outcome": "Reproduces a bug, finds the root cause and proposes the smallest fix.",+ "tools": ["core:coding-session", "core:run-shell", "cli:git"],+ "first_message": "Here is a bug I keep hitting: ",+ "template": {+ "schema": 1,+ "name": "Bug Hunter",+ "title": "Finds the root cause of bugs",+ "instructions": "You track down bugs to their root cause.\n\n## How you work\n- Reproduce the bug first and write down the exact steps.\n- Test one hypothesis at a time before moving on.\n- Propose the smallest fix and a test that would have caught it.\n\n## Done means\nThe cause is explained in two sentences and the fix is verified.",+ "tier": "specialist"+ }+ },+ {+ "id": "test-writer",+ "icon": "flask-conical",+ "outcome": "Finds untested code paths and writes focused tests for them.",+ "tools": ["core:coding-session", "core:run-shell"],+ "first_message": "Find the riskiest untested code in this project and write tests for it.",+ "template": {+ "schema": 1,+ "name": "Test Writer",+ "title": "Writes focused tests",+ "instructions": "You raise confidence in a codebase by writing tests.\n\n## How you work\n- Start with code that changes often or handles money, data or security.\n- Follow the project's existing test style and tools.\n- One behaviour per test, with a name that says what it proves.\n- Run the tests and report what passed and what failed.",+ "tier": "specialist"+ }+ },+ {+ "id": "release-notes",+ "icon": "scroll-text",+ "outcome": "Turns merged work into clear release notes once a week.",+ "tools": ["cli:git", "cli:gh"],+ "first_message": "Draft release notes for everything merged in the last seven days.",+ "routine": {+ "title": "Weekly release notes",+ "prompt": "Collect the changes merged since the last run and draft short release notes grouped by area.",+ "when": "weekly_friday"+ },+ "template": {+ "schema": 1,+ "name": "Release Notes",+ "title": "Writes release notes",+ "instructions": "You turn merged work into release notes people want to read.\n\n## How you work\n- Group changes by area and lead with what users will notice.\n- One line per change, in plain words, no internal jargon.\n- Link each line to its pull request when there is one.\n\n## Boundaries\n- You draft; publishing is up to me.",+ "tier": "specialist"+ }+ }+ ]+}diff --git a/dodaios/society/starters/inbox.json b/dodaios/society/starters/inbox.jsonnew file mode 100644index 0000000000..e5931fb857--- /dev/null+++ b/dodaios/society/starters/inbox.json@@ -0,0 +1,88 @@+{+ "area": "inbox",+ "starters": [+ {+ "id": "inbox-sorter",+ "icon": "inbox",+ "outcome": "Sorts new mail, sums up what matters and drafts replies for you to send.",+ "tools": ["plugin:gmail"],+ "first_message": "Go through my unread mail and tell me what needs me today.",+ "routine": {+ "title": "Morning inbox summary",+ "prompt": "Summarise the mail that arrived since the last run: what needs a reply, what can wait, and draft replies for the urgent ones.",+ "when": "weekday_morning"+ },+ "template": {+ "schema": 1,+ "name": "Inbox Sorter",+ "title": "Keeps the inbox under control",+ "instructions": "You keep my inbox under control.\n\n## How you work\n- Sort mail into: needs me, waiting on others, read later, noise.\n- Summarise each important thread in one line.\n- Draft replies in my tone when I ask.\n\n## Boundaries\n- Mail is sent only after approval.",+ "tier": "specialist",+ "require_approval": ["plugin:gmail:send"]+ }+ },+ {+ "id": "meeting-prep",+ "icon": "calendar-check",+ "outcome": "Prepares a one-page brief before each meeting on your calendar.",+ "tools": ["plugin:google_calendar", "plugin:gmail", "core:search-web"],+ "first_message": "Prepare briefs for my meetings today.",+ "routine": {+ "title": "Brief the day's meetings",+ "prompt": "Look at today's meetings and write a short brief for each: who attends, the context from recent mail, and what to decide.",+ "when": "weekday_morning"+ },+ "template": {+ "schema": 1,+ "name": "Meeting Prep",+ "title": "Briefs you before meetings",+ "instructions": "You prepare me for meetings.\n\n## Output\nPer meeting: purpose, attendees, relevant recent threads, open decisions and one suggested goal.\n\n## Boundaries\n- Calendar changes only after approval.",+ "tier": "specialist",+ "require_approval": [+ "plugin:google_calendar:create",+ "plugin:google_calendar:update",+ "plugin:google_calendar:delete"+ ]+ }+ },+ {+ "id": "scheduler",+ "icon": "calendar-clock",+ "outcome": "Finds free slots and proposes times; changes only after you say yes.",+ "tools": ["plugin:google_calendar"],+ "first_message": "Find three free slots next week for a one-hour meeting.",+ "template": {+ "schema": 1,+ "name": "Scheduler",+ "title": "Finds time in your calendar",+ "instructions": "You manage my time.\n\n## How you work\n- Respect focus blocks, travel time and working hours.\n- Offer two or three concrete options, never just one.\n\n## Boundaries\n- Events are created, moved or deleted only after approval.",+ "tier": "specialist",+ "require_approval": [+ "plugin:google_calendar:create",+ "plugin:google_calendar:update",+ "plugin:google_calendar:delete"+ ]+ }+ },+ {+ "id": "follow-up-keeper",+ "icon": "mail-check",+ "outcome": "Spots threads still waiting on a reply and lists them once a week.",+ "tools": ["plugin:gmail"],+ "first_message": "Which mail threads are still waiting on a reply, from me or from others?",+ "routine": {+ "title": "Weekly follow-up list",+ "prompt": "List the mail threads that have waited more than three days for a reply, mine or theirs, with a suggested next step for each.",+ "when": "weekly_friday"+ },+ "template": {+ "schema": 1,+ "name": "Follow-up Keeper",+ "title": "Makes sure nothing is dropped",+ "instructions": "You make sure no conversation is dropped.\n\n## How you work\n- Track threads waiting on me and threads waiting on others.\n- Mention each open thread once; do not repeat yourself.\n- Draft a short nudge when one is due.\n\n## Boundaries\n- Mail is sent only after approval.",+ "tier": "specialist",+ "require_approval": ["plugin:gmail:send"]+ }+ }+ ]+}diff --git a/dodaios/society/starters/ops.json b/dodaios/society/starters/ops.jsonnew file mode 100644index 0000000000..39f29a6782--- /dev/null+++ b/dodaios/society/starters/ops.json@@ -0,0 +1,73 @@+{+ "area": "ops",+ "starters": [+ {+ "id": "deploy-watcher",+ "icon": "rocket",+ "outcome": "Watches your deployments and explains failures in plain words.",+ "tools": ["plugin:vercel", "cli:gh"],+ "first_message": "Check my latest deployments and explain anything that failed.",+ "template": {+ "schema": 1,+ "name": "Deploy Watcher",+ "title": "Explains failed deployments",+ "instructions": "You keep an eye on deployments.\n\n## How you work\n- Read the build and runtime logs before you explain a failure.\n- Say what broke, why, and the smallest fix, in plain words.\n\n## Boundaries\n- New deployments only after approval.",+ "tier": "specialist",+ "require_approval": ["plugin:vercel:deploy"]+ }+ },+ {+ "id": "system-checker",+ "icon": "server",+ "outcome": "Checks your machines and containers and reports what needs attention.",+ "tools": ["core:run-shell", "cli:docker"],+ "first_message": "Check the health of this machine and its containers.",+ "routine": {+ "title": "Morning health check",+ "prompt": "Check disk space, memory, failing services and stopped containers. Report only what needs attention; say so in one line when everything is fine.",+ "when": "weekday_morning"+ },+ "template": {+ "schema": 1,+ "name": "System Checker",+ "title": "Checks machine health",+ "instructions": "You check the health of my machines.\n\n## How you work\n- Read-only checks first: disk, memory, services, containers, logs.\n- Report problems with their likely cause and a suggested fix.\n\n## Boundaries\n- You never restart, delete or reinstall anything without asking.",+ "tier": "specialist"+ }+ },+ {+ "id": "issue-triager",+ "icon": "list-checks",+ "outcome": "Sorts new issues, spots duplicates and drafts first replies.",+ "tools": ["cli:gh"],+ "first_message": "Triage the open issues in my repository that nobody has answered yet.",+ "template": {+ "schema": 1,+ "name": "Issue Triager",+ "title": "Triages incoming issues",+ "instructions": "You triage incoming issues.\n\n## How you work\n- Group issues into bug, request, question or duplicate.\n- Ask for missing reproduction steps in a friendly first reply.\n- Rank bugs by how many people they affect.\n\n## Boundaries\n- Creating or closing issues only after approval.",+ "tier": "specialist",+ "require_approval": ["cli:gh:create", "cli:gh:close"]+ }+ },+ {+ "id": "spend-watcher",+ "icon": "wallet",+ "outcome": "Keeps an eye on cloud and subscription costs and flags surprises.",+ "tools": ["cli:gcloud", "core:search-web"],+ "first_message": "Give me an overview of what my cloud services cost this month.",+ "routine": {+ "title": "Weekly spend check",+ "prompt": "Compare this week's cloud costs with the previous week and flag anything that grew by more than a fifth, with its likely cause.",+ "when": "weekly_monday"+ },+ "template": {+ "schema": 1,+ "name": "Spend Watcher",+ "title": "Flags cost surprises",+ "instructions": "You watch what my services cost.\n\n## How you work\n- Compare against the previous period, not against zero.\n- Explain every jump with its most likely cause.\n- Suggest one concrete saving when you see one.\n\n## Boundaries\n- You never change plans, quotas or resources yourself.",+ "tier": "specialist"+ }+ }+ ]+}diff --git a/dodaios/society/starters/personal.json b/dodaios/society/starters/personal.jsonnew file mode 100644index 0000000000..a1d82e86c1--- /dev/null+++ b/dodaios/society/starters/personal.json@@ -0,0 +1,80 @@+{+ "area": "personal",+ "starters": [+ {+ "id": "daily-briefing",+ "icon": "sunrise",+ "outcome": "Starts your day with calendar, mail and news in one short note.",+ "tools": ["plugin:google_calendar", "plugin:gmail", "core:search-web"],+ "first_message": "Give me a briefing for today.",+ "routine": {+ "title": "Morning briefing",+ "prompt": "Write a short briefing for today: the meetings, the mail that needs me, and the news on topics I care about.",+ "when": "weekday_morning"+ },+ "template": {+ "schema": 1,+ "name": "Daily Briefing",+ "title": "Briefs you every morning",+ "instructions": "You start my day with one short note.\n\n## Output\n- Today: meetings and deadlines.\n- Mail that needs me.\n- Two or three news items on topics I follow.\n\n## How you work\n- Fit the note on one screen; skip a section when it is empty.",+ "tier": "specialist"+ }+ },+ {+ "id": "trip-planner",+ "icon": "map",+ "outcome": "Plans trips: routes, places, timings and a packing list.",+ "tools": ["core:search-web", "core:remember"],+ "first_message": "Help me plan a trip to ",+ "template": {+ "schema": 1,+ "name": "Trip Planner",+ "title": "Plans trips end to end",+ "instructions": "You plan trips.\n\n## How you work\n- Ask for dates, budget and pace only when they matter for the plan.\n- Give a day-by-day plan with travel times and one backup per day.\n- Finish with a packing list for the weather and the activities.\n\n## Boundaries\n- You never book or pay for anything.",+ "tier": "specialist"+ }+ },+ {+ "id": "home-helper",+ "icon": "house",+ "outcome": "Runs your smart home: lights, climate and scenes.",+ "tools": ["plugin:home_assistant"],+ "first_message": "Show me which devices you can control in my home.",+ "template": {+ "schema": 1,+ "name": "Home Helper",+ "title": "Runs the smart home",+ "instructions": "You run my smart home.\n\n## How you work\n- Confirm in one line what you changed.\n- Prefer scenes over changing many devices one by one.\n\n## Boundaries\n- Locks, alarms and cameras only after I confirm.",+ "tier": "specialist"+ }+ },+ {+ "id": "learning-coach",+ "icon": "graduation-cap",+ "outcome": "Builds a study plan for a skill and quizzes you along the way.",+ "tools": ["core:search-web", "core:remember"],+ "first_message": "I want to learn ",+ "template": {+ "schema": 1,+ "name": "Learning Coach",+ "title": "Coaches you through a new skill",+ "instructions": "You help me learn a new skill.\n\n## How you work\n- Find out what I already know with a few quick questions.\n- Build a plan of short steps, each with one exercise.\n- Remember my progress and quiz me on earlier steps now and then.",+ "tier": "specialist"+ }+ },+ {+ "id": "playlist-curator",+ "icon": "music",+ "outcome": "Builds playlists for the moment from music you already like.",+ "tools": ["plugin:spotify"],+ "first_message": "Make me a playlist for ",+ "template": {+ "schema": 1,+ "name": "Playlist Curator",+ "title": "Builds playlists for the moment",+ "instructions": "You build playlists.\n\n## How you work\n- Start from what I already listen to and add a few discoveries.\n- Match tempo and mood to the moment I describe.\n- Name each playlist in a few words.",+ "tier": "specialist"+ }+ }+ ]+}diff --git a/dodaios/society/starters/research.json b/dodaios/society/starters/research.jsonnew file mode 100644index 0000000000..ccfed5d542--- /dev/null+++ b/dodaios/society/starters/research.json@@ -0,0 +1,66 @@+{+ "area": "research",+ "starters": [+ {+ "id": "researcher",+ "icon": "search",+ "outcome": "Answers a question with sources and keeps the findings for later.",+ "tools": ["core:search-web", "core:wiki-recall", "core:wiki-ingest"],+ "first_message": "Research this for me and cite your sources: ",+ "template": {+ "schema": 1,+ "name": "Researcher",+ "title": "Researches with sources",+ "instructions": "You answer questions with evidence.\n\n## How you work\n- Check what the wiki already knows before searching the web.\n- Prefer primary sources and say how recent each one is.\n- Separate facts from your own conclusions.\n- Save findings worth keeping as a short note in the wiki.\n\n## Output\nA short answer first, then the sources.",+ "tier": "specialist"+ }+ },+ {+ "id": "topic-watcher",+ "icon": "radar",+ "outcome": "Follows a topic or market and sends a short digest of what changed.",+ "tools": ["core:search-web", "core:wiki-ingest"],+ "first_message": "Keep an eye on this topic for me: ",+ "routine": {+ "title": "Weekly topic digest",+ "prompt": "Look for what changed on the topics you follow since the last digest and write a short summary with sources. Skip the digest when nothing meaningful changed.",+ "when": "weekly_monday"+ },+ "template": {+ "schema": 1,+ "name": "Topic Watcher",+ "title": "Tracks a topic over time",+ "instructions": "You follow the topics I give you and report what changed.\n\n## How you work\n- Keep a running note per topic in the wiki so you know what is new.\n- Report only real changes, never filler.\n- Three to five bullet points, each with its source.",+ "tier": "specialist"+ }+ },+ {+ "id": "document-digester",+ "icon": "book-open-text",+ "outcome": "Turns long documents and papers into key points and open questions.",+ "tools": ["core:wiki-ingest", "core:search-web"],+ "first_message": "Summarise this document into key points and open questions: ",+ "template": {+ "schema": 1,+ "name": "Document Digester",+ "title": "Summarises long documents",+ "instructions": "You make long documents quick to understand.\n\n## Output\n- A one-sentence summary.\n- The key points, one line each.\n- Open questions and weak spots.\n\n## How you work\n- Quote the document when a detail matters.\n- Never add content the document does not contain.",+ "tier": "specialist"+ }+ },+ {+ "id": "fact-checker",+ "icon": "badge-check",+ "outcome": "Checks the claims in a draft and flags anything unsupported.",+ "tools": ["core:search-web"],+ "first_message": "Fact-check this draft and flag every claim you cannot support: ",+ "template": {+ "schema": 1,+ "name": "Fact Checker",+ "title": "Checks claims against sources",+ "instructions": "You verify claims before they are published.\n\n## How you work\n- List every factual claim in the text.\n- Mark each one as supported, disputed or unsupported, with a source.\n- Suggest a corrected wording for anything that is wrong.",+ "tier": "specialist"+ }+ }+ ]+}diff --git a/dodaios/society/starters/writing.json b/dodaios/society/starters/writing.jsonnew file mode 100644index 0000000000..b44748d729--- /dev/null+++ b/dodaios/society/starters/writing.json@@ -0,0 +1,61 @@+{+ "area": "writing",+ "starters": [+ {+ "id": "editor",+ "icon": "pen-line",+ "outcome": "Tightens your drafts: clearer and shorter, in your own voice.",+ "tools": ["core:wiki-recall"],+ "first_message": "Edit this draft so it is clearer and shorter, but keep my voice: ",+ "template": {+ "schema": 1,+ "name": "Editor",+ "title": "Edits drafts for clarity",+ "instructions": "You edit my writing.\n\n## How you work\n- Keep my voice and my meaning; cut everything else.\n- Prefer short sentences and concrete words.\n- Return the edited text first, then the three most important changes.",+ "tier": "specialist"+ }+ },+ {+ "id": "post-writer",+ "icon": "megaphone",+ "outcome": "Turns notes and updates into short posts that sound like you.",+ "tools": ["core:wiki-recall", "core:search-web"],+ "first_message": "Turn this update into a short post: ",+ "template": {+ "schema": 1,+ "name": "Post Writer",+ "title": "Writes short posts",+ "instructions": "You turn updates into short posts.\n\n## How you work\n- Lead with the benefit, then the detail.\n- Short lines, one idea each, real numbers when there are any.\n- Offer two versions: a plain one and a bolder one.\n\n## Boundaries\n- You draft; I post.",+ "tier": "specialist"+ }+ },+ {+ "id": "docs-writer",+ "icon": "file-text",+ "outcome": "Writes and updates documentation from code and notes.",+ "tools": ["core:coding-session", "cli:git"],+ "first_message": "Find the part of this project with the weakest documentation and improve it.",+ "template": {+ "schema": 1,+ "name": "Docs Writer",+ "title": "Keeps documentation current",+ "instructions": "You write documentation people can follow.\n\n## How you work\n- Read the code before you describe it; never guess behaviour.\n- Start with what the reader wants to do, then how.\n- Keep examples short and make sure they run.",+ "tier": "specialist"+ }+ },+ {+ "id": "translator",+ "icon": "languages",+ "outcome": "Translates text and keeps your terms and tone consistent.",+ "tools": ["core:wiki-recall", "core:remember"],+ "first_message": "Translate this and keep my terms consistent: ",+ "template": {+ "schema": 1,+ "name": "Translator",+ "title": "Translates with a consistent voice",+ "instructions": "You translate my texts.\n\n## How you work\n- Keep meaning, tone and formatting.\n- Remember the terms I prefer and use them every time.\n- Flag phrases that do not translate well and offer options.",+ "tier": "specialist"+ }+ }+ ]+}diff --git a/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.starters.test.tsx b/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.starters.test.tsxnew file mode 100644index 0000000000..c37fee7f82--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.starters.test.tsx@@ -0,0 +1,384 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import type { AgentRuntimesResponse } from "@/lib/agentRuntimesApi";+import type { ProviderOption } from "@/store/agentChat";+import { CreateAgentDialogHost } from "./CreateAgentDialog";+import { isCreateCancelled, useCreateAgentDialog } from "./createAgentStore";+import type { Starter, StartersResponse } from "./startersApi";++const { STRINGS } = vi.hoisted(() => ({+ STRINGS: {+ "agent_create.preview.instructions_words": "{words} words",+ "agent_create.preview.instructions_rules": "{rules} rules · {words} words",+ "agent_create.preview.tools_value": "{picked} of {total}",+ } as Record<string, string>,+}));+vi.mock("@/i18n", () => ({+ useT: () => (key: string) => STRINGS[key] ?? key,+ translate: (key: string) => key,+ fill: (template: string, vars: Record<string, string | number>) =>+ template.replace(/\{(\w+)\}/g, (match, key: string) => (key in vars ? String(vars[key]) : match)),+}));+vi.mock("../companion/CompanionEditor", () => ({+ CompanionEditor: ({ value }: { value: { shape: string } }) => <div data-testid="companion-editor">{value.shape}</div>,+}));+const { createAgent, seed, spawn, menu } = vi.hoisted(() => ({+ createAgent: vi.fn(),+ seed: vi.fn(),+ spawn: vi.fn(),+ menu: { options: [] as unknown[], live: {} as Record<string, unknown[]> },+}));+vi.mock("../data", async () => {+ class AgentNameTaken extends Error {}+ class RuntimeProviderUnsupported extends Error {}+ const requestError = (body: { detail?: { reason?: string; detail?: string } | string } | null, fallback: string) => {+ const detail = body?.detail;+ if (typeof detail === "string") return new Error(detail);+ if (detail?.reason === "runtime_provider_unsupported") return new RuntimeProviderUnsupported(detail.detail ?? fallback);+ return new Error(detail?.detail ?? fallback);+ };+ return {+ AgentNameTaken, RuntimeProviderUnsupported, requestError, useCreateSocietyAgent: () => createAgent,+ rowToAgent: (row: { agent_id: string; name: string; session_id?: string }) => ({+ agentId: row.agent_id, name: row.name, chatSessionId: row.session_id ?? null,+ }),+ };+});+vi.mock("./firstMessage", () => ({ seedFirstMessage: seed }));+vi.mock("../world/spawnStore", () => ({ announceSpawn: spawn }));+vi.mock("../chat/useModelMenuData", () => ({+ useModelMenuData: () => ({+ options: menu.options, providers: [], live: menu.live,+ loading: false, refreshing: false, failed: false, refresh: () => Promise.resolve(),+ }),+}));+const READY: AgentRuntimesResponse = {+ runtimes: [+ { runtime: "hermes", label: "Hermes", installed: true, version: "0.21.0", minimum_version: "0.20.6",+ ready: true, problem: "", problem_kind: "", install_hint: "", job: null },+ ],+ supported_providers: ["openai"],+};+vi.mock("@/lib/agentRuntimesApi", () => ({+ fetchAgentRuntimes: () => Promise.resolve(READY),+ ensureAgentRuntime: vi.fn(),+}));++function provider(over: Partial<ProviderOption>): ProviderOption {+ return {+ id: "openai", label: "OpenAI", family: "openai", runner: "brain", models_source: "live",+ curated_models: [{ id: "gpt-5.2", label: "GPT-5.2" }, { id: "gpt-5.5", label: "GPT-5.5" }],+ default_model: "", keyless: false, native_resume: false, effort_levels: [], default_effort: "",+ permission_modes: [], default_permission_mode: "", cli_installed: null, connected: true, active: false,+ ...over,+ };+}++const SUMMARY = { instructions_words: 42, instructions_rules: 3, skills: null, routines: 1, tools: 3, asks_before: 1, limited_tools: false };+const STARTERS: Starter[] = [+ {+ id: "code-reviewer", area: "coding", icon: "git-pull-request", name: "Code Reviewer", title: "Reviews",+ outcome: "Reads a branch before you merge.", instructions: "You review.\n\n- a\n- b\n- c",+ first_message: "Review my branch.", routine: null,+ tools: [{ id: "cli:gh", label: "GitHub CLI", available: true, connected: true }],+ summary: { ...SUMMARY, routines: 0, tools: 1, asks_before: 2 },+ },+ {+ id: "daily-briefing", area: "personal", icon: "sunrise", name: "Daily Briefing", title: "Briefs",+ outcome: "Starts your day with one note.", instructions: "You brief me.",+ first_message: "Give me a briefing for today.",+ routine: { title: "Morning briefing", when: "weekday_morning", cron: "0 8 * * 1-5" },+ tools: [+ { id: "plugin:google_calendar", label: "Calendar", available: true, connected: true },+ { id: "plugin:gmail", label: "Gmail", available: true, connected: false },+ { id: "core:search-web", label: "Web search", available: false, connected: false },+ ],+ summary: { ...SUMMARY, instructions_rules: 0, instructions_words: 3 },+ },+];+const GALLERY: StartersResponse = { areas: ["coding", "personal"], starters: STARTERS, total: 2 };++const fetchMock = vi.fn();++function json(body: unknown, status = 200) {+ return Promise.resolve(new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } }));+}++function route(url: string, init?: RequestInit) {+ if (url === "/api/society/starters") return json(GALLERY);+ if (url === "/api/society/starters/install") {+ const body = JSON.parse(String(init?.body));+ return json({+ agent: { agent_id: "agent-9", name: body.name || "Imported", session_id: "society:agent-9" },+ created: true, renamed_from: null,+ first_message: body.starter_id ? "Give me a briefing for today." : "",+ routine: body.with_routine ? { id: "task-1", title: "[agent:x] Morning briefing" } : null,+ routine_error: null,+ });+ }+ if (url === "/api/society/starters/preview") {+ const body = JSON.parse(String(init?.body));+ const template = body.template as Record<string, unknown>;+ if (!template.instructions) return json({ ok: false, errors: ["the instructions are empty"], template: null, summary: null, tools: [] });+ return json({+ ok: true, errors: [],+ template: { name: template.name, title: "Keeps notes", instructions: template.instructions, require_approval: [] },+ summary: { ...SUMMARY, routines: 0, tools: 1, asks_before: 0, instructions_rules: 0, instructions_words: 3 },+ tools: [{ id: "core:search-web", label: "Web search", available: true, connected: true }],+ });+ }+ return json({}, 404);+}++function mount() {+ return render(+ <QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>+ <CreateAgentDialogHost />+ </QueryClientProvider>,+ );+}++function installCalls() {+ return fetchMock.mock.calls.filter(([url]) => url === "/api/society/starters/install")+ .map(([, init]) => JSON.parse(String((init as RequestInit).body)));+}++beforeEach(() => {+ menu.options = [provider({})];+ menu.live = {};+ fetchMock.mockImplementation(route);+ seed.mockResolvedValue(true);+ vi.stubGlobal("fetch", fetchMock);+ // The routine switch measures itself; the test DOM has no ResizeObserver.+ vi.stubGlobal("ResizeObserver", class { observe() {} unobserve() {} disconnect() {} });+});+afterEach(() => {+ cleanup();+ vi.clearAllMocks();+ vi.unstubAllGlobals();+ act(() => useCreateAgentDialog.getState().cancel());+});++describe("CreateAgentDialog: starters", () => {+ test("opens on the first starter and filters the gallery by area and search", async () => {+ mount();+ act(() => { useCreateAgentDialog.getState().request({ mode: "starter" }).catch(() => undefined); });+ expect(await screen.findByTestId("starter-code-reviewer")).toBeTruthy();+ expect(screen.getByTestId("starter-daily-briefing")).toBeTruthy();+ // The preview is never empty: the first starter is open.+ await waitFor(() => expect((screen.getByTestId("template-preview-name") as HTMLInputElement).value).toBe("Code Reviewer"));+ expect(screen.getByTestId("preview-count-instructions").textContent).toContain("3 rules · 42 words");+ expect(screen.getByTestId("starter-area-all").textContent).toContain("2");++ fireEvent.click(screen.getByTestId("starter-area-personal"));+ expect(screen.queryByTestId("starter-code-reviewer")).toBeNull();+ expect(screen.getByTestId("starter-daily-briefing")).toBeTruthy();++ fireEvent.click(screen.getByTestId("starter-area-all"));+ fireEvent.change(screen.getByTestId("starter-search"), { target: { value: "branch merge" } });+ expect(screen.getByTestId("starter-code-reviewer")).toBeTruthy();+ expect(screen.queryByTestId("starter-daily-briefing")).toBeNull();+ expect(screen.getByTestId("starter-area-personal").textContent).toContain("0");++ fireEvent.change(screen.getByTestId("starter-search"), { target: { value: "nothing like this" } });+ expect(screen.getByTestId("starter-empty")).toBeTruthy();+ });++ test("the preview counts what the starter brings and follows the picks", async () => {+ mount();+ act(() => { useCreateAgentDialog.getState().request({ mode: "starter" }).catch(() => undefined); });+ fireEvent.click(await screen.findByTestId("starter-daily-briefing"));+ await waitFor(() => expect((screen.getByTestId("template-preview-name") as HTMLInputElement).value).toBe("Daily Briefing"));+ expect(screen.getByTestId("preview-count-instructions").textContent).toContain("3 words");+ expect(screen.getByTestId("preview-count-skills").textContent).toContain("agent_create.preview.skills_all");+ // Only the connected tool starts ticked.+ expect(screen.getByTestId("preview-count-tools").textContent).toContain("1 of 3");+ expect((screen.getByTestId("preview-tool-plugin:google_calendar") as HTMLInputElement).checked).toBe(true);+ expect((screen.getByTestId("preview-tool-plugin:gmail") as HTMLInputElement).checked).toBe(false);+ expect((screen.getByTestId("preview-tool-core:search-web") as HTMLInputElement).checked).toBe(false);+ fireEvent.click(screen.getByTestId("preview-tool-plugin:gmail"));+ expect(screen.getByTestId("preview-count-tools").textContent).toContain("2 of 3");+ // The routine is opt-in: off, and counted only once ticked.+ expect(within(screen.getByTestId("preview-count-routines")).getByText("0")).toBeTruthy();+ fireEvent.click(screen.getByTestId("preview-routine-toggle"));+ expect(within(screen.getByTestId("preview-count-routines")).getByText("1")).toBeTruthy();+ expect(screen.getByTestId("preview-first-message").textContent).toBe("Give me a briefing for today.");+ expect(screen.getByTestId("preview-asks-before").textContent).toContain("agent_create.preview.asks_before_one");+ });++ test("creates from a starter on the dialog's seat and seeds the first message", async () => {+ mount();+ let pending!: Promise<{ agentId: string }>;+ act(() => { pending = useCreateAgentDialog.getState().request({ mode: "starter" }) as Promise<{ agentId: string }>; });+ fireEvent.click(await screen.findByTestId("starter-daily-briefing"));+ await waitFor(() => expect((screen.getByTestId("template-preview-name") as HTMLInputElement).value).toBe("Daily Briefing"));+ fireEvent.change(screen.getByTestId("template-preview-name"), { target: { value: "Morning Desk" } });+ fireEvent.click(screen.getByTestId("preview-routine-toggle"));+ await screen.findByTestId("create-agent-seat-summary");+ await waitFor(() => expect((screen.getByTestId("create-agent-submit") as HTMLButtonElement).disabled).toBe(false));+ fireEvent.click(screen.getByTestId("create-agent-submit"));+ await expect(pending).resolves.toMatchObject({ agentId: "agent-9", name: "Morning Desk" });+ const [body] = installCalls();+ expect(body).toMatchObject({+ starter_id: "daily-briefing",+ name: "Morning Desk",+ tools: ["plugin:google_calendar"],+ with_routine: true,+ seat: { provider: "openai", model: "gpt-5.5", execution_environment: "local" },+ });+ expect(typeof body.timezone).toBe("string");+ expect(body.seat.companion.shape).toBeTruthy();+ expect(body.seat.runtime).toBeUndefined();+ expect(spawn).toHaveBeenCalledWith("agent-9");+ expect(seed).toHaveBeenCalledWith(expect.objectContaining({ agentId: "agent-9" }), "Give me a briefing for today.");+ expect(createAgent).not.toHaveBeenCalled();+ });++ test("a starter on Hermes sends the runtime", async () => {+ mount();+ act(() => { useCreateAgentDialog.getState().request({ mode: "starter" }).catch(() => undefined); });+ await screen.findByTestId("starter-code-reviewer");+ fireEvent.click(await screen.findByTestId("create-agent-seat-summary").then((el) => within(el).getAllByRole("button")[0]));+ fireEvent.click(await screen.findByRole("radio", { name: "society.runtime.hermes" }));+ await waitFor(() => expect((screen.getByTestId("create-agent-submit") as HTMLButtonElement).disabled).toBe(false));+ fireEvent.click(screen.getByTestId("create-agent-submit"));+ await waitFor(() => expect(installCalls()).toHaveLength(1));+ expect(installCalls()[0]).toMatchObject({ starter_id: "code-reviewer", seat: { runtime: "hermes", provider: "openai" } });+ expect(installCalls()[0].with_routine).toBeUndefined();+ });++ test("a routine that could not be set up is said before the chat opens", async () => {+ fetchMock.mockImplementation((url: string, init?: RequestInit) => url === "/api/society/starters/install"+ ? json({ agent: { agent_id: "agent-3", name: "Daily Briefing" }, created: true, renamed_from: null,+ first_message: "", routine: null, routine_error: "timezone_required" })+ : route(url, init));+ mount();+ let pending!: Promise<unknown>;+ act(() => { pending = useCreateAgentDialog.getState().request({ mode: "starter" }); });+ fireEvent.click(await screen.findByTestId("starter-daily-briefing"));+ fireEvent.click(screen.getByTestId("preview-routine-toggle"));+ await waitFor(() => expect((screen.getByTestId("create-agent-submit") as HTMLButtonElement).disabled).toBe(false));+ fireEvent.click(screen.getByTestId("create-agent-submit"));+ expect(await screen.findByTestId("create-agent-routine-error")).toBeTruthy();+ expect(useCreateAgentDialog.getState().open).toBe(true);+ fireEvent.click(screen.getByTestId("create-agent-submit"));+ await expect(pending).resolves.toMatchObject({ agentId: "agent-3" });+ });+ test("a runtime that cannot drive the provider is said in the person's language", async () => {+ fetchMock.mockImplementation((url: string, init?: RequestInit) => url === "/api/society/starters/install"+ ? json({ detail: { reason: "runtime_provider_unsupported", detail: "Hermes cannot run this provider" } }, 422)+ : route(url, init));+ mount();+ act(() => { useCreateAgentDialog.getState().request({ mode: "starter" }).catch(() => undefined); });+ await screen.findByTestId("starter-code-reviewer");+ await waitFor(() => expect((screen.getByTestId("create-agent-submit") as HTMLButtonElement).disabled).toBe(false));+ fireEvent.click(screen.getByTestId("create-agent-submit"));+ expect(await screen.findByText("society.runtime.provider_unsupported")).toBeTruthy();+ expect(useCreateAgentDialog.getState().open).toBe(true);+ });++ test("the three ways in are tabs the arrow keys move through", async () => {+ mount();+ act(() => { useCreateAgentDialog.getState().request().catch(() => undefined); });+ const quick = await screen.findByTestId("create-agent-mode-quick");+ expect(quick.getAttribute("tabindex")).toBe("0");+ expect(screen.getByTestId("create-agent-mode-starter").getAttribute("tabindex")).toBe("-1");+ fireEvent.keyDown(quick, { key: "ArrowRight" });+ expect(screen.getByTestId("create-agent-mode-starter").getAttribute("aria-selected")).toBe("true");+ expect(document.activeElement).toBe(screen.getByTestId("create-agent-mode-starter"));+ fireEvent.keyDown(screen.getByTestId("create-agent-mode-starter"), { key: "End" });+ expect(screen.getByTestId("create-agent-mode-import").getAttribute("aria-selected")).toBe("true");+ fireEvent.keyDown(screen.getByTestId("create-agent-mode-import"), { key: "ArrowRight" });+ expect(screen.getByTestId("create-agent-mode-quick").getAttribute("aria-selected")).toBe("true");+ });+});++describe("CreateAgentDialog: import", () => {+ test("a template handed in opens on its preview, and nothing exists before Create", async () => {+ mount();+ let pending!: Promise<unknown>;+ act(() => {+ pending = useCreateAgentDialog.getState().request({+ template: { schema: 1, name: "Note Keeper", instructions: "Keep my notes.", focus: ["core:search-web"] },+ });+ });+ await waitFor(() => expect((screen.getByTestId("template-preview-name") as HTMLInputElement).value).toBe("Note Keeper"));+ expect(screen.getByTestId("create-agent-mode-import").getAttribute("aria-selected")).toBe("true");+ expect(installCalls()).toHaveLength(0);+ fireEvent.click(screen.getByTestId("preview-tool-core:search-web"));+ await waitFor(() => expect((screen.getByTestId("create-agent-submit") as HTMLButtonElement).disabled).toBe(false));+ fireEvent.click(screen.getByTestId("create-agent-submit"));+ await expect(pending).resolves.toMatchObject({ agentId: "agent-9" });+ expect(installCalls()[0]).toMatchObject({+ template: { name: "Note Keeper" }, name: "Note Keeper", tools: [], seat: { provider: "openai" },+ });+ expect(seed).toHaveBeenCalledWith(expect.anything(), "");+ });++ test("pasted text that is not a usable template cannot be created", async () => {+ mount();+ act(() => { useCreateAgentDialog.getState().request({ mode: "import" }).catch(() => undefined); });+ const field = await screen.findByTestId("import-text");+ fireEvent.change(field, { target: { value: "{not json" } });+ expect(await screen.findByText("agent_create.import.invalid_json")).toBeTruthy();+ expect((screen.getByTestId("create-agent-submit") as HTMLButtonElement).disabled).toBe(true);+ fireEvent.change(field, { target: { value: JSON.stringify({ kind: "agent", agent: { schema: 1, name: "X" } }) } });+ expect(await screen.findByTestId("import-errors")).toBeTruthy();+ expect((screen.getByTestId("create-agent-submit") as HTMLButtonElement).disabled).toBe(true);+ expect(screen.getByTestId("create-agent-empty-preview")).toBeTruthy();+ });++ test("an edit holds Create until the new text is checked", async () => {+ mount();+ act(() => {+ useCreateAgentDialog.getState().request({+ template: { schema: 1, name: "Note Keeper", instructions: "Keep my notes." },+ }).catch(() => undefined);+ });+ await waitFor(() => expect((screen.getByTestId("template-preview-name") as HTMLInputElement).value).toBe("Note Keeper"));+ await waitFor(() => expect((screen.getByTestId("create-agent-submit") as HTMLButtonElement).disabled).toBe(false));+ fireEvent.change(screen.getByTestId("import-text"), {+ target: { value: JSON.stringify({ schema: 1, name: "Other Keeper", instructions: "Keep other notes." }) },+ });+ // The old preview stays on screen, but it is no longer what Create would install.+ expect((screen.getByTestId("create-agent-submit") as HTMLButtonElement).disabled).toBe(true);+ await waitFor(() => expect((screen.getByTestId("template-preview-name") as HTMLInputElement).value).toBe("Other Keeper"));+ await waitFor(() => expect((screen.getByTestId("create-agent-submit") as HTMLButtonElement).disabled).toBe(false));+ });+});++describe("CreateAgentDialog: blank", () => {+ test("creates with a name only, and the job line becomes the mission", async () => {+ createAgent.mockResolvedValue({ agentId: "agent-1", name: "Scout" });+ mount();+ let pending!: Promise<unknown>;+ act(() => { pending = useCreateAgentDialog.getState().request(); });+ fireEvent.change(await screen.findByTestId("create-agent-name"), { target: { value: "Scout" } });+ fireEvent.change(screen.getByTestId("create-agent-job"), { target: { value: "Watches my repositories" } });+ await screen.findByTestId("create-agent-provider");+ fireEvent.click(screen.getByTestId("create-agent-submit"));+ await expect(pending).resolves.toMatchObject({ agentId: "agent-1" });+ expect(createAgent.mock.calls[0][0]).toMatchObject({ name: "Scout", mission: "Watches my repositories", runtime: "jarvis" });+ // The blank path never touches the gallery.+ expect(fetchMock.mock.calls.some(([url]) => String(url).startsWith("/api/society/starters"))).toBe(false);+ });++ test("the runtime note explains what is fixed for life", async () => {+ mount();+ act(() => { useCreateAgentDialog.getState().request().catch(() => undefined); });+ expect((await screen.findByTestId("create-agent-runtime-note")).textContent).toBe("agent_create.runtime_note.jarvis");+ fireEvent.click(await screen.findByRole("radio", { name: "society.runtime.hermes" }));+ expect(screen.getByTestId("create-agent-runtime-note").textContent).toBe("agent_create.runtime_note.hermes");+ });++ test("closing still rejects with CreateAgentCancelled", async () => {+ mount();+ let pending!: Promise<unknown>;+ act(() => { pending = useCreateAgentDialog.getState().request({ mode: "starter" }); });+ await screen.findByTestId("starter-code-reviewer");+ fireEvent.click(screen.getByRole("button", { name: "society.create_agent.cancel" }));+ await expect(pending).rejects.toSatisfy(isCreateCancelled);+ expect(installCalls()).toHaveLength(0);+ });+});diff --git a/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx b/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsxindex 87f0eae135..4bdc439926 100644--- a/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx+++ b/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx@@ -1,134 +1,206 @@/**- * "New agent": a name, the runtime it runs on (Jarvis, Hermes or OpenClaw —- * chosen here once and fixed for the agent's life), the model it starts on- * (provider, how it pays — subscription, API key or local — and the model- * itself; all changeable later in its chat) and the small companion bot that- * follows it. Only what is connected on this machine is offered- * (`seatChoice.ts`). Mounted once (App.tsx); every plus opens it through- * `useCreateAgentDialog`.+ * "New agent": three ways from an idea to a working teammate.+ *+ * - Blank: a name and, optionally, one line on its job (the structured+ * brief's mission), the seat and the companion.+ * - From a starter: a gallery of job-shaped agents we wrote ourselves+ * (`dodaios/society/starters`), each previewed with what it brings before+ * it is created; the chat then opens with a suggested first message in+ * the composer, never sent.+ * - Import: a template somebody shared, pasted or opened, previewed the same+ * way and checked against the marketplace's stranger-safety rules.+ *+ * Every path runs on the seat picked here (`SeatFields`): any runtime+ * (fixed for the agent's life) and any connected provider. Mounted once+ * (App.tsx); every plus opens it through `useCreateAgentDialog`.*/-import { useEffect, useMemo, useState, Suspense, lazy } from "react";+import { useEffect, useMemo, useRef, useState, Suspense, lazy, type KeyboardEvent, type ReactNode } from "react";import * as Dialog from "@radix-ui/react-dialog";-import { Loader2, RefreshCw, X } from "lucide-react";+import { useQueryClient } from "@tanstack/react-query";+import { ArrowLeft, FileInput, LayoutGrid, Loader2, PencilLine, TriangleAlert, X } from "lucide-react";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";-import { BrandedSelect } from "@/components/ui/select";-import { AgentMark } from "@/components/agentic/AgentMark";-import { ProviderLogo } from "@/components/providers/ProviderLogo";-import { useT } from "@/i18n";-import type { AgentRuntime } from "@/lib/societyApi";-import { AgentNameTaken, RuntimeProviderUnsupported, useCreateSocietyAgent } from "../data";+import { fill, useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { AgentNameTaken, RuntimeProviderUnsupported, rowToAgent, useCreateSocietyAgent, type SocietyAgent } from "../data";+import type { SocietyAgentRow } from "@/lib/societyApi";import { defaultCompanion, type CompanionAppearance } from "../companion/appearance";import { randomCreature } from "../companion/creature";-import { RuntimeChoice, useAgentRuntimes } from "../card/RuntimePicker";-import { SandboxChoice } from "../card/AgentSandboxSection";-import { modelSeats, runtimeSeats } from "../chat/modelChoices";-import { useModelMenuData } from "../chat/useModelMenuData";-import { accountChoice, accountHint } from "./brainPicker";-import { useCreateAgentDialog } from "./createAgentStore";-import { AccessChoice } from "./AccessChoice";-import { accessModels, defaultModel, pickableOption, providerChoices, type AccessBlocked, type AccessOption } from "./seatChoice";-import { useModelAccess, type ModelAccess } from "@/lib/modelAccess";+import { announceSpawn } from "../world/spawnStore";+import { useCreateAgentDialog, type CreateAgentMode } from "./createAgentStore";+import { seedFirstMessage } from "./firstMessage";+import { EMPTY_IMPORT, ImportTemplatePane, type ImportState } from "./ImportTemplatePane";+import { SeatFields, SeatSummary, useCreateSeat, type SeatPick } from "./SeatFields";+import { StarterGallery } from "./StarterGallery";+import { defaultTools, starterCopy, type AreaFilter } from "./starterFilters";+import { StarterIcon } from "./starterIcons";+import { installStarter, useStarters, type InstallStarterResult, type Starter, type StarterSeat } from "./startersApi";+import { TemplatePreviewCard } from "./TemplatePreviewCard";const CompanionEditor = lazy(() =>import("../companion/CompanionEditor").then((m) => ({ default: m.CompanionEditor })),);-/** A model list this long gets a search field. */-const SEARCH_FROM = 12;--function list(value: unknown): string[] {- return Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : [];-}+const MODES: readonly { id: CreateAgentMode; icon: ReactNode }[] = [+ { id: "quick", icon: <PencilLine className="size-3.5" aria-hidden /> },+ { id: "starter", icon: <LayoutGrid className="size-3.5" aria-hidden /> },+ { id: "import", icon: <FileInput className="size-3.5" aria-hidden /> },+];/** A new agent starts as a pixel creature; the shape underneath is there for a change of mind. */function randomCompanion(): CompanionAppearance {return { ...defaultCompanion(`${Date.now()}:${Math.random()}`), creature: randomCreature() };}+function starterSeat(pick: SeatPick, companion: CompanionAppearance): StarterSeat {+ const seat: StarterSeat = { companion, execution_environment: pick.executionEnvironment };+ if (pick.runtime !== "jarvis") seat.runtime = pick.runtime;+ if (pick.provider) {+ seat.provider = pick.provider;+ if (pick.model) seat.model = pick.model;+ if (pick.accountId) seat.account_id = pick.accountId;+ }+ return seat;+}+export function CreateAgentDialogHost() {const open = useCreateAgentDialog((s) => s.open);+ const requestId = useCreateAgentDialog((s) => s.requestId);// A fresh form every time it opens.- return open ? <CreateAgentDialog /> : null;+ return open ? <CreateAgentDialog key={requestId} /> : null;}function CreateAgentDialog() {const t = useT();+ const client = useQueryClient();const { finish, cancel } = useCreateAgentDialog.getState();+ const initial = useCreateAgentDialog((s) => s.initial);const createAgent = useCreateSocietyAgent();- const runtimes = useAgentRuntimes();+ const seat = useCreateSeat();+ const [mode, setMode] = useState<CreateAgentMode>(initial.mode ?? "quick");+ const modeTabs = useRef<(HTMLButtonElement | null)[]>([]);+ function onModeKey(event: KeyboardEvent<HTMLButtonElement>, index: number) {+ const last = MODES.length - 1;+ const next = { ArrowRight: index + 1, ArrowLeft: index - 1, Home: 0, End: last }[event.key];+ if (next === undefined) return;+ event.preventDefault();+ const target = (next + MODES.length) % MODES.length;+ modeTabs.current[target]?.focus();+ setMode(MODES[target].id);+ setError(null);+ }const [name, setName] = useState("");- const [runtime, setRuntime] = useState<AgentRuntime>("jarvis");- const [executionEnvironment, setExecutionEnvironment] = useState<"local" | "sandbox">("local");- const [providerId, setProviderId] = useState("");- const [access, rememberAccess] = useModelAccess();- const [model, setModel] = useState("");- const [account, setAccount] = useState("");- const [accountProvider, setAccountProvider] = useState("");+ const [job, setJob] = useState("");const [companion, setCompanion] = useState<CompanionAppearance>(randomCompanion);const [saving, setSaving] = useState(false);const [error, setError] = useState<string | null>(null);- // A stored catalog may be a startup fallback. Revalidate on this user gesture,- // and scope subscription models to the login that will actually run the agent.- const menu = useModelMenuData(null, undefined,- account && accountProvider ? { [accountProvider]: account } : {}, { refreshOnMount: true });+ // Created, but the routine it was asked for could not be set up: say so before the chat opens.+ const [created, setCreated] = useState<{ agent: SocietyAgent; routineError: string } | null>(null);++ // Starter path.+ const starters = useStarters(mode === "starter");+ const [area, setArea] = useState<AreaFilter>("all");+ const [query, setQuery] = useState("");+ const [starterId, setStarterId] = useState<string | null>(null);+ const [starterName, setStarterName] = useState("");+ const [picked, setPicked] = useState<Set<string>>(new Set());+ const [routineOn, setRoutineOn] = useState(false);+ const [mobilePreview, setMobilePreview] = useState(false);+ const starterList = useMemo(() => starters.data?.starters ?? [], [starters.data]);+ const starter = starterList.find((entry) => entry.id === starterId) ?? null;+ const copy = starter ? starterCopy(t, starter) : null;- const external = runtime !== "jarvis";- const defaultModelLabel = t("agent_chat.model_default");- const data = runtimes.data;- const supportedKey = list(data?.supported_providers).join(",");- const gatewayKey = list(data?.subscription_providers).join(",");- const loginKey = list(data?.login_providers).join(",");- const accessKey = JSON.stringify(data?.access && typeof data.access === "object" ? data.access : {});- // Refusals only concern Hermes / OpenClaw (Claude's login billed as Extra Usage).- const blockedKey = JSON.stringify(external && data?.access_blocked && typeof data.access_blocked === "object" ? data.access_blocked : {});- const choices = useMemo(() => {- const all = modelSeats(menu.options, Array.isArray(menu.providers) ? menu.providers : [], menu.live, defaultModelLabel);- const split = (key: string) => key.split(",").filter(Boolean);- const seats = external ? runtimeSeats(all, split(supportedKey), split(gatewayKey), split(loginKey)) : all;- return providerChoices(seats, JSON.parse(accessKey) as Record<string, string[]>, external, JSON.parse(blockedKey) as AccessBlocked);- }, [menu.options, menu.providers, menu.live, defaultModelLabel, external, supportedKey, gatewayKey, loginKey, accessKey, blockedKey]);+ function pickStarter(next: Starter) {+ if (next.id === starterId) { setMobilePreview(true); return; }+ setStarterId(next.id);+ setStarterName(starterCopy(t, next).name);+ setPicked(new Set(defaultTools(next.tools)));+ setRoutineOn(false);+ setMobilePreview(true);+ }+ useEffect(() => {+ // The preview is never empty: the gallery opens on its first starter.+ if (!starterId && starterList.length) {+ const first = starterList[0];+ setStarterId(first.id);+ setStarterName(starterCopy(t, first).name);+ setPicked(new Set(defaultTools(first.tools)));+ }+ // `t` is a fresh function every render; the first pick only follows the list.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [starterId, starterList]);- // The person's picks stay while they are offered; a pick that disappears (a- // key removed, another runtime chosen) falls back to the first one left.- const chosen = choices.find((choice) => choice.id === providerId)- ?? choices.find((choice) => pickableOption(choice)) ?? choices[0] ?? null;- // A refused access is listed with its reason but never picked.- const option: AccessOption | null = pickableOption(chosen, chosen ? access[chosen.id] : undefined);- const models = accessModels(option);- const accounts = accountChoice(option?.seat ?? null);- const modelValue = models.some((entry) => entry.id === model) ? model : defaultModel(option);- const accountValue = option?.seat.provider.id === accountProvider && accounts.some((entry) => entry.id === account) ? account : "";- const seatKey = `${chosen?.id ?? ""}|${option?.kind ?? ""}|${accountValue}`;+ // Import path.+ const [importText, setImportText] = useState(() => initial.template ? JSON.stringify(initial.template, null, 2) : "");+ const [imported, setImported] = useState<ImportState>(EMPTY_IMPORT);+ const [importName, setImportName] = useState("");+ const [importPicked, setImportPicked] = useState<Set<string>>(new Set());+ const importKey = imported.preview ? JSON.stringify(imported.template) : "";useEffect(() => {- // Another provider or access: its own default model, not the last one's id.- setModel("");- }, [seatKey]);+ if (!imported.preview) return;+ setImportName(imported.preview.template?.name ?? "");+ // The author's tools all stay picked; unticking narrows, nothing is added.+ setImportPicked(new Set(imported.preview.tools.map((tool) => tool.id)));+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [importKey]);- // A runtime still being set up does not hold creation back: the agent's- // first turn waits for the setup (agent_runtimes.manager). A Jarvis agent- // with nothing connected yet still starts: it takes the last chat seat.- const needsProvider = external && !option;- const accountBlocked = Boolean(account && accountProvider === option?.seat.provider.id- && (accountValue !== account || menu.loading || menu.failed));- const selectedModelsFailed = Boolean(option && menu.modelErrors?.includes(option.seat.provider.id));- const canCreate = !saving && !needsProvider && !accountBlocked && !selectedModelsFailed && (!option || models.length > 0);+ const pathReady = mode === "quick" ? true : mode === "starter" ? Boolean(starter) : Boolean(imported.preview && imported.template && !imported.pending);+ const canCreate = !saving && seat.ready && pathReady;++ async function afterInstall(result: InstallStarterResult, firstMessage: string) {+ const agent = rowToAgent(result.agent as unknown as SocietyAgentRow);+ // The island owes this row an entrance: it walks out of the foundry.+ announceSpawn(agent.agentId);+ await client.invalidateQueries({ queryKey: ["society", "roster"] });+ await seedFirstMessage(agent, firstMessage).catch(() => false);+ if (result.routine_error) {+ setCreated({ agent, routineError: result.routine_error });+ setSaving(false);+ return;+ }+ finish(agent);+ }async function submit() {+ if (created) { finish(created.agent); return; }if (!canCreate) return;setSaving(true);setError(null);try {- const agent = await createAgent({- name,- runtime,- executionEnvironment: external ? "local" : executionEnvironment,- provider: option?.seat.provider.id,- model: option ? modelValue : undefined,- accountId: option ? accountValue || option.accountId : undefined,- companion,- });- finish(agent);+ if (mode === "quick") {+ const agent = await createAgent({+ name,+ mission: job,+ runtime: seat.pick.runtime,+ executionEnvironment: seat.pick.executionEnvironment,+ provider: seat.pick.provider,+ model: seat.pick.model,+ accountId: seat.pick.accountId,+ companion,+ });+ finish(agent);+ return;+ }+ if (mode === "starter" && starter && copy) {+ const result = await installStarter({+ starterId: starter.id,+ name: starterName,+ tools: [...picked],+ withRoutine: Boolean(starter.routine && routineOn),+ seat: starterSeat(seat.pick, companion),+ });+ await afterInstall(result, copy.firstMessage);+ return;+ }+ if (mode === "import" && imported.template) {+ const result = await installStarter({+ template: imported.template,+ name: importName,+ tools: [...importPicked],+ seat: starterSeat(seat.pick, companion),+ });+ await afterInstall(result, "");+ }} catch (exc) {setError(exc instanceof AgentNameTaken@@ -141,149 +213,205 @@ function CreateAgentDialog() {}}+ const toggle = (set: Set<string>, id: string) => {+ const next = new Set(set);+ if (next.has(id)) next.delete(id); else next.add(id);+ return next;+ };++ const submitLabel = created+ ? t("agent_create.open_chat")+ : t(saving ? "society.create_agent.creating" : "society.create_agent.create");+return (- <Dialog.Root open onOpenChange={(next) => { if (!next && !saving) cancel(); }}>+ <Dialog.Root open onOpenChange={(next) => { if (!next && !saving) (created ? finish(created.agent) : cancel()); }}><Dialog.Portal>- <Dialog.Overlay className="fixed inset-0 z-50 bg-scrim/60 backdrop-blur-sm" />+ <Dialog.Overlay className="fixed inset-0 z-50 bg-scrim/60 backdrop-blur-sm motion-safe:animate-in motion-safe:fade-in-0" /><Dialog.Contentdata-testid="create-agent-dialog"- className="fixed left-1/2 top-1/2 z-50 flex max-h-[90dvh] w-[min(560px,calc(100vw-24px))] -translate-x-1/2 -translate-y-1/2 flex-col overflow-hidden rounded-xl border border-border bg-popover text-foreground shadow-float"+ aria-describedby={undefined}+ className={cn(+ "fixed left-1/2 top-1/2 z-50 flex max-h-[92dvh] -translate-x-1/2 -translate-y-1/2 flex-col overflow-hidden",+ "rounded-[18px] border border-border bg-popover text-foreground shadow-float",+ mode === "quick" ? "w-[min(880px,calc(100vw-24px))]" : "h-[min(720px,92dvh)] w-[min(960px,calc(100vw-24px))]",+ )}>- <header className="flex items-center gap-3 border-b border-border p-4">- <div className="flex-1">- <Dialog.Title className="font-semibold">{t("society.create_agent.title")}</Dialog.Title>- <Dialog.Description className="text-sm text-muted-foreground">- {t("society.create_agent.subtitle")}- </Dialog.Description>+ <header className="flex shrink-0 flex-col gap-3 border-b border-border px-5 pb-3 pt-4">+ <div className="flex items-start gap-3">+ <div className="min-w-0 flex-1">+ <Dialog.Title className="text-lg font-semibold text-foreground-strong">{t("society.create_agent.title")}</Dialog.Title>+ <p className="text-sm text-muted-foreground" data-testid="create-agent-subtitle">{t(`agent_create.mode.${mode}_hint`)}</p>+ </div>+ <button type="button" aria-label={t("society.card.close")} onClick={() => { if (!saving) (created ? finish(created.agent) : cancel()); }}+ className="rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <X size={18} />+ </button>+ </div>+ <div role="tablist" aria-label={t("agent_create.mode.label")} className="flex w-full gap-1 rounded-[10px] border border-border bg-background/60 p-1 sm:w-auto sm:self-start">+ {MODES.map((entry, index) => {+ const on = entry.id === mode;+ return (+ <button+ key={entry.id}+ ref={(node) => { modeTabs.current[index] = node; }}+ type="button"+ role="tab"+ aria-selected={on}+ tabIndex={on ? 0 : -1}+ onKeyDown={(event) => onModeKey(event, index)}+ disabled={saving || Boolean(created)}+ onClick={() => { setMode(entry.id); setError(null); }}+ data-testid={`create-agent-mode-${entry.id}`}+ className={cn(+ "inline-flex flex-1 items-center justify-center gap-1.5 rounded-[7px] px-3 py-1.5 text-sm transition-colors duration-150 sm:flex-none",+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50",+ on ? "bg-secondary text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground",+ )}+ >+ {entry.icon}+ {t(`agent_create.mode.${entry.id}`)}+ </button>+ );+ })}</div>- <button type="button" aria-label={t("society.card.close")} onClick={() => { if (!saving) cancel(); }} className="rounded p-2 hover:bg-secondary">- <X size={18} />- </button></header>- <form- className="flex min-h-0 flex-col"- onSubmit={(event) => { event.preventDefault(); void submit(); }}- >- <div className="flex min-h-0 flex-col gap-5 overflow-y-auto p-4">- <label className="flex flex-col gap-1.5 text-sm">- <span className="font-medium">{t("society.create_agent.name_label")}</span>- <Input- autoFocus- value={name}- maxLength={40}- onChange={(event) => setName(event.target.value)}- placeholder={t("society.create_agent.name_placeholder")}- disabled={saving}- data-testid="create-agent-name"- />- </label>- <div className="flex flex-col gap-1.5 text-sm">- <span className="font-medium">{t("society.create_agent.type_label")}</span>- <RuntimeChoice value={runtime} onChange={(next) => { setRuntime(next); setAccount(""); }} disabled={saving} />- <p className="text-xs text-muted-foreground">{t("society.create_agent.type_fixed")}</p>- </div>-- <div className="flex flex-col gap-1.5 text-sm">- <span className="font-medium">{t("society.create_agent.provider_label")}</span>- {chosen ? (- <BrandedSelect- value={chosen.id}- onValueChange={(next) => { setProviderId(next); setAccount(""); }}- ariaLabel={t("society.create_agent.provider_label")}- disabled={saving}- testId="create-agent-provider"- options={choices.map((choice) => ({- value: choice.id,- label: choice.label,- // A coding CLI wears its own mark: a letter in a box is not a logo.- icon: choice.mark- ? <AgentMark agent={choice.mark} label={choice.label} logoUrl={choice.logoUrl} variant="plain" size="sm" />- : <ProviderLogo providerId={choice.logo} label={choice.label} size="sm" />,- }))}- />- ) : (- <p className="text-xs text-muted-foreground">- {menu.loading- ? t("society.create.catalog_loading")- : t(external ? "society.create_agent.no_provider" : "society.create_agent.no_provider_jarvis")}- </p>- )}+ <form className="flex min-h-0 flex-1 flex-col" onSubmit={(event) => { event.preventDefault(); void submit(); }}>+ {mode === "quick" ? (+ <div className="grid min-h-0 flex-1 overflow-y-auto md:grid-cols-2 md:overflow-hidden">+ <div className="flex min-h-0 flex-col gap-5 p-5 md:overflow-y-auto">+ <label className="flex flex-col gap-1.5 text-sm">+ <span className="font-medium">{t("society.create_agent.name_label")}</span>+ <Input+ autoFocus+ value={name}+ maxLength={40}+ onChange={(event) => setName(event.target.value)}+ placeholder={t("society.create_agent.name_placeholder")}+ disabled={saving}+ data-testid="create-agent-name"+ />+ </label>+ <label className="flex flex-col gap-1.5 text-sm">+ <span className="flex items-baseline justify-between gap-2">+ <span className="font-medium">{t("agent_create.quick.job_label")}</span>+ <span className="text-xs text-foreground-faint">{t("agent_create.quick.optional")}</span>+ </span>+ <Input+ value={job}+ maxLength={300}+ onChange={(event) => setJob(event.target.value)}+ placeholder={t("agent_create.quick.job_placeholder")}+ disabled={saving}+ data-testid="create-agent-job"+ />+ <span className="text-xs text-muted-foreground">{t("agent_create.quick.job_hint")}</span>+ </label>+ <div className="flex flex-col gap-1.5 text-sm">+ <span className="font-medium">{t("society.create_agent.companion_label")}</span>+ <div className="-mx-5">+ <Suspense fallback={null}>+ <CompanionEditor value={companion} onChange={setCompanion} disabled={saving} />+ </Suspense>+ </div>+ </div>+ </div>+ <div className="min-h-0 border-t border-border p-5 md:overflow-y-auto md:border-l md:border-t-0">+ <SeatFields seat={seat} disabled={saving} />+ </div></div>-- {chosen ? (- <AccessChoice- options={chosen.options}- value={option?.kind ?? ""}- hint={option ? t(option.extraUsage ? "society.create_agent.access_extra_usage" : `society.create_agent.access_hint_${option.kind}`) : ""}- disabled={saving}- onChange={(next) => { rememberAccess(chosen.id, next as ModelAccess); setAccount(""); }}- />- ) : null}-- {!external ? <SandboxChoice value={executionEnvironment} onChange={setExecutionEnvironment} disabled={saving} /> : null}- {chosen && option && accounts.length ? (- <div className="flex flex-col gap-1.5 text-sm">- <span className="font-medium">{t("society.create_agent.account_label")}</span>- <BrandedSelect- value={accountValue}- onValueChange={(next) => { setAccountProvider(option.seat.provider.id); setAccount(next); setModel(""); }}- ariaLabel={t("society.create_agent.account_label")}- disabled={saving}- testId="create-agent-account"- options={[- { value: "", label: t("society.create_agent.active_account") },- ...accounts.map((entry) => ({ value: entry.id, label: entry.label, hint: accountHint(entry) })),- ]}+ ) : mode === "starter" ? (+ <div className="grid min-h-0 flex-1 md:grid-cols-[320px_minmax(0,1fr)]">+ <div className={cn("flex min-h-0 flex-col p-4 md:border-r md:border-border", mobilePreview && "hidden md:flex")}>+ <StarterGallery+ starters={starterList}+ areas={starters.data?.areas ?? []}+ loading={starters.isLoading}+ failed={starters.isError}+ onRetry={() => void starters.refetch()}+ area={area}+ onAreaChange={setArea}+ query={query}+ onQueryChange={setQuery}+ selectedId={starterId}+ onSelect={pickStarter}/></div>- ) : null}-- {chosen && option ? (- <div className="flex flex-col gap-1.5 text-sm">- <div className="flex items-center justify-between gap-2">- <span className="font-medium">{t("society.create_agent.model_label")}</span>- <button type="button" disabled={saving || menu.refreshing} onClick={() => void Promise.all([menu.refresh(), runtimes.refetch()])}- aria-label={t("society.chat.model_refresh")} title={t("society.chat.model_refresh")}- className="rounded p-1 text-muted-foreground hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50">- {menu.refreshing ? <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden /> : <RefreshCw className="h-3.5 w-3.5" aria-hidden />}- </button>- </div>- <BrandedSelect- value={modelValue}- onValueChange={setModel}- ariaLabel={t("society.create_agent.model_label")}- placeholder={t("agent_chat.no_models")}- disabled={saving || accountBlocked || models.length === 0}- testId="create-agent-model"- searchPlaceholder={models.length >= SEARCH_FROM ? t("society.create_agent.model_search") : undefined}- options={models.map((entry) => ({- value: entry.id,- label: entry.label || entry.id || defaultModelLabel,- }))}- />- <p className="text-xs text-muted-foreground">{t("society.create_agent.model_hint")}</p>- {menu.refreshing ? <p role="status" className="text-xs text-muted-foreground">{t("society.chat.models_loading")}</p> : null}- {menu.refreshFailed || selectedModelsFailed ? <p role="alert" className="text-xs text-destructive">{t("society.chat.model_load_failed")}</p> : null}+ <div className={cn("flex min-h-0 flex-col gap-4 overflow-y-auto p-5", !mobilePreview && "hidden md:flex")}>+ <button type="button" onClick={() => setMobilePreview(false)}+ className="inline-flex items-center gap-1.5 self-start rounded text-xs text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring md:hidden">+ <ArrowLeft className="size-3.5" aria-hidden /> {t("agent_create.gallery.back")}+ </button>+ {starter && copy ? (+ <TemplatePreviewCard+ icon={<StarterIcon name={starter.icon} />}+ name={starterName}+ onNameChange={setStarterName}+ outcome={copy.outcome}+ summary={starter.summary}+ instructions={starter.instructions}+ tools={starter.tools}+ picked={picked}+ onToggleTool={(id) => setPicked((current) => toggle(current, id))}+ routine={starter.routine ? { title: copy.routineTitle, when: starter.routine.when } : null}+ routineOn={routineOn}+ onRoutineChange={setRoutineOn}+ firstMessage={copy.firstMessage}+ disabled={saving || Boolean(created)}+ />+ ) : (+ <EmptyPreview text={t(starters.isLoading ? "agent_create.gallery.loading" : "agent_create.preview.pick_prompt")} />+ )}+ <SeatSummary seat={seat} disabled={saving} /></div>- ) : null}-- <div className="flex flex-col gap-1.5 text-sm">- <span className="font-medium">{t("society.create_agent.companion_label")}</span>- <div className="-mx-4">- <Suspense fallback={null}>- <CompanionEditor value={companion} onChange={setCompanion} disabled={saving} />- </Suspense>+ </div>+ ) : (+ <div className="grid min-h-0 flex-1 overflow-y-auto md:grid-cols-[minmax(0,5fr)_minmax(0,6fr)] md:overflow-hidden">+ <div className="min-h-0 p-5 md:overflow-y-auto md:border-r md:border-border">+ <ImportTemplatePane text={importText} onTextChange={setImportText} onChange={setImported} disabled={saving} />+ </div>+ <div className="flex min-h-0 flex-col gap-4 p-5 md:overflow-y-auto">+ {imported.preview?.template && imported.preview.summary ? (+ <TemplatePreviewCard+ icon={<FileInput />}+ name={importName}+ onNameChange={setImportName}+ outcome={imported.preview.template.title || t("agent_create.import.no_title")}+ summary={imported.preview.summary}+ instructions={imported.preview.template.instructions}+ tools={imported.preview.tools}+ picked={importPicked}+ onToggleTool={(id) => setImportPicked((current) => toggle(current, id))}+ disabled={saving || Boolean(created)}+ note={<p className="text-xs text-foreground-faint">{t("agent_create.import.design_only")}</p>}+ />+ ) : (+ <EmptyPreview text={t("agent_create.import.empty_preview")} />+ )}+ <SeatSummary seat={seat} disabled={saving} /></div></div>- </div>- <footer className="flex shrink-0 flex-wrap items-center justify-end gap-2 border-t border-border p-4">- {error ? <p role="alert" className="mr-auto text-sm text-destructive">{error}</p> : null}- <Button type="button" variant="ghost" onClick={() => cancel()} disabled={saving}>- {t("society.create_agent.cancel")}- </Button>- <Button type="submit" disabled={!canCreate} data-testid="create-agent-submit">- {t(saving ? "society.create_agent.creating" : "society.create_agent.create")}+ )}++ <footer className="flex shrink-0 flex-wrap items-center justify-end gap-2 border-t border-border px-5 py-3">+ {created ? (+ <p role="alert" className="mr-auto flex items-center gap-1.5 text-sm text-warning" data-testid="create-agent-routine-error">+ <TriangleAlert className="size-4 shrink-0" aria-hidden />+ {fill(t("agent_create.routine_failed"), { agent: created.agent.name })}+ </p>+ ) : error ? (+ <p role="alert" className="mr-auto text-sm text-destructive">{error}</p>+ ) : (+ <p className="mr-auto hidden text-xs text-muted-foreground sm:block">{t(`agent_create.footer.${mode}`)}</p>+ )}+ {!created ? (+ <Button type="button" variant="ghost" onClick={() => cancel()} disabled={saving}>+ {t("society.create_agent.cancel")}+ </Button>+ ) : null}+ <Button type="submit" disabled={!created && !canCreate} data-testid="create-agent-submit">+ {saving ? <Loader2 className="animate-spin" aria-hidden /> : null}+ {submitLabel}</Button></footer></form>@@ -292,3 +420,12 @@ function CreateAgentDialog() {</Dialog.Root>);}++function EmptyPreview({ text }: { text: string }) {+ return (+ <div className="flex min-h-[220px] flex-1 flex-col items-center justify-center gap-2 rounded-[12px] border border-dashed border-border px-6 text-center" data-testid="create-agent-empty-preview">+ <LayoutGrid className="size-5 text-foreground-faint" aria-hidden />+ <p className="max-w-[28ch] text-sm text-muted-foreground">{text}</p>+ </div>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/society/create/ImportTemplatePane.tsx b/dodaios/ui/web/frontend/src/components/society/create/ImportTemplatePane.tsxnew file mode 100644index 0000000000..7424291d26--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/create/ImportTemplatePane.tsx@@ -0,0 +1,151 @@+/**+ * Bring an agent somebody shared: paste its template or open the file. The+ * backend checks it against the same stranger-safety rules the marketplace+ * uses (`agent_template.validate_template`) and counts what it brings, and+ * nothing is created until the person has read the preview and pressed+ * Create.+ */+import { useEffect, useRef, useState } from "react";+import { FileJson, Loader2, ShieldAlert, Upload } from "lucide-react";+import { Textarea } from "@/components/ui/textarea";+import { useT } from "@/i18n";+import { readFileText } from "@/lib/agentShare";+import { parseTemplateText, previewTemplate, type TemplatePreview } from "./startersApi";++export interface ImportState {+ template: Record<string, unknown> | null;+ preview: TemplatePreview | null;+ /** The text changed and its check is still running: the preview on screen+ * is the previous text's, so nothing may be created from it yet. */+ pending: boolean;+}++export const EMPTY_IMPORT: ImportState = { template: null, preview: null, pending: false };++interface Props {+ text: string;+ onTextChange: (text: string) => void;+ onChange: (state: ImportState) => void;+ disabled: boolean;+}++/** Wait this long after the last keystroke before asking the backend. */+const CHECK_DELAY_MS = 350;++export function ImportTemplatePane({ text, onTextChange, onChange, disabled }: Props) {+ const t = useT();+ const fileInput = useRef<HTMLInputElement>(null);+ const [checking, setChecking] = useState(false);+ const [problem, setProblem] = useState<string | null>(null);+ const [errors, setErrors] = useState<string[]>([]);+ const onChangeRef = useRef(onChange);+ onChangeRef.current = onChange;+ const last = useRef<ImportState>(EMPTY_IMPORT);+ const emit = (state: ImportState) => { last.current = state; onChangeRef.current(state); };+ // useT hands out a new function every render; the check runs on text only.+ const tRef = useRef(t);+ tRef.current = t;++ useEffect(() => {+ const trimmed = text.trim();+ setErrors([]);+ if (!trimmed) {+ setProblem(null);+ emit(EMPTY_IMPORT);+ return;+ }+ const template = parseTemplateText(trimmed);+ if (!template) {+ setProblem(tRef.current("agent_create.import.invalid_json"));+ emit(EMPTY_IMPORT);+ return;+ }+ setProblem(null);+ // Keep the last preview on screen while this text is checked, but hold Create.+ emit({ ...last.current, pending: true });+ let live = true;+ const timer = window.setTimeout(() => {+ setChecking(true);+ previewTemplate(template)+ .then((preview) => {+ if (!live) return;+ setErrors(preview.ok ? [] : preview.errors);+ emit({ template, preview: preview.ok ? preview : null, pending: false });+ })+ .catch((exc: unknown) => {+ if (!live) return;+ setProblem(exc instanceof Error ? exc.message : String(exc));+ emit(EMPTY_IMPORT);+ })+ .finally(() => { if (live) setChecking(false); });+ }, CHECK_DELAY_MS);+ return () => { live = false; window.clearTimeout(timer); };+ // `emit` only writes through refs.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [text]);++ async function openFile(file: File | undefined) {+ if (!file) return;+ try {+ onTextChange(await readFileText(file));+ } catch (exc) {+ setProblem(exc instanceof Error ? exc.message : String(exc));+ }+ }++ return (+ <div className="flex flex-col gap-3" data-testid="import-pane">+ <div className="flex items-center justify-between gap-2">+ <label htmlFor="agent-import-text" className="text-sm font-medium">{t("agent_create.import.paste_label")}</label>+ <button+ type="button"+ onClick={() => fileInput.current?.click()}+ disabled={disabled}+ className="inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-xs text-foreground transition-colors hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50"+ data-testid="import-open-file"+ >+ <Upload className="size-3.5" aria-hidden /> {t("agent_create.import.open_file")}+ </button>+ <input+ ref={fileInput}+ type="file"+ accept=".json,application/json"+ className="hidden"+ onChange={(event) => { void openFile(event.target.files?.[0]); event.target.value = ""; }}+ data-testid="import-file-input"+ />+ </div>+ <Textarea+ id="agent-import-text"+ value={text}+ onChange={(event) => onTextChange(event.target.value)}+ placeholder={t("agent_create.import.paste_placeholder")}+ disabled={disabled}+ spellCheck={false}+ className="min-h-[120px] font-mono text-sm"+ data-testid="import-text"+ />+ {checking ? (+ <p className="flex items-center gap-2 text-xs text-muted-foreground" role="status">+ <Loader2 className="size-3.5 animate-spin" aria-hidden /> {t("agent_create.import.checking")}+ </p>+ ) : null}+ {problem ? <p role="alert" className="text-xs text-destructive">{problem}</p> : null}+ {errors.length ? (+ <div role="alert" className="flex flex-col gap-1 rounded-[10px] border border-destructive/30 bg-destructive/5 px-3 py-2.5 text-xs" data-testid="import-errors">+ <p className="flex items-center gap-1.5 font-medium text-destructive">+ <ShieldAlert className="size-3.5" aria-hidden /> {t("agent_create.import.errors_title")}+ </p>+ <ul className="list-disc pl-5 text-foreground-secondary">+ {errors.map((error) => <li key={error}>{error}</li>)}+ </ul>+ </div>+ ) : null}+ {!text.trim() ? (+ <p className="flex items-start gap-2 text-xs text-muted-foreground">+ <FileJson className="mt-0.5 size-3.5 shrink-0" aria-hidden /> {t("agent_create.import.safety_note")}+ </p>+ ) : null}+ </div>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/society/create/SeatFields.tsx b/dodaios/ui/web/frontend/src/components/society/create/SeatFields.tsxnew file mode 100644index 0000000000..b7a9586e5e--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/create/SeatFields.tsx@@ -0,0 +1,271 @@+/**+ * What a new agent runs on: its runtime (Jarvis, Hermes or OpenClaw — fixed+ * for the agent's life), the provider, how it pays (subscription, API key or+ * local), the login and the model. Only what is connected on this machine is+ * offered (`seatChoice.ts`). Every path of the New-agent dialog — blank, a+ * starter, an imported template — shares this one choice, so a starter works+ * on any runtime and any provider exactly like a blank agent.+ */+import { useEffect, useMemo, useState } from "react";+import { ChevronDown, Loader2, RefreshCw } from "lucide-react";+import { BrandedSelect } from "@/components/ui/select";+import { AgentMark } from "@/components/agentic/AgentMark";+import { ProviderLogo } from "@/components/providers/ProviderLogo";+import { useT } from "@/i18n";+import type { AgentRuntime } from "@/lib/societyApi";+import { useModelAccess, type ModelAccess } from "@/lib/modelAccess";+import { cn } from "@/lib/utils";+import { RuntimeChoice, useAgentRuntimes } from "../card/RuntimePicker";+import { SandboxChoice } from "../card/AgentSandboxSection";+import { modelSeats, runtimeSeats } from "../chat/modelChoices";+import { useModelMenuData } from "../chat/useModelMenuData";+import { accountChoice, accountHint } from "./brainPicker";+import { AccessChoice } from "./AccessChoice";+import { accessModels, defaultModel, pickableOption, providerChoices, type AccessBlocked, type AccessOption } from "./seatChoice";++/** A model list this long gets a search field. */+const SEARCH_FROM = 12;++function list(value: unknown): string[] {+ return Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : [];+}++/** What the create request carries for the seat; blanks keep the backend defaults. */+export interface SeatPick {+ runtime: AgentRuntime;+ executionEnvironment: "local" | "sandbox";+ provider?: string;+ model?: string;+ accountId?: string;+}++export function useCreateSeat() {+ const t = useT();+ const runtimes = useAgentRuntimes();+ const [runtime, setRuntimeState] = useState<AgentRuntime>("jarvis");+ const [executionEnvironment, setExecutionEnvironment] = useState<"local" | "sandbox">("local");+ const [providerId, setProviderId] = useState("");+ const [access, rememberAccess] = useModelAccess();+ const [model, setModel] = useState("");+ const [account, setAccount] = useState("");+ const [accountProvider, setAccountProvider] = useState("");+ // A stored catalog may be a startup fallback. Revalidate on this user gesture,+ // and scope subscription models to the login that will actually run the agent.+ const menu = useModelMenuData(null, undefined,+ account && accountProvider ? { [accountProvider]: account } : {}, { refreshOnMount: true });++ const external = runtime !== "jarvis";+ const defaultModelLabel = t("agent_chat.model_default");+ const data = runtimes.data;+ const supportedKey = list(data?.supported_providers).join(",");+ const gatewayKey = list(data?.subscription_providers).join(",");+ const loginKey = list(data?.login_providers).join(",");+ const accessKey = JSON.stringify(data?.access && typeof data.access === "object" ? data.access : {});+ // Refusals only concern Hermes / OpenClaw (Claude's login billed as Extra Usage).+ const blockedKey = JSON.stringify(external && data?.access_blocked && typeof data.access_blocked === "object" ? data.access_blocked : {});+ const choices = useMemo(() => {+ const all = modelSeats(menu.options, Array.isArray(menu.providers) ? menu.providers : [], menu.live, defaultModelLabel);+ const split = (key: string) => key.split(",").filter(Boolean);+ const seats = external ? runtimeSeats(all, split(supportedKey), split(gatewayKey), split(loginKey)) : all;+ return providerChoices(seats, JSON.parse(accessKey) as Record<string, string[]>, external, JSON.parse(blockedKey) as AccessBlocked);+ }, [menu.options, menu.providers, menu.live, defaultModelLabel, external, supportedKey, gatewayKey, loginKey, accessKey, blockedKey]);++ // The person's picks stay while they are offered; a pick that disappears (a+ // key removed, another runtime chosen) falls back to the first one left.+ const chosen = choices.find((choice) => choice.id === providerId)+ ?? choices.find((choice) => pickableOption(choice)) ?? choices[0] ?? null;+ // A refused access is listed with its reason but never picked.+ const option: AccessOption | null = pickableOption(chosen, chosen ? access[chosen.id] : undefined);+ const models = accessModels(option);+ const accounts = accountChoice(option?.seat ?? null);+ const modelValue = models.some((entry) => entry.id === model) ? model : defaultModel(option);+ const accountValue = option?.seat.provider.id === accountProvider && accounts.some((entry) => entry.id === account) ? account : "";+ const seatKey = `${chosen?.id ?? ""}|${option?.kind ?? ""}|${accountValue}`;+ useEffect(() => {+ // Another provider or access: its own default model, not the last one's id.+ setModel("");+ }, [seatKey]);++ // A runtime still being set up does not hold creation back: the agent's+ // first turn waits for the setup (agent_runtimes.manager). A Jarvis agent+ // with nothing connected yet still starts: it takes the last chat seat.+ const needsProvider = external && !option;+ const accountBlocked = Boolean(account && accountProvider === option?.seat.provider.id+ && (accountValue !== account || menu.loading || menu.failed));+ const selectedModelsFailed = Boolean(option && menu.modelErrors?.includes(option.seat.provider.id));+ const ready = !needsProvider && !accountBlocked && !selectedModelsFailed && (!option || models.length > 0);++ const pick: SeatPick = {+ runtime,+ executionEnvironment: external ? "local" : executionEnvironment,+ provider: option?.seat.provider.id,+ model: option ? modelValue : undefined,+ accountId: option ? accountValue || option.accountId : undefined,+ };+ const modelLabel = models.find((entry) => entry.id === modelValue)?.label || modelValue || defaultModelLabel;++ return {+ runtimes, menu, choices, chosen, option, models, accounts, modelValue, accountValue,+ runtime, external, executionEnvironment, ready, accountBlocked, selectedModelsFailed, pick, modelLabel,+ defaultModelLabel,+ setRuntime: (next: AgentRuntime) => { setRuntimeState(next); setAccount(""); },+ setProvider: (next: string) => { setProviderId(next); setAccount(""); },+ setAccess: (kind: string) => { if (chosen) rememberAccess(chosen.id, kind as ModelAccess); setAccount(""); },+ setAccount: (next: string) => { if (option) setAccountProvider(option.seat.provider.id); setAccount(next); setModel(""); },+ setModel,+ setExecutionEnvironment,+ };+}++export type CreateSeat = ReturnType<typeof useCreateSeat>;++/** The full choice: runtime cards, provider, access, login and model. */+export function SeatFields({ seat, disabled }: { seat: CreateSeat; disabled: boolean }) {+ const t = useT();+ const { chosen, option, choices, menu, runtimes, models, accounts } = seat;+ return (+ <div className="flex flex-col gap-5">+ <div className="flex flex-col gap-1.5 text-sm">+ <span className="font-medium">{t("society.create_agent.type_label")}</span>+ <RuntimeChoice value={seat.runtime} onChange={seat.setRuntime} disabled={disabled} />+ <p className="text-xs text-muted-foreground" data-testid="create-agent-runtime-note">+ {t(`agent_create.runtime_note.${seat.runtime}`)}+ </p>+ </div>++ <div className="flex flex-col gap-1.5 text-sm">+ <span className="font-medium">{t("society.create_agent.provider_label")}</span>+ {chosen ? (+ <BrandedSelect+ value={chosen.id}+ onValueChange={seat.setProvider}+ ariaLabel={t("society.create_agent.provider_label")}+ disabled={disabled}+ testId="create-agent-provider"+ options={choices.map((choice) => ({+ value: choice.id,+ label: choice.label,+ // A coding CLI wears its own mark: a letter in a box is not a logo.+ icon: choice.mark+ ? <AgentMark agent={choice.mark} label={choice.label} logoUrl={choice.logoUrl} variant="plain" size="sm" />+ : <ProviderLogo providerId={choice.logo} label={choice.label} size="sm" />,+ }))}+ />+ ) : (+ <p className="text-xs text-muted-foreground">+ {menu.loading+ ? t("society.create.catalog_loading")+ : t(seat.external ? "society.create_agent.no_provider" : "society.create_agent.no_provider_jarvis")}+ </p>+ )}+ </div>++ {chosen ? (+ <AccessChoice+ options={chosen.options}+ value={option?.kind ?? ""}+ hint={option ? t(option.extraUsage ? "society.create_agent.access_extra_usage" : `society.create_agent.access_hint_${option.kind}`) : ""}+ disabled={disabled}+ onChange={seat.setAccess}+ />+ ) : null}++ {!seat.external ? <SandboxChoice value={seat.executionEnvironment} onChange={seat.setExecutionEnvironment} disabled={disabled} /> : null}+ {chosen && option && accounts.length ? (+ <div className="flex flex-col gap-1.5 text-sm">+ <span className="font-medium">{t("society.create_agent.account_label")}</span>+ <BrandedSelect+ value={seat.accountValue}+ onValueChange={seat.setAccount}+ ariaLabel={t("society.create_agent.account_label")}+ disabled={disabled}+ testId="create-agent-account"+ options={[+ { value: "", label: t("society.create_agent.active_account") },+ ...accounts.map((entry) => ({ value: entry.id, label: entry.label, hint: accountHint(entry) })),+ ]}+ />+ </div>+ ) : null}++ {chosen && option ? (+ <div className="flex flex-col gap-1.5 text-sm">+ <div className="flex items-center justify-between gap-2">+ <span className="font-medium">{t("society.create_agent.model_label")}</span>+ <button type="button" disabled={disabled || menu.refreshing} onClick={() => void Promise.all([menu.refresh(), runtimes.refetch()])}+ aria-label={t("society.chat.model_refresh")} title={t("society.chat.model_refresh")}+ className="rounded p-1 text-muted-foreground hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50">+ {menu.refreshing ? <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden /> : <RefreshCw className="h-3.5 w-3.5" aria-hidden />}+ </button>+ </div>+ <BrandedSelect+ value={seat.modelValue}+ onValueChange={seat.setModel}+ ariaLabel={t("society.create_agent.model_label")}+ placeholder={t("agent_chat.no_models")}+ disabled={disabled || seat.accountBlocked || models.length === 0}+ testId="create-agent-model"+ searchPlaceholder={models.length >= SEARCH_FROM ? t("society.create_agent.model_search") : undefined}+ options={models.map((entry) => ({+ value: entry.id,+ label: entry.label || entry.id || seat.defaultModelLabel,+ }))}+ />+ <p className="text-xs text-muted-foreground">{t("society.create_agent.model_hint")}</p>+ {menu.refreshing ? <p role="status" className="text-xs text-muted-foreground">{t("society.chat.models_loading")}</p> : null}+ {menu.refreshFailed || seat.selectedModelsFailed ? <p role="alert" className="text-xs text-destructive">{t("society.chat.model_load_failed")}</p> : null}+ </div>+ ) : null}+ </div>+ );+}++/**+ * The seat as one quiet line — "Runs on OpenAI · GPT-5.5 · API key" — that+ * opens into the full choice. The starter and import paths lead with the+ * job; the seat is already right for most people and one click away.+ */+export function SeatSummary({ seat, disabled }: { seat: CreateSeat; disabled: boolean }) {+ const t = useT();+ const [open, setOpen] = useState(false);+ const { chosen, option } = seat;+ const parts = [+ t(`society.runtime.${seat.runtime}`),+ chosen?.label,+ option ? seat.modelLabel : null,+ option ? t(`society.create.kind_${option.kind}`) : null,+ ].filter(Boolean);+ const blocked = !seat.ready;+ return (+ <section className="rounded-[10px] border border-border bg-sheen/[0.02]" data-testid="create-agent-seat-summary">+ <button+ type="button"+ onClick={() => setOpen((value) => !value)}+ aria-expanded={open}+ disabled={disabled}+ className="flex w-full items-center gap-3 rounded-[10px] px-3 py-2.5 text-left transition-colors hover:bg-secondary/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <span className="flex size-7 shrink-0 items-center justify-center rounded-md border border-border bg-background">+ {chosen?.mark+ ? <AgentMark agent={chosen.mark} label={chosen.label} logoUrl={chosen.logoUrl} variant="plain" size="sm" />+ : chosen ? <ProviderLogo providerId={chosen.logo} label={chosen.label} size="sm" /> : null}+ </span>+ <span className="min-w-0 flex-1">+ <span className="block text-xs text-muted-foreground">{t("agent_create.seat.runs_on")}</span>+ <span className={cn("block truncate text-sm", blocked ? "text-warning" : "text-foreground")}>+ {blocked ? t("agent_create.seat.needs_choice") : parts.join(" · ")}+ </span>+ </span>+ <span className="flex shrink-0 items-center gap-1 text-xs text-muted-foreground">+ {t(open ? "agent_create.seat.hide" : "agent_create.seat.change")}+ <ChevronDown className={cn("size-3.5 transition-transform duration-200 motion-reduce:transition-none", open && "rotate-180")} aria-hidden />+ </span>+ </button>+ {open || blocked ? (+ <div className="border-t border-border px-3 py-4">+ <SeatFields seat={seat} disabled={disabled} />+ </div>+ ) : null}+ </section>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/society/create/StarterGallery.tsx b/dodaios/ui/web/frontend/src/components/society/create/StarterGallery.tsxnew file mode 100644index 0000000000..32b4e29c39--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/create/StarterGallery.tsx@@ -0,0 +1,158 @@+/**+ * The starter list: a search, one chip per area with its live count, and+ * dense rows (icon, name, the outcome in one line). Arrow keys move through+ * the rows; the picked row carries the selection wash.+ */+import { useMemo, useRef, type KeyboardEvent } from "react";+import { Loader2, Search } from "lucide-react";+import { Input } from "@/components/ui/input";+import { useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { AreaIcon, StarterIcon } from "./starterIcons";+import { areaCounts, filterStarters, starterCopy, type AreaFilter } from "./starterFilters";+import type { Starter, StarterArea } from "./startersApi";++interface Props {+ starters: Starter[];+ areas: StarterArea[];+ loading: boolean;+ failed: boolean;+ onRetry: () => void;+ area: AreaFilter;+ onAreaChange: (area: AreaFilter) => void;+ query: string;+ onQueryChange: (query: string) => void;+ selectedId: string | null;+ onSelect: (starter: Starter) => void;+}++export function StarterGallery(props: Props) {+ const t = useT();+ const rows = useRef<(HTMLButtonElement | null)[]>([]);+ const copyOf = useMemo(() => {+ const cache = new Map<string, ReturnType<typeof starterCopy>>();+ return (starter: Starter) => {+ let copy = cache.get(starter.id);+ if (!copy) {+ copy = starterCopy(t, starter);+ cache.set(starter.id, copy);+ }+ return copy;+ };+ }, [t]);+ const shown = useMemo(+ () => filterStarters(props.starters, props.area, props.query, copyOf),+ [props.starters, props.area, props.query, copyOf],+ );+ const counts = useMemo(+ () => areaCounts(props.starters, props.areas, props.query, copyOf),+ [props.starters, props.areas, props.query, copyOf],+ );+ const chips: AreaFilter[] = ["all", ...props.areas];+ // One row is always reachable with Tab, even when the picked starter is filtered out.+ const selectedShown = shown.some((starter) => starter.id === props.selectedId);++ function onRowKey(event: KeyboardEvent<HTMLButtonElement>, index: number) {+ const step = { ArrowDown: 1, ArrowUp: -1 }[event.key];+ if (!step) return;+ event.preventDefault();+ const next = Math.min(shown.length - 1, Math.max(0, index + step));+ rows.current[next]?.focus();+ props.onSelect(shown[next]);+ }++ return (+ <div className="flex min-h-0 flex-1 flex-col gap-3" data-testid="starter-gallery">+ <div className="relative">+ <Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-foreground-faint" aria-hidden />+ <Input+ value={props.query}+ onChange={(event) => props.onQueryChange(event.target.value)}+ placeholder={t("agent_create.gallery.search")}+ aria-label={t("agent_create.gallery.search")}+ className="pl-9"+ data-testid="starter-search"+ />+ </div>+ <div className="flex flex-wrap gap-1.5" role="group" aria-label={t("agent_create.gallery.areas")}>+ {chips.map((area) => {+ const on = props.area === area;+ return (+ <button+ key={area}+ type="button"+ aria-pressed={on}+ onClick={() => props.onAreaChange(area)}+ data-testid={`starter-area-${area}`}+ className={cn(+ "inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs transition-colors",+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ on+ ? "border-foreground/30 bg-secondary text-foreground"+ : "border-border text-muted-foreground hover:bg-secondary hover:text-foreground",+ )}+ >+ <AreaIcon area={area} className="size-3.5" />+ {t(`agent_create.area.${area}`)}+ <span className="tabular-nums text-foreground-faint">{counts[area] ?? 0}</span>+ </button>+ );+ })}+ </div>++ <div className="-mx-1 min-h-0 flex-1 overflow-y-auto px-1" role="listbox" aria-label={t("agent_create.mode.starter")}>+ {props.loading ? (+ <p className="flex items-center gap-2 px-2 py-6 text-sm text-muted-foreground" role="status">+ <Loader2 className="size-4 animate-spin" aria-hidden /> {t("agent_create.gallery.loading")}+ </p>+ ) : props.failed ? (+ <div className="flex flex-col items-start gap-2 px-2 py-6 text-sm">+ <p role="alert" className="text-destructive">{t("agent_create.gallery.failed")}</p>+ <button type="button" onClick={props.onRetry} className="rounded-full border border-border px-2.5 py-1 text-xs hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ {t("agent_create.gallery.retry")}+ </button>+ </div>+ ) : shown.length === 0 ? (+ <p className="px-2 py-6 text-sm text-muted-foreground" data-testid="starter-empty">{t("agent_create.gallery.empty")}</p>+ ) : (+ <ul className="flex flex-col gap-0.5">+ {shown.map((starter, index) => {+ const copy = copyOf(starter);+ const selected = starter.id === props.selectedId;+ return (+ <li key={starter.id}>+ <button+ ref={(node) => { rows.current[index] = node; }}+ type="button"+ role="option"+ aria-selected={selected}+ tabIndex={selected || (!selectedShown && index === 0) ? 0 : -1}+ onClick={() => props.onSelect(starter)}+ onKeyDown={(event) => onRowKey(event, index)}+ data-testid={`starter-${starter.id}`}+ className={cn(+ "group flex w-full items-center gap-3 rounded-[10px] px-2.5 py-2 text-left transition-colors duration-150",+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ selected ? "bg-accent-soft" : "hover:bg-secondary/70",+ )}+ >+ <span className={cn(+ "flex size-8 shrink-0 items-center justify-center rounded-[8px] border transition-colors",+ selected ? "border-accent/40 bg-background text-accent" : "border-border bg-secondary/60 text-foreground-secondary group-hover:text-foreground",+ )}>+ <StarterIcon name={starter.icon} className="size-4" />+ </span>+ <span className="min-w-0 flex-1">+ <span className="block truncate text-sm font-medium text-foreground">{copy.name}</span>+ <span className="block truncate text-xs text-muted-foreground">{copy.outcome}</span>+ </span>+ </button>+ </li>+ );+ })}+ </ul>+ )}+ </div>+ </div>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/society/create/TemplatePreviewCard.tsx b/dodaios/ui/web/frontend/src/components/society/create/TemplatePreviewCard.tsxnew file mode 100644index 0000000000..f8c5e9bf74--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/create/TemplatePreviewCard.tsx@@ -0,0 +1,208 @@+/**+ * What a starter or an imported template brings, before anything exists: a+ * name the person can change, the outcome in one line, counted contents+ * (instructions, skills, routines, tools, confirmations), the tools with+ * their state on THIS machine, the optional routine, and the first message+ * the chat will open with. One card for both paths, so a stranger's template+ * is read exactly as carefully as one of ours.+ */+import { useId, useState, type ReactNode } from "react";+import { BookText, Check, ChevronDown, Clock, Repeat, ShieldCheck, Sparkles, Wrench } from "lucide-react";+import { Input } from "@/components/ui/input";+import { Switch } from "@/components/ui/switch";+import { fill, useT } from "@/i18n";+import { cn } from "@/lib/utils";+import type { StarterTool, TemplateSummary } from "./startersApi";++export interface PreviewRoutine {+ title: string;+ /** The named schedule slot (`weekday_morning`, …). */+ when: string;+}++interface Props {+ icon: ReactNode;+ name: string;+ onNameChange: (name: string) => void;+ outcome: string;+ summary: TemplateSummary;+ instructions: string;+ tools: StarterTool[];+ /** Ticked tool ids. */+ picked: ReadonlySet<string>;+ onToggleTool: (id: string) => void;+ routine?: PreviewRoutine | null;+ routineOn?: boolean;+ onRoutineChange?: (on: boolean) => void;+ firstMessage?: string;+ disabled: boolean;+ /** Extra content under the header (an import's source line). */+ note?: ReactNode;+}++function Stat({ icon, label, value, testId }: { icon: ReactNode; label: string; value: string; testId: string }) {+ return (+ <div className="flex min-w-0 flex-col gap-1 rounded-[10px] border border-border bg-background/60 px-3 py-2.5" data-testid={testId}>+ <span className="flex items-center gap-1.5 text-xs text-muted-foreground">+ <span className="text-foreground-faint [&>svg]:size-3.5" aria-hidden>{icon}</span>+ {label}+ </span>+ <span className="truncate text-sm font-medium text-foreground-strong">{value}</span>+ </div>+ );+}++function toolState(tool: StarterTool): "connected" | "not_connected" | "missing" {+ if (tool.connected) return "connected";+ return tool.available ? "not_connected" : "missing";+}++export function TemplatePreviewCard(props: Props) {+ const t = useT();+ const nameId = useId();+ const [showInstructions, setShowInstructions] = useState(false);+ const { summary, tools, picked, routine } = props;+ const pickedCount = tools.filter((tool) => picked.has(tool.id)).length;+ const instructionsValue = summary.instructions_rules > 0+ ? fill(t("agent_create.preview.instructions_rules"), { rules: summary.instructions_rules, words: summary.instructions_words })+ : fill(t("agent_create.preview.instructions_words"), { words: summary.instructions_words });+ const routineCount = routine ? (props.routineOn ? 1 : 0) : summary.routines;++ return (+ <article className="flex flex-col gap-5" data-testid="template-preview">+ <header className="flex items-start gap-3">+ <span className="flex size-11 shrink-0 items-center justify-center rounded-[12px] border border-border bg-secondary text-foreground [&>svg]:size-5" aria-hidden>+ {props.icon}+ </span>+ <div className="flex min-w-0 flex-1 flex-col gap-1">+ <label htmlFor={nameId} className="sr-only">{t("agent_create.preview.name_label")}</label>+ <Input+ id={nameId}+ value={props.name}+ maxLength={40}+ onChange={(event) => props.onNameChange(event.target.value)}+ disabled={props.disabled}+ data-testid="template-preview-name"+ className="h-9 border-transparent bg-transparent px-2 -mx-2 text-lg font-semibold text-foreground-strong hover:border-border focus-visible:border-accent"+ />+ <p className="text-sm text-foreground-secondary">{props.outcome}</p>+ {props.note}+ </div>+ </header>++ <section aria-label={t("agent_create.preview.brings")} className="flex flex-col gap-2">+ <h3 className="text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground">{t("agent_create.preview.brings")}</h3>+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-4">+ <Stat icon={<BookText />} label={t("agent_create.preview.instructions")} value={instructionsValue} testId="preview-count-instructions" />+ <Stat icon={<Sparkles />} label={t("agent_create.preview.skills")}+ value={summary.skills === null ? t("agent_create.preview.skills_all") : String(summary.skills)} testId="preview-count-skills" />+ <Stat icon={<Repeat />} label={t("agent_create.preview.routines")} value={String(routineCount)} testId="preview-count-routines" />+ <Stat icon={<Wrench />} label={t("agent_create.preview.tools")}+ value={tools.length ? fill(t("agent_create.preview.tools_value"), { picked: pickedCount, total: tools.length }) : "0"} testId="preview-count-tools" />+ </div>+ {summary.asks_before > 0 ? (+ <p className="flex items-center gap-1.5 text-xs text-muted-foreground" data-testid="preview-asks-before">+ <ShieldCheck className="size-3.5 text-success" aria-hidden />+ {fill(t(summary.asks_before === 1 ? "agent_create.preview.asks_before_one" : "agent_create.preview.asks_before_other"), { count: summary.asks_before })}+ </p>+ ) : null}+ {summary.limited_tools ? (+ <p className="text-xs text-muted-foreground">{t("agent_create.preview.limited_tools")}</p>+ ) : null}+ </section>++ {tools.length ? (+ <section className="flex flex-col gap-2">+ <div className="flex items-baseline justify-between gap-2">+ <h3 className="text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground">{t("agent_create.preview.tools_title")}</h3>+ <span className="text-xs text-foreground-faint">{t("agent_create.preview.tools_hint")}</span>+ </div>+ <ul className="flex flex-col divide-y divide-border overflow-hidden rounded-[10px] border border-border">+ {tools.map((tool) => {+ const state = toolState(tool);+ const on = picked.has(tool.id);+ return (+ <li key={tool.id}>+ <label className={cn(+ "flex cursor-pointer items-center gap-3 px-3 py-2 text-sm transition-colors hover:bg-secondary/50",+ props.disabled && "cursor-default opacity-60",+ )}>+ <input+ type="checkbox"+ className="peer sr-only"+ checked={on}+ disabled={props.disabled}+ onChange={() => props.onToggleTool(tool.id)}+ data-testid={`preview-tool-${tool.id}`}+ />+ <span className={cn(+ "flex size-4 shrink-0 items-center justify-center rounded-[4px] border transition-colors peer-focus-visible:ring-2 peer-focus-visible:ring-ring",+ on ? "border-foreground bg-foreground text-background" : "border-border-strong bg-transparent",+ )} aria-hidden>+ {on ? <Check className="size-3" strokeWidth={3} /> : null}+ </span>+ <span className="min-w-0 flex-1 truncate text-foreground">{tool.label}</span>+ <span className={cn(+ "shrink-0 rounded-full px-2 py-0.5 text-xs",+ state === "connected" && "bg-success/10 text-success",+ state === "not_connected" && "bg-warning/10 text-warning",+ state === "missing" && "bg-secondary text-muted-foreground",+ )}>+ {t(`agent_create.preview.tool_${state}`)}+ </span>+ </label>+ </li>+ );+ })}+ </ul>+ </section>+ ) : null}++ {routine && props.onRoutineChange ? (+ <section className="flex items-start gap-3 rounded-[10px] border border-border px-3 py-3" data-testid="preview-routine">+ <Clock className="mt-0.5 size-4 shrink-0 text-muted-foreground" aria-hidden />+ <div className="min-w-0 flex-1">+ <p className="text-sm text-foreground">{routine.title}</p>+ <p className="text-xs text-muted-foreground">+ {t(`agent_create.when.${routine.when}`)} · {t("agent_create.preview.routine_hint")}+ </p>+ </div>+ <Switch+ checked={Boolean(props.routineOn)}+ onCheckedChange={props.onRoutineChange}+ disabled={props.disabled}+ aria-label={t("agent_create.preview.routine_toggle")}+ data-testid="preview-routine-toggle"+ />+ </section>+ ) : null}++ <section className="flex flex-col gap-2">+ <button+ type="button"+ onClick={() => setShowInstructions((value) => !value)}+ aria-expanded={showInstructions}+ className="flex items-center gap-1.5 self-start rounded text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ {t("agent_create.preview.read_instructions")}+ <ChevronDown className={cn("size-3.5 transition-transform duration-200 motion-reduce:transition-none", showInstructions && "rotate-180")} aria-hidden />+ </button>+ {showInstructions ? (+ <pre className="max-h-48 overflow-y-auto whitespace-pre-wrap rounded-[10px] border border-border bg-background/60 px-3 py-2.5 font-sans text-sm text-foreground-secondary" data-testid="preview-instructions">+ {props.instructions}+ </pre>+ ) : null}+ </section>++ {props.firstMessage ? (+ <section className="flex flex-col gap-1.5">+ <h3 className="text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground">{t("agent_create.preview.first_message")}</h3>+ <p className="rounded-[10px] border border-dashed border-border-strong px-3 py-2.5 text-sm text-foreground" data-testid="preview-first-message">+ {props.firstMessage}+ </p>+ <p className="text-xs text-foreground-faint">{t("agent_create.preview.first_message_hint")}</p>+ </section>+ ) : null}+ </article>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/society/create/agentCreate-i18n.test.ts b/dodaios/ui/web/frontend/src/components/society/create/agentCreate-i18n.test.tsnew file mode 100644index 0000000000..a43479a94d--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/create/agentCreate-i18n.test.ts@@ -0,0 +1,108 @@+/**+ * The New-agent dialog's own key block (`agent_create`) exists in all five+ * locales with the same keys, every key the dialog asks for is there, and+ * every starter in the backend catalogue has its translated copy and an icon+ * the gallery can draw.+ */+import { readFileSync, readdirSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, test } from "vitest";+import en from "@/i18n/locales/en.json";+import de from "@/i18n/locales/de.json";+import es from "@/i18n/locales/es.json";+import pt from "@/i18n/locales/pt.json";+import zh from "@/i18n/locales/zh.json";+import { KNOWN_STARTER_ICONS } from "./starterIcons";++const LOCALES: Record<string, Record<string, unknown>> = { en, de, es, pt, zh };+const STARTER_DIR = join(__dirname, "..", "..", "..", "..", "..", "..", "..", "society", "starters");++function flatten(obj: Record<string, unknown>, prefix = ""): string[] {+ return Object.entries(obj).flatMap(([key, value]) => {+ const path = prefix ? `${prefix}.${key}` : key;+ return value && typeof value === "object" && !Array.isArray(value)+ ? flatten(value as Record<string, unknown>, path)+ : [path];+ });+}++function block(locale: Record<string, unknown>): Record<string, unknown> {+ return (locale.agent_create ?? {}) as Record<string, unknown>;+}++function lookup(locale: Record<string, unknown>, key: string): unknown {+ return key.split(".").reduce<unknown>((node, part) =>+ node && typeof node === "object" ? (node as Record<string, unknown>)[part] : undefined, locale);+}++interface StarterEntry { id: string; icon: string; routine?: { when: string } }++function starters(): StarterEntry[] {+ return readdirSync(STARTER_DIR).filter((name) => name.endsWith(".json")).flatMap((name) =>+ (JSON.parse(readFileSync(join(STARTER_DIR, name), "utf8")) as { starters: StarterEntry[] }).starters);+}++function sourceKeys(): string[] {+ const dir = __dirname;+ const keys = new Set<string>();+ for (const name of readdirSync(dir)) {+ if (!/\.tsx?$/.test(name) || /\.test\.tsx?$/.test(name)) continue;+ const text = readFileSync(join(dir, name), "utf8");+ for (const match of text.matchAll(/t\(\s*"(agent_create\.[a-z0-9_.]+)"/g)) keys.add(match[1]);+ }+ return [...keys];+}++describe("agent_create locale block", () => {+ const reference = flatten(block(en)).sort();++ test("every locale carries exactly the English keys, none empty", () => {+ expect(reference.length).toBeGreaterThan(100);+ for (const [lang, locale] of Object.entries(LOCALES)) {+ expect(flatten(block(locale)).sort(), lang).toEqual(reference);+ for (const key of reference) {+ const value = lookup(block(locale), key);+ expect(typeof value === "string" && value.trim().length > 0, `${lang}: ${key}`).toBe(true);+ }+ }+ });++ test("every literal key the dialog uses exists", () => {+ const used = sourceKeys();+ expect(used.length).toBeGreaterThan(20);+ for (const key of used) expect(lookup(en, key), key).toBeTypeOf("string");+ });++ test("every templated key the dialog builds exists", () => {+ const keys = [+ ...["quick", "starter", "import"].flatMap((mode) => [`agent_create.mode.${mode}`, `agent_create.mode.${mode}_hint`, `agent_create.footer.${mode}`]),+ ...["jarvis", "hermes", "openclaw"].map((runtime) => `agent_create.runtime_note.${runtime}`),+ ...["all", "coding", "research", "inbox", "writing", "ops", "personal"].map((area) => `agent_create.area.${area}`),+ ...["connected", "not_connected", "missing"].map((state) => `agent_create.preview.tool_${state}`),+ ];+ for (const key of keys) expect(lookup(en, key), key).toBeTypeOf("string");+ });++ test("every starter has translated copy, a known schedule and a drawable icon", () => {+ const all = starters();+ expect(all.length).toBeGreaterThanOrEqual(20);+ for (const entry of all) {+ const base = `agent_create.starter.${entry.id.replace(/-/g, "_")}`;+ for (const [lang, locale] of Object.entries(LOCALES)) {+ for (const field of ["name", "outcome", "first"]) {+ expect(lookup(locale, `${base}.${field}`), `${lang}: ${base}.${field}`).toBeTypeOf("string");+ }+ expect(lookup(locale, `${base}.routine`) !== undefined, `${lang}: ${base}.routine`).toBe(Boolean(entry.routine));+ if (entry.routine) expect(lookup(locale, `agent_create.when.${entry.routine.when}`)).toBeTypeOf("string");+ }+ expect(KNOWN_STARTER_ICONS, entry.icon).toContain(entry.icon);+ }+ });++ test("German copy uses real umlauts, never ae/oe/ue stand-ins", () => {+ const text = JSON.stringify(block(de));+ for (const word of ["fuer", "Pruef", "waehl", "Uebersicht", "koennen", "moechte", "Laeuft"]) { // i18n-allow: stand-in spellings the test forbids+ expect(text.includes(word), word).toBe(false);+ }+ });+});diff --git a/dodaios/ui/web/frontend/src/components/society/create/createAgentStore.ts b/dodaios/ui/web/frontend/src/components/society/create/createAgentStore.tsindex 4c08fb6efc..4d193f2c61 100644--- a/dodaios/ui/web/frontend/src/components/society/create/createAgentStore.ts+++ b/dodaios/ui/web/frontend/src/components/society/create/createAgentStore.ts@@ -1,9 +1,9 @@/*** The "new agent" dialog, opened from every plus in the society (the Agents- * page, the office's reception, the foundry). `request()` opens it and- * settles once the person created an agent — or rejects with- * `CreateAgentCancelled` when they closed it — so each plus keeps its own- * "then open the new agent's chat" step.+ * page, the office's reception, the foundry) and from the marketplace's+ * template import. `request()` opens it and settles once the person created+ * an agent — or rejects with `CreateAgentCancelled` when they closed it — so+ * each plus keeps its own "then open the new agent's chat" step.*/import { create } from "zustand";import type { SocietyAgent } from "../data";@@ -15,9 +15,24 @@ export class CreateAgentCancelled extends Error {}}+/** The dialog's three ways in: blank, a starter from the gallery, an imported template. */+export type CreateAgentMode = "quick" | "starter" | "import";++export interface CreateAgentRequest {+ /** Which path the dialog opens on; blank by default. */+ mode?: CreateAgentMode;+ /** A template to preview straight away (opens on the import path). */+ template?: Record<string, unknown>;+}+interface CreateAgentDialogState {open: boolean;- request: () => Promise<SocietyAgent>;+ /** What the current request asked the dialog to open on. */+ initial: CreateAgentRequest;+ /** Counts requests that bring their own starting point (a template, a+ * path): those start from a fresh form, a plain second plus keeps it. */+ requestId: number;+ request: (options?: CreateAgentRequest) => Promise<SocietyAgent>;/** The dialog created the agent: settle the pending request. */finish: (agent: SocietyAgent) => void;cancel: () => void;@@ -27,23 +42,30 @@ let pending: { resolve: (agent: SocietyAgent) => void; reject: (error: Error) =>export const useCreateAgentDialog = create<CreateAgentDialogState>((set) => ({open: false,- request: () => {+ initial: {},+ requestId: 0,+ request: (options = {}) => {// A second plus while the dialog is open re-targets the same dialog.pending?.reject(new CreateAgentCancelled());+ const fresh = Boolean(options.mode || options.template);return new Promise<SocietyAgent>((resolve, reject) => {pending = { resolve, reject };- set({ open: true });+ set((state) => ({+ open: true,+ initial: fresh ? (options.template ? { mode: "import", ...options } : options) : state.open ? state.initial : {},+ requestId: fresh ? state.requestId + 1 : state.requestId,+ }));});},finish: (agent) => {pending?.resolve(agent);pending = null;- set({ open: false });+ set({ open: false, initial: {} });},cancel: () => {pending?.reject(new CreateAgentCancelled());pending = null;- set({ open: false });+ set({ open: false, initial: {} });},}));diff --git a/dodaios/ui/web/frontend/src/components/society/create/firstMessage.test.ts b/dodaios/ui/web/frontend/src/components/society/create/firstMessage.test.tsnew file mode 100644index 0000000000..6446e51ed2--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/create/firstMessage.test.ts@@ -0,0 +1,37 @@+import { describe, expect, test, vi } from "vitest";+import { readComposerDraft, writeComposerDraft } from "@/components/agentchat/composerDrafts";+import type { AgentChatStoreHook } from "@/store/agentChat";+import type { SocietyAgent } from "../data";+import { seedFirstMessage } from "./firstMessage";++const { store } = vi.hoisted(() => ({ store: {} as object }));+vi.mock("../chat/AgentChatPanel", () => ({ useSocietyChatStore: store }));++const chat = store as unknown as AgentChatStoreHook;+const agent = (agentId: string, chatSessionId: string | null = `society:${agentId}`) =>+ ({ agentId, chatSessionId }) as unknown as SocietyAgent;++describe("seedFirstMessage", () => {+ test("puts the message in the agent's composer without sending it", async () => {+ expect(await seedFirstMessage(agent("a1"), "Give me a briefing for today.")).toBe(true);+ expect(readComposerDraft(chat, "society:a1").text).toBe("Give me a briefing for today.");+ });++ test("keeps an open-ended prompt's trailing space for the person to continue", async () => {+ await seedFirstMessage(agent("a2"), "Here is a bug I keep hitting: ");+ expect(readComposerDraft(chat, "society:a2").text).toBe("Here is a bug I keep hitting: ");+ });++ test("falls back to the canonical session and never replaces typed text", async () => {+ await seedFirstMessage(agent("a3", null), "First");+ expect(readComposerDraft(chat, "society:a3").text).toBe("First");+ writeComposerDraft(chat, "society:a4", { text: "my own words", choices: [] });+ expect(await seedFirstMessage(agent("a4"), "Suggested")).toBe(false);+ expect(readComposerDraft(chat, "society:a4").text).toBe("my own words");+ });++ test("an empty suggestion writes nothing", async () => {+ expect(await seedFirstMessage(agent("a5"), " ")).toBe(false);+ expect(readComposerDraft(chat, "society:a5").text).toBe("");+ });+});diff --git a/dodaios/ui/web/frontend/src/components/society/create/firstMessage.ts b/dodaios/ui/web/frontend/src/components/society/create/firstMessage.tsnew file mode 100644index 0000000000..e5b8642cb0--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/create/firstMessage.ts@@ -0,0 +1,24 @@+/**+ * A new agent's chat opens with a suggested first message already in the+ * composer — typed out, never sent. The person reads it, edits it or deletes+ * it; nothing runs (and nothing bills) until they press send.+ *+ * The draft is written into the society chat's own draft store under the+ * agent's canonical session, which the composer reads when the chat mounts.+ * Text the person already typed there is never replaced.+ */+import type { SocietyAgent } from "../data";++export async function seedFirstMessage(agent: SocietyAgent, text: string): Promise<boolean> {+ const message = text.trim() ? text : "";+ const sessionId = agent.chatSessionId ?? `society:${agent.agentId}`;+ if (!message) return false;+ const [{ useSocietyChatStore }, drafts] = await Promise.all([+ import("../chat/AgentChatPanel"),+ import("@/components/agentchat/composerDrafts"),+ ]);+ const current = drafts.readComposerDraft(useSocietyChatStore, sessionId);+ if (current.text.trim()) return false;+ drafts.writeComposerDraft(useSocietyChatStore, sessionId, { text: message, choices: current.choices });+ return true;+}diff --git a/dodaios/ui/web/frontend/src/components/society/create/starterFilters.test.ts b/dodaios/ui/web/frontend/src/components/society/create/starterFilters.test.tsnew file mode 100644index 0000000000..3591864138--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/create/starterFilters.test.ts@@ -0,0 +1,79 @@+import { describe, expect, test } from "vitest";+import { areaCounts, defaultTools, filterStarters, starterCopy, translated } from "./starterFilters";+import type { Starter } from "./startersApi";++function starter(over: Partial<Starter>): Starter {+ return {+ id: "researcher", area: "research", icon: "search", name: "Researcher", title: "Researches with sources",+ outcome: "Answers a question with sources.", instructions: "You answer.\n\n- one\n- two", first_message: "Research this: ",+ tools: [], routine: null,+ summary: { instructions_words: 5, instructions_rules: 2, skills: null, routines: 0, tools: 0, asks_before: 0, limited_tools: false },+ ...over,+ };+}++const STARTERS: Starter[] = [+ starter({}),+ starter({ id: "code-reviewer", area: "coding", name: "Code Reviewer", outcome: "Reads a branch before you merge.",+ tools: [{ id: "cli:gh", label: "GitHub CLI", available: true, connected: true }] }),+ starter({ id: "inbox-sorter", area: "inbox", name: "Inbox Sorter", outcome: "Sorts new mail.",+ tools: [+ { id: "plugin:gmail", label: "Gmail", available: true, connected: false },+ { id: "core:search-web", label: "Search", available: true, connected: true },+ { id: "plugin:missing", label: "Missing", available: false, connected: false },+ ] }),+];++const identity = (key: string) => key;+const german: Record<string, string> = {+ "agent_create.starter.code_reviewer.name": "Code-Prüfer", // i18n-allow: translated fixture+ "agent_create.starter.code_reviewer.outcome": "Liest einen Branch vor dem Merge.", // i18n-allow: translated fixture+};+const de = (key: string) => german[key] ?? key;++describe("starter copy", () => {+ test("a missing translation falls back to the catalogue's English", () => {+ expect(translated(identity, "agent_create.nope", "Fallback")).toBe("Fallback");+ expect(starterCopy(identity, STARTERS[1]).name).toBe("Code Reviewer");+ expect(starterCopy(de, STARTERS[1])).toMatchObject({ name: "Code-Prüfer", outcome: "Liest einen Branch vor dem Merge." }); // i18n-allow: translated fixture+ });++ test("the routine title is empty without a routine", () => {+ expect(starterCopy(identity, STARTERS[0]).routineTitle).toBe("");+ const withRoutine = starter({ routine: { title: "Morning", when: "weekday_morning", cron: "0 8 * * 1-5" } });+ expect(starterCopy(identity, withRoutine).routineTitle).toBe("Morning");+ });+});++describe("gallery filtering", () => {+ const copyOf = (s: Starter) => starterCopy(de, s);++ test("by area", () => {+ expect(filterStarters(STARTERS, "all", "", copyOf)).toHaveLength(3);+ expect(filterStarters(STARTERS, "coding", "", copyOf).map((s) => s.id)).toEqual(["code-reviewer"]);+ expect(filterStarters(STARTERS, "writing", "", copyOf)).toEqual([]);+ });++ test("search matches translated and English copy, accents folded, every word", () => {+ expect(filterStarters(STARTERS, "all", "prufer", copyOf).map((s) => s.id)).toEqual(["code-reviewer"]);+ expect(filterStarters(STARTERS, "all", "reviewer", copyOf).map((s) => s.id)).toEqual(["code-reviewer"]);+ expect(filterStarters(STARTERS, "all", "gmail", copyOf).map((s) => s.id)).toEqual(["inbox-sorter"]);+ expect(filterStarters(STARTERS, "all", "mail sorts", copyOf).map((s) => s.id)).toEqual(["inbox-sorter"]);+ expect(filterStarters(STARTERS, "all", "mail zebra", copyOf)).toEqual([]);+ expect(filterStarters(STARTERS, "research", "branch", copyOf)).toEqual([]);+ });++ test("area chips count what the current search would show", () => {+ const counts = areaCounts(STARTERS, ["coding", "research", "inbox", "writing"], "", copyOf);+ expect(counts).toEqual({ all: 3, coding: 1, research: 1, inbox: 1, writing: 0 });+ const searched = areaCounts(STARTERS, ["coding", "research", "inbox"], "question", copyOf);+ expect(searched).toEqual({ all: 1, coding: 0, research: 1, inbox: 0 });+ });+});++describe("tools", () => {+ test("only connected tools start ticked", () => {+ expect(defaultTools(STARTERS[2].tools)).toEqual(["core:search-web"]);+ expect(defaultTools([])).toEqual([]);+ });+});diff --git a/dodaios/ui/web/frontend/src/components/society/create/starterFilters.ts b/dodaios/ui/web/frontend/src/components/society/create/starterFilters.tsnew file mode 100644index 0000000000..808f2c4efd--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/create/starterFilters.ts@@ -0,0 +1,75 @@+/**+ * Pure helpers for the starter gallery: the copy a person reads (translated,+ * with the catalogue's English as the fallback), filtering by area and+ * search, and which tools start ticked.+ */+import type { Starter, StarterArea, StarterTool } from "./startersApi";++type T = (key: string) => string;++export type AreaFilter = StarterArea | "all";++export interface StarterCopy {+ name: string;+ outcome: string;+ firstMessage: string;+ routineTitle: string;+}++/** A translated string, or `fallback` when the locale has no such key. */+export function translated(t: T, key: string, fallback: string): string {+ const value = t(key);+ return value && value !== key ? value : fallback;+}++export function starterCopy(t: T, starter: Starter): StarterCopy {+ const base = `agent_create.starter.${starter.id.replace(/-/g, "_")}`;+ return {+ name: translated(t, `${base}.name`, starter.name),+ outcome: translated(t, `${base}.outcome`, starter.outcome),+ firstMessage: translated(t, `${base}.first`, starter.first_message),+ routineTitle: starter.routine ? translated(t, `${base}.routine`, starter.routine.title) : "",+ };+}++function fold(text: string): string {+ return text.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase();+}++/** Starters in `area` whose name, outcome or tools match every word of `query`. */+export function filterStarters(+ starters: readonly Starter[],+ area: AreaFilter,+ query: string,+ copyOf: (starter: Starter) => StarterCopy,+): Starter[] {+ const words = fold(query).split(/\s+/).filter(Boolean);+ return starters.filter((starter) => {+ if (area !== "all" && starter.area !== area) return false;+ if (!words.length) return true;+ const copy = copyOf(starter);+ const haystack = fold([+ copy.name, copy.outcome, starter.name, starter.outcome, starter.title,+ ...starter.tools.map((tool) => tool.label),+ ].join(" "));+ return words.every((word) => haystack.includes(word));+ });+}++/** How many starters each area chip would show for the current search. */+export function areaCounts(+ starters: readonly Starter[],+ areas: readonly StarterArea[],+ query: string,+ copyOf: (starter: Starter) => StarterCopy,+): Record<AreaFilter, number> {+ const searched = filterStarters(starters, "all", query, copyOf);+ const counts = { all: searched.length } as Record<AreaFilter, number>;+ for (const area of areas) counts[area] = searched.filter((s) => s.area === area).length;+ return counts;+}++/** Only connected tools start ticked; nothing missing is ever pre-picked. */+export function defaultTools(tools: readonly StarterTool[]): string[] {+ return tools.filter((tool) => tool.connected).map((tool) => tool.id);+}diff --git a/dodaios/ui/web/frontend/src/components/society/create/starterIcons.tsx b/dodaios/ui/web/frontend/src/components/society/create/starterIcons.tsxnew file mode 100644index 0000000000..9fdf40e301--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/create/starterIcons.tsx@@ -0,0 +1,63 @@+/**+ * The icon a starter and an area wear in the gallery. The catalogue names+ * icons as plain words, so the data stays free of UI code; an unknown name+ * falls back to a neutral mark rather than an empty tile.+ */+import {+ Activity, BadgeCheck, BookOpenText, Bot, Bug, CalendarCheck, CalendarClock, Code2, Coffee, Feather,+ FileText, FlaskConical, GitPullRequest, GraduationCap, House, Inbox, Languages, LayoutGrid, ListChecks,+ Mail, MailCheck, Map as MapIcon, Megaphone, Music, PenLine, Radar, Rocket, ScrollText, Search, Server, Sunrise,+ Telescope, Wallet, type LucideIcon,+} from "lucide-react";+import type { AreaFilter } from "./starterFilters";++const STARTER_ICONS: Readonly<Record<string, LucideIcon>> = {+ "git-pull-request": GitPullRequest,+ bug: Bug,+ "flask-conical": FlaskConical,+ "scroll-text": ScrollText,+ search: Search,+ radar: Radar,+ "book-open-text": BookOpenText,+ "badge-check": BadgeCheck,+ inbox: Inbox,+ "calendar-check": CalendarCheck,+ "calendar-clock": CalendarClock,+ "mail-check": MailCheck,+ "pen-line": PenLine,+ megaphone: Megaphone,+ "file-text": FileText,+ languages: Languages,+ rocket: Rocket,+ server: Server,+ "list-checks": ListChecks,+ wallet: Wallet,+ sunrise: Sunrise,+ map: MapIcon,+ house: House,+ "graduation-cap": GraduationCap,+ music: Music,+};++const AREA_ICONS: Readonly<Record<AreaFilter, LucideIcon>> = {+ all: LayoutGrid,+ coding: Code2,+ research: Telescope,+ inbox: Mail,+ writing: Feather,+ ops: Activity,+ personal: Coffee,+};++export function StarterIcon({ name, className }: { name: string; className?: string }) {+ const Icon = STARTER_ICONS[name] ?? Bot;+ return <Icon className={className} aria-hidden />;+}++export function AreaIcon({ area, className }: { area: AreaFilter; className?: string }) {+ const Icon = AREA_ICONS[area] ?? LayoutGrid;+ return <Icon className={className} aria-hidden />;+}++/** Every icon name the gallery can draw (the data test checks the catalogue against it). */+export const KNOWN_STARTER_ICONS: readonly string[] = Object.keys(STARTER_ICONS);diff --git a/dodaios/ui/web/frontend/src/components/society/create/startersApi.ts b/dodaios/ui/web/frontend/src/components/society/create/startersApi.tsnew file mode 100644index 0000000000..1820ba155e--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/create/startersApi.ts@@ -0,0 +1,174 @@+/**+ * The starter gallery and the template import, as the New-agent dialog reads+ * them (`dodaios/society/starters.py`, `/api/society/starters*`). Starters+ * carry no seat: the dialog sends the seat the person picked on this+ * machine, so every runtime and provider works the same way.+ */+import { useQuery } from "@tanstack/react-query";+import { fill, translate } from "@/i18n";+import type { CompanionAppearance } from "../companion/appearance";+import type { AgentRuntime } from "@/lib/societyApi";+import { requestError } from "../data";++export type StarterArea = "coding" | "research" | "inbox" | "writing" | "ops" | "personal";++export interface StarterTool {+ id: string;+ label: string;+ /** The capability exists on this machine (connected or not). */+ available: boolean;+ /** It is connected and ready; only these start ticked. */+ connected: boolean;+}++export interface TemplateSummary {+ instructions_words: number;+ instructions_rules: number;+ /** `null`: the template does not narrow skills, every skill here is usable. */+ skills: number | null;+ routines: number;+ tools: number;+ asks_before: number;+ limited_tools: boolean;+}++export interface StarterRoutine {+ title: string;+ /** A named slot (`weekday_morning`, …) the dialog turns into a sentence. */+ when: string;+ cron: string;+}++export interface Starter {+ id: string;+ area: StarterArea;+ icon: string;+ name: string;+ title: string;+ outcome: string;+ instructions: string;+ first_message: string;+ tools: StarterTool[];+ routine: StarterRoutine | null;+ summary: TemplateSummary;+}++export interface StartersResponse {+ areas: StarterArea[];+ starters: Starter[];+ total: number;+}++export interface TemplatePreview {+ ok: boolean;+ errors: string[];+ template: { name: string; title: string; instructions: string; require_approval: string[] } | null;+ summary: TemplateSummary | null;+ tools: StarterTool[];+}++/** What the dialog picked on this machine; blanks keep the backend defaults. */+export interface StarterSeat {+ provider?: string;+ model?: string;+ account_id?: string;+ runtime?: AgentRuntime;+ execution_environment?: "local" | "sandbox";+ companion?: CompanionAppearance;+}++export interface InstallStarterRequest {+ starterId?: string;+ template?: Record<string, unknown>;+ name?: string;+ tools?: string[];+ seat: StarterSeat;+ withRoutine?: boolean;+}++export interface InstallStarterResult {+ agent: Record<string, unknown> & { agent_id: string; name: string };+ created: boolean;+ renamed_from: string | null;+ first_message: string;+ routine: { id: string; title: string; next_run?: string | null } | null;+ routine_error: string | null;+}++export const STARTERS_QUERY_KEY = ["society", "starters"] as const;++/** A failed request as the dialog shows it: Hermes / OpenClaw refusing the+ * provider stays typed (`RuntimeProviderUnsupported`), so the dialog says it+ * in the person's language, exactly like a blank agent's create. */+async function readError(res: Response): Promise<Error> {+ const body = (await res.json().catch(() => null)) as { detail?: unknown } | null;+ return requestError(body, fill(translate("common.request_failed"), { status: res.status }));+}++export async function fetchStarters(): Promise<StartersResponse> {+ const res = await fetch("/api/society/starters", { cache: "no-store" });+ if (!res.ok) throw await readError(res);+ return res.json();+}++/** The gallery; read only once the person opens it. */+export function useStarters(enabled: boolean) {+ return useQuery({ queryKey: STARTERS_QUERY_KEY, queryFn: fetchStarters, enabled, staleTime: 60_000 });+}++export async function previewTemplate(template: Record<string, unknown>): Promise<TemplatePreview> {+ const res = await fetch("/api/society/starters/preview", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ template }),+ });+ if (!res.ok) throw await readError(res);+ return res.json();+}++/** The person's IANA zone, for a starter routine's wall-clock schedule. */+export function localTimezone(): string {+ try {+ return Intl.DateTimeFormat().resolvedOptions().timeZone || "";+ } catch {+ return "";+ }+}++export async function installStarter(request: InstallStarterRequest): Promise<InstallStarterResult> {+ const body: Record<string, unknown> = { seat: request.seat };+ if (request.starterId) body.starter_id = request.starterId;+ if (request.template) body.template = request.template;+ if (request.name?.trim()) body.name = request.name.trim();+ if (request.tools) body.tools = request.tools;+ if (request.withRoutine) {+ body.with_routine = true;+ body.timezone = localTimezone();+ }+ const res = await fetch("/api/society/starters/install", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ });+ if (!res.ok) throw await readError(res);+ return res.json();+}++/**+ * A pasted or opened template as an object, or `null` when it is not JSON.+ * A whole marketplace submission (`{kind: "agent", agent}`) is unwrapped.+ */+export function parseTemplateText(text: string): Record<string, unknown> | null {+ let parsed: unknown;+ try {+ parsed = JSON.parse(text);+ } catch {+ return null;+ }+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;+ const record = parsed as Record<string, unknown>;+ if (record.kind === "agent" && record.agent && typeof record.agent === "object" && !Array.isArray(record.agent)) {+ return record.agent as Record<string, unknown>;+ }+ return record;+}diff --git a/dodaios/ui/web/frontend/src/components/society/data.ts b/dodaios/ui/web/frontend/src/components/society/data.tsindex 987c24084e..51dc83989f 100644--- a/dodaios/ui/web/frontend/src/components/society/data.ts+++ b/dodaios/ui/web/frontend/src/components/society/data.ts@@ -474,6 +474,8 @@ export interface NewAgentChoice {accountId?: string;/** The small companion bot that follows the agent. */companion?: CompanionAppearance;+ /** One line on its job: the structured brief's mission (`society/brief.py`). */+ mission?: string;}/**@@ -495,6 +497,7 @@ export function useCreateSocietyAgent() {if (choice.accountId) body.account_id = choice.accountId;}if (choice.companion) body.avatar = { companion: choice.companion };+ if (choice.mission?.trim()) body.mission = choice.mission.trim();const res = await fetch("/api/society/agents", {method: "POST",headers: { "Content-Type": "application/json" },diff --git a/dodaios/ui/web/frontend/src/i18n/locales/de.json b/dodaios/ui/web/frontend/src/i18n/locales/de.jsonindex 9830ad4a4e..3bfc3a95a7 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/de.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/de.json@@ -5550,6 +5550,239 @@"note": "Der Wechsel gilt für jedes ab jetzt geöffnete Terminal, Teilungen eingeschlossen — vorhandene Fenster behalten das Konto, mit dem sie gestartet sind, damit kein laufender Agent seine Unterhaltung verliert. Nur ein Fenster, dessen Abo bewusst gewählt wurde (im Arbeitsbereich-Assistenten), gibt diese Wahl beim Teilen weiter."}},+ "agent_create": {+ "mode": {+ "label": "Wie starten",+ "quick": "Leer",+ "starter": "Aus einer Vorlage",+ "import": "Importieren",+ "quick_hint": "Gib ihm einen Namen, seine Aufgabe in einer Zeile und wähle, worauf er läuft.",+ "starter_hint": "Wähle eine fertige Aufgabe, prüfe, was sie mitbringt, und in Sekunden ist er bereit.",+ "import_hint": "Füge eine geteilte Vorlage ein oder öffne sie. Erstellt wird erst, wenn du bestätigst."+ },+ "quick": {+ "job_label": "Seine Aufgabe",+ "optional": "Optional",+ "job_placeholder": "Zum Beispiel: hält mein Postfach sortiert und entwirft Antworten",+ "job_hint": "Wird der Anfang seiner Anweisungen. Du kannst sie jederzeit in seinem Chat verfeinern."+ },+ "runtime_note": {+ "jarvis": "Unsere eigene Agentenschleife: jedes Werkzeug und jeder verbundene Anbieter. Der Typ steht fest, sobald der Agent existiert; das Modell kannst du jederzeit wechseln.",+ "hermes": "Läuft in der Hermes-Laufzeit, die für dich eingerichtet wird. Der Typ steht fest, sobald der Agent existiert; das Modell kannst du jederzeit wechseln.",+ "openclaw": "Läuft in der OpenClaw-Laufzeit, die für dich eingerichtet wird. Der Typ steht fest, sobald der Agent existiert; das Modell kannst du jederzeit wechseln."+ },+ "seat": {+ "runs_on": "Läuft auf",+ "change": "Ändern",+ "hide": "Ausblenden",+ "needs_choice": "Wähle, worauf er läuft"+ },+ "gallery": {+ "search": "Vorlagen durchsuchen",+ "areas": "Bereiche",+ "loading": "Vorlagen werden geladen…",+ "failed": "Die Vorlagen konnten nicht geladen werden.",+ "retry": "Erneut versuchen",+ "empty": "Keine Vorlage passt. Versuch ein anderes Wort oder einen anderen Bereich.",+ "back": "Alle Vorlagen"+ },+ "area": {+ "all": "Alle",+ "coding": "Programmieren",+ "research": "Recherche",+ "inbox": "Postfach & Kalender",+ "writing": "Schreiben",+ "ops": "Betrieb",+ "personal": "Persönlich"+ },+ "preview": {+ "name_label": "Name des Agenten",+ "brings": "Was er mitbringt",+ "instructions": "Anweisungen",+ "instructions_rules": "{rules} Regeln · {words} Wörter",+ "instructions_words": "{words} Wörter",+ "skills": "Skills",+ "skills_all": "Alle deine",+ "routines": "Routinen",+ "tools": "Werkzeuge",+ "tools_value": "{picked} von {total}",+ "asks_before_one": "Fragt dich vor {count} Art von Aktion",+ "asks_before_other": "Fragt dich vor {count} Arten von Aktionen",+ "limited_tools": "Nutzt nur die Werkzeuge, die seine Vorlage nennt.",+ "tools_title": "Werkzeuge, die er zuerst nimmt",+ "tools_hint": "Alle anderen Werkzeuge, die du erlaubst, bleiben verfügbar.",+ "tool_connected": "Verbunden",+ "tool_not_connected": "Nicht verbunden",+ "tool_missing": "Nicht auf diesem Computer",+ "routine_toggle": "Diese Routine auch einrichten",+ "routine_hint": "läuft von selbst, jederzeit pausierbar",+ "read_instructions": "Anweisungen lesen",+ "first_message": "Sein Chat öffnet mit",+ "first_message_hint": "Steht im Eingabefeld, wird nicht gesendet. Bearbeite oder lösche ihn.",+ "pick_prompt": "Wähle eine Vorlage, um zu sehen, was sie mitbringt."+ },+ "when": {+ "weekday_morning": "Werktags um 08:00",+ "daily_morning": "Täglich um 08:00",+ "daily_evening": "Täglich um 18:00",+ "weekly_monday": "Montags um 09:00",+ "weekly_friday": "Freitags um 16:00"+ },+ "import": {+ "paste_label": "Vorlage",+ "open_file": "Datei öffnen",+ "paste_placeholder": "Füge hier eine Agentenvorlage (JSON) ein",+ "checking": "Vorlage wird geprüft…",+ "invalid_json": "Das ist keine Vorlage: Der Text ist kein gültiges JSON.",+ "errors_title": "Diese Vorlage kann nicht verwendet werden",+ "safety_note": "Eine Vorlage enthält nur das Design eines Agenten: Anweisungen, Werkzeuge und Aussehen. Nie ein Modell, ein Konto oder weitere Rechte.",+ "empty_preview": "Füge eine Vorlage ein oder öffne sie, um zu sehen, was sie mitbringt.",+ "no_title": "Ein geteilter Agent",+ "design_only": "Die Rechte starten mit deinen eigenen Standards."+ },+ "footer": {+ "quick": "Modell, Werkzeuge und Regeln kannst du später ändern.",+ "starter": "Sein Chat öffnet mit einer fertigen ersten Nachricht. Gesendet wird erst, wenn du auf Senden drückst.",+ "import": "Nur das Design reist mit. Die Rechte starten mit deinen eigenen Standards."+ },+ "open_chat": "Seinen Chat öffnen",+ "routine_failed": "{agent} ist bereit, aber seine Routine konnte nicht eingerichtet werden. Du kannst sie in seinem Chat hinzufügen.",+ "starter": {+ "code_reviewer": {+ "name": "Code-Prüfer",+ "outcome": "Liest einen Branch vor dem Merge und listet, was zu beheben ist, das Riskanteste zuerst.",+ "first": "Prüfe die Änderungen auf meinem aktuellen Branch und sag mir, was ich vor dem Merge beheben sollte."+ },+ "bug_hunter": {+ "name": "Fehlerjäger",+ "outcome": "Reproduziert einen Fehler, findet die Ursache und schlägt den kleinsten Fix vor.",+ "first": "Hier ist ein Fehler, auf den ich immer wieder stoße: "+ },+ "test_writer": {+ "name": "Testschreiber",+ "outcome": "Findet ungetestete Codepfade und schreibt gezielte Tests dafür.",+ "first": "Finde den riskantesten ungetesteten Code in diesem Projekt und schreib Tests dafür."+ },+ "release_notes": {+ "name": "Release Notes",+ "outcome": "Macht aus zusammengeführter Arbeit einmal pro Woche klare Release Notes.",+ "first": "Entwirf Release Notes für alles, was in den letzten sieben Tagen gemergt wurde.",+ "routine": "Wöchentliche Release Notes"+ },+ "inbox_sorter": {+ "name": "Postfach-Sortierer",+ "outcome": "Sortiert neue Mails, fasst das Wichtige zusammen und entwirft Antworten zum Absenden.",+ "first": "Geh meine ungelesenen Mails durch und sag mir, was heute meine Aufmerksamkeit braucht.",+ "routine": "Morgendliche Postfach-Übersicht"+ },+ "meeting_prep": {+ "name": "Meeting-Vorbereitung",+ "outcome": "Bereitet vor jedem Termin in deinem Kalender eine einseitige Übersicht vor.",+ "first": "Bereite Übersichten für meine heutigen Termine vor.",+ "routine": "Die Termine des Tages vorbereiten"+ },+ "scheduler": {+ "name": "Terminplaner",+ "outcome": "Findet freie Zeiten und schlägt Termine vor; Änderungen erst nach deinem Ja.",+ "first": "Finde drei freie Zeitfenster nächste Woche für ein einstündiges Meeting."+ },+ "follow_up_keeper": {+ "name": "Nachfass-Hüter",+ "outcome": "Erkennt Unterhaltungen, die noch auf eine Antwort warten, und listet sie einmal pro Woche.",+ "first": "Welche Mail-Unterhaltungen warten noch auf eine Antwort, von mir oder von anderen?",+ "routine": "Wöchentliche Nachfassliste"+ },+ "deploy_watcher": {+ "name": "Deploy-Wächter",+ "outcome": "Beobachtet deine Deployments und erklärt Fehler in einfachen Worten.",+ "first": "Prüfe meine letzten Deployments und erkläre alles, was fehlgeschlagen ist."+ },+ "system_checker": {+ "name": "System-Prüfer",+ "outcome": "Prüft deine Rechner und Container und meldet, was Aufmerksamkeit braucht.",+ "first": "Prüfe den Zustand dieses Rechners und seiner Container.",+ "routine": "Morgendlicher Gesundheitscheck"+ },+ "issue_triager": {+ "name": "Issue-Sortierer",+ "outcome": "Sortiert neue Issues, erkennt Duplikate und entwirft erste Antworten.",+ "first": "Sortiere die offenen Issues in meinem Repository, auf die noch niemand geantwortet hat."+ },+ "spend_watcher": {+ "name": "Kostenwächter",+ "outcome": "Behält Cloud- und Abokosten im Blick und meldet Überraschungen.",+ "first": "Gib mir einen Überblick, was meine Cloud-Dienste diesen Monat kosten.",+ "routine": "Wöchentlicher Kostencheck"+ },+ "daily_briefing": {+ "name": "Tagesbriefing",+ "outcome": "Startet deinen Tag mit Kalender, Mails und Nachrichten in einer kurzen Notiz.",+ "first": "Gib mir ein Briefing für heute.",+ "routine": "Morgenbriefing"+ },+ "trip_planner": {+ "name": "Reiseplaner",+ "outcome": "Plant Reisen: Routen, Orte, Zeiten und eine Packliste.",+ "first": "Hilf mir, eine Reise zu planen nach "+ },+ "home_helper": {+ "name": "Haushelfer",+ "outcome": "Steuert dein Smart Home: Licht, Klima und Szenen.",+ "first": "Zeig mir, welche Geräte in meinem Zuhause du steuern kannst."+ },+ "learning_coach": {+ "name": "Lerncoach",+ "outcome": "Erstellt einen Lernplan für eine Fähigkeit und fragt dich unterwegs ab.",+ "first": "Ich möchte lernen: "+ },+ "playlist_curator": {+ "name": "Playlist-Kurator",+ "outcome": "Stellt Playlists für den Moment zusammen, aus Musik, die du schon magst.",+ "first": "Mach mir eine Playlist für "+ },+ "researcher": {+ "name": "Rechercheur",+ "outcome": "Beantwortet eine Frage mit Quellen und behält die Erkenntnisse für später.",+ "first": "Recherchiere das für mich und nenne deine Quellen: "+ },+ "topic_watcher": {+ "name": "Themenwächter",+ "outcome": "Verfolgt ein Thema oder einen Markt und schickt eine kurze Übersicht, was sich geändert hat.",+ "first": "Behalte dieses Thema für mich im Blick: ",+ "routine": "Wöchentliche Themenübersicht"+ },+ "document_digester": {+ "name": "Dokumentenleser",+ "outcome": "Macht aus langen Dokumenten und Papern Kernpunkte und offene Fragen.",+ "first": "Fasse dieses Dokument in Kernpunkte und offene Fragen zusammen: "+ },+ "fact_checker": {+ "name": "Faktenprüfer",+ "outcome": "Prüft die Behauptungen in einem Entwurf und markiert alles Unbelegte.",+ "first": "Prüfe die Fakten in diesem Entwurf und markiere jede Behauptung, die du nicht belegen kannst: "+ },+ "editor": {+ "name": "Lektor",+ "outcome": "Strafft deine Entwürfe: klarer und kürzer, in deiner eigenen Stimme.",+ "first": "Überarbeite diesen Entwurf, damit er klarer und kürzer wird, aber behalte meine Stimme: "+ },+ "post_writer": {+ "name": "Post-Schreiber",+ "outcome": "Macht aus Notizen und Neuigkeiten kurze Posts, die nach dir klingen.",+ "first": "Mach aus diesem Update einen kurzen Post: "+ },+ "docs_writer": {+ "name": "Doku-Schreiber",+ "outcome": "Schreibt und aktualisiert Dokumentation aus Code und Notizen.",+ "first": "Finde den am schlechtesten dokumentierten Teil dieses Projekts und verbessere ihn."+ },+ "translator": {+ "name": "Übersetzer",+ "outcome": "Übersetzt Texte und hält deine Begriffe und deinen Ton einheitlich.",+ "first": "Übersetze das und halte meine Begriffe einheitlich: "+ }+ }+ },"ide_chats": {"workspace_band": "Workspace {n}","heading": "Offene Workspaces",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/en.json b/dodaios/ui/web/frontend/src/i18n/locales/en.jsonindex 09c16eedb8..e5e369eaa0 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/en.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/en.json@@ -5550,6 +5550,239 @@"note": "Switching applies to every terminal opened from now on, splits included — the panes you already have keep the account they started with, so no running agent loses its conversation. Only a pane whose subscription was chosen deliberately (in the workspace wizard) passes that choice on when you split it."}},+ "agent_create": {+ "mode": {+ "label": "How to start",+ "quick": "Blank",+ "starter": "From a starter",+ "import": "Import",+ "quick_hint": "Name it, give it a job in one line and pick what it runs on.",+ "starter_hint": "Pick a ready-made job, check what it brings, and it is ready in seconds.",+ "import_hint": "Paste or open a template somebody shared. Nothing is created until you confirm."+ },+ "quick": {+ "job_label": "Its job",+ "optional": "Optional",+ "job_placeholder": "For example: keeps my inbox sorted and drafts replies",+ "job_hint": "Becomes the start of its instructions. Refine them any time in its chat."+ },+ "runtime_note": {+ "jarvis": "Our own agent loop: every tool and any connected provider. The type is fixed once the agent exists; the model can change any time.",+ "hermes": "Runs in the Hermes runtime, which is set up for you. The type is fixed once the agent exists; the model can change any time.",+ "openclaw": "Runs in the OpenClaw runtime, which is set up for you. The type is fixed once the agent exists; the model can change any time."+ },+ "seat": {+ "runs_on": "Runs on",+ "change": "Change",+ "hide": "Hide",+ "needs_choice": "Choose what it runs on"+ },+ "gallery": {+ "search": "Search starters",+ "areas": "Areas",+ "loading": "Loading starters…",+ "failed": "The starters could not be loaded.",+ "retry": "Try again",+ "empty": "No starter matches. Try another word or area.",+ "back": "All starters"+ },+ "area": {+ "all": "All",+ "coding": "Coding",+ "research": "Research",+ "inbox": "Inbox & calendar",+ "writing": "Writing",+ "ops": "Operations",+ "personal": "Personal"+ },+ "preview": {+ "name_label": "Agent name",+ "brings": "What it brings",+ "instructions": "Instructions",+ "instructions_rules": "{rules} rules · {words} words",+ "instructions_words": "{words} words",+ "skills": "Skills",+ "skills_all": "All of yours",+ "routines": "Routines",+ "tools": "Tools",+ "tools_value": "{picked} of {total}",+ "asks_before_one": "Asks you first before {count} kind of action",+ "asks_before_other": "Asks you first before {count} kinds of action",+ "limited_tools": "Uses only the tools its template lists.",+ "tools_title": "Tools it reaches for first",+ "tools_hint": "Every other tool you allow stays available.",+ "tool_connected": "Connected",+ "tool_not_connected": "Not connected",+ "tool_missing": "Not on this computer",+ "routine_toggle": "Also set up this routine",+ "routine_hint": "runs on its own, pause it any time",+ "read_instructions": "Read the instructions",+ "first_message": "Its chat opens with",+ "first_message_hint": "Ready in the composer, not sent. Edit it or delete it.",+ "pick_prompt": "Pick a starter to see what it brings."+ },+ "when": {+ "weekday_morning": "Weekdays at 08:00",+ "daily_morning": "Every day at 08:00",+ "daily_evening": "Every day at 18:00",+ "weekly_monday": "Mondays at 09:00",+ "weekly_friday": "Fridays at 16:00"+ },+ "import": {+ "paste_label": "Template",+ "open_file": "Open file",+ "paste_placeholder": "Paste an agent template (JSON) here",+ "checking": "Checking the template…",+ "invalid_json": "This is not a template: the text is not valid JSON.",+ "errors_title": "This template cannot be used",+ "safety_note": "A template carries an agent's design only: its instructions, tools and look. Never a model, an account or wider permissions.",+ "empty_preview": "Paste or open a template to see what it brings.",+ "no_title": "A shared agent",+ "design_only": "Permissions start at your own defaults."+ },+ "footer": {+ "quick": "You can change its model, tools and rules later.",+ "starter": "Its chat opens with a first message ready. Nothing is sent until you press send.",+ "import": "Only the design travels. Permissions start at your own defaults."+ },+ "open_chat": "Open its chat",+ "routine_failed": "{agent} is ready, but its routine could not be set up. You can add it from its chat.",+ "starter": {+ "code_reviewer": {+ "name": "Code Reviewer",+ "outcome": "Reads a branch before you merge and lists what to fix, riskiest first.",+ "first": "Review the changes on my current branch and tell me what to fix before I merge."+ },+ "bug_hunter": {+ "name": "Bug Hunter",+ "outcome": "Reproduces a bug, finds the root cause and proposes the smallest fix.",+ "first": "Here is a bug I keep hitting: "+ },+ "test_writer": {+ "name": "Test Writer",+ "outcome": "Finds untested code paths and writes focused tests for them.",+ "first": "Find the riskiest untested code in this project and write tests for it."+ },+ "release_notes": {+ "name": "Release Notes",+ "outcome": "Turns merged work into clear release notes once a week.",+ "first": "Draft release notes for everything merged in the last seven days.",+ "routine": "Weekly release notes"+ },+ "inbox_sorter": {+ "name": "Inbox Sorter",+ "outcome": "Sorts new mail, sums up what matters and drafts replies for you to send.",+ "first": "Go through my unread mail and tell me what needs me today.",+ "routine": "Morning inbox summary"+ },+ "meeting_prep": {+ "name": "Meeting Prep",+ "outcome": "Prepares a one-page brief before each meeting on your calendar.",+ "first": "Prepare briefs for my meetings today.",+ "routine": "Brief the day's meetings"+ },+ "scheduler": {+ "name": "Scheduler",+ "outcome": "Finds free slots and proposes times; changes only after you say yes.",+ "first": "Find three free slots next week for a one-hour meeting."+ },+ "follow_up_keeper": {+ "name": "Follow-up Keeper",+ "outcome": "Spots threads still waiting on a reply and lists them once a week.",+ "first": "Which mail threads are still waiting on a reply, from me or from others?",+ "routine": "Weekly follow-up list"+ },+ "deploy_watcher": {+ "name": "Deploy Watcher",+ "outcome": "Watches your deployments and explains failures in plain words.",+ "first": "Check my latest deployments and explain anything that failed."+ },+ "system_checker": {+ "name": "System Checker",+ "outcome": "Checks your machines and containers and reports what needs attention.",+ "first": "Check the health of this machine and its containers.",+ "routine": "Morning health check"+ },+ "issue_triager": {+ "name": "Issue Triager",+ "outcome": "Sorts new issues, spots duplicates and drafts first replies.",+ "first": "Triage the open issues in my repository that nobody has answered yet."+ },+ "spend_watcher": {+ "name": "Spend Watcher",+ "outcome": "Keeps an eye on cloud and subscription costs and flags surprises.",+ "first": "Give me an overview of what my cloud services cost this month.",+ "routine": "Weekly spend check"+ },+ "daily_briefing": {+ "name": "Daily Briefing",+ "outcome": "Starts your day with calendar, mail and news in one short note.",+ "first": "Give me a briefing for today.",+ "routine": "Morning briefing"+ },+ "trip_planner": {+ "name": "Trip Planner",+ "outcome": "Plans trips: routes, places, timings and a packing list.",+ "first": "Help me plan a trip to "+ },+ "home_helper": {+ "name": "Home Helper",+ "outcome": "Runs your smart home: lights, climate and scenes.",+ "first": "Show me which devices you can control in my home."+ },+ "learning_coach": {+ "name": "Learning Coach",+ "outcome": "Builds a study plan for a skill and quizzes you along the way.",+ "first": "I want to learn "+ },+ "playlist_curator": {+ "name": "Playlist Curator",+ "outcome": "Builds playlists for the moment from music you already like.",+ "first": "Make me a playlist for "+ },+ "researcher": {+ "name": "Researcher",+ "outcome": "Answers a question with sources and keeps the findings for later.",+ "first": "Research this for me and cite your sources: "+ },+ "topic_watcher": {+ "name": "Topic Watcher",+ "outcome": "Follows a topic or market and sends a short digest of what changed.",+ "first": "Keep an eye on this topic for me: ",+ "routine": "Weekly topic digest"+ },+ "document_digester": {+ "name": "Document Digester",+ "outcome": "Turns long documents and papers into key points and open questions.",+ "first": "Summarise this document into key points and open questions: "+ },+ "fact_checker": {+ "name": "Fact Checker",+ "outcome": "Checks the claims in a draft and flags anything unsupported.",+ "first": "Fact-check this draft and flag every claim you cannot support: "+ },+ "editor": {+ "name": "Editor",+ "outcome": "Tightens your drafts: clearer and shorter, in your own voice.",+ "first": "Edit this draft so it is clearer and shorter, but keep my voice: "+ },+ "post_writer": {+ "name": "Post Writer",+ "outcome": "Turns notes and updates into short posts that sound like you.",+ "first": "Turn this update into a short post: "+ },+ "docs_writer": {+ "name": "Docs Writer",+ "outcome": "Writes and updates documentation from code and notes.",+ "first": "Find the part of this project with the weakest documentation and improve it."+ },+ "translator": {+ "name": "Translator",+ "outcome": "Translates text and keeps your terms and tone consistent.",+ "first": "Translate this and keep my terms consistent: "+ }+ }+ },"ide_chats": {"workspace_band": "Workspace {n}","heading": "Open workspaces",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/es.json b/dodaios/ui/web/frontend/src/i18n/locales/es.jsonindex 1a49fbda7b..f66d20b068 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/es.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/es.json@@ -5550,6 +5550,239 @@"note": "El cambio se aplica a todos los terminales que se abran a partir de ahora, divisiones incluidas: los paneles que ya tienes conservan la cuenta con la que empezaron, así ningún agente en marcha pierde su conversación. Solo un panel cuya suscripción se eligió a propósito (en el asistente del espacio de trabajo) transmite esa elección al dividirlo."}},+ "agent_create": {+ "mode": {+ "label": "Cómo empezar",+ "quick": "En blanco",+ "starter": "Desde una plantilla",+ "import": "Importar",+ "quick_hint": "Ponle nombre, describe su trabajo en una línea y elige en qué funciona.",+ "starter_hint": "Elige un trabajo listo, revisa lo que trae y estará listo en segundos.",+ "import_hint": "Pega o abre una plantilla que alguien compartió. No se crea nada hasta que confirmes."+ },+ "quick": {+ "job_label": "Su trabajo",+ "optional": "Opcional",+ "job_placeholder": "Por ejemplo: mantiene mi bandeja ordenada y redacta respuestas",+ "job_hint": "Será el inicio de sus instrucciones. Puedes afinarlas cuando quieras en su chat."+ },+ "runtime_note": {+ "jarvis": "Nuestro propio bucle de agente: todas las herramientas y cualquier proveedor conectado. El tipo queda fijo al crear el agente; el modelo se puede cambiar cuando quieras.",+ "hermes": "Funciona en el entorno Hermes, que se configura por ti. El tipo queda fijo al crear el agente; el modelo se puede cambiar cuando quieras.",+ "openclaw": "Funciona en el entorno OpenClaw, que se configura por ti. El tipo queda fijo al crear el agente; el modelo se puede cambiar cuando quieras."+ },+ "seat": {+ "runs_on": "Funciona con",+ "change": "Cambiar",+ "hide": "Ocultar",+ "needs_choice": "Elige en qué funciona"+ },+ "gallery": {+ "search": "Buscar plantillas",+ "areas": "Áreas",+ "loading": "Cargando plantillas…",+ "failed": "No se pudieron cargar las plantillas.",+ "retry": "Reintentar",+ "empty": "Ninguna plantilla coincide. Prueba otra palabra u otra área.",+ "back": "Todas las plantillas"+ },+ "area": {+ "all": "Todas",+ "coding": "Programación",+ "research": "Investigación",+ "inbox": "Correo y calendario",+ "writing": "Escritura",+ "ops": "Operaciones",+ "personal": "Personal"+ },+ "preview": {+ "name_label": "Nombre del agente",+ "brings": "Lo que trae",+ "instructions": "Instrucciones",+ "instructions_rules": "{rules} reglas · {words} palabras",+ "instructions_words": "{words} palabras",+ "skills": "Habilidades",+ "skills_all": "Todas las tuyas",+ "routines": "Rutinas",+ "tools": "Herramientas",+ "tools_value": "{picked} de {total}",+ "asks_before_one": "Te pregunta antes de {count} tipo de acción",+ "asks_before_other": "Te pregunta antes de {count} tipos de acción",+ "limited_tools": "Usa solo las herramientas que indica su plantilla.",+ "tools_title": "Herramientas que usa primero",+ "tools_hint": "Todas las demás herramientas que permitas siguen disponibles.",+ "tool_connected": "Conectada",+ "tool_not_connected": "Sin conectar",+ "tool_missing": "No está en este equipo",+ "routine_toggle": "Configurar también esta rutina",+ "routine_hint": "se ejecuta sola, puedes pausarla cuando quieras",+ "read_instructions": "Leer las instrucciones",+ "first_message": "Su chat se abre con",+ "first_message_hint": "Listo en el campo de mensaje, sin enviar. Edítalo o bórralo.",+ "pick_prompt": "Elige una plantilla para ver lo que trae."+ },+ "when": {+ "weekday_morning": "Días laborables a las 08:00",+ "daily_morning": "Cada día a las 08:00",+ "daily_evening": "Cada día a las 18:00",+ "weekly_monday": "Los lunes a las 09:00",+ "weekly_friday": "Los viernes a las 16:00"+ },+ "import": {+ "paste_label": "Plantilla",+ "open_file": "Abrir archivo",+ "paste_placeholder": "Pega aquí una plantilla de agente (JSON)",+ "checking": "Comprobando la plantilla…",+ "invalid_json": "Esto no es una plantilla: el texto no es JSON válido.",+ "errors_title": "Esta plantilla no se puede usar",+ "safety_note": "Una plantilla solo lleva el diseño de un agente: sus instrucciones, herramientas y aspecto. Nunca un modelo, una cuenta ni permisos más amplios.",+ "empty_preview": "Pega o abre una plantilla para ver lo que trae.",+ "no_title": "Un agente compartido",+ "design_only": "Los permisos empiezan con tus propios valores."+ },+ "footer": {+ "quick": "Puedes cambiar su modelo, herramientas y reglas más tarde.",+ "starter": "Su chat se abre con un primer mensaje listo. No se envía nada hasta que pulses enviar.",+ "import": "Solo viaja el diseño. Los permisos empiezan con tus propios valores."+ },+ "open_chat": "Abrir su chat",+ "routine_failed": "{agent} está listo, pero no se pudo configurar su rutina. Puedes añadirla desde su chat.",+ "starter": {+ "code_reviewer": {+ "name": "Revisor de código",+ "outcome": "Lee una rama antes de fusionarla y enumera qué corregir, lo más arriesgado primero.",+ "first": "Revisa los cambios de mi rama actual y dime qué debo corregir antes de fusionar."+ },+ "bug_hunter": {+ "name": "Cazador de errores",+ "outcome": "Reproduce un error, encuentra la causa y propone la corrección más pequeña.",+ "first": "Este es un error con el que me encuentro una y otra vez: "+ },+ "test_writer": {+ "name": "Autor de pruebas",+ "outcome": "Encuentra rutas de código sin probar y escribe pruebas precisas para ellas.",+ "first": "Encuentra el código sin pruebas más arriesgado de este proyecto y escribe pruebas para él."+ },+ "release_notes": {+ "name": "Notas de versión",+ "outcome": "Convierte el trabajo fusionado en notas de versión claras una vez por semana.",+ "first": "Redacta notas de versión de todo lo fusionado en los últimos siete días.",+ "routine": "Notas de versión semanales"+ },+ "inbox_sorter": {+ "name": "Organizador de correo",+ "outcome": "Ordena el correo nuevo, resume lo importante y redacta respuestas para que las envíes.",+ "first": "Revisa mi correo sin leer y dime qué necesita mi atención hoy.",+ "routine": "Resumen matinal del correo"+ },+ "meeting_prep": {+ "name": "Preparador de reuniones",+ "outcome": "Prepara un resumen de una página antes de cada reunión de tu calendario.",+ "first": "Prepara resúmenes para mis reuniones de hoy.",+ "routine": "Preparar las reuniones del día"+ },+ "scheduler": {+ "name": "Planificador",+ "outcome": "Encuentra huecos libres y propone horarios; cambia algo solo cuando dices que sí.",+ "first": "Encuentra tres huecos libres la semana que viene para una reunión de una hora."+ },+ "follow_up_keeper": {+ "name": "Guardián de seguimientos",+ "outcome": "Detecta conversaciones que aún esperan respuesta y las enumera una vez por semana.",+ "first": "¿Qué conversaciones de correo siguen esperando respuesta, mía o de otros?",+ "routine": "Lista semanal de seguimientos"+ },+ "deploy_watcher": {+ "name": "Vigía de despliegues",+ "outcome": "Vigila tus despliegues y explica los fallos con palabras sencillas.",+ "first": "Revisa mis últimos despliegues y explica lo que haya fallado."+ },+ "system_checker": {+ "name": "Revisor de sistemas",+ "outcome": "Revisa tus equipos y contenedores e informa de lo que necesita atención.",+ "first": "Revisa el estado de este equipo y de sus contenedores.",+ "routine": "Revisión matinal del sistema"+ },+ "issue_triager": {+ "name": "Clasificador de incidencias",+ "outcome": "Ordena las incidencias nuevas, detecta duplicados y redacta primeras respuestas.",+ "first": "Clasifica las incidencias abiertas de mi repositorio que nadie ha respondido todavía."+ },+ "spend_watcher": {+ "name": "Vigía de gastos",+ "outcome": "Vigila los costes de la nube y de las suscripciones y avisa de sorpresas.",+ "first": "Dame un resumen de lo que cuestan este mes mis servicios en la nube.",+ "routine": "Revisión semanal de gastos"+ },+ "daily_briefing": {+ "name": "Resumen diario",+ "outcome": "Empieza tu día con calendario, correo y noticias en una nota breve.",+ "first": "Dame un resumen para hoy.",+ "routine": "Resumen matinal"+ },+ "trip_planner": {+ "name": "Planificador de viajes",+ "outcome": "Planifica viajes: rutas, lugares, horarios y una lista de equipaje.",+ "first": "Ayúdame a planificar un viaje a "+ },+ "home_helper": {+ "name": "Asistente del hogar",+ "outcome": "Controla tu hogar inteligente: luces, clima y escenas.",+ "first": "Muéstrame qué dispositivos de mi casa puedes controlar."+ },+ "learning_coach": {+ "name": "Entrenador de aprendizaje",+ "outcome": "Crea un plan de estudio para una habilidad y te pone a prueba por el camino.",+ "first": "Quiero aprender "+ },+ "playlist_curator": {+ "name": "Curador de listas",+ "outcome": "Crea listas para cada momento a partir de la música que ya te gusta.",+ "first": "Hazme una lista de reproducción para "+ },+ "researcher": {+ "name": "Investigador",+ "outcome": "Responde una pregunta con fuentes y guarda lo encontrado para después.",+ "first": "Investiga esto por mí y cita tus fuentes: "+ },+ "topic_watcher": {+ "name": "Vigía de temas",+ "outcome": "Sigue un tema o un mercado y envía un breve resumen de lo que cambió.",+ "first": "Vigila este tema por mí: ",+ "routine": "Resumen semanal del tema"+ },+ "document_digester": {+ "name": "Lector de documentos",+ "outcome": "Convierte documentos y artículos largos en puntos clave y preguntas abiertas.",+ "first": "Resume este documento en puntos clave y preguntas abiertas: "+ },+ "fact_checker": {+ "name": "Verificador de datos",+ "outcome": "Comprueba las afirmaciones de un borrador y marca todo lo que no tenga respaldo.",+ "first": "Verifica este borrador y marca cada afirmación que no puedas respaldar: "+ },+ "editor": {+ "name": "Editor",+ "outcome": "Pule tus borradores: más claros y más cortos, con tu propia voz.",+ "first": "Edita este borrador para que sea más claro y más corto, pero mantén mi voz: "+ },+ "post_writer": {+ "name": "Redactor de publicaciones",+ "outcome": "Convierte notas y novedades en publicaciones breves que suenan a ti.",+ "first": "Convierte esta novedad en una publicación breve: "+ },+ "docs_writer": {+ "name": "Redactor de documentación",+ "outcome": "Escribe y actualiza documentación a partir de código y notas.",+ "first": "Encuentra la parte peor documentada de este proyecto y mejórala."+ },+ "translator": {+ "name": "Traductor",+ "outcome": "Traduce textos y mantiene tus términos y tu tono coherentes.",+ "first": "Traduce esto y mantén mis términos coherentes: "+ }+ }+ },"ide_chats": {"workspace_band": "Workspace {n}","heading": "Workspaces abiertos",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/pt.json b/dodaios/ui/web/frontend/src/i18n/locales/pt.jsonindex f0ed5ecf72..1445c3354e 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/pt.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/pt.json@@ -5550,6 +5550,239 @@"note": "A mudança aplica-se a todos os terminais abertos a partir de agora, divisões incluídas — os painéis que já tens mantêm a conta com que começaram, para que nenhum agente em execução perca a conversa. Só um painel cuja subscrição foi escolhida de propósito (no assistente do workspace) passa essa escolha quando o divides."}},+ "agent_create": {+ "mode": {+ "label": "Como começar",+ "quick": "Em branco",+ "starter": "A partir de um modelo",+ "import": "Importar",+ "quick_hint": "Dê um nome, descreva o trabalho em uma linha e escolha onde ele roda.",+ "starter_hint": "Escolha um trabalho pronto, veja o que ele traz e em segundos está pronto.",+ "import_hint": "Cole ou abra um modelo que alguém compartilhou. Nada é criado até você confirmar."+ },+ "quick": {+ "job_label": "O trabalho dele",+ "optional": "Opcional",+ "job_placeholder": "Por exemplo: mantém minha caixa de entrada organizada e escreve rascunhos de respostas",+ "job_hint": "Vira o início das instruções. Você pode refiná-las a qualquer momento no chat dele."+ },+ "runtime_note": {+ "jarvis": "Nosso próprio ciclo de agente: todas as ferramentas e qualquer provedor conectado. O tipo fica fixo quando o agente é criado; o modelo pode mudar a qualquer momento.",+ "hermes": "Roda no ambiente Hermes, configurado para você. O tipo fica fixo quando o agente é criado; o modelo pode mudar a qualquer momento.",+ "openclaw": "Roda no ambiente OpenClaw, configurado para você. O tipo fica fixo quando o agente é criado; o modelo pode mudar a qualquer momento."+ },+ "seat": {+ "runs_on": "Roda em",+ "change": "Alterar",+ "hide": "Ocultar",+ "needs_choice": "Escolha onde ele roda"+ },+ "gallery": {+ "search": "Buscar modelos",+ "areas": "Áreas",+ "loading": "Carregando modelos…",+ "failed": "Não foi possível carregar os modelos.",+ "retry": "Tentar de novo",+ "empty": "Nenhum modelo corresponde. Tente outra palavra ou área.",+ "back": "Todos os modelos"+ },+ "area": {+ "all": "Todas",+ "coding": "Programação",+ "research": "Pesquisa",+ "inbox": "E-mail e agenda",+ "writing": "Escrita",+ "ops": "Operações",+ "personal": "Pessoal"+ },+ "preview": {+ "name_label": "Nome do agente",+ "brings": "O que ele traz",+ "instructions": "Instruções",+ "instructions_rules": "{rules} regras · {words} palavras",+ "instructions_words": "{words} palavras",+ "skills": "Habilidades",+ "skills_all": "Todas as suas",+ "routines": "Rotinas",+ "tools": "Ferramentas",+ "tools_value": "{picked} de {total}",+ "asks_before_one": "Pergunta antes de {count} tipo de ação",+ "asks_before_other": "Pergunta antes de {count} tipos de ação",+ "limited_tools": "Usa apenas as ferramentas que o modelo lista.",+ "tools_title": "Ferramentas que ele usa primeiro",+ "tools_hint": "Todas as outras ferramentas que você permitir continuam disponíveis.",+ "tool_connected": "Conectada",+ "tool_not_connected": "Não conectada",+ "tool_missing": "Não está neste computador",+ "routine_toggle": "Configurar também esta rotina",+ "routine_hint": "roda sozinha, pause quando quiser",+ "read_instructions": "Ler as instruções",+ "first_message": "O chat dele abre com",+ "first_message_hint": "Pronto no campo de mensagem, sem enviar. Edite ou apague.",+ "pick_prompt": "Escolha um modelo para ver o que ele traz."+ },+ "when": {+ "weekday_morning": "Dias úteis às 08:00",+ "daily_morning": "Todo dia às 08:00",+ "daily_evening": "Todo dia às 18:00",+ "weekly_monday": "Às segundas às 09:00",+ "weekly_friday": "Às sextas às 16:00"+ },+ "import": {+ "paste_label": "Modelo",+ "open_file": "Abrir arquivo",+ "paste_placeholder": "Cole aqui um modelo de agente (JSON)",+ "checking": "Verificando o modelo…",+ "invalid_json": "Isto não é um modelo: o texto não é um JSON válido.",+ "errors_title": "Este modelo não pode ser usado",+ "safety_note": "Um modelo leva só o design de um agente: instruções, ferramentas e aparência. Nunca um modelo de IA, uma conta ou permissões maiores.",+ "empty_preview": "Cole ou abra um modelo para ver o que ele traz.",+ "no_title": "Um agente compartilhado",+ "design_only": "As permissões começam com os seus próprios padrões."+ },+ "footer": {+ "quick": "Você pode mudar o modelo, as ferramentas e as regras depois.",+ "starter": "O chat dele abre com uma primeira mensagem pronta. Nada é enviado até você clicar em enviar.",+ "import": "Só o design viaja. As permissões começam com os seus próprios padrões."+ },+ "open_chat": "Abrir o chat dele",+ "routine_failed": "{agent} está pronto, mas a rotina dele não pôde ser configurada. Você pode adicioná-la pelo chat dele.",+ "starter": {+ "code_reviewer": {+ "name": "Revisor de código",+ "outcome": "Lê um branch antes do merge e lista o que corrigir, o mais arriscado primeiro.",+ "first": "Revise as mudanças no meu branch atual e diga o que devo corrigir antes do merge."+ },+ "bug_hunter": {+ "name": "Caçador de bugs",+ "outcome": "Reproduz um bug, encontra a causa e propõe a menor correção.",+ "first": "Este é um bug que encontro o tempo todo: "+ },+ "test_writer": {+ "name": "Escritor de testes",+ "outcome": "Encontra caminhos de código sem teste e escreve testes focados para eles.",+ "first": "Encontre o código sem testes mais arriscado deste projeto e escreva testes para ele."+ },+ "release_notes": {+ "name": "Notas de versão",+ "outcome": "Transforma o trabalho integrado em notas de versão claras uma vez por semana.",+ "first": "Escreva notas de versão de tudo o que foi integrado nos últimos sete dias.",+ "routine": "Notas de versão semanais"+ },+ "inbox_sorter": {+ "name": "Organizador de e-mail",+ "outcome": "Organiza e-mails novos, resume o que importa e escreve rascunhos de resposta para você enviar.",+ "first": "Veja meus e-mails não lidos e diga o que precisa de mim hoje.",+ "routine": "Resumo matinal do e-mail"+ },+ "meeting_prep": {+ "name": "Preparador de reuniões",+ "outcome": "Prepara um resumo de uma página antes de cada reunião da sua agenda.",+ "first": "Prepare resumos para as minhas reuniões de hoje.",+ "routine": "Preparar as reuniões do dia"+ },+ "scheduler": {+ "name": "Agendador",+ "outcome": "Encontra horários livres e sugere opções; muda algo só depois do seu sim.",+ "first": "Encontre três horários livres na próxima semana para uma reunião de uma hora."+ },+ "follow_up_keeper": {+ "name": "Guardião de retornos",+ "outcome": "Percebe conversas que ainda esperam resposta e as lista uma vez por semana.",+ "first": "Quais conversas de e-mail ainda esperam resposta, minha ou de outras pessoas?",+ "routine": "Lista semanal de retornos"+ },+ "deploy_watcher": {+ "name": "Observador de deploys",+ "outcome": "Acompanha seus deploys e explica falhas em palavras simples.",+ "first": "Verifique meus últimos deploys e explique o que falhou."+ },+ "system_checker": {+ "name": "Verificador de sistemas",+ "outcome": "Verifica suas máquinas e contêineres e avisa o que precisa de atenção.",+ "first": "Verifique a saúde desta máquina e dos seus contêineres.",+ "routine": "Verificação matinal do sistema"+ },+ "issue_triager": {+ "name": "Triador de issues",+ "outcome": "Organiza issues novas, encontra duplicadas e escreve as primeiras respostas.",+ "first": "Faça a triagem das issues abertas no meu repositório que ninguém respondeu ainda."+ },+ "spend_watcher": {+ "name": "Observador de gastos",+ "outcome": "Acompanha custos de nuvem e assinaturas e avisa sobre surpresas.",+ "first": "Me dê uma visão geral de quanto meus serviços de nuvem custam neste mês.",+ "routine": "Verificação semanal de gastos"+ },+ "daily_briefing": {+ "name": "Resumo do dia",+ "outcome": "Começa o seu dia com agenda, e-mails e notícias em uma nota curta.",+ "first": "Me dê um resumo para hoje.",+ "routine": "Resumo da manhã"+ },+ "trip_planner": {+ "name": "Planejador de viagens",+ "outcome": "Planeja viagens: rotas, lugares, horários e uma lista do que levar.",+ "first": "Me ajude a planejar uma viagem para "+ },+ "home_helper": {+ "name": "Assistente da casa",+ "outcome": "Controla sua casa inteligente: luzes, clima e cenas.",+ "first": "Mostre quais dispositivos da minha casa você consegue controlar."+ },+ "learning_coach": {+ "name": "Coach de aprendizado",+ "outcome": "Monta um plano de estudo para uma habilidade e faz perguntas pelo caminho.",+ "first": "Quero aprender "+ },+ "playlist_curator": {+ "name": "Curador de playlists",+ "outcome": "Monta playlists para o momento a partir das músicas que você já curte.",+ "first": "Faça uma playlist para "+ },+ "researcher": {+ "name": "Pesquisador",+ "outcome": "Responde a uma pergunta com fontes e guarda as descobertas para depois.",+ "first": "Pesquise isto para mim e cite suas fontes: "+ },+ "topic_watcher": {+ "name": "Observador de temas",+ "outcome": "Acompanha um tema ou mercado e envia um resumo curto do que mudou.",+ "first": "Fique de olho neste tema para mim: ",+ "routine": "Resumo semanal do tema"+ },+ "document_digester": {+ "name": "Leitor de documentos",+ "outcome": "Transforma documentos e artigos longos em pontos-chave e perguntas em aberto.",+ "first": "Resuma este documento em pontos-chave e perguntas em aberto: "+ },+ "fact_checker": {+ "name": "Verificador de fatos",+ "outcome": "Confere as afirmações de um rascunho e marca tudo o que não tem base.",+ "first": "Verifique os fatos deste rascunho e marque cada afirmação que você não consegue comprovar: "+ },+ "editor": {+ "name": "Editor",+ "outcome": "Enxuga seus rascunhos: mais claros e mais curtos, com a sua voz.",+ "first": "Edite este rascunho para ficar mais claro e mais curto, mas mantenha a minha voz: "+ },+ "post_writer": {+ "name": "Redator de posts",+ "outcome": "Transforma notas e novidades em posts curtos que soam como você.",+ "first": "Transforme esta novidade em um post curto: "+ },+ "docs_writer": {+ "name": "Redator de documentação",+ "outcome": "Escreve e atualiza documentação a partir de código e notas.",+ "first": "Encontre a parte pior documentada deste projeto e melhore-a."+ },+ "translator": {+ "name": "Tradutor",+ "outcome": "Traduz textos e mantém seus termos e seu tom consistentes.",+ "first": "Traduza isto e mantenha meus termos consistentes: "+ }+ }+ },"ide_chats": {"workspace_band": "Workspace {n}","heading": "Workspaces abertos",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/zh.json b/dodaios/ui/web/frontend/src/i18n/locales/zh.jsonindex 4aaad4253a..90e98b0bdc 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/zh.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/zh.json@@ -5550,6 +5550,239 @@"note": "切换会应用于此后打开的每个终端,包括拆分出的终端——现有窗格保留启动时的账号,因此运行中的智能体不会丢失对话。只有在工作区向导中特意选择了订阅的窗格,拆分时才会沿用该选择。"}},+ "agent_create": {+ "mode": {+ "label": "如何开始",+ "quick": "空白",+ "starter": "从模板开始",+ "import": "导入",+ "quick_hint": "起个名字,用一句话写下它的工作,再选择它运行在哪里。",+ "starter_hint": "选一个现成的工作,看看它带来什么,几秒钟就能用。",+ "import_hint": "粘贴或打开别人分享的模板。确认之前不会创建任何东西。"+ },+ "quick": {+ "job_label": "它的工作",+ "optional": "可选",+ "job_placeholder": "例如:整理我的收件箱并起草回复",+ "job_hint": "会成为它指令的开头。之后随时可以在它的聊天中完善。"+ },+ "runtime_note": {+ "jarvis": "我们自己的智能体循环:所有工具,任意已连接的提供商。智能体创建后类型固定;模型随时可以更换。",+ "hermes": "运行在 Hermes 运行时中,会自动为你配置。智能体创建后类型固定;模型随时可以更换。",+ "openclaw": "运行在 OpenClaw 运行时中,会自动为你配置。智能体创建后类型固定;模型随时可以更换。"+ },+ "seat": {+ "runs_on": "运行于",+ "change": "更改",+ "hide": "收起",+ "needs_choice": "选择它运行在哪里"+ },+ "gallery": {+ "search": "搜索模板",+ "areas": "领域",+ "loading": "正在加载模板…",+ "failed": "无法加载模板。",+ "retry": "重试",+ "empty": "没有匹配的模板。换个词或领域试试。",+ "back": "全部模板"+ },+ "area": {+ "all": "全部",+ "coding": "编程",+ "research": "调研",+ "inbox": "邮件与日历",+ "writing": "写作",+ "ops": "运维",+ "personal": "个人"+ },+ "preview": {+ "name_label": "智能体名称",+ "brings": "它带来什么",+ "instructions": "指令",+ "instructions_rules": "{rules} 条规则 · {words} 词",+ "instructions_words": "{words} 词",+ "skills": "技能",+ "skills_all": "你的全部技能",+ "routines": "例行任务",+ "tools": "工具",+ "tools_value": "{picked} / {total}",+ "asks_before_one": "执行 {count} 类操作前会先问你",+ "asks_before_other": "执行 {count} 类操作前会先问你",+ "limited_tools": "只使用模板列出的工具。",+ "tools_title": "优先使用的工具",+ "tools_hint": "你允许的其他工具仍然可用。",+ "tool_connected": "已连接",+ "tool_not_connected": "未连接",+ "tool_missing": "此电脑上没有",+ "routine_toggle": "同时设置这个例行任务",+ "routine_hint": "自动运行,随时可以暂停",+ "read_instructions": "查看指令",+ "first_message": "它的聊天将以此开始",+ "first_message_hint": "已放在输入框中,不会自动发送。可以编辑或删除。",+ "pick_prompt": "选择一个模板,看看它带来什么。"+ },+ "when": {+ "weekday_morning": "工作日 08:00",+ "daily_morning": "每天 08:00",+ "daily_evening": "每天 18:00",+ "weekly_monday": "每周一 09:00",+ "weekly_friday": "每周五 16:00"+ },+ "import": {+ "paste_label": "模板",+ "open_file": "打开文件",+ "paste_placeholder": "在此粘贴智能体模板(JSON)",+ "checking": "正在检查模板…",+ "invalid_json": "这不是模板:文本不是有效的 JSON。",+ "errors_title": "此模板无法使用",+ "safety_note": "模板只包含智能体的设计:指令、工具和外观。绝不包含模型、账户或更多权限。",+ "empty_preview": "粘贴或打开模板,看看它带来什么。",+ "no_title": "一个分享的智能体",+ "design_only": "权限从你自己的默认设置开始。"+ },+ "footer": {+ "quick": "之后可以更改它的模型、工具和规则。",+ "starter": "它的聊天会带着准备好的第一条消息打开。在你按下发送前不会发送任何内容。",+ "import": "只传递设计。权限从你自己的默认设置开始。"+ },+ "open_chat": "打开它的聊天",+ "routine_failed": "{agent} 已就绪,但它的例行任务未能设置。你可以在它的聊天中添加。",+ "starter": {+ "code_reviewer": {+ "name": "代码审查员",+ "outcome": "在合并前阅读分支,按风险从高到低列出需要修复的问题。",+ "first": "审查我当前分支上的改动,告诉我合并前需要修复什么。"+ },+ "bug_hunter": {+ "name": "除虫手",+ "outcome": "复现缺陷,找到根本原因,并提出最小的修复方案。",+ "first": "这是我反复遇到的一个缺陷:"+ },+ "test_writer": {+ "name": "测试编写员",+ "outcome": "找出未经测试的代码路径,并为它们编写有针对性的测试。",+ "first": "找出这个项目中风险最高的未测试代码,并为它编写测试。"+ },+ "release_notes": {+ "name": "发布说明",+ "outcome": "每周把已合并的工作整理成清晰的发布说明。",+ "first": "为过去七天合并的所有内容起草发布说明。",+ "routine": "每周发布说明"+ },+ "inbox_sorter": {+ "name": "收件箱整理员",+ "outcome": "整理新邮件,总结重点,并起草回复供你发送。",+ "first": "看看我的未读邮件,告诉我今天有哪些需要我处理。",+ "routine": "早间收件箱摘要"+ },+ "meeting_prep": {+ "name": "会议准备员",+ "outcome": "在日历中的每场会议前准备一页简报。",+ "first": "为我今天的会议准备简报。",+ "routine": "准备当天的会议"+ },+ "scheduler": {+ "name": "日程安排员",+ "outcome": "找出空闲时段并给出时间建议;只有你同意后才会更改。",+ "first": "找出下周三个空闲时段,用于一小时的会议。"+ },+ "follow_up_keeper": {+ "name": "跟进管家",+ "outcome": "发现仍在等待回复的邮件往来,每周列出一次。",+ "first": "哪些邮件往来还在等待回复,无论是我还是别人?",+ "routine": "每周跟进清单"+ },+ "deploy_watcher": {+ "name": "部署观察员",+ "outcome": "关注你的部署,用通俗的话解释失败原因。",+ "first": "检查我最近的部署,并解释所有失败的部分。"+ },+ "system_checker": {+ "name": "系统检查员",+ "outcome": "检查你的机器和容器,报告需要关注的问题。",+ "first": "检查这台机器及其容器的健康状况。",+ "routine": "早间健康检查"+ },+ "issue_triager": {+ "name": "问题分拣员",+ "outcome": "整理新问题,识别重复项,并起草首次回复。",+ "first": "分拣我仓库中尚无人回复的未关闭问题。"+ },+ "spend_watcher": {+ "name": "开支观察员",+ "outcome": "留意云服务和订阅费用,发现意外支出及时提醒。",+ "first": "给我一个本月云服务费用的概览。",+ "routine": "每周费用检查"+ },+ "daily_briefing": {+ "name": "每日简报",+ "outcome": "用一条简短笔记开启你的一天:日程、邮件和新闻。",+ "first": "给我一份今天的简报。",+ "routine": "早间简报"+ },+ "trip_planner": {+ "name": "旅行规划师",+ "outcome": "规划旅行:路线、地点、时间安排和行李清单。",+ "first": "帮我规划一次去这里的旅行:"+ },+ "home_helper": {+ "name": "家居助手",+ "outcome": "管理你的智能家居:灯光、温控和场景。",+ "first": "告诉我你能控制我家里的哪些设备。"+ },+ "learning_coach": {+ "name": "学习教练",+ "outcome": "为一项技能制定学习计划,并在过程中考考你。",+ "first": "我想学习:"+ },+ "playlist_curator": {+ "name": "歌单策划",+ "outcome": "根据你已经喜欢的音乐,为当下的场景制作歌单。",+ "first": "帮我做一个适合这个场景的歌单:"+ },+ "researcher": {+ "name": "研究员",+ "outcome": "带着来源回答问题,并把发现保存下来以备后用。",+ "first": "帮我调研这个问题并注明来源:"+ },+ "topic_watcher": {+ "name": "话题观察员",+ "outcome": "跟踪某个话题或市场,发送简短的变化摘要。",+ "first": "帮我关注这个话题:",+ "routine": "每周话题摘要"+ },+ "document_digester": {+ "name": "文档精读员",+ "outcome": "把冗长的文档和论文整理成要点和待解问题。",+ "first": "把这份文档总结成要点和待解问题:"+ },+ "fact_checker": {+ "name": "事实核查员",+ "outcome": "核查草稿中的说法,标出所有缺乏依据的内容。",+ "first": "核查这份草稿,标出你无法证实的每一个说法:"+ },+ "editor": {+ "name": "编辑",+ "outcome": "精简你的草稿:更清晰、更简短,保留你自己的风格。",+ "first": "把这份草稿改得更清晰、更简短,但保留我的风格:"+ },+ "post_writer": {+ "name": "帖子写手",+ "outcome": "把笔记和动态写成听起来像你的简短帖子。",+ "first": "把这条动态写成一篇简短的帖子:"+ },+ "docs_writer": {+ "name": "文档写手",+ "outcome": "根据代码和笔记编写并更新文档。",+ "first": "找出这个项目中文档最薄弱的部分并加以改进。"+ },+ "translator": {+ "name": "翻译员",+ "outcome": "翻译文本,并保持你的术语和语气一致。",+ "first": "翻译这段内容,并保持我的术语一致:"+ }+ }+ },"ide_chats": {"workspace_band": "工作区 {n}","heading": "打开的工作区",diff --git a/dodaios/ui/web/frontend/src/views/MarketplaceView.agents.test.tsx b/dodaios/ui/web/frontend/src/views/MarketplaceView.agents.test.tsxindex aa08b0af89..844539a61c 100644--- a/dodaios/ui/web/frontend/src/views/MarketplaceView.agents.test.tsx+++ b/dodaios/ui/web/frontend/src/views/MarketplaceView.agents.test.tsx@@ -6,7 +6,7 @@* No jest-dom in this repo — assertions use toBeTruthy()/toBeNull().*/import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";vi.mock("@/views/ChatsView", () => ({@@ -20,6 +20,8 @@ vi.mock("@/views/ChatsView", () => ({vi.mock("@/lib/openExternal", () => ({ openExternalUrl: vi.fn() }));import { MarketplaceView } from "@/views/MarketplaceView";+import { useCreateAgentDialog } from "@/components/society/create/createAgentStore";+import type { SocietyAgent } from "@/components/society/data";import type { CommunityResponse } from "@/views/PluginsCommunity";const TEMPLATE = {@@ -134,7 +136,7 @@ describe("MarketplaceView — agents", () => {expect(await screen.findByText(/on your team now/)).toBeTruthy();});- it("imports an exported template file as a new teammate", async () => {+ it("previews an exported template file in the New-agent dialog before it becomes a teammate", async () => {const fetchMock = installFetchMock();renderView();await screen.findByText("Inbox Butler");@@ -145,10 +147,30 @@ describe("MarketplaceView — agents", () => {});fireEvent.change(input, { target: { files: [file] } });+ // The dialog opens on the import preview; nothing is installed yet.+ await waitFor(() => expect(useCreateAgentDialog.getState().open).toBe(true));+ expect(useCreateAgentDialog.getState().initial).toMatchObject({+ mode: "import",+ template: { kind: "agent", agent: { name: "Scribe" } },+ });+ expect(fetchMock.mock.calls.some(([url]) => String(url).includes("/install"))).toBe(false);++ // The person confirms in the dialog: the marketplace lands on the new teammate.+ act(() => useCreateAgentDialog.getState().finish({ agentId: "agent-scribe", name: "Scribe" } as SocietyAgent));expect(await screen.findByText(/Scribe installed/)).toBeTruthy();- expect(- fetchMock.mock.calls.some(([url]) => String(url) === "/api/society/templates/install"),- ).toBe(true);+ });++ it("a closed import dialog installs nothing and shows no error", async () => {+ const fetchMock = installFetchMock();+ renderView();+ await screen.findByText("Inbox Butler");+ const input = screen.getByTestId("marketplace-import-agent-input") as HTMLInputElement;+ fireEvent.change(input, { target: { files: [new File([JSON.stringify(TEMPLATE)], "t.agent.json")] } });+ await waitFor(() => expect(useCreateAgentDialog.getState().open).toBe(true));+ act(() => useCreateAgentDialog.getState().cancel());+ await waitFor(() => expect(useCreateAgentDialog.getState().open).toBe(false));+ expect(screen.queryByText(/could not be imported/)).toBeNull();+ expect(fetchMock.mock.calls.some(([url]) => String(url).includes("/install"))).toBe(false);});it("names the problem when an imported file is not JSON", async () => {diff --git a/dodaios/ui/web/frontend/src/views/MarketplaceView.tsx b/dodaios/ui/web/frontend/src/views/MarketplaceView.tsxindex f821d4f7a3..415e2dde78 100644--- a/dodaios/ui/web/frontend/src/views/MarketplaceView.tsx+++ b/dodaios/ui/web/frontend/src/views/MarketplaceView.tsx@@ -37,7 +37,8 @@ import { MARKETPLACE_REPO_URL } from "@/lib/branding";import { openExternalUrl } from "@/lib/openExternal";import { bundledPluginLogo } from "@/lib/pluginLogos";import { useEventStore, type SectionId } from "@/store/events";-import { installAgentTemplate, readFileText, type AgentTemplateWire } from "@/lib/agentShare";+import { readFileText, type AgentTemplateWire } from "@/lib/agentShare";+import { isCreateCancelled, useCreateAgentDialog } from "@/components/society/create/createAgentStore";import { CompanionMark } from "@/components/society/companion/CompanionMark";import { resolveCompanion } from "@/components/society/companion/appearance";import {@@ -343,29 +344,29 @@ export function MarketplaceView() {},});- // An exported template from somebody else: installed straight from the file.+ // An exported template from somebody else: previewed in the New-agent+ // dialog, and created only once the person confirms it there.const importAgent = useMutation({- mutationFn: async (file: File): Promise<InstallResultWire> => {+ mutationFn: async (file: File): Promise<InstallResultWire | null> => {let parsed: unknown;try {parsed = JSON.parse(await readFileText(file));} catch {throw new Error(fill(t("marketplace.import_failed"), { error: file.name }));}+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {+ throw new Error(fill(t("marketplace.import_failed"), { error: file.name }));+ }try {- const done = await installAgentTemplate(parsed as Record<string, unknown>);- return {- ok: true,- kind: "agent",- id: done.agent.agent_id,- title: done.agent.name,- ready: true,- };+ const agent = await useCreateAgentDialog.getState().request({ template: parsed as Record<string, unknown> });+ return { ok: true, kind: "agent", id: agent.agentId, title: agent.name, ready: true };} catch (err) {+ if (isCreateCancelled(err)) return null;throw new Error(fill(t("marketplace.import_failed"), { error: (err as Error).message }));}},onSuccess: (result) => {+ if (!result) return;setLanding(result);queryClient.invalidateQueries({ queryKey: ["society", "roster"] });queryClient.invalidateQueries({ queryKey: ["marketplace-community"] });diff --git a/dodaios/ui/web/society_routes.py b/dodaios/ui/web/society_routes.pyindex 985c587aa2..4016960ead 100644--- a/dodaios/ui/web/society_routes.py+++ b/dodaios/ui/web/society_routes.py@@ -2431,12 +2431,17 @@ async def _free_agent_name(rt: SocietyRuntime, wanted: str) -> str:raise HTTPException(409, {"reason": "name_taken", "detail": "pick another name"})-async def install_template(template: dict[str, Any], request: Request) -> dict[str, Any]:+async def install_template(+ template: dict[str, Any], request: Request, seat: dict[str, Any] | None = None+) -> dict[str, Any]:"""Create a NEW agent from a template on this install's own model.- Shared by the import route below and the marketplace's install-by-name.- Use the normal creation defaults, including Bypass permissions. Explicit- template approval rules and any creator restrictions still apply.+ Shared by the import route below, the starter gallery and the+ marketplace's install-by-name. Use the normal creation defaults, including+ Bypass permissions. Explicit template approval rules and any creator+ restrictions still apply. ``seat`` carries what the New-agent dialog+ picked on THIS machine (provider, model, account, runtime, placement,+ companion); a template never brings one of its own."""from dodaios.society.agent_template import TemplateError, create_fields@@ -2448,7 +2453,12 @@ async def install_template(template: dict[str, Any], request: Request) -> dict[swanted = fields.pop("name")name = await _free_agent_name(rt, wanted)scope = template.get("knowledge_scope", "shared")- body = CreateAgentBody(name=name, **fields)+ merged = {**fields, **(seat or {})}+ if seat and isinstance(seat.get("avatar"), dict):+ # The template's figure has been through ``public_avatar``; the seat+ # only brings the dialog's companion on top of it.+ merged["avatar"] = {**(fields.get("avatar") or {}), **seat["avatar"]}+ body = CreateAgentBody(name=name, **merged)created = await create_agent(body, request)agent_row = created["agent"]if scope == "own" and agent_row.get("knowledge_scope") != "own":@@ -2476,6 +2486,163 @@ async def install_template_route(body: InstallTemplateBody, request: Request) ->return await install_template(template, request)+# ----------------------------------------------------------------- starters+#+# The New-agent dialog's gallery (dodaios/society/starters.py): job-shaped+# templates we wrote ourselves, installed through the same create path as an+# imported template, on the seat the person picked in the dialog.+++class StarterSeat(BaseModel):+ """The dialog's seat and look; every field may be left out."""++ model_config = ConfigDict(extra="forbid")++ provider: str = Field(default="", max_length=80)+ model: str = Field(default="", max_length=200)+ account_id: str = Field(default="", max_length=200)+ runtime: str | None = Field(default=None, max_length=20)+ execution_environment: ExecutionEnvironment | None = None+ companion: dict[str, Any] | None = None+++class InstallStarterBody(BaseModel):+ model_config = ConfigDict(extra="forbid")++ #: A gallery starter by id, or a pasted / opened template (bare or wrapped).+ starter_id: str | None = Field(default=None, max_length=40)+ template: dict[str, Any] | None = None+ name: str | None = Field(default=None, max_length=40)+ #: The ticked tools; only ids the starter suggests count. ``None`` = all.+ tools: list[str] | None = Field(default=None, max_length=20)+ seat: StarterSeat = Field(default_factory=StarterSeat)+ #: Also set up the starter's routine (off unless the person ticks it).+ with_routine: bool = False+ #: The person's IANA zone, for the routine's wall-clock schedule.+ timezone: str = Field(default="", max_length=100)+++class PreviewTemplateBody(BaseModel):+ template: dict[str, Any]+++def _unwrap_template(template: dict[str, Any]) -> dict[str, Any]:+ """A bare template, from a bare one or a whole marketplace submission."""+ if template.get("kind") == "agent" and isinstance(template.get("agent"), dict):+ return template["agent"]+ return template+++def _seat_fields(seat: StarterSeat) -> dict[str, Any]:+ """CreateAgentBody fields from the dialog's seat; blanks keep the defaults."""+ fields: dict[str, Any] = {+ key: value+ for key, value in seat.model_dump(exclude_none=True, exclude={"companion"}).items()+ if value not in ("", None)+ }+ if fields.get("runtime") == "jarvis":+ fields.pop("runtime")+ if seat.companion:+ # ``install_template`` lays it over the template's checked figure; the+ # raw template avatar never reaches the roster unchecked.+ fields["avatar"] = {"companion": seat.companion}+ return fields+++def _catalog_or_empty(rt: SocietyRuntime) -> list[Any]:+ try:+ return list(rt.catalog())+ except Exception: # noqa: BLE001 — the gallery still shows; tools read as unavailable+ log.warning("society: capability catalog unavailable for the starters", exc_info=True)+ return []++[email protected]("/starters", openapi_extra={"x-jarvis-readonly": True})+async def list_starters(request: Request) -> dict[str, Any]:+ """The gallery: every starter, with its suggested tools as they stand here."""+ from dodaios.society.starters import AREAS, load_starters, starter_payload++ rt = await _runtime(request)+ catalog = _catalog_or_empty(rt)+ rows = [starter_payload(starter, catalog) for starter in load_starters()]+ return {"areas": list(AREAS), "starters": rows, "total": len(rows)}++[email protected]("/starters/preview", openapi_extra={"x-jarvis-readonly": True})+async def preview_template(body: PreviewTemplateBody, request: Request) -> dict[str, Any]:+ """Check and count an imported template before anything is created."""+ from dodaios.society.starters import preview_payload++ rt = await _runtime(request)+ return preview_payload(_unwrap_template(body.template), _catalog_or_empty(rt))++[email protected]("/starters/install")+async def install_starter(body: InstallStarterBody, request: Request) -> dict[str, Any]:+ """Create an agent from a starter or an imported template on the dialog's seat."""+ from dodaios.society.starters import (+ StarterError,+ routine_schedule,+ starter_by_id,+ starter_template,+ )++ if (body.starter_id is None) == (body.template is None):+ raise HTTPException(+ 422, {"reason": "invalid_request", "detail": "send a starter or a template"}+ )+ starter = None+ if body.starter_id is not None:+ try:+ starter = starter_by_id(body.starter_id)+ except StarterError as exc:+ raise HTTPException(404, {"reason": "unknown_starter", "detail": str(exc)}) from exc+ template = starter_template(starter, name=body.name, tools=body.tools)+ else:+ template = dict(_unwrap_template(body.template or {}))+ if body.name and body.name.strip():+ template["name"] = " ".join(body.name.split())+ if body.tools is not None and isinstance(template.get("focus"), list):+ # Unticking narrows the author's focus; nothing can be added here.+ template["focus"] = [cap for cap in template["focus"] if cap in set(body.tools)]+ installed = await install_template(template, request, _seat_fields(body.seat))+ result: dict[str, Any] = {+ **installed,+ "first_message": starter.first_message if starter else "",+ "routine": None,+ "routine_error": None,+ }+ if starter is None or starter.routine is None or not body.with_routine:+ return result+ if not body.timezone.strip():+ result["routine_error"] = "timezone_required"+ return result+ rt = await _runtime(request)+ agent = await rt.roster.resolve(installed["agent"]["agent_id"])+ schedule = routine_schedule(starter, body.timezone.strip())+ if agent is None or schedule is None:+ result["routine_error"] = "agent_missing"+ return result+ try:+ result["routine"] = await _create_routine_for(+ agent,+ RoutineBody(+ title=starter.routine["title"],+ prompt=starter.routine["prompt"],+ schedule=schedule,+ ),+ request,+ )+ except HTTPException as exc:+ # The agent stands; the routine can still be added from its chat.+ log.warning("society: starter routine not created: %s", exc.detail)+ detail = exc.detail+ result["routine_error"] = (+ str(detail.get("reason")) if isinstance(detail, dict) else str(detail)+ )+ return result++# ----------------------------------------------------------------- controlsdiff --git a/pyproject.toml b/pyproject.tomlindex 4124fd4831..144c8f22b8 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -915,6 +915,8 @@ dodaios = ["skills/safe_imports.txt","core/review/verdict_schema.json","society/mars/definition.json",+ # The New-agent dialog's starter gallery (society/starters.py).+ "society/starters/*.json",# The Hermes / OpenClaw releases setup installs and accepts# (agent_runtimes/versions.py); without it setup falls back to latest."agent_runtimes/runtime-versions.json",diff --git a/tests/contract/test_agent_mcp_harmony.py b/tests/contract/test_agent_mcp_harmony.pyindex 6b489bcefa..5bfa2547eb 100644--- a/tests/contract/test_agent_mcp_harmony.py+++ b/tests/contract/test_agent_mcp_harmony.py@@ -97,6 +97,18 @@ WITHHELD: Final[dict[str, str]] = {"installing a stranger's template is a consent decision made in the app, ""where the instructions are on screen first"),+ "GET /api/society/starters": (+ "the starter gallery is the New-agent dialog's catalogue; MCP clients "+ "create agents through agent_create"+ ),+ "POST /api/society/starters/preview": (+ "the import preview exists so the owner reads a template on screen "+ "before anything is created"+ ),+ "POST /api/society/starters/install": (+ "creating from a starter or an imported template is the dialog's consent "+ "step, made in the app with the preview on screen"+ ),"PATCH /api/society/agents/{agent_id}": ("editing a roster row (model, ceiling, focus) is configuration the owner ""does at their own keyboard, not something a remote client should change"diff --git a/tests/unit/society/test_starters.py b/tests/unit/society/test_starters.pynew file mode 100644index 0000000000..0caba542c8--- /dev/null+++ b/tests/unit/society/test_starters.py@@ -0,0 +1,251 @@+"""The starter gallery's data: every starter is a safe, valid agent template."""++from __future__ import annotations++import json+import re+from pathlib import Path++import pytest++from dodaios.society import starters as starters_mod+from dodaios.society.agent_template import (+ TEMPLATE_KEYS,+ create_fields,+ scrub_text,+ validate_template,+)+from dodaios.society.capabilities import CapabilityKind, CapabilityRow+from dodaios.society.starters import (+ AREAS,+ ROUTINE_SCHEDULES,+ StarterError,+ load_starters,+ preview_payload,+ routine_schedule,+ starter_by_id,+ starter_payload,+ starter_template,+ template_summary,+ validate_starter,+)+from dodaios.tasks.cron_schedule import validate_cron++DATA = Path(starters_mod.__file__).with_name("starters")++#: Names that never belong in our own starter copy: other assistants and+#: agent products, and the trademarked name our lead used to carry.+FORBIDDEN_WORDS = (+ "jarvis",+ "chatgpt",+ "openai",+ "anthropic",+ "claude",+ "gemini",+ "copilot",+ "cursor",+ "codex",+ "openclaw",+ "hermes",+ "grok",+ "kimi",+ "perplexity",+ "notion",+)+++def _raw_entries() -> list[tuple[str, dict]]:+ out = []+ for path in sorted(DATA.glob("*.json")):+ data = json.loads(path.read_text(encoding="utf-8"))+ out += [(data["area"], entry) for entry in data["starters"]]+ return out+++def test_the_gallery_is_big_enough_and_covers_every_area():+ starters = load_starters()+ assert 20 <= len(starters) <= 30+ assert {s.area for s in starters} == set(AREAS)+ assert len({s.id for s in starters}) == len(starters)+ # Area order is the display order.+ order = [AREAS.index(s.area) for s in starters]+ assert order == sorted(order)+++def test_every_file_entry_loads_none_is_silently_dropped():+ raw = _raw_entries()+ assert len(raw) == len(load_starters())+ for area, entry in raw:+ assert validate_starter(entry, area) == [], entry.get("id")++[email protected]("starter", load_starters(), ids=lambda s: s.id)+def test_every_starter_passes_template_validation(starter):+ template = starter_template(starter)+ assert validate_template(template) == []+ # And the installer accepts it as-is.+ fields = create_fields(template)+ assert fields["name"] == template["name"]++[email protected]("starter", load_starters(), ids=lambda s: s.id)+def test_no_starter_widens_approvals_or_brings_a_seat(starter):+ template = dict(starter.template)+ assert set(template) <= TEMPLATE_KEYS+ for key in ("provider", "model", "account_id", "permission_ceiling", "approval_mode"):+ assert key not in template+ fields = create_fields(starter_template(starter))+ # Always-allow never travels; require_approval only adds confirmations.+ assert fields["approval_rules"]["always_allow"] == []+ assert fields.get("grant_mode", "all") == "all"+ assert fields.get("denies", []) == []++[email protected]("starter", load_starters(), ids=lambda s: s.id)+def test_no_starter_names_a_machine_a_person_or_a_brand(starter):+ texts = [+ starter.outcome,+ starter.first_message,+ str(starter.template.get("instructions")),+ str(starter.template.get("title")),+ str(starter.template.get("name")),+ ]+ if starter.routine:+ texts += [starter.routine["title"], starter.routine["prompt"]]+ for text in texts:+ cleaned, findings = scrub_text(text, "starter")+ assert findings == [] and cleaned == text, (starter.id, text)+ words = set(re.findall(r"[a-z]+", text.lower()))+ assert not words & set(FORBIDDEN_WORDS), (starter.id, words & set(FORBIDDEN_WORDS))+++def test_routines_use_valid_named_schedules():+ for when, expression in ROUTINE_SCHEDULES.items():+ validate_cron(expression, "Europe/Berlin")+ assert when+ with_routine = [s for s in load_starters() if s.routine]+ assert len(with_routine) >= 5+ schedule = routine_schedule(with_routine[0], "America/New_York")+ assert schedule == {+ "kind": "cron",+ "expression": ROUTINE_SCHEDULES[with_routine[0].routine["when"]],+ "timezone": "America/New_York",+ }+ no_routine = next(s for s in load_starters() if s.routine is None)+ assert routine_schedule(no_routine, "UTC") is None+++def test_picked_tools_narrow_the_suggestion_and_never_widen_it():+ starter = starter_by_id("meeting-prep")+ assert starter.tools[0] == "plugin:google_calendar"+ narrowed = starter_template(starter, tools=["plugin:gmail", "core:run-shell"])+ assert narrowed["focus"] == ["plugin:gmail"]+ unticked = starter_template(starter, tools=[])+ assert "focus" not in unticked+ full = starter_template(starter)+ assert full["focus"] == list(starter.tools)+ # The catalogue itself stays untouched.+ assert "focus" not in starter.template+++def test_a_picked_name_replaces_the_starter_name():+ starter = starter_by_id("researcher")+ assert starter_template(starter, name=" Ada Scout ")["name"] == "Ada Scout"+ assert starter_template(starter, name=" ")["name"] == "Researcher"+++def test_unknown_starter_is_a_starter_error():+ with pytest.raises(StarterError):+ starter_by_id("nope")+++def _row(cap_id: str, connected: bool) -> CapabilityRow:+ kind = CapabilityKind(cap_id.split(":", 1)[0])+ return CapabilityRow(+ id=cap_id,+ kind=kind,+ label=cap_id.split(":", 1)[1].title(),+ one_liner="",+ risk_tier="read",+ connected=connected,+ tool_name=cap_id.split(":", 1)[1],+ )+++def test_payload_marks_connected_and_missing_tools():+ starter = starter_by_id("meeting-prep")+ catalog = [_row("plugin:google_calendar", True), _row("plugin:gmail", False)]+ payload = starter_payload(starter, catalog)+ tools = {t["id"]: t for t in payload["tools"]}+ assert tools["plugin:google_calendar"] == {+ "id": "plugin:google_calendar",+ "label": "Google_Calendar",+ "available": True,+ "connected": True,+ }+ assert tools["plugin:gmail"]["available"] and not tools["plugin:gmail"]["connected"]+ assert not tools["core:search-web"]["available"]+ assert payload["routine"]["when"] == "weekday_morning"+ summary = payload["summary"]+ assert summary["tools"] == 3+ assert summary["routines"] == 1+ assert summary["asks_before"] == 3+ assert summary["skills"] is None+ assert summary["instructions_words"] > 10+++def test_summary_counts_rules_and_skills():+ template = {+ "instructions": "Do it.\n\n- one\n- two\n* three",+ "skills": ["a", "b"],+ "focus": ["core:search-web"],+ "require_approval": ["plugin:gmail:send"],+ "grant_mode": "allowlist",+ }+ summary = template_summary(template)+ assert summary["instructions_rules"] == 3+ assert summary["skills"] == 2+ assert summary["tools"] == 1+ assert summary["asks_before"] == 1+ assert summary["limited_tools"] is True+++def test_preview_reports_errors_without_creating_anything():+ bad = preview_payload({"schema": 1, "name": "x"}, [])+ assert not bad["ok"] and bad["errors"]+ not_object = preview_payload(["nope"], [])+ assert not not_object["ok"] and not_object["template"] is None+ good = preview_payload(+ {+ "schema": 1,+ "name": "Helper",+ "instructions": "Keep my notes.",+ "focus": ["core:search-web"],+ },+ [_row("core:search-web", True)],+ )+ assert good["ok"] and good["errors"] == []+ assert good["tools"][0]["connected"] is True+ assert good["summary"]["tools"] == 1+++def test_a_broken_entry_is_skipped_not_fatal(tmp_path: Path, caplog):+ good = json.loads((DATA / "writing.json").read_text(encoding="utf-8"))+ good["starters"] = good["starters"][:1]+ broken = {+ "area": "ops",+ "starters": [+ {"id": "Bad Id", "icon": "x", "outcome": "", "first_message": "", "template": {}},+ ],+ }+ (tmp_path / "a.json").write_text(json.dumps(good), encoding="utf-8")+ (tmp_path / "b.json").write_text(json.dumps(broken), encoding="utf-8")+ (tmp_path / "c.json").write_text("{not json", encoding="utf-8")+ loaded = load_starters.__wrapped__(tmp_path)+ assert [s.id for s in loaded] == [good["starters"][0]["id"]]+++def test_a_template_focus_in_the_data_is_refused():+ entry = dict(_raw_entries()[0][1])+ entry["template"] = {**entry["template"], "focus": ["core:search-web"]}+ assert any("focus" in problem for problem in validate_starter(entry, "coding"))diff --git a/tests/unit/society/test_starters_routes.py b/tests/unit/society/test_starters_routes.pynew file mode 100644index 0000000000..b5e422eade--- /dev/null+++ b/tests/unit/society/test_starters_routes.py@@ -0,0 +1,305 @@+"""Starters install through the normal create path on every runtime and seat.++Headless: no keys, no network. The external runtimes' setup is faked, so a+Hermes or OpenClaw agent is created exactly as the dialog would create it.+"""++from __future__ import annotations++from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from dodaios.agent_chat.service import resolve_runner+from dodaios.society.runtime import SocietyRuntime+from dodaios.society.starters import load_starters+from dodaios.tasks.store import TaskStore+from dodaios.ui.web.society_routes import router+++def ensured(monkeypatch) -> list[str]:+ from dodaios.agent_runtimes import manager++ calls: list[str] = []++ async def _ensure(runtime: str, *args, **kwargs):+ calls.append(runtime)++ monkeypatch.setattr(manager, "ensure", _ensure)+ return calls+++def _client(tmp_path: Path, task_store: TaskStore | None = None):+ runtime = SocietyRuntime(tmp_path, seed_starter_team=False)+ app = FastAPI()+ app.include_router(router)+ app.state.society_factory = lambda: runtime+ if task_store is not None:+ app.state.task_store = task_store+ app.state.task_scheduler = None+ return TestClient(app), runtime+++#: (seat, expected runner) — brain/API seat, the Claude and Codex CLIs, and+#: the two ACP runtimes.+SEATS = [+ ({"provider": "openai", "model": "gpt-5.2"}, None),+ ({"provider": "claude-api", "account_id": "subscription"}, None),+ ({"provider": "openai-codex"}, None),+ ({"provider": "openai", "runtime": "hermes"}, "hermes-cli"),+ ({"provider": "openai", "runtime": "openclaw"}, "openclaw-cli"),+]+++def test_gallery_lists_every_starter(tmp_path: Path):+ client, runtime = _client(tmp_path)+ with client:+ try:+ body = client.get("/api/society/starters").json()+ finally:+ client.portal.call(runtime.close)+ assert body["total"] == len(load_starters())+ assert body["areas"][0] == "coding"+ first = body["starters"][0]+ assert {"id", "area", "icon", "name", "outcome", "tools", "summary", "first_message"} <= set(+ first+ )++[email protected]("seat,runner", SEATS, ids=lambda v: str(v))+def test_every_starter_creates_an_agent_on_every_runtime(+ tmp_path: Path, ensured: list[str], seat: dict, runner: str | None+):+ client, runtime = _client(tmp_path)+ with client:+ try:+ for starter in load_starters():+ res = client.post(+ "/api/society/starters/install",+ json={"starter_id": starter.id, "seat": seat},+ )+ assert res.status_code == 200, (starter.id, res.text)+ body = res.json()+ agent = body["agent"]+ assert agent["provider"] == seat["provider"]+ assert agent["runtime"] == seat.get("runtime", "jarvis")+ assert agent["approval_mode"] == "bypass"+ assert agent["approval_rules"]["always_allow"] == []+ assert agent["approval_rules"]["require_approval"] == list(+ starter.template.get("require_approval", [])+ )+ assert body["first_message"] == starter.first_message+ assert body["routine"] is None+ resolved = resolve_runner(+ agent["provider"],+ surface="society",+ runtime="" if agent["runtime"] == "jarvis" else agent["runtime"],+ account_id=agent.get("account_id", ""),+ )+ assert resolved != "unknown"+ if runner:+ assert resolved == runner+ finally:+ client.portal.call(runtime.close)+ if seat.get("runtime"):+ assert set(ensured) == {seat["runtime"]}+++def test_install_applies_name_tools_and_companion(tmp_path: Path, ensured: list[str]):+ client, runtime = _client(tmp_path)+ companion = {"shape": "drop", "color": "#c9a227"}+ with client:+ try:+ res = client.post(+ "/api/society/starters/install",+ json={+ "starter_id": "meeting-prep",+ "name": "Morning Desk",+ "tools": ["plugin:google_calendar", "core:run-shell"],+ "seat": {"provider": "openai", "companion": companion},+ },+ )+ assert res.status_code == 200, res.text+ agent = res.json()["agent"]+ assert agent["name"] == "Morning Desk"+ assert agent["focus"] == ["plugin:google_calendar"]+ assert agent["avatar"]["companion"]["shape"] == "drop"+ # Same starter again: a free name, never the first agent adopted.+ again = client.post(+ "/api/society/starters/install",+ json={"starter_id": "meeting-prep", "name": "Morning Desk"},+ ).json()+ assert again["agent"]["name"] == "Morning Desk 2"+ assert again["renamed_from"] == "Morning Desk"+ finally:+ client.portal.call(runtime.close)+++def test_install_refuses_bad_requests(tmp_path: Path):+ client, runtime = _client(tmp_path)+ with client:+ try:+ both = client.post(+ "/api/society/starters/install",+ json={"starter_id": "editor", "template": {"schema": 1}},+ )+ assert both.status_code == 422+ neither = client.post("/api/society/starters/install", json={})+ assert neither.status_code == 422+ unknown = client.post("/api/society/starters/install", json={"starter_id": "nope"})+ assert unknown.status_code == 404+ reserved = client.post(+ "/api/society/starters/install", json={"starter_id": "editor", "name": "Jarvis"}+ )+ assert reserved.status_code == 422+ extra = client.post(+ "/api/society/starters/install",+ json={"starter_id": "editor", "seat": {"approval_mode": "bypass"}},+ )+ assert extra.status_code == 422+ finally:+ client.portal.call(runtime.close)+++def test_imported_template_previews_then_installs_on_the_dialog_seat(tmp_path: Path):+ client, runtime = _client(tmp_path)+ template = {+ "schema": 1,+ "name": "Imported helper",+ "instructions": "Maintain the task list.\n\n- Keep it short.",+ "require_approval": ["plugin:gmail:send"],+ "focus": ["core:search-web"],+ }+ with client:+ try:+ before = client.get("/api/society/agents").json()["total"]+ preview = client.post(+ "/api/society/starters/preview",+ json={"template": {"kind": "agent", "agent": template}},+ ).json()+ assert preview["ok"] is True+ assert preview["template"]["name"] == "Imported helper"+ assert preview["summary"]["asks_before"] == 1+ assert preview["summary"]["instructions_rules"] == 1+ bad = client.post(+ "/api/society/starters/preview",+ json={"template": {**template, "provider": "openai"}},+ ).json()+ assert bad["ok"] is False and any("provider" in e for e in bad["errors"])+ # A preview creates nothing.+ assert client.get("/api/society/agents").json()["total"] == before+ res = client.post(+ "/api/society/starters/install",+ json={"template": template, "seat": {"provider": "openai", "model": "gpt-5.2"}},+ )+ assert res.status_code == 200, res.text+ agent = res.json()["agent"]+ assert agent["model"] == "gpt-5.2"+ assert agent["approval_rules"]["require_approval"] == ["plugin:gmail:send"]+ assert res.json()["first_message"] == ""+ narrowed = client.post(+ "/api/society/starters/install",+ json={"template": template, "tools": ["core:run-shell"]},+ ).json()["agent"]+ assert "core:search-web" not in narrowed["focus"]+ assert "core:run-shell" not in narrowed["focus"]+ refused = client.post(+ "/api/society/starters/install",+ json={"template": {**template, "provider": "openai"}},+ )+ assert refused.status_code == 422+ finally:+ client.portal.call(runtime.close)+++def test_imported_figure_stays_under_the_dialog_companion(tmp_path: Path):+ client, runtime = _client(tmp_path)+ template = {+ "schema": 1,+ "name": "Figure check",+ "instructions": "Keep the notes tidy.",+ "avatar": {"archetype": "scout"},+ }+ companion = {"shape": "drop", "color": "#c9a227"}+ with client:+ try:+ res = client.post(+ "/api/society/starters/install",+ json={"template": template, "seat": {"provider": "openai", "companion": companion}},+ )+ assert res.status_code == 200, res.text+ avatar = res.json()["agent"]["avatar"]+ # The template's checked figure stays; the dialog's companion wins.+ assert avatar["archetype"] == "scout"+ assert avatar["companion"]["shape"] == "drop"+ finally:+ client.portal.call(runtime.close)+++async def test_routine_is_created_only_when_ticked(tmp_path: Path):+ import httpx++ store = TaskStore(tmp_path / "tasks.db")+ await store.init()+ runtime = SocietyRuntime(tmp_path / "society", seed_starter_team=False)+ app = FastAPI()+ app.include_router(router)+ app.state.society_factory = lambda: runtime+ app.state.task_store = store+ app.state.task_scheduler = None+ transport = httpx.ASGITransport(app=app)+ try:+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:+ plain = await client.post(+ "/api/society/starters/install", json={"starter_id": "daily-briefing"}+ )+ assert plain.json()["routine"] is None+ no_zone = await client.post(+ "/api/society/starters/install",+ json={"starter_id": "daily-briefing", "with_routine": True},+ )+ assert no_zone.json()["routine_error"] == "timezone_required"+ ticked = await client.post(+ "/api/society/starters/install",+ json={+ "starter_id": "daily-briefing",+ "with_routine": True,+ "timezone": "Europe/Berlin",+ },+ )+ body = ticked.json()+ assert ticked.status_code == 200, ticked.text+ assert body["routine_error"] is None+ assert body["routine"]["title"].endswith("Morning briefing")+ agent_id = body["agent"]["agent_id"]+ routines = (await client.get(f"/api/society/agents/{agent_id}/routines")).json()+ assert routines["total"] == 1+ # A starter without a routine ignores the tick.+ quiet = await client.post(+ "/api/society/starters/install",+ json={"starter_id": "editor", "with_routine": True, "timezone": "UTC"},+ )+ assert quiet.json()["routine"] is None and quiet.json()["routine_error"] is None+ finally:+ await runtime.close()+ await store.close()+++def test_routine_without_a_task_store_keeps_the_agent(tmp_path: Path):+ client, runtime = _client(tmp_path)+ with client:+ try:+ before = client.get("/api/society/agents").json()["total"]+ res = client.post(+ "/api/society/starters/install",+ json={"starter_id": "daily-briefing", "with_routine": True, "timezone": "UTC"},+ )+ assert res.status_code == 200+ assert res.json()["routine"] is None+ assert res.json()["routine_error"]+ assert client.get("/api/society/agents").json()["total"] == before + 1+ finally:+ client.portal.call(runtime.close)