Skip to content

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.

feat(marketplace): share agents as templates, publish without a server (#371)

Ruben Lütke99907c74981e
diff --git a/docs/jarvis-cli-reference.md b/docs/jarvis-cli-reference.md
index ee56c4b0d1..a09fe9abbc 100644
--- a/docs/jarvis-cli-reference.md
+++ b/docs/jarvis-cli-reference.md
@@ -153,7 +153,7 @@ _Generated from the curated command tree by `scripts/ci/gen_cli_reference.py`
- `jarvis marketplace connect-poll <plugin_id> <flow_id>` — Poll an in-progress OAuth connect flow.
- `jarvis marketplace connect-start <plugin_id> --yes --dry-run` — Begin an OAuth connect flow (prints the redirect URI + flow id).
- `jarvis marketplace disconnect <plugin_id> --yes --dry-run` — Disconnect a plugin.
-- `jarvis marketplace install <item_id> --yes --dry-run` — Install a marketplace entry by name — skill or plugin — and report it.
+- `jarvis marketplace install <item_id> --yes --dry-run` — Install a marketplace entry by name — skill, plugin or agent — and report it.
- `jarvis marketplace list` — List marketplace plugins + their connection status.
## mcps
diff --git a/docs/marketplace/agent-templates.md b/docs/marketplace/agent-templates.md
new file mode 100644
index 0000000000..d3cfeded14
--- /dev/null
+++ b/docs/marketplace/agent-templates.md
@@ -0,0 +1,165 @@
+# Agent templates — sharing an agent through the marketplace
+
+**Status:** shipped 2026-10-03 ·
+**Registry side:** `PersonalJarvis/marketplace` (`scripts/validate.py` →
+`validate_agent`, `scripts/intake.py`, workflow `intake.yml`) ·
+**App side:** `jarvis/society/agent_template.py`
+
+A person who built a good agent can hand it to everybody else: its job line,
+its standing instructions, its look and the tools it reaches for first. What
+travels is the agent's **design**, never its operation — no account, no
+model choice, no chats, no memory, no files, no permissions that would run
+anything without asking on somebody else's machine.
+
+## The flow
+
+```
+Agent card ─ Share ─► Share sheet ──────────────► Publish (signed in with GitHub)
+ │ template built + scrubbed │
+ │ by the server ▼
+ │ issue on PersonalJarvis/marketplace
+ │ "Ask <agent>" │ (opened AS the user)
+ └► chat message → agent ▼
+ society_share_template intake.yml: publisher = issue author,
+ writes the public version validate.py, commit, publish.yml
+ │
+ ▼
+ index.json "agents" ─► Marketplace → Agents
+ │ Install / jarvis marketplace install
+ ▼
+ a NEW agent on the installer's own model
+```
+
+1. **Share** (agent card, Options rail; never on the lead or sample rows)
+ opens the sheet. The server builds the template from the roster row
+ (`GET /api/society/agents/{id}/template`); the sheet shows it as a code
+ block to copy or export (`<name>.agent.json`) beside the public version:
+ the store-card summary, the marketplace name, version and tags.
+2. **Ask &lt;agent&gt;** sends the agent a chat message asking it to write its
+ own public version — a summary for strangers and its instructions with
+ everything personal taken out. The agent saves it with the
+ `society_share_template` tool (`jarvis/society/share_tool.py`, `safe`
+ tier: it writes a local draft only). The sheet polls until the draft
+ changes. The agent is never the privacy boundary — what it writes goes
+ through the same scrubber as everything else.
+3. **Publish** needs the GitHub sign-in (device flow on the marketplace
+ GitHub App, the same identity the Publish studio uses). The app opens an
+ issue on the registry as that user; the registry publishes it within a
+ minute or two and the sheet watches the feed until the version is live.
+4. **Install** — from the marketplace card, from
+ `jarvis marketplace install <name>`, or by importing an exported file —
+ creates a new agent. A name already on the team gets a number
+ ("Release Scribe 2"); the roster would otherwise adopt the existing agent.
+
+## What a template carries — and what it never does
+
+The template is an allowlist (`TEMPLATE_KEYS` in `agent_template.py`, the
+same list as `AGENT_KEYS` in the registry validator — change both):
+
+| Field | Meaning |
+|---|---|
+| `schema` | `1` |
+| `name`, `title` | roster name (1–40 chars, never "Jarvis") and job line |
+| `instructions` | the standing instructions (the roster `description`), ≤ 20 000 bytes |
+| `tier` | `specialist` or `orchestrator` — never `lead` |
+| `effort` | a short word or empty |
+| `focus`, `grant_mode`, `grants`, `denies`, `skills` | which tools it reaches for first / may use |
+| `require_approval` | capability ids that always ask — can only ADD confirmations |
+| `knowledge_scope` | `shared` or `own` |
+| `avatar` | the figure recipe: catalog ids and `#rrggbb` colours only |
+
+Refused by name, in the app and in the registry, because each would either
+point at the author's machine or let a stranger's template decide what runs
+without asking on the installer's machine: `account_id`, `provider`, `model`,
+`workspace_dir`, `wiki_namespace`, `computer_id`, `parent_agent_id`,
+`permission_ceiling`, `approval_mode`, `approval_rules` / `always_allow`,
+`daily_budget_usd`, `max_concurrent_runs`, `browser_mode`,
+`browser_allowed_domains`, and an imported figure file (`avatar.model`).
+
+This is stricter than the machine-to-machine ecosystem bundle
+(`jarvis/mcp/agents/portable.py`), which moves a person's OWN team to their
+own other computer and therefore keeps model choices and budgets.
+
+## Scrubbing
+
+`scrub_text` replaces, in the instructions, the job line and the summary:
+
+- credentials — the registry's secret patterns plus generic
+ `password: …` / `api_key = …` shapes and secret URL parameters
+ (`?token=…`, `&key=…`);
+- e-mail addresses (except `example.com/.org/.net`);
+- international phone numbers (a leading `+`; bare digit runs are dates and
+ ids far more often);
+- home folders (the Windows `Users` folder and the macOS and Linux home roots);
+- private network addresses (10/8, 172.16/12, 192.168/16).
+
+Each replacement is listed on the sheet with a hint that names it to its
+author without repeating it (`ma…om`). The registry independently refuses a
+credential anywhere in the file and a home folder in the instructions.
+
+## Publishing without a server
+
+The storefront that used to receive submissions was retired, so publishing
+now needs no server of ours at all:
+
+- The marketplace GitHub App (`publish_github_client_id`) signs the user in
+ with the **device flow** — no client secret in the binary.
+- Its user token opens an **issue** on `publish_registry_repo`
+ (default `PersonalJarvis/marketplace`). A GitHub App user token can do that
+ on a public repository where the App is installed **with the Issues
+ permission** — the same mechanism giscus and utterances use for comments.
+- The registry's `intake.yml` runs on `issues` events from the default
+ branch only, reads the body as data (never executes it, never interpolates
+ it into a shell), **replaces `publisher` and `publisher_id` with the issue
+ author**, runs `validate.py` with the pre-change tree as base (ownership by
+ numeric account id, version must increase, kind may not change), commits
+ `submissions/<name>.json` and starts `publish.yml`. Red checks are answered
+ on the issue with the reasons; editing the issue re-runs them.
+
+The same door serves skills and plugins: with no `publish_endpoint`
+configured, the Publish studio files its submissions the same way, which
+brought in-app publishing back after the storefront's retirement. A fork can
+point `publish_registry_repo` at its own registry, or set `publish_endpoint`
+to a hosted endpoint of its own.
+
+**If GitHub refuses the issue** (App without the Issues permission, issues
+turned off), the sheet says so in one sentence and offers *Copy and open
+GitHub*: the template goes to the clipboard and the registry's
+"Publish to the marketplace" issue form opens in the browser — one paste,
+same checks.
+
+## Installing safely
+
+`create_fields` turns a validated template into roster fields; the install
+route (`POST /api/society/templates/install`, also used by the marketplace's
+install-by-name) adds:
+
+- the model is the installer's own (the create route inherits their last
+ chat seat); nothing of the publisher's accounts travels;
+- `approval_mode = ask` wherever the resolved runner can hold an approval
+ prompt, so a stranger's agent asks before it acts until the person changes
+ that; runners that cannot fall back to the app's default;
+- `always_allow` is always empty; `require_approval` only adds prompts;
+- budget, concurrency, ceiling and browser settings are the app's defaults.
+
+The marketplace card shows, before the Install button: the instructions in
+full, the tools it reaches for first, what it always asks before, and that it
+runs on the installer's own model.
+
+## Pieces
+
+| Piece | Where |
+|---|---|
+| Build, scrub, validate, install fields, share draft on disk | `jarvis/society/agent_template.py` |
+| Agent tool `society_share_template` | `jarvis/society/share_tool.py` (registered in `surface.society_tools`) |
+| REST `GET/PUT /api/society/agents/{id}/template`, `POST …/template/publish`, `POST /api/society/templates/install` | `jarvis/ui/web/society_routes.py` |
+| Issue intake submit, `registry_repo()`, agent drafts | `jarvis/marketplace/publish.py` |
+| Feed model `CommunityAgentEntry`, `index.agents` | `jarvis/marketplace/community_source.py` |
+| Browse payload `agents`, install by name | `jarvis/ui/web/marketplace_routes.py` |
+| CLI `jarvis marketplace install/browse` | `jarvis/cli_ctl/commands/marketplace.py` |
+| Share sheet | `frontend/src/components/society/card/ShareAgentDialog.tsx` |
+| Agents shelf, drawer, import | `frontend/src/views/MarketplaceView.tsx` |
+| Client | `frontend/src/lib/agentShare.ts` |
+
+Share drafts live at `<data>/society/<agent_id>/share-template.json`; they
+hold only the public-version edits and the last published version.
diff --git a/docs/marketplace/community-registry.md b/docs/marketplace/community-registry.md
index a657572365..41e78bbb28 100644
--- a/docs/marketplace/community-registry.md
+++ b/docs/marketplace/community-registry.md
@@ -3,9 +3,13 @@
**Status:** live since 2026-08-12 ·
**Decisions:** [public-marketplace-analysis.md](public-marketplace-analysis.md) ·
**Packaging:** [agent-plugins-standard.md](agent-plugins-standard.md) ·
-**Skills for other agents:** [portable-skills.md](portable-skills.md)
+**Skills for other agents:** [portable-skills.md](portable-skills.md) ·
+**Agents:** [agent-templates.md](agent-templates.md)
-Anyone can publish plugins and skills for Personal Jarvis; every submission
+Anyone can publish plugins, skills and agent templates for Personal Jarvis.
+Besides a pull request, a submission can arrive as an issue — that is how
+the app publishes after GitHub sign-in (see agent-templates.md, "Publishing
+without a server"). Every submission
that passes automated checks is listed automatically — an open registry in
the ClawHub spirit, with **zero maintainer infrastructure**: GitHub pull
requests are the upload API, Actions is the validation pipeline, and Pages
diff --git a/jarvis/cli_ctl/commands/marketplace.py b/jarvis/cli_ctl/commands/marketplace.py
index 9c91fdb159..0313daa8b4 100644
--- a/jarvis/cli_ctl/commands/marketplace.py
+++ b/jarvis/cli_ctl/commands/marketplace.py
@@ -47,6 +47,7 @@ def _fail(exc: ApiError) -> typer.Exit:
_SECTIONS: tuple[tuple[str, str], ...] = (
("skills", "skill"),
("plugins", "plugin"),
+ ("agents", "agent"),
)
@@ -89,10 +90,15 @@ _BLURBS = {
"A connector to an outside service. Installing it only puts it on your "
"list — it stays powerless until you connect your account."
),
+ "agent": (
+ "A ready-made teammate: its job, its instructions and its look. It joins "
+ "your agents on YOUR model and asks before it acts."
+ ),
}
_LANDS_IN = {
"skill": "your skills",
"plugin": "your plugin list",
+ "agent": "your agents",
}
@@ -133,6 +139,14 @@ def _report_installed(payload: dict[str, Any]) -> int:
if payload.get("location"):
_field("File", str(payload["location"]))
+ if kind == "agent" and payload.get("ready"):
+ _field("Status", "on your team — it runs on your own model")
+ if payload.get("renamed_from"):
+ _field("Name", f"{title} (you already had a {payload['renamed_from']!r})")
+ _field("Talk to it", "open the app → Agents")
+ render.line()
+ return 0
+
if payload.get("ready"):
_field(
"Status",
@@ -167,6 +181,10 @@ def _report_already_there(kind: str, item_id: str, client: Any) -> int:
render.line(f"[green]Already installed:[/green] [bold]{item_id}[/bold]")
render.line()
_field("Kind", kind)
+ if kind == "agent":
+ _field("Status", "already on your team — open the app → Agents")
+ render.line()
+ return 0
if kind == "skill":
try:
detail = client.request("GET", f"/api/skills/{item_id}")
@@ -207,7 +225,7 @@ def install(
yes: bool = options.yes_opt(),
dry_run: bool = options.dry_opt(),
) -> None:
- """Install a marketplace entry by name — skill or plugin — and report it.
+ """Install a marketplace entry by name — skill, plugin or agent — and report it.
At a terminal this shows what the entry is and asks once before installing,
then states plainly whether the thing is usable now or still needs a step.
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index 3a98de5e14..bb948355bd 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -4189,6 +4189,12 @@ class MarketplaceConfig(BaseModel):
# retired, so a stock install offers no Publish button instead of firing
# a request at a host that answers nothing.
publish_endpoint: str = ""
+ # The registry repository the in-app Publish flow files submissions to
+ # when no endpoint is configured: an issue opened as the signed-in user,
+ # which the registry's intake workflow validates and publishes
+ # (docs/marketplace/agent-templates.md). This is the default path — it
+ # needs no server. Empty string hides Publish.
+ publish_registry_repo: str = "PersonalJarvis/marketplace"
# Client id of the marketplace GitHub App (public by design — device flow
# needs no secret, which is why a downloadable binary can use it).
publish_github_client_id: str = "Iv23li1YcX62KJO67whO"
diff --git a/jarvis/core/events.py b/jarvis/core/events.py
index de8f569af1..0fa312a991 100644
--- a/jarvis/core/events.py
+++ b/jarvis/core/events.py
@@ -2557,7 +2557,7 @@ class MarketplaceItemInstalled(Event):
usable right now (a skill that validated), False when it
still needs the user (a plugin waiting to be connected).
"""
- kind: str = "" # "skill" | "plugin"
+ kind: str = "" # "skill" | "plugin" | "agent"
item_id: str = ""
title: str = ""
ready: bool = False
diff --git a/jarvis/marketplace/community_source.py b/jarvis/marketplace/community_source.py
index 5d160493a5..b918a42273 100644
--- a/jarvis/marketplace/community_source.py
+++ b/jarvis/marketplace/community_source.py
@@ -1,7 +1,8 @@
"""Fetch and cache the community marketplace index.
The registry repo (PersonalJarvis/marketplace) compiles every published
-plugin and skill into one static ``index.json`` served from GitHub Pages.
+plugin, skill and agent template into one static ``index.json`` served from
+GitHub Pages.
This module is the app's only reader of that feed: fetch with short
timeouts, validate into typed models, and persist the result under
``data/marketplace_index.json`` so browsing keeps working offline and on a
@@ -159,11 +160,46 @@ class CommunitySkillEntry(_Tolerant):
return self.flavor == "portable"
+class CommunityAgentEntry(_Tolerant):
+ """A published agent template (``kind: "agent"`` in the registry).
+
+ ``agent`` is the template verbatim. It is validated at INSTALL time by
+ ``jarvis.society.agent_template`` — the same rule the publisher's app
+ applied — so one malformed entry degrades to one uninstallable card.
+ """
+
+ name: str
+ title: str | None = None
+ description: str = ""
+ publisher: str | None = None
+ publisher_id: int | None = None
+ version: str | None = None
+ published_at: str | None = None
+ categories: list[str] = Field(default_factory=list)
+ source_url: str | None = None
+ agent: dict[str, Any] = Field(default_factory=dict)
+
+
class CommunityIndex(_Tolerant):
revision: int = 0
generated_at: str | None = None
plugins: list[CommunityPluginEntry] = Field(default_factory=list)
skills: list[CommunitySkillEntry] = Field(default_factory=list)
+ #: Absent on an index from a registry older than agent templates.
+ agents: list[CommunityAgentEntry] = Field(default_factory=list)
+
+ @field_validator("agents", mode="after")
+ @classmethod
+ def _drop_unsafe_agent_names(
+ cls, value: list[CommunityAgentEntry]
+ ) -> list[CommunityAgentEntry]:
+ kept: list[CommunityAgentEntry] = []
+ for entry in value:
+ if _SKILL_NAME_RE.fullmatch(entry.name) and ".." not in entry.name:
+ kept.append(entry)
+ else:
+ logger.warning("community index: dropping agent with unsafe name %r", entry.name)
+ return kept
@field_validator("skills", mode="after")
@classmethod
@@ -305,6 +341,7 @@ async def get_index(
__all__ = [
"SKILL_FLAVORS",
+ "CommunityAgentEntry",
"CommunityIndex",
"CommunityPluginEntry",
"CommunitySkillEntry",
diff --git a/jarvis/marketplace/install_standard.py b/jarvis/marketplace/install_standard.py
index 4e7ab31ab2..5350c18e7b 100644
--- a/jarvis/marketplace/install_standard.py
+++ b/jarvis/marketplace/install_standard.py
@@ -32,7 +32,7 @@ from typing import Literal, TypedDict
# which is what makes a copy-paste one-liner possible at all.
_NAME_RE = re.compile(r"^[a-z0-9](?:[a-z0-9.-]{0,62}[a-z0-9])?$")
-EntryKind = Literal["plugin", "skill"]
+EntryKind = Literal["plugin", "skill", "agent"]
class InstallBlock(TypedDict):
diff --git a/jarvis/marketplace/publish.py b/jarvis/marketplace/publish.py
index 9a518e8281..558fa187cb 100644
--- a/jarvis/marketplace/publish.py
+++ b/jarvis/marketplace/publish.py
@@ -1,16 +1,24 @@
"""In-app publishing: sign in with GitHub, validate, submit, watch it go live.
-The desktop half of the marketplace's publish path
-(docs/marketplace/github-signin-implementation.md §7): the app must never
-hold the website's cookie or any client secret, so identity comes from the
-GitHub **device flow** on the marketplace App (public client id), the token
-lands in the keyring ``TokenStore``, and the submission is POSTed to the
-storefront endpoint as ``Authorization: Bearer``. The endpoint proves the
-token belongs to OUR App (confused-deputy check), derives the publisher from
-it, and opens the registry PR as the bot — one publishing implementation for
-web and app.
-
-A package (plugin or skill) travels as JSON to ``/submit`` and ends up in
+The desktop half of the marketplace's publish path. Identity comes from the
+GitHub **device flow** on the marketplace App (public client id, no secret
+in the binary), and the token lands in the keyring ``TokenStore``.
+
+Where the submission goes:
+
+* **The registry's issue intake (default, no server).** The app opens an
+ issue on the registry repository AS the signed-in user, its body carrying
+ the submission as one fenced JSON block. The registry's ``intake``
+ workflow takes the publisher from the issue's author — GitHub
+ authenticated that account — runs the same validator every pull request
+ meets, and publishes (docs/marketplace/agent-templates.md). The App needs
+ the Issues permission on the registry for its user tokens to do this.
+* **A hosted endpoint (``publish_endpoint``), when configured.** The token
+ goes as ``Authorization: Bearer``; the endpoint derives the publisher and
+ opens the registry PR as the bot. The original storefront that served this
+ was retired, so this path is for forks running their own.
+
+A package (plugin, skill or agent template) travels as JSON and ends up in
the same feed the store reads back.
Validation here MIRRORS the endpoint's rules (``_lib/validate.ts``, itself a
@@ -58,6 +66,14 @@ _GITHUB_TOKEN_URL = "https://github.com/login/oauth/access_token" # noqa: S105
_GITHUB_USER_URL = "https://api.github.com/user"
_HTTP_TIMEOUT = httpx.Timeout(connect=5.0, read=30.0, write=30.0, pool=30.0)
+_GITHUB_API = "https://api.github.com"
+_REPO_RE = re.compile(r"^[A-Za-z0-9-]{1,39}/[A-Za-z0-9._-]{1,100}$")
+#: GitHub keeps at most this many characters of an issue body.
+_MAX_ISSUE_BODY = 65_536
+#: The registry intake picks up issues with this title tag or body marker
+#: (scripts/intake.py in PersonalJarvis/marketplace — keep them identical).
+INTAKE_TITLE_TAG = "[publish]"
+INTAKE_BODY_MARKER = "<!-- jarvis-marketplace-submission -->"
_UA = {"User-Agent": "Personal-Jarvis/1.0"}
# ---------------------------------------------------------------------------
@@ -116,8 +132,8 @@ def validate_draft(draft: dict[str, Any]) -> tuple[dict[str, Any] | None, list[F
"""
errors: list[FieldError] = []
kind = draft.get("kind")
- if kind not in ("plugin", "skill"):
- return None, [FieldError('kind must be "plugin" or "skill"', "kind")]
+ if kind not in ("plugin", "skill", "agent"):
+ return None, [FieldError('kind must be "plugin", "skill" or "agent"', "kind")]
name = str(draft.get("name") or "").strip()
name_is_valid = _is_valid_name(name)
@@ -135,7 +151,9 @@ def validate_draft(draft: dict[str, Any]) -> tuple[dict[str, Any] | None, list[F
value: dict[str, Any] = {"kind": kind, "name": name, "version": version}
- if kind == "skill":
+ if kind == "agent":
+ _validate_agent_draft(draft, value, errors)
+ elif kind == "skill":
title = str(draft.get("title") or "").strip()
description = str(draft.get("description") or "").strip()
raw_skill_md = draft.get("skill_md")
@@ -232,6 +250,46 @@ def validate_draft(draft: dict[str, Any]) -> tuple[dict[str, Any] | None, list[F
return value, []
+def _validate_agent_draft(
+ draft: dict[str, Any], value: dict[str, Any], errors: list[FieldError]
+) -> None:
+ """An agent template submission: the listing fields plus the template.
+
+ The template rules live in ``jarvis/society/agent_template.py`` — the
+ module that builds and installs templates — so the check here is the
+ same judgment the installer will make, not a second copy.
+ """
+ from jarvis.society.agent_template import validate_template
+
+ template = draft.get("agent")
+ listing = {
+ "name": value["name"],
+ "version": value["version"],
+ "description": str(draft.get("description") or "").strip(),
+ }
+ for problem in validate_template(template, listing):
+ # The listing name and version carry their own field errors above.
+ if problem.startswith(("the marketplace name", "the version")):
+ continue
+ field = "description" if "summary" in problem else "agent"
+ errors.append(FieldError(problem, field))
+ title = str(draft.get("title") or "").strip()
+ if not title:
+ errors.append(FieldError("title is required for an agent", "title"))
+ raw_categories = draft.get("categories")
+ categories = (
+ [c for c in raw_categories if isinstance(c, str)][:10]
+ if isinstance(raw_categories, list)
+ else []
+ )
+ value.update(
+ title=title,
+ description=listing["description"],
+ categories=categories,
+ agent=template if isinstance(template, dict) else {},
+ )
+
+
def _validate_bundled_skills(
raw: Any, *, plugin_name: str
) -> tuple[list[dict[str, str]], list[FieldError]]:
@@ -341,6 +399,25 @@ def publish_endpoint() -> str:
return MarketplaceConfig().publish_endpoint
+def registry_repo() -> str:
+ """``owner/name`` of the registry whose issue intake takes submissions."""
+ from jarvis.core.config import load_config
+
+ try:
+ value = str(load_config().marketplace.publish_registry_repo).strip()
+ except Exception: # noqa: BLE001 - config trouble must not kill the view
+ log.warning("publish: could not read config for the registry repo")
+ from jarvis.core.config import MarketplaceConfig
+
+ value = MarketplaceConfig().publish_registry_repo
+ return value if _REPO_RE.fullmatch(value) else ""
+
+
+def publishing_enabled() -> bool:
+ """Whether this install can publish at all (issue intake or an endpoint)."""
+ return bool(publish_endpoint() or registry_repo())
+
+
def make_device_handler() -> DeviceFlowHandler:
"""A device-flow handler for the marketplace GitHub App.
@@ -439,19 +516,23 @@ async def submit(
store: TokenStore | None = None,
transport: httpx.AsyncBaseTransport | None = None,
) -> dict[str, Any]:
- """POST an already-validated submission; returns ``{pr_url, submission_path}``.
+ """Submit an already-validated submission as the signed-in user.
- The token goes as ``Authorization: Bearer`` — the endpoint verifies it
- belongs to the marketplace App and derives the publisher from it, so
- nothing identity-shaped travels in the body.
+ Returns ``{issue_url, issue_number, submission_path}`` on the issue
+ intake, or ``{pr_url, submission_path}`` from a hosted endpoint. Nothing
+ identity-shaped travels in the body: the intake takes the publisher from
+ the issue's author, an endpoint from the token.
"""
endpoint = publish_endpoint()
- if not endpoint:
+ repo = registry_repo()
+ if not endpoint and not repo:
raise SubmitError(503, "publishing is disabled in this deployment")
store = store or TokenStore()
tokens = await asyncio.to_thread(store.load, PUBLISHER_TOKEN_ID)
if tokens is None:
raise SubmitError(401, "sign in with GitHub first")
+ if not endpoint:
+ return await submit_issue(normalized, tokens, repo, transport=transport)
try:
async with httpx.AsyncClient(timeout=_HTTP_TIMEOUT, transport=transport) as client:
r = await client.post(
@@ -475,6 +556,94 @@ async def submit(
raise SubmitError(r.status_code, error, field if isinstance(field, str) else None)
+def issue_title(normalized: dict[str, Any]) -> str:
+ return (
+ f"{INTAKE_TITLE_TAG} {normalized['kind']}: {normalized['name']} "
+ f"{normalized['version']}"
+ )
+
+
+def issue_body(normalized: dict[str, Any]) -> str:
+ """The submission as the registry intake reads it: one fenced JSON block.
+
+ The prose above the block is for people browsing the issue list; the
+ intake reads only the code block.
+ """
+ label = str(normalized.get("title") or normalized["name"])
+ summary = " ".join(str(normalized.get("description") or "").split())
+ lines = [
+ INTAKE_BODY_MARKER,
+ f"**{label}** — {normalized['kind']} `{normalized['name']}` {normalized['version']}",
+ ]
+ if summary:
+ lines += ["", f"> {summary}"]
+ lines += [
+ "",
+ "Published from Personal Jarvis. The automated checks run now; this issue "
+ "closes itself once the entry is live.",
+ "",
+ "### Submission",
+ "",
+ "```json",
+ json.dumps(normalized, indent=2, ensure_ascii=False),
+ "```",
+ "",
+ ]
+ return "\n".join(lines)
+
+
+def issue_form_url(repo: str) -> str:
+ """The browser fallback: the registry's issue form, for a paste by hand."""
+ return f"https://github.com/{repo}/issues/new?template=publish.yml"
+
+
+async def submit_issue(
+ normalized: dict[str, Any],
+ tokens: Tokens,
+ repo: str,
+ *,
+ transport: httpx.AsyncBaseTransport | None = None,
+) -> dict[str, Any]:
+ """Open the intake issue on ``repo`` as the token's user."""
+ body = issue_body(normalized)
+ if len(body) > _MAX_ISSUE_BODY:
+ raise SubmitError(413, "the submission is too large for a GitHub issue — shorten it")
+ try:
+ async with httpx.AsyncClient(timeout=_HTTP_TIMEOUT, transport=transport) as client:
+ r = await client.post(
+ f"{_GITHUB_API}/repos/{repo}/issues",
+ json={"title": issue_title(normalized), "body": body},
+ headers={
+ **_UA,
+ "Authorization": f"Bearer {tokens.access}",
+ "Accept": "application/vnd.github+json",
+ "X-GitHub-Api-Version": "2022-11-28",
+ },
+ )
+ except httpx.HTTPError as exc:
+ raise SubmitError(502, f"GitHub is unreachable: {exc}") from exc
+ if r.status_code == 201:
+ data = r.json()
+ return {
+ "issue_url": data.get("html_url"),
+ "issue_number": data.get("number"),
+ "submission_path": f"submissions/{normalized['name']}.json",
+ }
+ if r.status_code == 401:
+ raise SubmitError(401, "your GitHub sign-in expired — sign in again")
+ # 403/404: the App's user token cannot open issues there (the App lacks
+ # the Issues permission or is not installed on the registry), or issues
+ # are off. GitHub's body stays out of the message (AP-34); the view gets a
+ # sentence and the browser route instead.
+ log.warning("publish: GitHub refused the intake issue (HTTP %s)", r.status_code)
+ raise SubmitError(
+ 502,
+ "GitHub did not accept the submission from the app. Copy it and file it "
+ f"in the browser instead: {issue_form_url(repo)}",
+ "browser_fallback",
+ )
+
+
async def live_status(name: str, version: str, *, force: bool = False) -> dict[str, Any]:
"""Whether ``name`` at ``version`` is in the community index yet.
@@ -486,7 +655,7 @@ async def live_status(name: str, version: str, *, force: bool = False) -> dict[s
index, status = await community_source.get_index(force=force)
live = False
if index is not None:
- entries: list[Any] = [*index.plugins, *index.skills]
+ entries: list[Any] = [*index.plugins, *index.skills, *index.agents]
for entry in entries:
if entry.name == name and (entry.version or "") == version:
live = True
diff --git a/jarvis/society/agent_template.py b/jarvis/society/agent_template.py
new file mode 100644
index 0000000000..e4853b2e0a
--- /dev/null
+++ b/jarvis/society/agent_template.py
@@ -0,0 +1,613 @@
+"""Shareable agent templates: one agent's design, safe to hand to a stranger.
+
+A template is what the Share button on an agent exports and what the
+marketplace installs as a new teammate (``kind: "agent"`` in the community
+registry, docs/marketplace/agent-templates.md). It differs from the
+machine-to-machine ecosystem bundle (``jarvis/mcp/agents/portable.py``) in
+whom it trusts: a bundle moves YOUR team to YOUR other computer, a template
+goes to people you do not know and comes from people you do not know. So
+the field list here is stricter, in both directions:
+
+* **Nothing that names the author's machine** — accounts, providers and
+ models, workspace folders, connected computers, an imported figure file.
+* **Nothing that widens what runs without asking on the installer's
+ machine** — the permission ceiling, the approval mode, always-allow rules,
+ the spending budget, browser attach mode. ``require_approval`` travels,
+ because it can only ADD confirmations.
+* **No secrets and no personal details in the text** — the standing
+ instructions and the summary are scrubbed: credentials, e-mail addresses,
+ phone numbers, home folders, private network addresses and secret URL
+ parameters are replaced by a placeholder, and every replacement is listed
+ so the person sees what was taken out before anything leaves the machine.
+
+The registry re-checks all of it (``scripts/validate.py``, ``validate_agent``)
+— this module is the first line, never the only one. Keep the two field
+lists identical.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import re
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Final
+
+from pydantic import ValidationError
+
+from .companion import CompanionAppearance
+from .roster import AgentRecord, slugify
+
+log = logging.getLogger(__name__)
+
+__all__ = [
+ "MAX_INSTRUCTIONS_BYTES",
+ "MAX_SUMMARY_CHARS",
+ "TEMPLATE_SCHEMA",
+ "Finding",
+ "ShareDraft",
+ "TemplateError",
+ "build_draft",
+ "create_fields",
+ "load_overlay",
+ "public_avatar",
+ "save_overlay",
+ "scrub_text",
+ "submission",
+ "validate_template",
+]
+
+TEMPLATE_SCHEMA: Final[int] = 1
+#: Same caps as the registry (rules.json ``limits``).
+MAX_INSTRUCTIONS_BYTES: Final[int] = 20_000
+MAX_SUMMARY_CHARS: Final[int] = 500
+MAX_TITLE_CHARS: Final[int] = 120
+MAX_CAPABILITIES: Final[int] = 60
+MAX_CATEGORIES: Final[int] = 10
+
+#: The fields a template carries — an allowlist, mirrored by the registry.
+TEMPLATE_KEYS: Final[frozenset[str]] = frozenset(
+ {
+ "schema",
+ "name",
+ "title",
+ "instructions",
+ "tier",
+ "effort",
+ "focus",
+ "grant_mode",
+ "grants",
+ "denies",
+ "skills",
+ "require_approval",
+ "knowledge_scope",
+ "avatar",
+ }
+)
+
+_AGENT_NAME_RE: Final[re.Pattern[str]] = re.compile(r"^[^/\\:@#<>\"'`\x00-\x1f]{1,40}$")
+_LISTING_NAME_RE: Final[re.Pattern[str]] = re.compile(r"^[a-z0-9](?:[a-z0-9.-]{0,62}[a-z0-9])?$")
+_CAPABILITY_RE: Final[re.Pattern[str]] = re.compile(r"^[a-z]+:[A-Za-z0-9_.:-]{1,80}$")
+_SKILL_RE: Final[re.Pattern[str]] = re.compile(r"^[A-Za-z0-9_.-]{1,80}$")
+_EFFORT_RE: Final[re.Pattern[str]] = re.compile(r"^[a-z]{0,16}$")
+_TIERS: Final[tuple[str, ...]] = ("specialist", "orchestrator")
+_GRANT_MODES: Final[tuple[str, ...]] = ("all", "allowlist")
+_SCOPES: Final[tuple[str, ...]] = ("shared", "own")
+
+# The figure recipe: catalog ids and colours. ``model`` (an imported GLB) is a
+# URL served by the author's own app and never travels.
+_AVATAR_ID_RE: Final[re.Pattern[str]] = re.compile(r"^[a-z0-9_-]{1,40}$")
+_HEX_RE: Final[re.Pattern[str]] = re.compile(r"^#[0-9a-fA-F]{6}$")
+_AVATAR_STRINGS: Final[tuple[str, ...]] = (
+ "archetype",
+ "base",
+ "style",
+ "hairStyle",
+ "outfit",
+ "eyewear",
+)
+_COMPANION_KEYS: Final[frozenset[str]] = frozenset(
+ {"shape", "color", "eyes", "enabled", "sizeM", "followDistanceM"}
+)
+
+
+class TemplateError(ValueError):
+ """A template cannot be built or installed; the message is user-facing."""
+
+
+# ---------------------------------------------------------------------------
+# Scrubbing
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True, slots=True)
+class Finding:
+ """One thing taken out of the text, described without repeating it."""
+
+ kind: str
+ field: str
+ hint: str
+
+ def to_dict(self) -> dict[str, str]:
+ return {"kind": self.kind, "field": self.field, "hint": self.hint}
+
+
+# Credential shapes: the registry's SECRET_PATTERNS plus the publish
+# pre-check's (jarvis/marketplace/publish.py), and a generic "key = value".
+_SECRET_RES: Final[tuple[re.Pattern[str], ...]] = (
+ re.compile(r"gh[pousr]_[A-Za-z0-9]{20,}"),
+ re.compile(r"github_pat_[A-Za-z0-9_]{20,}"),
+ re.compile(r"sk-[A-Za-z0-9_-]{20,}"),
+ re.compile(r"xox[baprs]-[A-Za-z0-9-]{10,}"),
+ re.compile(r"AKIA[0-9A-Z]{16}"),
+ re.compile(r"AIza[0-9A-Za-z_-]{30,}"),
+ re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)"),
+ re.compile(r"eyJ[A-Za-z0-9_-]{20,}\.eyJ[A-Za-z0-9_-]{20,}(?:\.[A-Za-z0-9_-]+)?"),
+ re.compile(
+ r"(?i)\b(?:api[_-]?key|secret|password|passwd|token|bearer)\b\s*[:=]\s*[\"']?"
+ r"[^\s\"']{8,}"
+ ),
+)
+_URL_SECRET_RE: Final[re.Pattern[str]] = re.compile(
+ r"(?i)([?&](?:token|key|api_key|apikey|secret|sig|signature|access_token|auth|password)=)"
+ r"[^&\s#)]+"
+)
+_EMAIL_RE: Final[re.Pattern[str]] = re.compile(
+ r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b"
+)
+# Home folders: they name the machine and, nearly always, the person. A path
+# ends before trailing sentence punctuation ("… copies in /home/x/notes.").
+_PATH_TAIL: Final[str] = r"[^\s\"'`)]*[^\s\"'`).,;:!?]"
+_HOME_RE: Final[re.Pattern[str]] = re.compile(
+ r"(?i)(?:\b[A-Za-z]:[\\/]+Users[\\/]+"
+ + _PATH_TAIL
+ + r"|/Users/"
+ + _PATH_TAIL
+ + r"|/home/"
+ + _PATH_TAIL
+ + r")"
+)
+# International numbers only (a leading +): bare digit runs are dates, ids and
+# version numbers far more often than phone numbers.
+_PHONE_RE: Final[re.Pattern[str]] = re.compile(
+ r"(?<![\w+])\+\d{1,3}[\s.-]?\(?\d{1,4}\)?(?:[\s.-]?\d{2,4}){2,4}(?!\w)"
+)
+_PRIVATE_IP_RE: Final[re.Pattern[str]] = re.compile(
+ r"\b(?:10\.\d{1,3}|192\.168|172\.(?:1[6-9]|2\d|3[01]))\.\d{1,3}\.\d{1,3}\b"
+)
+
+#: Example addresses a public template may legitimately show.
+_EXAMPLE_DOMAINS: Final[tuple[str, ...]] = ("example.com", "example.org", "example.net")
+
+
+def _mask(text: str) -> str:
+ """A hint that identifies the match to its author without repeating it."""
+ text = text.strip()
+ if len(text) <= 4:
+ return "…"
+ return f"{text[:2]}…{text[-2:]}"
+
+
+def scrub_text(text: str, field_name: str) -> tuple[str, list[Finding]]:
+ """``text`` with every credential and personal detail replaced, plus the list.
+
+ Order matters: a secret inside a URL or a path is taken out as a secret
+ first, so the finding names the worse of the two.
+ """
+ findings: list[Finding] = []
+
+ def _sub(pattern: re.Pattern[str], kind: str, placeholder: str, value: str) -> str:
+ def _replace(match: re.Match[str]) -> str:
+ found = match.group(0)
+ if kind == "email" and found.lower().split("@", 1)[-1] in _EXAMPLE_DOMAINS:
+ return found
+ findings.append(Finding(kind=kind, field=field_name, hint=_mask(found)))
+ return placeholder
+
+ return pattern.sub(_replace, value)
+
+ out = text
+ for pattern in _SECRET_RES:
+ out = _sub(pattern, "secret", "[secret removed]", out)
+
+ def _url(match: re.Match[str]) -> str:
+ findings.append(Finding(kind="secret", field=field_name, hint=match.group(1)))
+ return f"{match.group(1)}[removed]"
+
+ out = _URL_SECRET_RE.sub(_url, out)
+ out = _sub(_HOME_RE, "path", "[folder]", out)
+ out = _sub(_EMAIL_RE, "email", "[email]", out)
+ out = _sub(_PHONE_RE, "phone", "[phone]", out)
+ out = _sub(_PRIVATE_IP_RE, "address", "[address]", out)
+ return out, findings
+
+
+# ---------------------------------------------------------------------------
+# Building
+# ---------------------------------------------------------------------------
+
+
+def _clean_ids(values: Any, pattern: re.Pattern[str]) -> list[str]:
+ if not isinstance(values, list):
+ return []
+ out: list[str] = []
+ for value in values:
+ if isinstance(value, str) and pattern.fullmatch(value) and value not in out:
+ out.append(value)
+ if len(out) >= MAX_CAPABILITIES:
+ break
+ return out
+
+
+def public_avatar(avatar: Any) -> dict[str, Any]:
+ """The catalog part of a figure recipe; anything else is dropped."""
+ if not isinstance(avatar, dict):
+ return {}
+ out: dict[str, Any] = {}
+ if avatar.get("contract") == 1:
+ out["contract"] = 1
+ for key in _AVATAR_STRINGS:
+ value = avatar.get(key)
+ if isinstance(value, str) and _AVATAR_ID_RE.fullmatch(value):
+ out[key] = value
+ parts = avatar.get("parts")
+ if isinstance(parts, dict):
+ out["parts"] = {
+ k: v
+ for k, v in list(parts.items())[:32]
+ if isinstance(k, str)
+ and _AVATAR_ID_RE.fullmatch(k)
+ and isinstance(v, str)
+ and _AVATAR_ID_RE.fullmatch(v)
+ }
+ palette = avatar.get("palette")
+ if isinstance(palette, dict):
+ out["palette"] = {
+ k: v
+ for k, v in list(palette.items())[:32]
+ if isinstance(k, str)
+ and _AVATAR_ID_RE.fullmatch(k)
+ and isinstance(v, str)
+ and _HEX_RE.fullmatch(v)
+ }
+ inner = avatar.get("inner")
+ if isinstance(inner, str) and _HEX_RE.fullmatch(inner):
+ out["inner"] = inner
+ height = avatar.get("heightM")
+ if isinstance(height, (int, float)) and not isinstance(height, bool) and 0.2 <= height <= 4:
+ out["heightM"] = float(height)
+ companion = avatar.get("companion")
+ if isinstance(companion, dict):
+ kept = {k: v for k, v in companion.items() if k in _COMPANION_KEYS}
+ # The roster validates this namespace strictly; a companion it would
+ # refuse is dropped here, so a template never fails to install over
+ # the colour of a floating shape.
+ try:
+ CompanionAppearance.model_validate(kept)
+ except ValidationError: # silent by design: an unusable companion drops, the look stays
+ kept = {}
+ if kept:
+ out["companion"] = kept
+ return out
+
+
+def _first_paragraph(text: str) -> str:
+ for block in re.split(r"\n\s*\n", text or ""):
+ line = " ".join(block.replace("#", " ").split())
+ if line:
+ return line
+ return ""
+
+
+def _clip(text: str, limit: int) -> str:
+ text = " ".join(text.split())
+ if len(text) <= limit:
+ return text
+ return text[: limit - 1].rstrip() + "…"
+
+
+@dataclass(slots=True)
+class ShareDraft:
+ """Everything the Share sheet shows: the template, its listing, what was cut."""
+
+ template: dict[str, Any]
+ listing: dict[str, Any]
+ findings: list[Finding] = field(default_factory=list)
+ polished_by: str = ""
+ published: dict[str, Any] | None = None
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "template": self.template,
+ "listing": self.listing,
+ "findings": [f.to_dict() for f in self.findings],
+ "polished_by": self.polished_by,
+ "published": self.published,
+ "submission": submission(self.template, self.listing),
+ }
+
+
+def build_draft(agent: AgentRecord, overlay: dict[str, Any] | None = None) -> ShareDraft:
+ """The shareable template for ``agent``, with ``overlay`` edits applied.
+
+ ``overlay`` is what the person or the agent itself wrote for the public
+ version (``summary``, ``instructions``, ``title``, ``categories``,
+ ``listing_name``, ``version``); every text in it is scrubbed exactly like
+ the agent's own fields.
+ """
+ if str(agent.tier) == "lead":
+ raise TemplateError("Jarvis is the lead every install already has — share a teammate")
+ overlay = overlay or {}
+ findings: list[Finding] = []
+
+ raw_instructions = str(overlay.get("instructions") or agent.description or "")
+ instructions, found = scrub_text(raw_instructions, "instructions")
+ findings += found
+ raw_title = str(overlay.get("title") or agent.title or "")
+ title, found = scrub_text(raw_title, "title")
+ findings += found
+ raw_summary = str(
+ overlay.get("summary") or agent.title or _first_paragraph(agent.description) or agent.name
+ )
+ summary, found = scrub_text(raw_summary, "summary")
+ findings += found
+
+ effort = str(agent.effort or "").strip().lower()
+ template: dict[str, Any] = {
+ "schema": TEMPLATE_SCHEMA,
+ "name": agent.name,
+ "title": _clip(title, MAX_TITLE_CHARS),
+ "instructions": _fit_bytes(instructions.strip(), MAX_INSTRUCTIONS_BYTES),
+ "tier": str(agent.tier) if str(agent.tier) in _TIERS else "specialist",
+ "effort": effort if _EFFORT_RE.fullmatch(effort) else "",
+ "focus": _clean_ids(agent.focus, _CAPABILITY_RE),
+ "grant_mode": str(agent.grant_mode) if str(agent.grant_mode) in _GRANT_MODES else "all",
+ "grants": _clean_ids(agent.grants, _CAPABILITY_RE),
+ "denies": _clean_ids(agent.denies, _CAPABILITY_RE),
+ "skills": (_clean_ids(agent.skills, _SKILL_RE) if agent.skills is not None else None),
+ "require_approval": _clean_ids(
+ (agent.approval_rules or {}).get("require_approval", []), _CAPABILITY_RE
+ ),
+ "knowledge_scope": (
+ str(agent.knowledge_scope) if str(agent.knowledge_scope) in _SCOPES else "shared"
+ ),
+ "avatar": public_avatar(agent.avatar),
+ }
+ categories = [
+ _clip(str(c).lower(), 32)
+ for c in (overlay.get("categories") or [])
+ if isinstance(c, str) and c.strip()
+ ][:MAX_CATEGORIES]
+ listing_name = str(overlay.get("listing_name") or slugify(agent.name)).strip().lower()
+ listing = {
+ "name": listing_name,
+ "title": agent.name,
+ "description": _clip(summary, MAX_SUMMARY_CHARS),
+ "categories": categories,
+ "version": str(overlay.get("version") or _next_version(overlay.get("published"))),
+ }
+ published = overlay.get("published") if isinstance(overlay.get("published"), dict) else None
+ # The summary often IS the title, so one address would be listed twice.
+ unique: list[Finding] = []
+ for finding in findings:
+ if all((f.kind, f.hint) != (finding.kind, finding.hint) for f in unique):
+ unique.append(finding)
+ return ShareDraft(
+ template=template,
+ listing=listing,
+ findings=unique,
+ polished_by=str(overlay.get("polished_by") or ""),
+ published=published,
+ )
+
+
+def _fit_bytes(text: str, limit: int) -> str:
+ data = text.encode("utf-8")
+ if len(data) <= limit:
+ return text
+ return data[: limit - 3].decode("utf-8", errors="ignore").rstrip() + "…"
+
+
+def _next_version(published: Any) -> str:
+ """1.0.0 for a first share; the next patch after the last published one."""
+ if isinstance(published, dict):
+ version = str(published.get("version") or "")
+ parts = version.split(".")
+ if len(parts) == 3 and all(p.isdigit() for p in parts):
+ return f"{parts[0]}.{parts[1]}.{int(parts[2]) + 1}"
+ return "1.0.0"
+
+
+def submission(template: dict[str, Any], listing: dict[str, Any]) -> dict[str, Any]:
+ """The registry submission (``kind: "agent"``) for a template + listing.
+
+ ``publisher`` is left out on purpose: the registry takes it from the
+ GitHub account that files the submission, never from the file.
+ """
+ return {
+ "kind": "agent",
+ "name": listing.get("name", ""),
+ "version": listing.get("version", "1.0.0"),
+ "title": listing.get("title", ""),
+ "description": listing.get("description", ""),
+ "categories": list(listing.get("categories") or []),
+ "agent": template,
+ }
+
+
+# ---------------------------------------------------------------------------
+# Validation (the registry's rules, mirrored for instant feedback)
+# ---------------------------------------------------------------------------
+
+
+def validate_template(template: Any, listing: dict[str, Any] | None = None) -> list[str]:
+ """Every problem with a template (and its listing), as sentences."""
+ errors: list[str] = []
+ if not isinstance(template, dict):
+ return ["a template is a JSON object"]
+ for key in template:
+ if key not in TEMPLATE_KEYS:
+ errors.append(f"{key} is not a template field")
+ if template.get("schema") != TEMPLATE_SCHEMA:
+ errors.append(f"schema must be {TEMPLATE_SCHEMA} (this Jarvis reads version 1)")
+ name = template.get("name")
+ if not isinstance(name, str) or not _AGENT_NAME_RE.fullmatch(name.strip() or "/"):
+ errors.append("name must be 1-40 characters without / \\ : @ # < > or quotes")
+ elif name.strip().lower() == "jarvis":
+ errors.append("'Jarvis' is the lead every install already has")
+ title = template.get("title", "")
+ if not isinstance(title, str) or len(title) > MAX_TITLE_CHARS:
+ errors.append(f"title must be at most {MAX_TITLE_CHARS} characters")
+ instructions = template.get("instructions")
+ if not isinstance(instructions, str) or not instructions.strip():
+ errors.append("the instructions are empty — write what this agent does")
+ elif len(instructions.encode("utf-8")) > MAX_INSTRUCTIONS_BYTES:
+ errors.append(f"the instructions are longer than {MAX_INSTRUCTIONS_BYTES} bytes")
+ elif _HOME_RE.search(instructions):
+ errors.append("the instructions name a folder on your machine")
+ if template.get("tier", "specialist") not in _TIERS:
+ errors.append("tier must be specialist or orchestrator")
+ if template.get("grant_mode", "all") not in _GRANT_MODES:
+ errors.append("grant_mode must be all or allowlist")
+ if template.get("knowledge_scope", "shared") not in _SCOPES:
+ errors.append("knowledge_scope must be shared or own")
+ effort = template.get("effort", "")
+ if not isinstance(effort, str) or not _EFFORT_RE.fullmatch(effort):
+ errors.append("effort must be a short lowercase word")
+ for key in ("focus", "grants", "denies", "require_approval"):
+ value = template.get(key, [])
+ if not isinstance(value, list) or not all(
+ isinstance(v, str) and _CAPABILITY_RE.fullmatch(v) for v in value
+ ):
+ errors.append(f"{key} must be a list of capability ids")
+ elif len(value) > MAX_CAPABILITIES:
+ errors.append(f"{key}: at most {MAX_CAPABILITIES} entries")
+ skills = template.get("skills")
+ if skills is not None and (
+ not isinstance(skills, list)
+ or not all(isinstance(v, str) and _SKILL_RE.fullmatch(v) for v in skills)
+ ):
+ errors.append("skills must be a list of skill names or null")
+ avatar = template.get("avatar", {})
+ # The cleaner drops whatever is not a catalog id or a colour, so a recipe
+ # it leaves unchanged is one that carries nothing else.
+ if not isinstance(avatar, dict) or public_avatar(avatar) != avatar:
+ errors.append("avatar may only carry catalog ids and #rrggbb colours")
+ text = json.dumps(template, ensure_ascii=False)
+ if any(p.search(text) for p in _SECRET_RES):
+ errors.append("the template contains something that looks like a credential")
+ if listing is not None:
+ listing_name = str(listing.get("name") or "")
+ if (
+ not _LISTING_NAME_RE.fullmatch(listing_name)
+ or "--" in listing_name
+ or ".." in listing_name
+ ):
+ errors.append(
+ "the marketplace name must be 1-64 characters of a-z 0-9 - . "
+ "(no leading/trailing separators)"
+ )
+ if not re.fullmatch(r"\d+\.\d+\.\d+", str(listing.get("version") or "")):
+ errors.append("the version must look like 1.0.0")
+ description = str(listing.get("description") or "")
+ if not description.strip():
+ errors.append("write a one-line summary for the store card")
+ elif len(description) > MAX_SUMMARY_CHARS:
+ errors.append(f"the summary is longer than {MAX_SUMMARY_CHARS} characters")
+ return errors
+
+
+# ---------------------------------------------------------------------------
+# Installing
+# ---------------------------------------------------------------------------
+
+
+def create_fields(template: dict[str, Any]) -> dict[str, Any]:
+ """Roster fields for a new agent from a VALIDATED template.
+
+ Only design fields: the model is the installer's own choice (the create
+ route inherits their last chat seat), and permissions start at the app's
+ defaults — ``require_approval`` can only add confirmations.
+ """
+ errors = validate_template(template)
+ if errors:
+ raise TemplateError(errors[0])
+ fields: dict[str, Any] = {
+ "name": template["name"].strip(),
+ "title": template.get("title", ""),
+ "description": template["instructions"],
+ "tier": template.get("tier", "specialist"),
+ "grant_mode": template.get("grant_mode", "all"),
+ "focus": list(template.get("focus", [])),
+ "grants": list(template.get("grants", [])),
+ "denies": list(template.get("denies", [])),
+ "approval_rules": {
+ "require_approval": list(template.get("require_approval", [])),
+ "always_allow": [],
+ },
+ }
+ if template.get("effort"):
+ fields["effort"] = template["effort"]
+ if template.get("skills") is not None:
+ fields["skills"] = list(template["skills"])
+ if template.get("avatar"):
+ fields["avatar"] = public_avatar(template["avatar"])
+ return fields
+
+
+# ---------------------------------------------------------------------------
+# The share overlay on disk
+# ---------------------------------------------------------------------------
+
+_OVERLAY_KEYS: Final[frozenset[str]] = frozenset(
+ {
+ "summary",
+ "instructions",
+ "title",
+ "categories",
+ "listing_name",
+ "version",
+ "polished_by",
+ "published",
+ }
+)
+
+
+def _overlay_path(data_dir: Path, agent_id: str) -> Path:
+ return Path(data_dir) / "society" / agent_id / "share-template.json"
+
+
+def load_overlay(data_dir: Path, agent_id: str) -> dict[str, Any]:
+ """The saved public-version edits for an agent; ``{}`` when none."""
+ path = _overlay_path(data_dir, agent_id)
+ try:
+ raw = json.loads(path.read_text(encoding="utf-8"))
+ except FileNotFoundError: # silent by design: no draft yet is the normal first state
+ return {}
+ except (OSError, ValueError):
+ log.warning("society: unreadable share draft at %s — starting fresh", path)
+ return {}
+ return {k: v for k, v in raw.items() if k in _OVERLAY_KEYS} if isinstance(raw, dict) else {}
+
+
+def save_overlay(data_dir: Path, agent_id: str, changes: dict[str, Any]) -> dict[str, Any]:
+ """Merge ``changes`` into the saved overlay (atomic write); returns the result.
+
+ A ``None`` value clears that key, so "back to the agent's own text" is one
+ call.
+ """
+ current = load_overlay(data_dir, agent_id)
+ for key, value in changes.items():
+ if key not in _OVERLAY_KEYS:
+ continue
+ if value is None:
+ current.pop(key, None)
+ else:
+ current[key] = value
+ path = _overlay_path(data_dir, agent_id)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = path.with_suffix(".json.tmp")
+ tmp.write_text(json.dumps(current, ensure_ascii=False, indent=2), encoding="utf-8")
+ tmp.replace(path)
+ return current
diff --git a/jarvis/society/share_tool.py b/jarvis/society/share_tool.py
new file mode 100644
index 0000000000..c4b5553305
--- /dev/null
+++ b/jarvis/society/share_tool.py
@@ -0,0 +1,127 @@
+"""``society_share_template`` — an agent prepares the public version of itself.
+
+The Share sheet on an agent offers "Let <agent> prepare it": that sends the
+agent a chat message asking it to write the shareable version of itself — a
+summary for the store card and standing instructions with everything personal
+taken out. This tool is how the agent hands that back. It writes only the
+local share draft (``agent_template.save_overlay``); nothing leaves the
+machine until the person presses Publish in the sheet, so the tool is
+``safe``.
+
+The agent is never the privacy boundary: whatever it writes is scrubbed by
+the same deterministic pass as the agent's own fields, and the registry
+checks it again.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from typing import Any, Final
+
+from jarvis.core.protocols import ToolResult
+
+from .agent_template import MAX_SUMMARY_CHARS, TemplateError, build_draft, save_overlay
+from .failure_reasons import FailureReason, retry_action
+from .roster import AgentState
+
+log = logging.getLogger(__name__)
+
+__all__ = ["SHARE_TOOL_NAME", "ShareTemplateTool"]
+
+SHARE_TOOL_NAME: Final[str] = "society_share_template"
+_MAX_INSTRUCTIONS_CHARS: Final[int] = 20_000
+
+
+def _failure(reason: FailureReason, detail: str) -> ToolResult:
+ return ToolResult(
+ success=False,
+ output={"reason": str(reason), "retry": str(retry_action(reason))},
+ error=f"{reason}: {detail}",
+ )
+
+
+class ShareTemplateTool:
+ """Save the public version of the calling agent as its share draft."""
+
+ name: str = SHARE_TOOL_NAME
+ risk_tier: str = "safe"
+ description: str = (
+ "Prepare the shareable template of YOURSELF for the Personal Jarvis marketplace. "
+ "Call it when the user asks you to create, prepare or improve your template. "
+ "Write 'summary': one or two plain sentences a stranger reads on the store card "
+ "(what you do, for whom). Write 'instructions': your standing instructions "
+ "rewritten for anyone — keep the working method, drop everything personal (names, "
+ "e-mail addresses, companies, folders, accounts, private projects) and every "
+ "credential; use neutral words like 'the user' or '[your company]'. Optional: "
+ "'title' (your job line), 'categories' (up to 5 short tags). Call it without "
+ "arguments to read your current draft. It saves a local draft only — the user "
+ "reviews it and publishes it themselves. Afterwards tell the user in one sentence "
+ "that the draft is ready in the Share window."
+ )
+ schema: dict[str, Any] = {
+ "type": "object",
+ "properties": {
+ "summary": {
+ "type": "string",
+ "description": f"Store-card summary, at most {MAX_SUMMARY_CHARS} characters.",
+ },
+ "instructions": {
+ "type": "string",
+ "description": "Standing instructions for anyone, with nothing personal in them.",
+ },
+ "title": {"type": "string", "description": "Your job line, short."},
+ "categories": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": "Up to 5 short lowercase tags, e.g. ['email', 'productivity'].",
+ },
+ },
+ "required": [],
+ }
+
+ def __init__(self, runtime: Any, agent_id: str) -> None:
+ self._runtime = runtime
+ self._agent_id = agent_id
+
+ async def execute(self, args: dict[str, Any], ctx: Any) -> ToolResult:
+ rt = self._runtime
+ agent = await rt.roster.get(self._agent_id)
+ if agent is None or agent.state is not AgentState.ACTIVE:
+ return _failure(FailureReason.BLOCKED_BY_POLICY, "caller is not an active agent")
+ changes: dict[str, Any] = {}
+ for key, limit in (
+ ("summary", MAX_SUMMARY_CHARS),
+ ("instructions", _MAX_INSTRUCTIONS_CHARS),
+ ("title", 120),
+ ):
+ value = args.get(key)
+ if isinstance(value, str) and value.strip():
+ changes[key] = value.strip()[:limit]
+ categories = args.get("categories")
+ if isinstance(categories, list):
+ changes["categories"] = [
+ str(c).strip().lower()[:32] for c in categories if str(c).strip()
+ ][:5]
+ try:
+ if changes:
+ changes["polished_by"] = agent.name
+ overlay = save_overlay(rt.data_dir, agent.agent_id, changes)
+ else:
+ from .agent_template import load_overlay
+
+ overlay = load_overlay(rt.data_dir, agent.agent_id)
+ draft = build_draft(agent, overlay)
+ except TemplateError as exc: # not silent: returned to the agent as a typed refusal
+ return _failure(FailureReason.BLOCKED_BY_POLICY, str(exc))
+ except OSError as exc:
+ log.warning("society: share draft for %s not saved", agent.agent_id, exc_info=True)
+ return _failure(FailureReason.INTERNAL_ERROR, f"the draft could not be saved: {exc}")
+ output = {
+ "saved": bool(changes),
+ "summary": draft.listing["description"],
+ "removed": [f.to_dict() for f in draft.findings],
+ "template": json.dumps(draft.template, ensure_ascii=False, indent=2),
+ "note": "Draft saved locally. The user publishes it from the Share window.",
+ }
+ return ToolResult(success=True, output=output)
diff --git a/jarvis/society/surface.py b/jarvis/society/surface.py
index 1ed39ab8ae..40abe8521e 100644
--- a/jarvis/society/surface.py
+++ b/jarvis/society/surface.py
@@ -50,6 +50,7 @@ from .memory import resolve_society_vault
from .roster import PAIR_SESSION_MARKER, AgentRecord, canonical_session_id
from .routine_runner import is_routine_session
from .runtime import current_runtime
+from .share_tool import ShareTemplateTool
log = logging.getLogger(__name__)
@@ -374,6 +375,7 @@ def society_tools(cfg: Any, brain: Any, session: Any) -> dict[str, Tool]:
ConversationRecallTool.name: cast(Tool, ConversationRecallTool(rt, agent_id)),
RoutineListTool.name: cast(Tool, RoutineListTool(rt, agent_id)),
RoutineInvokeTool.name: cast(Tool, RoutineInvokeTool(rt, agent_id)),
+ ShareTemplateTool.name: cast(Tool, ShareTemplateTool(rt, agent_id)),
ProposeChangeTool.name: cast(
Tool,
ProposeChangeTool(
diff --git a/jarvis/ui/web/frontend/src/components/marketplace/PublishStudio.test.tsx b/jarvis/ui/web/frontend/src/components/marketplace/PublishStudio.test.tsx
index be0f6d7902..5798fe3860 100644
--- a/jarvis/ui/web/frontend/src/components/marketplace/PublishStudio.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/marketplace/PublishStudio.test.tsx
@@ -130,7 +130,7 @@ describe("PublishStudio", () => {
fireEvent.click(screen.getByTestId("studio-publish"));
const done = await screen.findByTestId("studio-published");
expect(done.textContent).toContain("three-point-check");
- expect(done.textContent).toContain("View the pull request");
+ expect(done.textContent).toContain("View the submission");
});
it("puts a field error where the field is", async () => {
diff --git a/jarvis/ui/web/frontend/src/components/marketplace/PublishStudio.tsx b/jarvis/ui/web/frontend/src/components/marketplace/PublishStudio.tsx
index 7b95b8043f..2cce02f0fa 100644
--- a/jarvis/ui/web/frontend/src/components/marketplace/PublishStudio.tsx
+++ b/jarvis/ui/web/frontend/src/components/marketplace/PublishStudio.tsx
@@ -76,6 +76,8 @@ interface SubmitResultWire {
name: string;
version: string;
pr_url?: string | null;
+ /** The intake issue the submission was filed as (the default, server-less path). */
+ issue_url?: string | null;
submission_path?: string | null;
/** The three commands other people will run to install this — computed
* server-side by install_standard.py, never derived here. */
@@ -1579,11 +1581,11 @@ function PublishedCard({
{t("marketplace.studio_done_body")}
</p>
<div className="mt-4 flex flex-wrap items-center gap-2">
- {result.pr_url && (
+ {(result.issue_url ?? result.pr_url) && (
<Button
size="sm"
variant="outline"
- onClick={() => openExternalUrl(result.pr_url ?? "")}
+ onClick={() => openExternalUrl(result.issue_url ?? result.pr_url ?? "")}
>
<ExternalLink className="mr-1.5 h-3.5 w-3.5" />
{t("marketplace.studio_done_view_pr")}
diff --git a/jarvis/ui/web/frontend/src/components/society/card/OptionsRail.tsx b/jarvis/ui/web/frontend/src/components/society/card/OptionsRail.tsx
index deb66896f0..95d24056be 100644
--- a/jarvis/ui/web/frontend/src/components/society/card/OptionsRail.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/card/OptionsRail.tsx
@@ -6,7 +6,7 @@
* what you can do to the agent.
*/
import { lazy, Suspense, useEffect, useRef, useState } from "react";
-import { MoreHorizontal } from "lucide-react";
+import { MoreHorizontal, Share2 } from "lucide-react";
import { useT } from "@/i18n";
@@ -16,6 +16,7 @@ import { AgentRoutinesList } from "./AgentRoutinesList";
import { JarvisHistoryRail } from "../chat/JarvisHistoryRail";
import { RetireButton } from "./RetireButton";
const AgentAppearanceDialog = lazy(() => import("../companion/AgentAppearanceDialog").then(m => ({ default: m.AgentAppearanceDialog })));
+const ShareAgentDialog = lazy(() => import("./ShareAgentDialog").then(m => ({ default: m.ShareAgentDialog })));
export interface OptionsRailProps {
agent: SocietyAgent;
@@ -28,12 +29,14 @@ export function OptionsRail({ agent, onRetired, sample = false }: OptionsRailPro
const t = useT();
const [more, setMore] = useState(false);
const [appearanceOpen, setAppearanceOpen] = useState(false);
+ const [shareOpen, setShareOpen] = useState(false);
const [routineOpen, setRoutineOpen] = useState(false);
const moreRef = useRef<HTMLDivElement>(null);
useEffect(() => {
setMore(false);
setAppearanceOpen(false);
+ setShareOpen(false);
}, [agent.agentId]);
useEffect(() => {
@@ -85,7 +88,16 @@ export function OptionsRail({ agent, onRetired, sample = false }: OptionsRailPro
</div>
</header>
<div className="flex min-h-0 flex-1 flex-col gap-3 overflow-hidden px-3 pb-3 pt-2">
- <button type="button" onClick={() => setAppearanceOpen(true)} data-testid="edit-agent-appearance" className="shrink-0 rounded-lg border border-border px-3 py-2 text-left text-sm font-medium text-foreground hover:bg-secondary">{t("society.companion.appearance")}</button>
+ <div className="flex shrink-0 gap-2">
+ <button type="button" onClick={() => setAppearanceOpen(true)} data-testid="edit-agent-appearance" className="min-w-0 flex-1 rounded-lg border border-border px-3 py-2 text-left text-sm font-medium text-foreground hover:bg-secondary">{t("society.companion.appearance")}</button>
+ {/* The lead is every install's own Jarvis and sample rows are not real agents: neither is shareable. */}
+ {agent.tier !== "lead" && !sample && (
+ <button type="button" onClick={() => setShareOpen(true)} data-testid="share-agent" title={t("society.share.cta_hint")} className="flex shrink-0 items-center gap-1.5 rounded-lg border border-border px-3 py-2 text-sm font-medium text-foreground hover:bg-secondary">
+ <Share2 className="h-3.5 w-3.5 text-muted-foreground" aria-hidden />
+ {t("society.share.cta")}
+ </button>
+ )}
+ </div>
<div className={routineOpen ? "hidden" : "contents"}>
<AgentBrowserPreview agent={agent} />
{agent.tier === "lead" ? <JarvisHistoryRail /> : null}
@@ -100,6 +112,7 @@ export function OptionsRail({ agent, onRetired, sample = false }: OptionsRailPro
/>
</div>
{appearanceOpen && <Suspense fallback={null}><AgentAppearanceDialog key={agent.agentId} agent={agent} sample={sample} onClose={() => setAppearanceOpen(false)} /></Suspense>}
+ {shareOpen && <Suspense fallback={null}><ShareAgentDialog key={agent.agentId} agent={agent} onClose={() => setShareOpen(false)} /></Suspense>}
</aside>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/society/card/ShareAgentDialog.test.tsx b/jarvis/ui/web/frontend/src/components/society/card/ShareAgentDialog.test.tsx
new file mode 100644
index 0000000000..888f491e24
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/card/ShareAgentDialog.test.tsx
@@ -0,0 +1,186 @@
+/**
+ * The Share sheet: the template as the server built it, what was taken out,
+ * the edit loop, and publishing under the signed-in GitHub name.
+ *
+ * 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 { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@/lib/openExternal", () => ({ openExternalUrl: vi.fn() }));
+// The chat column's store: sending is observed, never run.
+const send = vi.fn(async () => "sent" as const);
+vi.mock("../chat/AgentChatPanel", () => {
+ const state = { activeSessionId: "society:release-scribe", send: (...args: unknown[]) => send(...(args as [])) };
+ return { useSocietyChatStore: (selector: (s: typeof state) => unknown) => selector(state) };
+});
+// Shiki is not what is under test; the plain code text is.
+vi.mock("@/components/docs/CodeBlock", () => ({
+ CodeBlock: ({ code }: { code: string }) => <pre data-testid="code">{code}</pre>,
+}));
+
+import { ShareAgentDialog } from "@/components/society/card/ShareAgentDialog";
+import type { SocietyAgent } from "@/components/society/data";
+import type { ShareDraftWire } from "@/lib/agentShare";
+
+const AGENT = {
+ agentId: "release-scribe",
+ name: "Release Scribe",
+ title: "Writes the release notes",
+ tier: "specialist",
+ figure: null,
+ palette: { primary: "#2f6f4f", secondary: "#8a5a3b", accent: "#ffd166" },
+ chatSessionId: "society:release-scribe",
+} as unknown as SocietyAgent;
+
+function draft(over: Partial<ShareDraftWire> = {}): ShareDraftWire {
+ const template = {
+ schema: 1 as const,
+ name: "Release Scribe",
+ title: "Writes the release notes",
+ instructions: "Collect merged pull requests and write release notes. Mail drafts to [email].",
+ tier: "specialist" as const,
+ effort: "",
+ focus: ["plugin:github"],
+ grant_mode: "all" as const,
+ grants: [],
+ denies: [],
+ skills: null,
+ require_approval: [],
+ knowledge_scope: "shared" as const,
+ avatar: {},
+ };
+ const listing = {
+ name: "release-scribe",
+ title: "Release Scribe",
+ description: "Writes the release notes",
+ categories: [],
+ version: "1.0.0",
+ };
+ return {
+ template,
+ listing,
+ findings: [{ kind: "email", field: "instructions", hint: "me…ev" }],
+ polished_by: "",
+ published: null,
+ submission: { kind: "agent", name: listing.name, version: listing.version, agent: template },
+ errors: [],
+ ...over,
+ };
+}
+
+let identity: Record<string, unknown> = { enabled: true, signed_in: false };
+let current = draft();
+
+function installFetchMock() {
+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ const method = init?.method ?? "GET";
+ const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }) as Response;
+ if (url === "/api/society/agents/release-scribe/template" && method === "GET") return ok(current);
+ if (url === "/api/society/agents/release-scribe/template" && method === "PUT") {
+ const edits = JSON.parse(String(init?.body)) as { summary?: string };
+ current = draft({ listing: { ...current.listing, description: edits.summary ?? "" } });
+ return ok(current);
+ }
+ if (url === "/api/society/agents/release-scribe/template/publish" && method === "POST") {
+ return ok({
+ ok: true,
+ name: "release-scribe",
+ version: "1.0.0",
+ issue_url: "https://github.com/PersonalJarvis/marketplace/issues/7",
+ install: { cli: "jarvis marketplace install release-scribe", runner: "", prompt: "" },
+ });
+ }
+ if (url === "/api/marketplace/publish/identity") return ok(identity);
+ if (url.startsWith("/api/marketplace/publish/status")) return ok({ live: false });
+ throw new Error(`unexpected fetch: ${method} ${url}`);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ return fetchMock;
+}
+
+function mount() {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ return render(
+ <QueryClientProvider client={client}>
+ <ShareAgentDialog agent={AGENT} onClose={() => undefined} />
+ </QueryClientProvider>,
+ );
+}
+
+beforeEach(() => {
+ current = draft();
+ identity = { enabled: true, signed_in: false };
+ send.mockClear();
+});
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+describe("ShareAgentDialog", () => {
+ it("shows the template the server built and what was taken out", async () => {
+ installFetchMock();
+ mount();
+ const code = await screen.findByTestId("code");
+ expect(code.textContent).toContain('"kind": "agent"');
+ expect(code.textContent).toContain("[email]");
+ const privacy = screen.getByTestId("share-privacy");
+ expect(privacy.textContent).toMatch(/1 private details removed/);
+ expect(privacy.textContent).toContain("me…ev");
+ expect(privacy.textContent).toMatch(/Never shared/);
+ });
+
+ it("saves an edited summary and shows the server's answer", async () => {
+ const fetchMock = installFetchMock();
+ mount();
+ const summary = (await screen.findByTestId("share-summary")) as HTMLTextAreaElement;
+ fireEvent.change(summary, { target: { value: "Turns merged PRs into notes." } });
+ await waitFor(
+ () =>
+ expect(
+ fetchMock.mock.calls.some(([, init]) => (init as RequestInit | undefined)?.method === "PUT"),
+ ).toBe(true),
+ { timeout: 2000 },
+ );
+ });
+
+ it("asks for GitHub sign-in before publishing", async () => {
+ installFetchMock();
+ mount();
+ expect(await screen.findByTestId("share-sign-in")).toBeTruthy();
+ expect(screen.queryByTestId("share-publish")).toBeNull();
+ });
+
+ it("publishes as the signed-in user and shows the install line", async () => {
+ identity = { enabled: true, signed_in: true, login: "octocat" };
+ installFetchMock();
+ mount();
+ fireEvent.click(await screen.findByTestId("share-publish"));
+ const done = await screen.findByTestId("share-published");
+ expect(done.textContent).toContain("release-scribe 1.0.0 submitted");
+ expect(done.textContent).toContain("jarvis marketplace install release-scribe");
+ });
+
+ it("lets the agent prepare its own public version through its chat", async () => {
+ installFetchMock();
+ mount();
+ fireEvent.click(await screen.findByTestId("share-polish"));
+ await waitFor(() => expect(send).toHaveBeenCalledTimes(1));
+ const calls = send.mock.calls as unknown as string[][];
+ expect(calls[0][0]).toContain("society_share_template");
+ });
+
+ it("blocks publishing while the template has a problem", async () => {
+ identity = { enabled: true, signed_in: true, login: "octocat" };
+ current = draft({ errors: ["write a one-line summary for the store card"] });
+ installFetchMock();
+ mount();
+ const publish = (await screen.findByTestId("share-publish")) as HTMLButtonElement;
+ expect(publish.disabled).toBe(true);
+ expect(screen.getByText(/write a one-line summary/)).toBeTruthy();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/society/card/ShareAgentDialog.tsx b/jarvis/ui/web/frontend/src/components/society/card/ShareAgentDialog.tsx
new file mode 100644
index 0000000000..ae9f74a968
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/society/card/ShareAgentDialog.tsx
@@ -0,0 +1,583 @@
+/**
+ * Share an agent: its design as a template others can install.
+ *
+ * Left: the public version — the store-card summary, the marketplace name and
+ * version, and the privacy check (what was taken out, what never travels).
+ * Right: the template itself as a code block, ready to copy or export. Bottom:
+ * publish to the marketplace under the person's GitHub name.
+ *
+ * The server builds the template (jarvis/society/agent_template.py); every
+ * edit here is saved and the code block shows the server's answer, so what
+ * the person reads is byte for byte what Publish files. "Let <agent> prepare
+ * it" sends the agent a chat message; the agent writes its own public version
+ * with the society_share_template tool and this sheet picks it up.
+ */
+import { lazy, Suspense, useEffect, useMemo, useRef, useState } from "react";
+import * as Dialog from "@radix-ui/react-dialog";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import {
+ AlertTriangle,
+ Check,
+ Copy,
+ Download,
+ ExternalLink,
+ FileJson,
+ Github,
+ Loader2,
+ Lock,
+ ShieldCheck,
+ Sparkles,
+ UploadCloud,
+ X,
+} from "lucide-react";
+
+import { Button } from "@/components/ui/button";
+import {
+ GithubSignInDialog,
+ PublisherAvatar,
+ usePublishIdentity,
+} from "@/components/marketplace/PublishIdentity";
+import { fill, useLocaleChunk, useT } from "@/i18n";
+import {
+ MARKETPLACE_ISSUE_FORM_URL,
+ ShareError,
+ downloadTemplate,
+ fetchLiveStatus,
+ fetchShareDraft,
+ publishShareDraft,
+ saveShareDraft,
+ shareDraftKey,
+ templateFileName,
+ type PublishShareResult,
+ type ShareDraftEdits,
+ type ShareDraftWire,
+ type ShareFinding,
+} from "@/lib/agentShare";
+import { robustCopy } from "@/lib/clipboard";
+import { openExternalUrl } from "@/lib/openExternal";
+import { cn } from "@/lib/utils";
+
+import { AgentSwatch } from "../AgentSwatch";
+import { useSocietyChatStore } from "../chat/AgentChatPanel";
+import type { SocietyAgent } from "../data";
+
+const CodeBlock = lazy(() =>
+ import("@/components/docs/CodeBlock").then((m) => ({ default: m.CodeBlock })),
+);
+
+/** How long the sheet waits for the agent to write its public version. */
+const POLISH_TIMEOUT_MS = 4 * 60 * 1000;
+const SAVE_DEBOUNCE_MS = 600;
+
+interface FormState {
+ summary: string;
+ listingName: string;
+ version: string;
+ categories: string;
+}
+
+function formFrom(draft: ShareDraftWire): FormState {
+ return {
+ summary: draft.listing.description,
+ listingName: draft.listing.name,
+ version: draft.listing.version,
+ categories: draft.listing.categories.join(", "),
+ };
+}
+
+function editsFrom(form: FormState): ShareDraftEdits {
+ return {
+ summary: form.summary,
+ listing_name: form.listingName.trim().toLowerCase(),
+ version: form.version.trim(),
+ categories: form.categories
+ .split(",")
+ .map((c) => c.trim().toLowerCase())
+ .filter(Boolean)
+ .slice(0, 10),
+ };
+}
+
+export function ShareAgentDialog({ agent, onClose }: { agent: SocietyAgent; onClose: () => void }) {
+ const t = useT();
+ useLocaleChunk("society");
+ useLocaleChunk("marketplace");
+ const client = useQueryClient();
+ const key = shareDraftKey(agent.agentId);
+ const [waitingSince, setWaitingSince] = useState<number | null>(null);
+ const draftQuery = useQuery({
+ queryKey: key,
+ queryFn: () => fetchShareDraft(agent.agentId),
+ // While the agent writes its public version, look for it every few seconds.
+ refetchInterval: waitingSince !== null ? 2500 : false,
+ });
+ const draft = draftQuery.data;
+ const [form, setForm] = useState<FormState | null>(null);
+ const dirty = useRef(false);
+ const polishedBefore = useRef<string | null>(null);
+
+ // The form follows the server until the person starts typing.
+ useEffect(() => {
+ if (draft && (!dirty.current || form === null)) setForm(formFrom(draft));
+ }, [draft]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ const save = useMutation({
+ mutationFn: (edits: ShareDraftEdits) => saveShareDraft(agent.agentId, edits),
+ onSuccess: (fresh) => {
+ dirty.current = false;
+ client.setQueryData(key, fresh);
+ },
+ });
+
+ // Debounced save: the code block always shows what the server built.
+ useEffect(() => {
+ if (!form || !dirty.current) return;
+ const timer = window.setTimeout(() => save.mutate(editsFrom(form)), SAVE_DEBOUNCE_MS);
+ return () => window.clearTimeout(timer);
+ }, [form]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ // The agent finished its public version (or gave up): stop waiting.
+ useEffect(() => {
+ if (waitingSince === null || !draft) return;
+ const signature = `${draft.polished_by}|${draft.listing.description}|${draft.template.instructions.length}`;
+ if (polishedBefore.current !== null && signature !== polishedBefore.current) {
+ dirty.current = false;
+ setForm(formFrom(draft));
+ setWaitingSince(null);
+ } else if (Date.now() - waitingSince > POLISH_TIMEOUT_MS) {
+ setWaitingSince(null);
+ }
+ }, [draft, waitingSince]);
+
+ const edit = (patch: Partial<FormState>) => {
+ dirty.current = true;
+ setForm((current) => (current ? { ...current, ...patch } : current));
+ };
+
+ const json = useMemo(
+ () => (draft ? JSON.stringify(draft.submission, null, 2) : ""),
+ [draft],
+ );
+
+ return (
+ <Dialog.Root open onOpenChange={(open) => (open ? undefined : onClose())}>
+ <Dialog.Portal>
+ <Dialog.Overlay className="fixed inset-0 z-50 bg-scrim/60 backdrop-blur-sm" />
+ <Dialog.Content
+ data-testid="share-agent-dialog"
+ className="fixed left-1/2 top-1/2 z-50 flex max-h-[92dvh] w-[min(1040px,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 focus:outline-none"
+ >
+ <header className="flex shrink-0 items-center gap-3 border-b border-border px-5 py-4">
+ <AgentSwatch agent={agent} size={40} />
+ <div className="min-w-0 flex-1">
+ <Dialog.Title className="truncate font-display text-base font-semibold tracking-tight">
+ {fill(t("society.share.title"), { agent: agent.name })}
+ </Dialog.Title>
+ <Dialog.Description className="text-xs text-muted-foreground">
+ {t("society.share.subtitle")}
+ </Dialog.Description>
+ </div>
+ <button
+ type="button"
+ aria-label={t("society.card.close")}
+ onClick={onClose}
+ className="rounded-md p-2 text-muted-foreground hover:bg-secondary hover:text-foreground"
+ >
+ <X className="h-4 w-4" />
+ </button>
+ </header>
+
+ {draftQuery.isLoading && (
+ <p className="flex items-center gap-2 px-5 py-10 text-sm text-muted-foreground">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ {t("society.share.loading")}
+ </p>
+ )}
+ {draftQuery.error && (
+ <p role="alert" className="flex items-center gap-2 px-5 py-10 text-sm text-destructive">
+ <AlertTriangle className="h-4 w-4 shrink-0" />
+ {(draftQuery.error as Error).message}
+ </p>
+ )}
+
+ {draft && form && (
+ <>
+ <div className="grid min-h-0 flex-1 overflow-y-auto md:grid-cols-[minmax(0,1fr)_minmax(0,1.15fr)] md:overflow-hidden">
+ <section className="min-h-0 space-y-5 px-5 py-4 md:overflow-y-auto" aria-label={t("society.share.public_version")}>
+ <PolishBar
+ agent={agent}
+ draft={draft}
+ waiting={waitingSince !== null}
+ onSent={() => {
+ polishedBefore.current = `${draft.polished_by}|${draft.listing.description}|${draft.template.instructions.length}`;
+ setWaitingSince(Date.now());
+ }}
+ onReset={() => {
+ dirty.current = false;
+ save.mutate({ reset: true });
+ }}
+ />
+
+ <label className="block">
+ <span className="mb-1 flex items-baseline justify-between text-xs font-medium text-foreground">
+ {t("society.share.summary")}
+ <span className="tabular-nums text-muted-foreground">{form.summary.length}/500</span>
+ </span>
+ <textarea
+ value={form.summary}
+ maxLength={500}
+ rows={3}
+ onChange={(e) => edit({ summary: e.target.value })}
+ placeholder={t("society.share.summary_placeholder")}
+ data-testid="share-summary"
+ className="w-full resize-none rounded-md border border-border bg-background px-3 py-2 text-sm text-foreground outline-none placeholder:text-faint-foreground focus:border-border-strong"
+ />
+ </label>
+
+ <div className="grid grid-cols-[minmax(0,1fr)_7rem] gap-3">
+ <label className="block min-w-0">
+ <span className="mb-1 block text-xs font-medium text-foreground">{t("society.share.listing_name")}</span>
+ <input
+ value={form.listingName}
+ onChange={(e) => edit({ listingName: e.target.value })}
+ spellCheck={false}
+ className="h-9 w-full rounded-md border border-border bg-background px-3 font-mono text-xs text-foreground outline-none focus:border-border-strong"
+ />
+ </label>
+ <label className="block">
+ <span className="mb-1 block text-xs font-medium text-foreground">{t("society.share.version")}</span>
+ <input
+ value={form.version}
+ onChange={(e) => edit({ version: e.target.value })}
+ spellCheck={false}
+ className="h-9 w-full rounded-md border border-border bg-background px-3 font-mono text-xs tabular-nums text-foreground outline-none focus:border-border-strong"
+ />
+ </label>
+ </div>
+
+ <label className="block">
+ <span className="mb-1 block text-xs font-medium text-foreground">{t("society.share.categories")}</span>
+ <input
+ value={form.categories}
+ onChange={(e) => edit({ categories: e.target.value })}
+ placeholder={t("society.share.categories_placeholder")}
+ className="h-9 w-full rounded-md border border-border bg-background px-3 text-sm text-foreground outline-none placeholder:text-faint-foreground focus:border-border-strong"
+ />
+ </label>
+
+ <PrivacyCheck findings={draft.findings} />
+ </section>
+
+ <section className="flex min-h-[18rem] flex-col border-t border-border bg-background/40 px-5 py-4 md:min-h-0 md:border-l md:border-t-0" aria-label={t("society.share.template")}>
+ <TemplateCode
+ fileName={templateFileName(draft.listing)}
+ json={json}
+ saving={save.isPending}
+ />
+ </section>
+ </div>
+
+ <PublishBar agentId={agent.agentId} draft={draft} json={json} saving={save.isPending || dirty.current} />
+ </>
+ )}
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog.Root>
+ );
+}
+
+/** "Let <agent> prepare it": the agent writes its own public version. */
+function PolishBar({
+ agent,
+ draft,
+ waiting,
+ onSent,
+ onReset,
+}: {
+ agent: SocietyAgent;
+ draft: ShareDraftWire;
+ waiting: boolean;
+ onSent: () => void;
+ onReset: () => void;
+}) {
+ const t = useT();
+ // The card's chat column runs on the society store; the message lands in
+ // the conversation the person sees right beside this sheet.
+ const activeSessionId = useSocietyChatStore((s) => s.activeSessionId);
+ const send = useSocietyChatStore((s) => s.send);
+ const [error, setError] = useState<string | null>(null);
+ const chatReady = Boolean(agent.chatSessionId) && activeSessionId === agent.chatSessionId;
+
+ const ask = async () => {
+ setError(null);
+ const result = await send(t("society.share.polish_prompt"));
+ if (result === "failed" || result === "stale") setError(t("society.share.polish_failed"));
+ else onSent();
+ };
+
+ return (
+ <div className="rounded-lg border border-border bg-card px-3 py-3">
+ <div className="flex items-start gap-3">
+ <Sparkles className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
+ <div className="min-w-0 flex-1">
+ <p className="text-sm font-medium text-foreground">
+ {draft.polished_by
+ ? fill(t("society.share.polished_by"), { agent: draft.polished_by })
+ : fill(t("society.share.polish_title"), { agent: agent.name })}
+ </p>
+ <p className="mt-0.5 text-xs leading-relaxed text-muted-foreground">
+ {waiting
+ ? fill(t("society.share.polish_waiting"), { agent: agent.name })
+ : chatReady
+ ? fill(t("society.share.polish_hint"), { agent: agent.name })
+ : t("society.share.polish_unavailable")}
+ </p>
+ {error && <p role="alert" className="mt-1 text-xs text-destructive">{error}</p>}
+ </div>
+ <div className="flex shrink-0 flex-col items-end gap-1">
+ <Button size="sm" variant="outline" onClick={() => void ask()} disabled={!chatReady || waiting} data-testid="share-polish">
+ {waiting ? <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" /> : <Sparkles className="mr-1.5 h-3.5 w-3.5" />}
+ {fill(t("society.share.polish_cta"), { agent: agent.name })}
+ </Button>
+ {draft.polished_by && !waiting && (
+ <button type="button" onClick={onReset} className="text-micro text-muted-foreground underline-offset-2 hover:text-foreground hover:underline">
+ {t("society.share.reset")}
+ </button>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+const FINDING_ORDER: ShareFinding["kind"][] = ["secret", "email", "phone", "path", "address"];
+
+/** What was taken out, and what never travels at all. */
+function PrivacyCheck({ findings }: { findings: ShareFinding[] }) {
+ const t = useT();
+ const sorted = [...findings].sort(
+ (a, b) => FINDING_ORDER.indexOf(a.kind) - FINDING_ORDER.indexOf(b.kind),
+ );
+ return (
+ <div className="space-y-3" data-testid="share-privacy">
+ <div className="rounded-lg border border-border bg-card px-3 py-3">
+ <p className="flex items-center gap-2 text-sm font-medium text-foreground">
+ <ShieldCheck className="h-4 w-4 text-muted-foreground" />
+ {sorted.length === 0
+ ? t("society.share.privacy_clean")
+ : fill(t("society.share.privacy_removed"), { count: sorted.length })}
+ </p>
+ {sorted.length === 0 ? (
+ <p className="mt-1 text-xs leading-relaxed text-muted-foreground">{t("society.share.privacy_clean_hint")}</p>
+ ) : (
+ <ul className="mt-2 space-y-1">
+ {sorted.map((finding, index) => (
+ <li key={`${finding.kind}-${finding.hint}-${index}`} className="flex items-baseline gap-2 text-xs text-muted-foreground">
+ <span className="shrink-0 rounded bg-secondary px-1.5 py-0.5 text-micro font-medium text-foreground">
+ {t(`society.share.finding_${finding.kind}`)}
+ </span>
+ <span className="min-w-0 truncate">
+ {fill(t("society.share.finding_where"), {
+ hint: finding.hint,
+ field: t(`society.share.field_${finding.field}`),
+ })}
+ </span>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ <div className="rounded-lg bg-secondary px-3 py-2.5">
+ <p className="flex items-center gap-2 text-xs font-medium text-foreground">
+ <Lock className="h-3.5 w-3.5 text-muted-foreground" />
+ {t("society.share.never_title")}
+ </p>
+ <p className="mt-1 text-xs leading-relaxed text-muted-foreground">{t("society.share.never_body")}</p>
+ </div>
+ </div>
+ );
+}
+
+/** The template as the code block people copy, export, or read before publishing. */
+function TemplateCode({ fileName, json, saving }: { fileName: string; json: string; saving: boolean }) {
+ const t = useT();
+ const [copied, setCopied] = useState(false);
+ const copy = () =>
+ void robustCopy(json).then((ok) => {
+ if (!ok) return;
+ setCopied(true);
+ window.setTimeout(() => setCopied(false), 1500);
+ });
+ return (
+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden rounded-lg border border-border bg-muted/40" data-testid="share-template-code">
+ <div className="flex shrink-0 items-center gap-2 border-b border-border/60 bg-muted/30 px-3 py-1.5">
+ <FileJson className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
+ <span className="min-w-0 flex-1 truncate font-mono text-xs text-foreground">{fileName}</span>
+ {saving && <Loader2 className="h-3 w-3 animate-spin text-muted-foreground" aria-label={t("society.card.saving")} />}
+ <button type="button" onClick={copy} className="flex items-center gap-1 rounded px-1.5 py-1 text-micro text-muted-foreground hover:bg-muted hover:text-foreground">
+ {copied ? <Check className="h-3 w-3" /> : <Copy className="h-3 w-3" />}
+ {copied ? t("society.share.copied") : t("society.share.copy")}
+ </button>
+ <button type="button" onClick={() => downloadTemplate(fileName, json)} className="flex items-center gap-1 rounded px-1.5 py-1 text-micro text-muted-foreground hover:bg-muted hover:text-foreground" data-testid="share-export">
+ <Download className="h-3 w-3" />
+ {t("society.share.export")}
+ </button>
+ </div>
+ {/* Wrapped, not scrolled sideways: the instructions are one long JSON
+ string, and reading them is the point of showing the template. */}
+ <div className="min-h-0 flex-1 overflow-auto [&_pre]:!whitespace-pre-wrap [&_pre]:[overflow-wrap:anywhere]">
+ <Suspense fallback={<pre className="m-0 px-3 py-2 text-xs text-foreground/90"><code>{json}</code></pre>}>
+ <CodeBlock language="json" code={json} chrome={false} />
+ </Suspense>
+ </div>
+ </div>
+ );
+}
+
+/** Sign in, publish, and watch it go live. */
+function PublishBar({
+ agentId,
+ draft,
+ json,
+ saving,
+}: {
+ agentId: string;
+ draft: ShareDraftWire;
+ json: string;
+ saving: boolean;
+}) {
+ const t = useT();
+ const client = useQueryClient();
+ const identity = usePublishIdentity();
+ const [signInOpen, setSignInOpen] = useState(false);
+ const [result, setResult] = useState<PublishShareResult | null>(null);
+ const [live, setLive] = useState(false);
+ const signedIn = Boolean(identity.data?.signed_in);
+ const enabled = identity.data?.enabled !== false;
+
+ const publish = useMutation({
+ mutationFn: () => publishShareDraft(agentId),
+ onSuccess: (done) => {
+ setResult(done);
+ void client.invalidateQueries({ queryKey: shareDraftKey(agentId) });
+ void client.invalidateQueries({ queryKey: ["marketplace-community"] });
+ },
+ });
+
+ // Watch the feed until the published version is live (or the sheet closes).
+ useEffect(() => {
+ if (!result || live) return;
+ let cancelled = false;
+ const tick = async () => {
+ const isLive = await fetchLiveStatus(result.name, result.version).catch(() => false);
+ if (!cancelled && isLive) {
+ setLive(true);
+ void client.invalidateQueries({ queryKey: ["marketplace-community"] });
+ }
+ };
+ void tick();
+ const timer = window.setInterval(() => void tick(), 15_000);
+ return () => {
+ cancelled = true;
+ window.clearInterval(timer);
+ };
+ }, [result, live, client]);
+
+ const failure = publish.error instanceof ShareError ? publish.error : null;
+ const browserFallback = failure?.field === "browser_fallback";
+ const fileByHand = () => {
+ void robustCopy(json);
+ openExternalUrl(MARKETPLACE_ISSUE_FORM_URL);
+ };
+
+ if (result) {
+ const url = result.issue_url ?? result.pr_url ?? result.url ?? null;
+ return (
+ <footer className="shrink-0 space-y-2 border-t border-border bg-card px-5 py-3" data-testid="share-published">
+ <div className="flex flex-wrap items-center gap-3">
+ <span className={cn("grid h-8 w-8 shrink-0 place-items-center rounded-lg bg-secondary", live ? "text-foreground-strong" : "text-foreground")}>
+ {live ? <Check className="h-4 w-4" /> : <Loader2 className="h-4 w-4 animate-spin" />}
+ </span>
+ <div className="min-w-0 flex-1">
+ <p className="text-sm font-medium text-foreground">
+ {live
+ ? fill(t("society.share.live_title"), { entry: result.name, version: result.version })
+ : fill(t("society.share.submitted_title"), { entry: result.name, version: result.version })}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {live ? t("society.share.live_body") : t("society.share.submitted_body")}
+ </p>
+ </div>
+ {url && (
+ <Button size="sm" variant="outline" onClick={() => openExternalUrl(url)}>
+ <ExternalLink className="mr-1.5 h-3.5 w-3.5" />
+ {t("society.share.view_submission")}
+ </Button>
+ )}
+ </div>
+ {result.install?.cli && (
+ <code className="block rounded-md border border-border bg-muted px-2.5 py-1.5 font-mono text-xs text-foreground">
+ {result.install.cli}
+ </code>
+ )}
+ </footer>
+ );
+ }
+
+ return (
+ <footer className="shrink-0 space-y-2 border-t border-border bg-card px-5 py-3">
+ {draft.errors.length > 0 && (
+ <p role="alert" className="flex items-start gap-2 text-xs text-destructive">
+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
+ {draft.errors[0]}
+ </p>
+ )}
+ {failure && (
+ <p role="alert" className="flex items-start gap-2 text-xs text-destructive">
+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
+ {browserFallback ? t("society.share.fallback_hint") : failure.message}
+ </p>
+ )}
+ <div className="flex flex-wrap items-center gap-3">
+ <p className="min-w-0 flex-1 text-xs leading-relaxed text-muted-foreground">
+ {draft.published
+ ? fill(t("society.share.published_before"), { version: draft.published.version })
+ : t("society.share.publish_hint")}
+ </p>
+ {browserFallback && (
+ <Button size="sm" variant="outline" onClick={fileByHand}>
+ <Github className="mr-1.5 h-3.5 w-3.5" />
+ {t("society.share.fallback_cta")}
+ </Button>
+ )}
+ {!enabled ? (
+ <span className="text-xs text-muted-foreground">{t("society.share.publish_disabled")}</span>
+ ) : !signedIn ? (
+ <Button size="sm" onClick={() => setSignInOpen(true)} disabled={identity.isLoading} data-testid="share-sign-in">
+ <Github className="mr-1.5 h-3.5 w-3.5" />
+ {t("society.share.sign_in")}
+ </Button>
+ ) : (
+ <div className="flex items-center gap-2">
+ <span className="flex items-center gap-1.5 text-xs text-muted-foreground">
+ <PublisherAvatar login={identity.data?.login} url={identity.data?.avatar_url} size={20} />
+ @{identity.data?.login}
+ </span>
+ <Button
+ size="sm"
+ onClick={() => publish.mutate()}
+ disabled={publish.isPending || saving || draft.errors.length > 0}
+ data-testid="share-publish"
+ >
+ {publish.isPending ? <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" /> : <UploadCloud className="mr-1.5 h-3.5 w-3.5" />}
+ {t("society.share.publish")}
+ </Button>
+ </div>
+ )}
+ </div>
+ {signInOpen && <GithubSignInDialog onClose={() => setSignInOpen(false)} />}
+ </footer>
+ );
+}
+
+export default ShareAgentDialog;
diff --git a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts b/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts
index b9ee261cef..000ca74d7f 100644
--- a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts
@@ -721,6 +721,8 @@ export function useWebSocket(): void {
void queryClient.invalidateQueries({ queryKey: ["skills"] });
} else if (p.kind === "plugin") {
void queryClient.invalidateQueries({ queryKey: ["marketplace-plugins"] });
+ } else if (p.kind === "agent") {
+ void queryClient.invalidateQueries({ queryKey: ["society", "roster"] });
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 405ca5d9c0..f1dd2c7020 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -4880,7 +4880,7 @@
"loading": "Der Marketplace wird geladen…",
"refresh": "Verzeichnis neu laden",
"open_web": "Webseite",
- "search_placeholder": "Plugins und Skills durchsuchen…",
+ "search_placeholder": "Plugins, Skills und Agenten durchsuchen…",
"subtitle_count": "{count} veröffentlichte Einträge",
"subtitle_revision": "Stand {revision}",
"filter_all": "Alle",
@@ -4898,7 +4898,7 @@
"empty": "In dieser Kategorie ist noch nichts veröffentlicht.",
"empty_search": "Nichts passt zu „{query}“.",
"empty_clear": "Suche zurücksetzen",
- "publish_hint": "Etwas gebaut, das andere gebrauchen können? Veröffentlichen ist ein Pull Request auf die offene Registry.",
+ "publish_hint": "Etwas gebaut, das andere brauchen können? Veröffentliche es aus der App unter deinem GitHub-Namen – oder teile einen Agenten über seine Karte.",
"publish_cta": "Eigenes veröffentlichen",
"close": "Schließen",
"kind_plugin": "Plugin",
@@ -4922,7 +4922,19 @@
"portable_skill": "Portabler Skill — läuft auch in",
"portable_any": "anderen Agenten, die SKILL.md lesen",
"seed_conflict": "Ein Plugin dieses Namens liegt der App schon bei. Dieses hier ersetzt es.",
- "landed_open": "Zeig es mir"
+ "landed_open": "Zeig es mir",
+ "filter_agents": "Agenten",
+ "shelf_agents": "Agenten",
+ "shelf_agents_hint": "Fertige Teammitglieder mit einer Aufgabe und eigenen Anweisungen",
+ "kind_agent": "Agent",
+ "landed_agent": "Er ist jetzt in deinem Team und läuft auf deinem eigenen Modell. Öffne Agenten, um mit ihm zu sprechen.",
+ "agent_model": "Läuft auf deinem eigenen Modell – nichts von den Konten oder Einstellungen des Veröffentlichenden kommt mit.",
+ "agent_focus": "Greift zuerst zu",
+ "agent_asks": "Fragt immer vor",
+ "agent_asks_default": "Er fragt dich, bevor er handelt, bis du das änderst.",
+ "agent_instructions": "Seine festen Anweisungen",
+ "import_agent": "Agenten-Datei importieren",
+ "import_failed": "Die Datei konnte nicht importiert werden: {error}"
},
"costs_view": {
"title": "Kosten & Tokens",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 8ea24e6539..0976a63a18 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -4880,7 +4880,7 @@
"loading": "Loading the marketplace index…",
"refresh": "Fetch the index again",
"open_web": "Storefront",
- "search_placeholder": "Search plugins and skills…",
+ "search_placeholder": "Search plugins, skills and agents…",
"subtitle_count": "{count} published entries",
"subtitle_revision": "index {revision}",
"filter_all": "All",
@@ -4898,7 +4898,7 @@
"empty": "Nothing is published in this category yet.",
"empty_search": "Nothing matches “{query}”.",
"empty_clear": "Clear the search",
- "publish_hint": "Built something worth sharing? Publishing is a pull request against the open registry.",
+ "publish_hint": "Built something worth sharing? Publish it from the app under your GitHub name — or share an agent from its card.",
"publish_cta": "Publish yours",
"close": "Close",
"kind_plugin": "Plugin",
@@ -4922,7 +4922,19 @@
"portable_skill": "Portable skill — also runs in",
"portable_any": "other agents that read SKILL.md",
"seed_conflict": "A plugin of this name already ships with the app. Installing this one replaces it.",
- "landed_open": "Show me"
+ "landed_open": "Show me",
+ "filter_agents": "Agents",
+ "shelf_agents": "Agents",
+ "shelf_agents_hint": "Ready-made teammates with a job and their own instructions",
+ "kind_agent": "Agent",
+ "landed_agent": "It is on your team now and runs on your own model. Open Agents to talk to it.",
+ "agent_model": "Runs on your own model — nothing of the publisher's accounts or settings comes with it.",
+ "agent_focus": "Reaches first for",
+ "agent_asks": "Always asks before",
+ "agent_asks_default": "It asks you before it acts until you change that.",
+ "agent_instructions": "Its standing instructions",
+ "import_agent": "Import an agent file",
+ "import_failed": "That file could not be imported: {error}"
},
"costs_view": {
"title": "Spend & Tokens",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 895deea4ee..204c0ea0cb 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -4880,7 +4880,7 @@
"loading": "Cargando el índice del marketplace…",
"refresh": "Volver a cargar el índice",
"open_web": "Sitio web",
- "search_placeholder": "Buscar plugins y skills…",
+ "search_placeholder": "Buscar plugins, skills y agentes…",
"subtitle_count": "{count} entradas publicadas",
"subtitle_revision": "índice {revision}",
"filter_all": "Todo",
@@ -4898,7 +4898,7 @@
"empty": "Todavía no hay nada publicado en esta categoría.",
"empty_search": "Nada coincide con «{query}».",
"empty_clear": "Borrar la búsqueda",
- "publish_hint": "¿Has creado algo que merece compartirse? Publicar es un pull request al registro abierto.",
+ "publish_hint": "¿Has creado algo que valga la pena compartir? Publícalo desde la app con tu nombre de GitHub, o comparte un agente desde su tarjeta.",
"publish_cta": "Publica el tuyo",
"close": "Cerrar",
"kind_plugin": "Plugin",
@@ -4922,7 +4922,19 @@
"portable_skill": "Skill portable: también funciona en",
"portable_any": "otros agentes que leen SKILL.md",
"seed_conflict": "La app ya trae un plugin con este nombre. Instalar este lo sustituye.",
- "landed_open": "Muéstramelo"
+ "landed_open": "Muéstramelo",
+ "filter_agents": "Agentes",
+ "shelf_agents": "Agentes",
+ "shelf_agents_hint": "Compañeros listos para usar, con un trabajo y sus propias instrucciones",
+ "kind_agent": "Agente",
+ "landed_agent": "Ya está en tu equipo y funciona con tu propio modelo. Abre Agentes para hablar con él.",
+ "agent_model": "Funciona con tu propio modelo: no viene nada de las cuentas ni de los ajustes de quien lo publicó.",
+ "agent_focus": "Recurre primero a",
+ "agent_asks": "Siempre pregunta antes de",
+ "agent_asks_default": "Te pregunta antes de actuar hasta que lo cambies.",
+ "agent_instructions": "Sus instrucciones permanentes",
+ "import_agent": "Importar un archivo de agente",
+ "import_failed": "No se pudo importar ese archivo: {error}"
},
"costs_view": {
"title": "Gastos y tokens",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/marketplace/de.json b/jarvis/ui/web/frontend/src/i18n/locales/marketplace/de.json
index 9e733cfc33..2af4d28173 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/marketplace/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/marketplace/de.json
@@ -4,7 +4,7 @@
"empty_mine": "Unter deinem Namen ist noch nichts veröffentlicht. Dein erstes Paket ist einen Klick entfernt.",
"hero_eyebrow": "Community-Marketplace",
"hero_title": "Gebaut von Leuten, die diese App benutzen",
- "hero_body": "Plugins und Skills — von der Community veröffentlicht, mit einem Klick installiert. Jeder kann veröffentlichen: mit GitHub anmelden, und alles, was die automatischen Prüfungen besteht, geht unter deinem Namen live.",
+ "hero_body": "Plugins, Skills und fertige Agenten — von der Community veröffentlicht, mit einem Klick installiert. Jeder kann veröffentlichen: mit GitHub anmelden, und alles, was die automatischen Prüfungen besteht, geht unter deinem Namen live.",
"hero_publish_signed_in": "Etwas veröffentlichen",
"publish_on_web": "Auf der Website",
"identity_label": "Identität",
@@ -115,8 +115,8 @@
"studio_preview_bundled": "{count} gebündelte(r) Skill(s)",
"studio_preview_note": "So ungefähr wird dein Eintrag im Store aussehen — für alle, sobald die Prüfungen bestanden sind.",
"studio_done_eyebrow": "An die Registry übermittelt",
- "studio_done_body": "Die Registry hat dein Paket erhalten und den Pull Request eröffnet. Jetzt laufen die automatischen Prüfungen; wenn sie bestehen, wird gemergt und der Eintrag erscheint von selbst im Store.",
- "studio_done_view_pr": "Pull Request ansehen",
+ "studio_done_body": "Die Registry hat dein Paket erhalten. Jetzt laufen die automatischen Prüfungen; wenn sie bestehen, erscheint der Eintrag von selbst im Store.",
+ "studio_done_view_pr": "Einreichung ansehen",
"studio_done_another": "Noch eins veröffentlichen",
"studio_done_live": "Live — {name} v{version} ist jetzt im Marketplace.",
"studio_done_waited_out": "Nach mehreren Minuten noch nicht im Feed — öffne den Pull Request oben und sieh nach, was die Prüfungen sagen.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/marketplace/en.json b/jarvis/ui/web/frontend/src/i18n/locales/marketplace/en.json
index 9fda74afba..7448c06f10 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/marketplace/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/marketplace/en.json
@@ -4,7 +4,7 @@
"empty_mine": "Nothing published under your name yet. Your first package is one click away.",
"hero_eyebrow": "Community marketplace",
"hero_title": "Built by people who use this app",
- "hero_body": "Plugins and skills, published by the community and installed in one click. Anyone can publish — sign in with GitHub, and whatever passes the automated checks goes live under your name.",
+ "hero_body": "Plugins, skills and ready-made agents, published by the community and installed in one click. Anyone can publish — sign in with GitHub, and whatever passes the automated checks goes live under your name.",
"hero_publish_signed_in": "Publish something",
"publish_on_web": "On the website",
"identity_label": "Identity",
@@ -115,8 +115,8 @@
"studio_preview_bundled": "{count} bundled skill(s)",
"studio_preview_note": "This is roughly how your entry will look in the store — for everyone, as soon as the checks pass.",
"studio_done_eyebrow": "Submitted to the registry",
- "studio_done_body": "The registry received your package and opened its pull request. The automated checks now run; when they pass, it merges and appears in the store on its own.",
- "studio_done_view_pr": "View the pull request",
+ "studio_done_body": "The registry received your package. The automated checks now run; when they pass, it appears in the store on its own.",
+ "studio_done_view_pr": "View the submission",
"studio_done_another": "Publish another",
"studio_done_live": "Live — {name} v{version} is in the marketplace now.",
"studio_done_waited_out": "Still not in the feed after several minutes — open the pull request above to see what its checks say.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/marketplace/es.json b/jarvis/ui/web/frontend/src/i18n/locales/marketplace/es.json
index 6a7b20357b..2841c6e9e8 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/marketplace/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/marketplace/es.json
@@ -4,7 +4,7 @@
"empty_mine": "Todavía no hay nada publicado con tu nombre. Tu primer paquete está a un clic.",
"hero_eyebrow": "Marketplace de la comunidad",
"hero_title": "Creado por gente que usa esta app",
- "hero_body": "Plugins y skills, publicados por la comunidad e instalados con un clic. Cualquiera puede publicar: inicia sesión con GitHub y todo lo que supere las comprobaciones automáticas sale en vivo con tu nombre.",
+ "hero_body": "Plugins, skills y agentes listos para usar, publicados por la comunidad e instalados con un clic. Cualquiera puede publicar: inicia sesión con GitHub y todo lo que supere las comprobaciones automáticas sale en vivo con tu nombre.",
"hero_publish_signed_in": "Publicar algo",
"publish_on_web": "En la web",
"identity_label": "Identidad",
@@ -115,8 +115,8 @@
"studio_preview_bundled": "{count} skill(s) incluida(s)",
"studio_preview_note": "Así se verá más o menos tu entrada en la tienda, para todos, en cuanto pasen las comprobaciones.",
"studio_done_eyebrow": "Enviado al registro",
- "studio_done_body": "El registro recibió tu paquete y abrió su pull request. Ahora se ejecutan las comprobaciones automáticas; cuando pasen, se fusiona y aparece en la tienda por sí solo.",
- "studio_done_view_pr": "Ver el pull request",
+ "studio_done_body": "El registro recibió tu paquete. Ahora se ejecutan las comprobaciones automáticas; cuando pasen, aparece en la tienda por sí solo.",
+ "studio_done_view_pr": "Ver el envío",
"studio_done_another": "Publicar otro",
"studio_done_live": "En vivo — {name} v{version} ya está en el marketplace.",
"studio_done_waited_out": "Tras varios minutos sigue sin aparecer en el feed: abre el pull request de arriba para ver qué dicen sus comprobaciones.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
index 5bc35b3e85..64f6d08928 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json
@@ -710,6 +710,59 @@
"open_preview": "Mars-Vorschau",
"previous_world": "Bisherige Welt"
},
+ "share": {
+ "cta": "Teilen",
+ "cta_hint": "Diesen Agenten als Vorlage teilen, die andere installieren können",
+ "title": "{agent} teilen",
+ "subtitle": "Eine Vorlage aus Aufgabe, Anweisungen und Aussehen dieses Agenten – ohne Privates.",
+ "loading": "Vorlage wird erstellt…",
+ "public_version": "Öffentliche Fassung",
+ "template": "Vorlage",
+ "summary": "Kurzbeschreibung für die Store-Karte",
+ "summary_placeholder": "Was dieser Agent tut und für wen – ein oder zwei Sätze.",
+ "listing_name": "Name im Marketplace",
+ "version": "Version",
+ "categories": "Schlagwörter",
+ "categories_placeholder": "email, produktivität",
+ "polish_title": "{agent} vorbereiten lassen",
+ "polished_by": "Vorbereitet von {agent}",
+ "polish_hint": "{agent} schreibt seine Anweisungen für alle um und verfasst die Kurzbeschreibung. Du siehst es im Chat.",
+ "polish_waiting": "{agent} schreibt die öffentliche Fassung – schau im Chat zu. Dieses Fenster aktualisiert sich selbst.",
+ "polish_unavailable": "Öffne den Chat dieses Agenten, damit er die Vorlage selbst vorbereiten kann.",
+ "polish_cta": "{agent} fragen",
+ "polish_failed": "Die Nachricht konnte nicht gesendet werden. Versuch es noch einmal im Chat.",
+ "polish_prompt": "Bitte bereite deine teilbare Vorlage für den Personal-Jarvis-Marketplace vor. Schreib eine Kurzbeschreibung mit ein oder zwei Sätzen für die Store-Karte und formuliere deine festen Anweisungen so um, dass jeder sie nutzen kann: Behalte die Arbeitsweise bei und entferne alles Persönliche – Namen, E-Mail-Adressen, Firmen, Ordner, Konten – und jeden Zugangsschlüssel. Speichere sie mit dem Werkzeug society_share_template und sag mir danach in einem Satz, dass sie fertig ist.",
+ "reset": "Zurück zum eigenen Text des Agenten",
+ "privacy_clean": "Nichts Privates gefunden",
+ "privacy_clean_hint": "Keine Schlüssel, Passwörter, E-Mail-Adressen, Telefonnummern oder Ordner von dir stehen in der Vorlage.",
+ "privacy_removed": "{count} private Angaben vor dem Teilen entfernt",
+ "finding_secret": "Schlüssel",
+ "finding_email": "E-Mail",
+ "finding_phone": "Telefon",
+ "finding_path": "Ordner",
+ "finding_address": "Adresse",
+ "finding_where": "{hint} in {field}",
+ "field_instructions": "den Anweisungen",
+ "field_title": "der Rollenzeile",
+ "field_summary": "der Kurzbeschreibung",
+ "never_title": "Wird nie geteilt",
+ "never_body": "Dein Modell und deine Konten, Chats, Gedächtnis, Dateien und Ordner, verbundene Computer, Budget und Freigabe-Einstellungen bleiben auf diesem Computer. Wer die Vorlage installiert, nutzt sein eigenes Modell, und der Agent fragt ihn, bevor er handelt.",
+ "copy": "Kopieren",
+ "copied": "Kopiert",
+ "export": "Exportieren",
+ "sign_in": "Mit GitHub anmelden, um zu veröffentlichen",
+ "publish": "Im Marketplace veröffentlichen",
+ "publish_hint": "Beim Veröffentlichen erscheint die Vorlage unter deinem GitHub-Namen im Marketplace. Zuerst laufen automatische Prüfungen; niemand muss sie freigeben.",
+ "publish_disabled": "Veröffentlichen ist in dieser Installation ausgeschaltet – exportiere stattdessen die Datei.",
+ "published_before": "Version {version} ist schon veröffentlicht. Erneutes Veröffentlichen bringt die nächste Version heraus.",
+ "submitted_title": "{entry} {version} eingereicht",
+ "submitted_body": "Der Marketplace prüft die Vorlage jetzt und listet sie in wenigen Minuten.",
+ "live_title": "{entry} {version} ist live",
+ "live_body": "Jeder kann sie jetzt installieren – mit der Zeile unten oder im Marketplace.",
+ "view_submission": "Auf GitHub ansehen",
+ "fallback_hint": "GitHub hat die Einreichung aus der App nicht angenommen. Kopiere die Vorlage und reiche sie im Browser ein – das ist ein einziges Einfügen.",
+ "fallback_cta": "Kopieren und GitHub öffnen"
+ },
"companion": {
"title": "Dein Begleiter",
"hint": "Dein Profilbild folgt deinem Charakter auf der Map. Charakter und Begleiter kannst du getrennt gestalten.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
index 81e932d44a..25f856b053 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json
@@ -710,6 +710,59 @@
"open_preview": "Mars preview",
"previous_world": "Previous world"
},
+ "share": {
+ "cta": "Share",
+ "cta_hint": "Turn this agent into a template others can install",
+ "title": "Share {agent}",
+ "subtitle": "A template of this agent's job, instructions and look — without anything private.",
+ "loading": "Building the template…",
+ "public_version": "Public version",
+ "template": "Template",
+ "summary": "Summary for the store card",
+ "summary_placeholder": "What this agent does, and for whom — one or two sentences.",
+ "listing_name": "Marketplace name",
+ "version": "Version",
+ "categories": "Tags",
+ "categories_placeholder": "email, productivity",
+ "polish_title": "Let {agent} prepare it",
+ "polished_by": "Prepared by {agent}",
+ "polish_hint": "{agent} rewrites its own instructions for anyone and writes the summary. You see it happen in the chat.",
+ "polish_waiting": "{agent} is writing the public version — watch it in the chat. This sheet updates by itself.",
+ "polish_unavailable": "Open this agent's chat to let it prepare the template itself.",
+ "polish_cta": "Ask {agent}",
+ "polish_failed": "The message could not be sent. Try again from the chat.",
+ "polish_prompt": "Please prepare your shareable template for the Personal Jarvis marketplace. Write a one- or two-sentence summary for the store card, and rewrite your standing instructions so anyone can use them: keep the working method, and remove everything personal — names, e-mail addresses, companies, folders, accounts — and every credential. Save it with the society_share_template tool, then tell me in one sentence that it is ready.",
+ "reset": "Back to the agent's own text",
+ "privacy_clean": "Nothing private found",
+ "privacy_clean_hint": "No keys, passwords, e-mail addresses, phone numbers or folders of yours are in the template.",
+ "privacy_removed": "{count} private details removed before sharing",
+ "finding_secret": "Key",
+ "finding_email": "E-mail",
+ "finding_phone": "Phone",
+ "finding_path": "Folder",
+ "finding_address": "Address",
+ "finding_where": "{hint} in the {field}",
+ "field_instructions": "instructions",
+ "field_title": "job line",
+ "field_summary": "summary",
+ "never_title": "Never shared",
+ "never_body": "Your model and accounts, chats, memory, files and folders, connected computers, budget and approval settings stay on this computer. Whoever installs the template runs it on their own model, and it asks them before it acts.",
+ "copy": "Copy",
+ "copied": "Copied",
+ "export": "Export",
+ "sign_in": "Sign in with GitHub to publish",
+ "publish": "Publish to the marketplace",
+ "publish_hint": "Publishing lists it in the marketplace under your GitHub name. Automated checks run first; nobody has to approve it.",
+ "publish_disabled": "Publishing is switched off in this install — export the file instead.",
+ "published_before": "Version {version} is already published. Publishing again releases the next version.",
+ "submitted_title": "{entry} {version} submitted",
+ "submitted_body": "The marketplace checks it now and lists it within a few minutes.",
+ "live_title": "{entry} {version} is live",
+ "live_body": "Anyone can install it now — with the line below, or from the marketplace.",
+ "view_submission": "View on GitHub",
+ "fallback_hint": "GitHub did not take the submission from the app. Copy the template and file it in your browser instead — it takes one paste.",
+ "fallback_cta": "Copy and open GitHub"
+ },
"companion": {
"title": "Your companion",
"hint": "Your profile picture follows your character on the map. Character and companion are customized separately.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
index 394af67a4e..bc43349b16 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json
@@ -710,6 +710,59 @@
"open_preview": "Vista previa de Marte",
"previous_world": "Mundo anterior"
},
+ "share": {
+ "cta": "Compartir",
+ "cta_hint": "Convierte este agente en una plantilla que otros pueden instalar",
+ "title": "Compartir {agent}",
+ "subtitle": "Una plantilla con el trabajo, las instrucciones y el aspecto de este agente, sin nada privado.",
+ "loading": "Creando la plantilla…",
+ "public_version": "Versión pública",
+ "template": "Plantilla",
+ "summary": "Resumen para la tarjeta de la tienda",
+ "summary_placeholder": "Qué hace este agente y para quién, en una o dos frases.",
+ "listing_name": "Nombre en el marketplace",
+ "version": "Versión",
+ "categories": "Etiquetas",
+ "categories_placeholder": "correo, productividad",
+ "polish_title": "Deja que {agent} la prepare",
+ "polished_by": "Preparada por {agent}",
+ "polish_hint": "{agent} reescribe sus instrucciones para cualquiera y redacta el resumen. Lo verás en el chat.",
+ "polish_waiting": "{agent} está escribiendo la versión pública; míralo en el chat. Esta ventana se actualiza sola.",
+ "polish_unavailable": "Abre el chat de este agente para que prepare la plantilla él mismo.",
+ "polish_cta": "Pedírselo a {agent}",
+ "polish_failed": "No se pudo enviar el mensaje. Inténtalo de nuevo desde el chat.",
+ "polish_prompt": "Por favor, prepara tu plantilla para compartir en el marketplace de Personal Jarvis. Escribe un resumen de una o dos frases para la tarjeta de la tienda y reescribe tus instrucciones permanentes para que cualquiera pueda usarlas: conserva el método de trabajo y elimina todo lo personal (nombres, direcciones de correo, empresas, carpetas, cuentas) y cualquier credencial. Guárdala con la herramienta society_share_template y luego dime en una frase que está lista.",
+ "reset": "Volver al texto propio del agente",
+ "privacy_clean": "No se encontró nada privado",
+ "privacy_clean_hint": "La plantilla no contiene claves, contraseñas, correos, teléfonos ni carpetas tuyas.",
+ "privacy_removed": "{count} datos privados eliminados antes de compartir",
+ "finding_secret": "Clave",
+ "finding_email": "Correo",
+ "finding_phone": "Teléfono",
+ "finding_path": "Carpeta",
+ "finding_address": "Dirección",
+ "finding_where": "{hint} en {field}",
+ "field_instructions": "las instrucciones",
+ "field_title": "la línea de puesto",
+ "field_summary": "el resumen",
+ "never_title": "Nunca se comparte",
+ "never_body": "Tu modelo y tus cuentas, chats, memoria, archivos y carpetas, ordenadores conectados, presupuesto y ajustes de aprobación se quedan en este ordenador. Quien instala la plantilla la ejecuta con su propio modelo, y el agente le pregunta antes de actuar.",
+ "copy": "Copiar",
+ "copied": "Copiado",
+ "export": "Exportar",
+ "sign_in": "Inicia sesión con GitHub para publicar",
+ "publish": "Publicar en el marketplace",
+ "publish_hint": "Al publicar, aparece en el marketplace con tu nombre de GitHub. Primero se ejecutan comprobaciones automáticas; nadie tiene que aprobarla.",
+ "publish_disabled": "Publicar está desactivado en esta instalación; exporta el archivo en su lugar.",
+ "published_before": "La versión {version} ya está publicada. Publicar de nuevo lanza la siguiente versión.",
+ "submitted_title": "{entry} {version} enviada",
+ "submitted_body": "El marketplace la comprueba ahora y la lista en unos minutos.",
+ "live_title": "{entry} {version} ya está publicada",
+ "live_body": "Cualquiera puede instalarla ya, con la línea de abajo o desde el marketplace.",
+ "view_submission": "Ver en GitHub",
+ "fallback_hint": "GitHub no aceptó el envío desde la app. Copia la plantilla y envíala desde tu navegador; basta con pegarla.",
+ "fallback_cta": "Copiar y abrir GitHub"
+ },
"companion": {
"title": "Tu compañero",
"hint": "Tu imagen de perfil sigue a tu personaje en el mapa. Personaliza el personaje y su compañero por separado.",
diff --git a/jarvis/ui/web/frontend/src/lib/agentShare.ts b/jarvis/ui/web/frontend/src/lib/agentShare.ts
new file mode 100644
index 0000000000..cdf9c6da5c
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/agentShare.ts
@@ -0,0 +1,197 @@
+/**
+ * Share an agent as a template, and install one somebody else shared.
+ *
+ * Wire types mirror jarvis/ui/web/society_routes.py ("templates" section) and
+ * jarvis/society/agent_template.py. The template is always BUILT by the
+ * server from the roster row plus the public-version edits; this module never
+ * sends a template of its own to publish, so what leaves the machine is
+ * exactly what the server's scrubber let through.
+ */
+
+export type ShareFindingKind = "secret" | "email" | "path" | "phone" | "address";
+
+/** One thing taken out of the text before sharing — named, never repeated. */
+export interface ShareFinding {
+ kind: ShareFindingKind;
+ /** "instructions" | "title" | "summary" */
+ field: string;
+ /** First and last characters of what was removed, so its author recognises it. */
+ hint: string;
+}
+
+/** The template itself: the agent's design, nothing of its operation. */
+export interface AgentTemplateWire {
+ schema: 1;
+ name: string;
+ title: string;
+ instructions: string;
+ tier: "specialist" | "orchestrator";
+ effort: string;
+ focus: string[];
+ grant_mode: "all" | "allowlist";
+ grants: string[];
+ denies: string[];
+ skills: string[] | null;
+ require_approval: string[];
+ knowledge_scope: "shared" | "own";
+ avatar: Record<string, unknown>;
+}
+
+/** How the template is listed in the marketplace. */
+export interface ShareListing {
+ /** The marketplace name (a-z 0-9 - .) — the id people install by. */
+ name: string;
+ title: string;
+ /** The store-card summary. */
+ description: string;
+ categories: string[];
+ version: string;
+}
+
+export interface SharePublished {
+ name: string;
+ version: string;
+ url?: string | null;
+}
+
+export interface ShareDraftWire {
+ template: AgentTemplateWire;
+ listing: ShareListing;
+ findings: ShareFinding[];
+ /** The agent's name when it wrote the public version itself; "" otherwise. */
+ polished_by: string;
+ published: SharePublished | null;
+ /** Exactly what Publish files: `{kind: "agent", name, version, …, agent}`. */
+ submission: Record<string, unknown>;
+ /** Why it cannot be published yet; empty when it can. */
+ errors: string[];
+}
+
+export interface ShareDraftEdits {
+ summary?: string;
+ title?: string;
+ categories?: string[];
+ listing_name?: string;
+ version?: string;
+ reset?: boolean;
+}
+
+export interface PublishShareResult {
+ ok: boolean;
+ name: string;
+ version: string;
+ url?: string | null;
+ issue_url?: string | null;
+ pr_url?: string | null;
+ install?: { cli: string; runner: string; prompt: string } | null;
+}
+
+export interface InstallTemplateResult {
+ agent: { agent_id: string; name: string };
+ created: boolean;
+ renamed_from: string | null;
+}
+
+/** A refusal from the server, with the field it concerns when there is one. */
+export class ShareError extends Error {
+ constructor(
+ message: string,
+ readonly status: number,
+ readonly field: string | null = null,
+ ) {
+ super(message);
+ }
+}
+
+export const shareDraftKey = (agentId: string) => ["society", "share-template", agentId] as const;
+
+/** The registry's issue form — the browser route when the app may not file it. */
+export const MARKETPLACE_ISSUE_FORM_URL =
+ "https://github.com/PersonalJarvis/marketplace/issues/new?template=publish.yml";
+
+async function readError(res: Response): Promise<ShareError> {
+ const body = (await res.json().catch(() => ({}))) as {
+ detail?: string | { error?: string; detail?: string; field?: string | null };
+ };
+ const detail = body.detail;
+ if (typeof detail === "string") return new ShareError(detail, res.status);
+ const message = detail?.error ?? detail?.detail ?? `Request failed (${res.status})`;
+ return new ShareError(message, res.status, detail?.field ?? null);
+}
+
+const agentUrl = (agentId: string) => `/api/society/agents/${encodeURIComponent(agentId)}/template`;
+
+export async function fetchShareDraft(agentId: string): Promise<ShareDraftWire> {
+ const res = await fetch(agentUrl(agentId), { cache: "no-store" });
+ if (!res.ok) throw await readError(res);
+ return res.json();
+}
+
+export async function saveShareDraft(
+ agentId: string,
+ edits: ShareDraftEdits,
+): Promise<ShareDraftWire> {
+ const res = await fetch(agentUrl(agentId), {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(edits),
+ });
+ if (!res.ok) throw await readError(res);
+ return res.json();
+}
+
+export async function publishShareDraft(agentId: string): Promise<PublishShareResult> {
+ const res = await fetch(`${agentUrl(agentId)}/publish`, { method: "POST" });
+ if (!res.ok) throw await readError(res);
+ return res.json();
+}
+
+/** Create a NEW agent from a template (a file, pasted JSON, or a submission). */
+export async function installAgentTemplate(
+ template: Record<string, unknown>,
+): Promise<InstallTemplateResult> {
+ const res = await fetch("/api/society/templates/install", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ template }),
+ });
+ if (!res.ok) throw await readError(res);
+ return res.json();
+}
+
+/** Whether ``name@version`` is in the live marketplace feed yet. */
+export async function fetchLiveStatus(name: string, version: string): Promise<boolean> {
+ const params = new URLSearchParams({ name, version, force: "true" });
+ const res = await fetch(`/api/marketplace/publish/status?${params}`, { cache: "no-store" });
+ if (!res.ok) return false;
+ const body = (await res.json()) as { live?: boolean };
+ return Boolean(body.live);
+}
+
+/** A picked file's text — FileReader, which every WebView and test DOM has. */
+export function readFileText(file: Blob): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(String(reader.result ?? ""));
+ reader.onerror = () => reject(reader.error ?? new Error("the file could not be read"));
+ reader.readAsText(file);
+ });
+}
+
+/** The file name an exported template is saved under. */
+export function templateFileName(listing: Pick<ShareListing, "name">): string {
+ return `${listing.name || "agent"}.agent.json`;
+}
+
+/** Hand the template to the person as a file (the Export button). */
+export function downloadTemplate(fileName: string, json: string): void {
+ const blob = new Blob([json], { type: "application/json" });
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = fileName;
+ document.body.appendChild(link);
+ link.click();
+ link.remove();
+ window.setTimeout(() => URL.revokeObjectURL(url), 1000);
+}
diff --git a/jarvis/ui/web/frontend/src/views/MarketplaceView.agents.test.tsx b/jarvis/ui/web/frontend/src/views/MarketplaceView.agents.test.tsx
new file mode 100644
index 0000000000..3a42858c52
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/MarketplaceView.agents.test.tsx
@@ -0,0 +1,164 @@
+/**
+ * Agent templates in the storefront: their own shelf and filter, a drawer that
+ * shows the instructions and the safe defaults BEFORE the install button, an
+ * install that lands on the team, and the import of an exported file.
+ *
+ * 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 { afterEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@/views/ChatsView", () => ({
+ ViewHeader: ({ title, right }: { title: string; right?: React.ReactNode }) => (
+ <header>
+ <h2>{title}</h2>
+ {right}
+ </header>
+ ),
+}));
+vi.mock("@/lib/openExternal", () => ({ openExternalUrl: vi.fn() }));
+
+import { MarketplaceView } from "@/views/MarketplaceView";
+import type { CommunityResponse } from "@/views/PluginsCommunity";
+
+const TEMPLATE = {
+ schema: 1 as const,
+ name: "Inbox Butler",
+ title: "Keeps the inbox at zero",
+ instructions: "Sort new mail into Action, Waiting and Read later.",
+ tier: "specialist" as const,
+ effort: "",
+ focus: ["plugin:gmail"],
+ grant_mode: "all" as const,
+ grants: [],
+ denies: [],
+ skills: null,
+ require_approval: ["plugin:gmail:send"],
+ knowledge_scope: "shared" as const,
+ avatar: { companion: { shape: "circle", color: "#3366ff" } },
+};
+
+const INDEX: CommunityResponse = {
+ status: "fresh",
+ plugins: [],
+ skills: [],
+ agents: [
+ {
+ name: "inbox-butler",
+ title: "Inbox Butler",
+ description: "Sorts the inbox and drafts the answers that matter.",
+ publisher: "octocat",
+ version: "1.0.0",
+ categories: ["email"],
+ source_url: "https://github.com/PersonalJarvis/marketplace/tree/main/agents/inbox-butler",
+ agent: TEMPLATE,
+ valid: true,
+ installed: false,
+ },
+ ],
+};
+
+function installFetchMock() {
+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ const method = init?.method ?? "GET";
+ const ok = (body: unknown) => ({ ok: true, status: 200, json: async () => body }) as Response;
+ if (url === "/api/marketplace/community" && method === "GET") return ok(INDEX);
+ if (url === "/api/marketplace/publish/identity") return ok({ enabled: true, signed_in: false });
+ if (url.endsWith("/contents")) {
+ return ok({ kind: "agent", name: "inbox-butler", title: "Inbox Butler", root: "agents/inbox-butler", files: [] });
+ }
+ if (url === "/api/marketplace/community/install/inbox-butler" && method === "POST") {
+ return ok({ ok: true, kind: "agent", id: "inbox-butler", title: "Inbox Butler", ready: true });
+ }
+ if (url === "/api/society/templates/install" && method === "POST") {
+ // Like the server: a whole submission is unwrapped to its template.
+ const body = JSON.parse(String(init?.body)) as {
+ template: { name?: string; agent?: { name?: string } };
+ };
+ const template = body.template.agent ?? body.template;
+ return ok({
+ agent: { agent_id: "imported", name: template.name ?? "Imported" },
+ created: true,
+ renamed_from: null,
+ });
+ }
+ throw new Error(`unexpected fetch: ${method} ${url}`);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ return fetchMock;
+}
+
+function renderView() {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ return render(
+ <QueryClientProvider client={client}>
+ <MarketplaceView />
+ </QueryClientProvider>,
+ );
+}
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+describe("MarketplaceView — agents", () => {
+ it("lists agents on their own shelf with their own filter", async () => {
+ installFetchMock();
+ renderView();
+ expect(await screen.findByText("Inbox Butler")).toBeTruthy();
+ expect(screen.getByRole("button", { name: /Agents 1/ })).toBeTruthy();
+ });
+
+ it("shows the instructions and the safe defaults before installing", async () => {
+ const fetchMock = installFetchMock();
+ renderView();
+ fireEvent.click(await screen.findByText("Inbox Butler"));
+
+ expect(await screen.findByText(/Sort new mail into Action/)).toBeTruthy();
+ expect(screen.getByText(/Runs on your own model/)).toBeTruthy();
+ expect(screen.getByText("plugin:gmail:send")).toBeTruthy();
+
+ fireEvent.click(screen.getByRole("button", { name: "Install" }));
+ await waitFor(() =>
+ expect(
+ fetchMock.mock.calls.some(
+ ([url, init]) =>
+ String(url) === "/api/marketplace/community/install/inbox-butler" &&
+ (init as RequestInit | undefined)?.method === "POST",
+ ),
+ ).toBe(true),
+ );
+ expect(await screen.findByText(/on your team now/)).toBeTruthy();
+ });
+
+ it("imports an exported template file as a new teammate", async () => {
+ const fetchMock = installFetchMock();
+ renderView();
+ await screen.findByText("Inbox Butler");
+
+ const input = screen.getByTestId("marketplace-import-agent-input") as HTMLInputElement;
+ const file = new File([JSON.stringify({ kind: "agent", agent: { ...TEMPLATE, name: "Scribe" } })], "scribe.agent.json", {
+ type: "application/json",
+ });
+ fireEvent.change(input, { target: { files: [file] } });
+
+ expect(await screen.findByText(/Scribe installed/)).toBeTruthy();
+ expect(
+ fetchMock.mock.calls.some(([url]) => String(url) === "/api/society/templates/install"),
+ ).toBe(true);
+ });
+
+ it("names the problem when an imported file is not JSON", async () => {
+ installFetchMock();
+ renderView();
+ await screen.findByText("Inbox Butler");
+
+ const input = screen.getByTestId("marketplace-import-agent-input") as HTMLInputElement;
+ fireEvent.change(input, { target: { files: [new File(["not json"], "notes.txt")] } });
+
+ expect(await screen.findByText(/could not be imported: notes.txt/)).toBeTruthy();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/views/MarketplaceView.test.tsx b/jarvis/ui/web/frontend/src/views/MarketplaceView.test.tsx
index 84f93a31da..1db34d99c8 100644
--- a/jarvis/ui/web/frontend/src/views/MarketplaceView.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/MarketplaceView.test.tsx
@@ -298,10 +298,10 @@ describe("MarketplaceView", () => {
// The German strings resolve from the locale file, including the count
// template whose {count} token this view fills itself.
expect(await screen.findByText(/2 veröffentlichte Einträge/)).toBeTruthy(); // i18n-allow
- expect(screen.getByLabelText(/Plugins und Skills durchsuchen/)).toBeTruthy(); // i18n-allow
+ expect(screen.getByLabelText(/Plugins, Skills und Agenten durchsuchen/)).toBeTruthy(); // i18n-allow
setUiLanguage("es");
- expect(await screen.findByLabelText(/Buscar plugins y skills/)).toBeTruthy(); // i18n-allow
+ expect(await screen.findByLabelText(/Buscar plugins, skills y agentes/)).toBeTruthy(); // i18n-allow
});
it("opens the public storefront in a real browser", async () => {
diff --git a/jarvis/ui/web/frontend/src/views/MarketplaceView.tsx b/jarvis/ui/web/frontend/src/views/MarketplaceView.tsx
index 030914e39e..afadabf800 100644
--- a/jarvis/ui/web/frontend/src/views/MarketplaceView.tsx
+++ b/jarvis/ui/web/frontend/src/views/MarketplaceView.tsx
@@ -1,10 +1,11 @@
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
AlertTriangle,
ArrowRight,
Check,
ExternalLink,
+ FileInput,
FileText,
Loader2,
Package,
@@ -29,8 +30,12 @@ import { fill, useLocaleChunk, useT } from "@/i18n";
import { cn } from "@/lib/utils";
import { openExternalUrl } from "@/lib/openExternal";
import { useEventStore, type SectionId } from "@/store/events";
+import { installAgentTemplate, readFileText, type AgentTemplateWire } from "@/lib/agentShare";
+import { AgentSymbol } from "@/components/society/AgentSymbol";
+import { resolveCompanion } from "@/components/society/companion/appearance";
import {
MARKETPLACE_SUBMIT_URL,
+ type CommunityAgentWire,
type CommunityPluginWire,
type CommunityResponse,
type CommunitySkillWire,
@@ -59,7 +64,7 @@ import {
/** The public storefront — the same catalogue, on the web. */
const MARKETPLACE_WEB_URL = "https://github.com/PersonalJarvis/marketplace";
-type Kind = "plugin" | "skill";
+type Kind = "plugin" | "skill" | "agent";
type KindFilter = "all" | Kind | "mine";
/** One entry of any kind, flattened into what the storefront draws. */
@@ -95,12 +100,15 @@ interface Entry {
seedConflict?: boolean;
/** Skills only: a portable Agent Skill states the agents it also runs in. */
portableAgents?: string[] | null;
+ /** Agents only: the template the install turns into a new teammate. */
+ agent?: AgentTemplateWire | null;
}
/** Where an installed entry of this kind now lives in the app. */
const HOME_SECTION: Record<Kind, SectionId> = {
plugin: "plugins",
skill: "skills",
+ agent: "agents",
};
function pluginEntry(p: CommunityPluginWire): Entry {
@@ -142,6 +150,33 @@ function skillEntry(s: CommunitySkillWire): Entry {
};
}
+function agentEntry(a: CommunityAgentWire): Entry {
+ return {
+ kind: "agent",
+ name: a.name,
+ title: a.title || a.name,
+ description: a.description ?? "",
+ publisher: a.publisher,
+ version: a.version,
+ categories: a.categories ?? [],
+ sourceUrl: a.source_url,
+ installed: Boolean(a.installed),
+ broken: !a.valid,
+ problem: a.error ?? null,
+ agent: a.agent,
+ };
+}
+
+/** The agent's own symbol, from the look its template carries. */
+function AgentTile({ entry }: { entry: Entry }) {
+ const appearance = resolveCompanion(entry.agent?.name || entry.name, entry.agent?.avatar?.companion);
+ return (
+ <div className="grid h-10 w-10 shrink-0 place-items-center rounded-lg bg-secondary">
+ <AgentSymbol {...appearance} size={30} />
+ </div>
+ );
+}
+
function matches(entry: Entry, needle: string): boolean {
if (!needle) return true;
const hay = [
@@ -235,6 +270,36 @@ export function MarketplaceView() {
queryClient.invalidateQueries({ queryKey: ["marketplace-community"] });
queryClient.invalidateQueries({ queryKey: ["marketplace-plugins"] });
queryClient.invalidateQueries({ queryKey: ["skills"] });
+ queryClient.invalidateQueries({ queryKey: ["society", "roster"] });
+ },
+ });
+
+ // An exported template from somebody else: installed straight from the file.
+ const importAgent = useMutation({
+ mutationFn: async (file: File): Promise<InstallResultWire> => {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(await readFileText(file));
+ } catch {
+ 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,
+ };
+ } catch (err) {
+ throw new Error(fill(t("marketplace.import_failed"), { error: (err as Error).message }));
+ }
+ },
+ onSuccess: (result) => {
+ setLanding(result);
+ queryClient.invalidateQueries({ queryKey: ["society", "roster"] });
+ queryClient.invalidateQueries({ queryKey: ["marketplace-community"] });
},
});
@@ -243,6 +308,7 @@ export function MarketplaceView() {
return [
...(data.plugins ?? []).map(pluginEntry),
...(data.skills ?? []).map(skillEntry),
+ ...(data.agents ?? []).map(agentEntry),
];
}, [data]);
@@ -264,6 +330,7 @@ export function MarketplaceView() {
const plugins = visible.filter((e) => e.kind === "plugin");
const skills = visible.filter((e) => e.kind === "skill");
+ const agents = visible.filter((e) => e.kind === "agent");
const status = data?.status;
const offline = status === "stale" || status === "unavailable";
@@ -335,6 +402,7 @@ export function MarketplaceView() {
all: entries.length,
plugin: entries.filter((e) => e.kind === "plugin").length,
skill: entries.filter((e) => e.kind === "skill").length,
+ agent: entries.filter((e) => e.kind === "agent").length,
mine: mineCount,
}}
showMine={login !== null}
@@ -425,10 +493,28 @@ export function MarketplaceView() {
</Shelf>
)}
+ {agents.length > 0 && (
+ <Shelf
+ title={t("marketplace.shelf_agents")}
+ hint={t("marketplace.shelf_agents_hint")}
+ count={agents.length}
+ >
+ <EntryList
+ entries={agents}
+ onOpen={setOpenEntry}
+ icon={(entry) => <AgentTile entry={entry} />}
+ t={t}
+ />
+ </Shelf>
+ )}
+
{!isLoading && !error && (
<PublishFooter
enabled={publishEnabled}
onPublish={() => setStudioOpen(true)}
+ onImport={(file) => importAgent.mutate(file)}
+ importing={importAgent.isPending}
+ importError={importAgent.error ? (importAgent.error as Error).message : null}
t={t}
/>
)}
@@ -465,7 +551,8 @@ function subtitleFor(
if (loading) return t("marketplace.loading");
if (!data) return "";
if (data.status === "disabled") return t("marketplace.status_disabled");
- const total = (data.plugins?.length ?? 0) + (data.skills?.length ?? 0);
+ const total =
+ (data.plugins?.length ?? 0) + (data.skills?.length ?? 0) + (data.agents?.length ?? 0);
const parts = [fill(t("marketplace.subtitle_count"), { count: total })];
if (data.revision != null) {
parts.push(fill(t("marketplace.subtitle_revision"), { revision: data.revision }));
@@ -501,6 +588,7 @@ function FilterChips({
{ id: "all", label: t("marketplace.filter_all") },
{ id: "plugin", label: t("marketplace.filter_plugins") },
{ id: "skill", label: t("marketplace.filter_skills") },
+ { id: "agent", label: t("marketplace.filter_agents") },
];
if (showMine) chips.push({ id: "mine", label: t("marketplace.filter_mine") });
return (
@@ -705,6 +793,7 @@ function Hero({
const counts = {
plugins: data?.plugins?.length ?? 0,
skills: data?.skills?.length ?? 0,
+ agents: data?.agents?.length ?? 0,
};
return (
<section
@@ -744,9 +833,10 @@ function Hero({
)}
</div>
</div>
- <dl className="grid grid-cols-2 gap-3 sm:gap-4">
+ <dl className="grid grid-cols-3 gap-3 sm:gap-4">
<Stat value={counts.plugins} label={t("marketplace.filter_plugins")} />
<Stat value={counts.skills} label={t("marketplace.filter_skills")} />
+ <Stat value={counts.agents} label={t("marketplace.filter_agents")} />
</dl>
</div>
</section>
@@ -767,16 +857,57 @@ function Stat({ value, label }: { value: number; label: string }) {
function PublishFooter({
enabled,
onPublish,
+ onImport,
+ importing,
+ importError,
t,
}: {
enabled: boolean;
onPublish: () => void;
+ onImport: (file: File) => void;
+ importing: boolean;
+ importError: string | null;
t: Translate;
}) {
+ const fileInput = useRef<HTMLInputElement | null>(null);
return (
<div className="mt-10 flex flex-wrap items-center justify-between gap-3 rounded-xl border border-dashed border-border bg-card px-4 py-3 backdrop-blur-sm">
- <p className="text-xs text-muted-foreground">{t("marketplace.publish_hint")}</p>
+ <div className="min-w-0 flex-1">
+ <p className="text-xs text-muted-foreground">{t("marketplace.publish_hint")}</p>
+ {importError && (
+ <p role="alert" className="mt-1 flex items-start gap-1.5 text-xs text-destructive">
+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
+ {importError}
+ </p>
+ )}
+ </div>
<div className="flex items-center gap-2">
+ <input
+ ref={fileInput}
+ type="file"
+ accept=".json,application/json"
+ className="hidden"
+ data-testid="marketplace-import-agent-input"
+ onChange={(event) => {
+ const file = event.target.files?.[0];
+ event.target.value = "";
+ if (file) onImport(file);
+ }}
+ />
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => fileInput.current?.click()}
+ disabled={importing}
+ data-testid="marketplace-import-agent"
+ >
+ {importing ? (
+ <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <FileInput className="mr-1.5 h-3.5 w-3.5" />
+ )}
+ {t("marketplace.import_agent")}
+ </Button>
<Button
variant="ghost"
size="sm"
@@ -998,7 +1129,7 @@ function EntryDrawer({
* not tell anybody where their data ends up.
*/
function Destination({ entry, t }: { entry: Entry; t: Translate }) {
- const rows: { label: string; value?: string; code?: string }[] = [];
+ const rows: { label: string; value?: string; code?: string; text?: string }[] = [];
if (entry.kind === "plugin") {
const mcp = entry.mcp;
@@ -1016,6 +1147,21 @@ function Destination({ entry, t }: { entry: Entry; t: Translate }) {
if (auth) rows.push({ label: t("marketplace.sign_in_method"), value: auth });
}
+ if (entry.kind === "agent" && entry.agent) {
+ rows.push({ label: t("marketplace.agent_model") });
+ if (entry.agent.focus.length > 0) {
+ rows.push({ label: t("marketplace.agent_focus"), value: entry.agent.focus.join(", ") });
+ }
+ rows.push({
+ label: t("marketplace.agent_asks"),
+ value:
+ entry.agent.require_approval.length > 0
+ ? entry.agent.require_approval.join(", ")
+ : t("marketplace.agent_asks_default"),
+ });
+ rows.push({ label: t("marketplace.agent_instructions"), text: entry.agent.instructions });
+ }
+
if (entry.portableAgents) {
rows.push({
label: t("marketplace.portable_skill"),
@@ -1045,6 +1191,11 @@ function Destination({ entry, t }: { entry: Entry; t: Translate }) {
</code>
)}
{row.value && <p className="text-xs text-muted-foreground">{row.value}</p>}
+ {row.text && (
+ <p className="max-h-56 overflow-auto whitespace-pre-wrap rounded-md border border-border bg-background px-3 py-2 text-xs leading-relaxed text-foreground">
+ {row.text}
+ </p>
+ )}
</div>
))}
</div>
diff --git a/jarvis/ui/web/frontend/src/views/PluginsCommunity.tsx b/jarvis/ui/web/frontend/src/views/PluginsCommunity.tsx
index fd13a9c7bb..4f1ea64b5c 100644
--- a/jarvis/ui/web/frontend/src/views/PluginsCommunity.tsx
+++ b/jarvis/ui/web/frontend/src/views/PluginsCommunity.tsx
@@ -18,6 +18,7 @@ import { installBlock } from "@/lib/installStandard";
import { openExternalUrl } from "@/lib/openExternal";
import { PRODUCT_NAME } from "@/lib/branding";
import { useEventStore } from "@/store/events";
+import type { AgentTemplateWire } from "@/lib/agentShare";
// ---------------------------------------------------------------------------
// Community marketplace tab.
@@ -91,12 +92,31 @@ function portableNote(skill: CommunitySkillWire): string | null {
: "Portable skill · also runs in other agents";
}
+/** A published agent template (see jarvis/society/agent_template.py). */
+export interface CommunityAgentWire {
+ name: string;
+ title: string;
+ description: string;
+ publisher?: string | null;
+ version?: string | null;
+ published_at?: string | null;
+ categories: string[];
+ source_url?: string | null;
+ agent: AgentTemplateWire;
+ /** The install would accept it (the same rule the install applies). */
+ valid: boolean;
+ error?: string | null;
+ installed: boolean;
+}
+
export interface CommunityResponse {
status: "fresh" | "fetched" | "stale" | "unavailable" | "disabled";
revision?: number | null;
generated_at?: string | null;
plugins: CommunityPluginWire[];
skills: CommunitySkillWire[];
+ /** Absent from a backend older than agent templates. */
+ agents?: CommunityAgentWire[];
}
/** One readable file of a published entry — mirrors ``_text_file`` server-side. */
diff --git a/jarvis/ui/web/marketplace_publish_routes.py b/jarvis/ui/web/marketplace_publish_routes.py
index 206e20073b..3dd29170fe 100644
--- a/jarvis/ui/web/marketplace_publish_routes.py
+++ b/jarvis/ui/web/marketplace_publish_routes.py
@@ -6,7 +6,7 @@ Endpoints:
GET /api/marketplace/publish/signin/poll/{id} — poll until approved
DELETE /api/marketplace/publish/identity — sign out (drop token)
POST /api/marketplace/publish/validate — field-level pre-check
- POST /api/marketplace/publish/submit — publish (opens the bot PR)
+ POST /api/marketplace/publish/submit — publish (files the intake issue)
GET /api/marketplace/publish/status — is name@version live in the feed
The heavy lifting lives in ``jarvis/marketplace/publish.py``; this layer only
@@ -63,10 +63,10 @@ async def _complete_signin(handler: Any, session: Any) -> dict[str, Any]:
@router.get("/identity", openapi_extra={"x-jarvis-readonly": True})
async def publish_identity(response: Response) -> dict[str, Any]:
"""Signed-in state, plus whether publishing is enabled at all."""
- from jarvis.marketplace.publish import current_identity, publish_endpoint
+ from jarvis.marketplace.publish import current_identity, publishing_enabled
response.headers["Cache-Control"] = "no-store"
- enabled = bool(publish_endpoint())
+ enabled = publishing_enabled()
if not enabled:
return {"enabled": False, "signed_in": False}
try:
@@ -88,9 +88,9 @@ async def publish_identity(response: Response) -> dict[str, Any]:
@router.post("/signin/start")
async def signin_start() -> dict[str, Any]:
"""Begin the device flow: returns the user code to type at GitHub."""
- from jarvis.marketplace.publish import make_device_handler, publish_endpoint
+ from jarvis.marketplace.publish import make_device_handler, publishing_enabled
- if not publish_endpoint():
+ if not publishing_enabled():
raise HTTPException(status_code=503, detail="publishing is disabled in this deployment")
_sweep_finished_flows()
handler = make_device_handler()
@@ -180,6 +180,9 @@ class SubmissionDraft(BaseModel):
# (publishing-plan.md §3). Kept loose on purpose — `validate_draft`
# delegates to the installer's own rules, which are the authority.
skills: list[dict[str, Any]] | None = None
+ # An agent template rides as one object (kind="agent"); the rules live in
+ # jarvis/society/agent_template.py, which validate_draft delegates to.
+ agent: dict[str, Any] | None = None
@router.post("/validate", openapi_extra={"x-jarvis-readonly": True})
@@ -197,7 +200,8 @@ async def validate(body: SubmissionDraft) -> dict[str, Any]:
# the view's explicit Publish click.
@router.post("/submit", openapi_extra={"x-jarvis-dangerous": True})
async def submit(body: SubmissionDraft) -> dict[str, Any]:
- """Validate, then POST to the storefront endpoint as the signed-in user."""
+ """Validate, then file the submission as the signed-in user (intake issue,
+ or a configured endpoint)."""
from jarvis.marketplace.publish import SubmitError, validate_draft
from jarvis.marketplace.publish import submit as do_submit
@@ -220,7 +224,7 @@ async def submit(body: SubmissionDraft) -> dict[str, Any]:
# is live — the view only shows it after the registry confirms that.
from jarvis.marketplace.install_standard import install_block
- kind: Literal["plugin", "skill"] = "skill" if normalized["kind"] == "skill" else "plugin"
+ kind: Literal["plugin", "skill", "agent"] = normalized["kind"]
return {
"ok": True,
"name": normalized["name"],
diff --git a/jarvis/ui/web/marketplace_routes.py b/jarvis/ui/web/marketplace_routes.py
index 3d4b421312..425ea50214 100644
--- a/jarvis/ui/web/marketplace_routes.py
+++ b/jarvis/ui/web/marketplace_routes.py
@@ -1038,7 +1038,9 @@ async def disconnect(plugin_id: str, request: Request) -> dict[str, Any]:
# ----------------------------------------------------------------------
-def _community_payload(index: Any, status: str) -> dict[str, Any]:
+def _community_payload(
+ index: Any, status: str, installed_agents: frozenset[str] = frozenset()
+) -> dict[str, Any]:
"""Convert a fetched index into the wire shape the Plugins view renders.
Every plugin entry is run through the SAME converter the install path
@@ -1058,6 +1060,7 @@ def _community_payload(index: Any, status: str) -> dict[str, Any]:
plugins: list[dict[str, Any]] = []
skills: list[dict[str, Any]] = []
+ agents: list[dict[str, Any]] = []
if index is not None:
for entry in index.plugins:
base = {
@@ -1118,33 +1121,73 @@ def _community_payload(index: Any, status: str) -> dict[str, Any]:
}
)
+ from jarvis.society.agent_template import validate_template
+
+ for agent_entry in index.agents:
+ template = agent_entry.agent
+ problems = validate_template(template)
+ name = str(template.get("name") or "") if isinstance(template, dict) else ""
+ agents.append(
+ {
+ "name": agent_entry.name,
+ "title": agent_entry.title or agent_entry.name,
+ "description": agent_entry.description,
+ "publisher": agent_entry.publisher,
+ "version": agent_entry.version,
+ "published_at": agent_entry.published_at,
+ "categories": list(agent_entry.categories),
+ "source_url": agent_entry.source_url,
+ "agent": template,
+ # Same rule the install applies, so a card never offers a
+ # button the install would refuse.
+ "valid": not problems,
+ "error": problems[0] if problems else None,
+ "installed": name.strip().lower() in installed_agents,
+ }
+ )
+
return {
"status": status,
"revision": getattr(index, "revision", None),
"generated_at": getattr(index, "generated_at", None),
"plugins": plugins,
"skills": skills,
+ "agents": agents,
}
+def _installed_agent_names(request: Request) -> frozenset[str]:
+ """Names on this install's roster, from the runtime's in-memory snapshot.
+
+ No IO and no runtime start: browsing the store must not boot the society.
+ Before the society first ran, nothing is marked installed — the honest
+ answer the moment it cannot know.
+ """
+ runtime = getattr(request.app.state, "society", None)
+ roster = getattr(runtime, "roster", None)
+ if roster is None:
+ return frozenset()
+ return frozenset(agent.name.strip().lower() for agent in roster.snapshot())
+
+
@router.get("/community", openapi_extra={"x-jarvis-readonly": True})
-async def community_browse(response: Response) -> dict[str, Any]:
+async def community_browse(request: Request, response: Response) -> dict[str, Any]:
"""The community index (TTL-cached fetch), enriched with install state."""
from jarvis.marketplace import community_source
response.headers["Cache-Control"] = "no-store"
index, status = await community_source.get_index()
- return _community_payload(index, status)
+ return _community_payload(index, status, _installed_agent_names(request))
@router.post("/community/refresh")
-async def community_refresh(response: Response) -> dict[str, Any]:
+async def community_refresh(request: Request, response: Response) -> dict[str, Any]:
"""Force a re-fetch of the community index, bypassing the TTL."""
from jarvis.marketplace import community_source
response.headers["Cache-Control"] = "no-store"
index, status = await community_source.get_index(force=True)
- return _community_payload(index, status)
+ return _community_payload(index, status, _installed_agent_names(request))
# ----------------------------------------------------------------------
@@ -1554,13 +1597,46 @@ async def _announce_install(request: Request, result: dict[str, Any]) -> None:
log.debug("MarketplaceItemInstalled publish failed: %s", exc)
+async def _install_community_agent(entry: Any, request: Request) -> dict[str, Any]:
+ """A published agent template becomes a NEW teammate on this install.
+
+ The template's own rules decide (``jarvis.society.agent_template``); the
+ agent runs on this person's model, never the publisher's, and asks before
+ it acts where its runner can.
+ """
+ from .society_routes import install_template
+
+ installed = await install_template(entry.agent, request)
+ agent = installed["agent"]
+ return {
+ "ok": True,
+ "kind": "agent",
+ "id": agent.get("agent_id", entry.name),
+ "title": agent.get("name") or entry.title or entry.name,
+ "publisher": entry.publisher,
+ "version": entry.version,
+ "source_url": entry.source_url,
+ "location": "",
+ "state": "installed",
+ "ready": True,
+ "problem": None,
+ "next_action": "open",
+ "renamed_from": installed.get("renamed_from"),
+ "agent": agent,
+ }
+
+
def _install_by_name_404(item_id: str, index: Any) -> HTTPException:
"""404 that names the closest existing entry instead of a dead end."""
import difflib
names: list[str] = []
if index is not None:
- names = [e.name for e in index.plugins] + [s.name for s in index.skills]
+ names = (
+ [e.name for e in index.plugins]
+ + [s.name for s in index.skills]
+ + [a.name for a in index.agents]
+ )
close = difflib.get_close_matches(item_id, names, n=1, cutoff=0.6)
hint = f" Closest match: {close[0]!r}." if close else ""
return HTTPException(
@@ -1571,7 +1647,7 @@ def _install_by_name_404(item_id: str, index: Any) -> HTTPException:
@router.post("/community/install/{item_id}")
async def community_install_by_name(item_id: str, request: Request) -> dict[str, Any]:
- """Install a marketplace entry by name — skill or plugin, one call.
+ """Install a marketplace entry by name — skill, plugin or agent, one call.
The one-liner a downloader copies off a marketplace page
(``jarvis marketplace install <name>``) never says which of the two an
@@ -1583,14 +1659,17 @@ async def community_install_by_name(item_id: str, request: Request) -> dict[str,
from jarvis.marketplace import community_source
index, _ = await community_source.get_index()
- plugin_entry = skill_entry = None
+ plugin_entry = skill_entry = agent_entry = None
if index is not None:
plugin_entry = next((e for e in index.plugins if e.name == item_id), None)
skill_entry = next((s for s in index.skills if s.name == item_id), None)
- if plugin_entry is None and skill_entry is None:
+ agent_entry = next((a for a in index.agents if a.name == item_id), None)
+ if plugin_entry is None and skill_entry is None and agent_entry is None:
raise _install_by_name_404(item_id, index)
- if skill_entry is not None:
+ if agent_entry is not None:
+ result = await _install_community_agent(agent_entry, request)
+ elif skill_entry is not None:
result = await _install_community_skill(skill_entry, request)
else:
item = await _install_community_plugin(item_id)
diff --git a/jarvis/ui/web/society_routes.py b/jarvis/ui/web/society_routes.py
index 570b943521..4e8b857184 100644
--- a/jarvis/ui/web/society_routes.py
+++ b/jarvis/ui/web/society_routes.py
@@ -1634,6 +1634,185 @@ async def memory_file(request: Request, path: str = "") -> dict[str, Any]:
}
+# ---------------------------------------------------------------- templates
+#
+# Share an agent as a template, and install one somebody else shared
+# (docs/marketplace/agent-templates.md). The template is always BUILT here from
+# the roster row plus the person's public-version edits — the view never sends
+# a template of its own to publish, so what leaves the machine is exactly what
+# the scrubber in jarvis/society/agent_template.py let through.
+
+
+class ShareDraftBody(BaseModel):
+ """Edits to the public version. ``None`` keeps a field; ``reset`` drops all."""
+
+ summary: str | None = Field(default=None, max_length=500)
+ instructions: str | None = Field(default=None, max_length=20_000)
+ title: str | None = Field(default=None, max_length=120)
+ categories: list[str] | None = Field(default=None, max_length=10)
+ listing_name: str | None = Field(default=None, max_length=64)
+ version: str | None = Field(default=None, max_length=32)
+ reset: bool = False
+
+
+class InstallTemplateBody(BaseModel):
+ template: dict[str, Any]
+
+
+async def _share_draft(rt: SocietyRuntime, agent_id: str) -> tuple[AgentRecord, Any]:
+ from jarvis.society.agent_template import TemplateError, build_draft, load_overlay
+
+ agent = await rt.roster.resolve(agent_id)
+ if agent is None:
+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)})
+ try:
+ return agent, build_draft(agent, load_overlay(rt.data_dir, agent.agent_id))
+ except TemplateError as exc:
+ raise HTTPException(409, {"reason": "not_shareable", "detail": str(exc)}) from exc
+
+
+def _draft_payload(draft: Any) -> dict[str, Any]:
+ from jarvis.society.agent_template import validate_template
+
+ payload: dict[str, Any] = draft.to_dict()
+ payload["errors"] = validate_template(draft.template, draft.listing)
+ return payload
+
+
[email protected]("/agents/{agent_id}/template", openapi_extra={"x-jarvis-readonly": True})
+async def get_share_template(agent_id: str, request: Request) -> dict[str, Any]:
+ """The agent's shareable template: what would be published, and what was cut."""
+ rt = await _runtime(request)
+ _, draft = await _share_draft(rt, agent_id)
+ return _draft_payload(draft)
+
+
[email protected]("/agents/{agent_id}/template")
+async def save_share_template(
+ agent_id: str, body: ShareDraftBody, request: Request
+) -> dict[str, Any]:
+ """Save edits to the public version (never touches the agent itself)."""
+ from jarvis.society.agent_template import load_overlay, save_overlay
+
+ rt = await _runtime(request)
+ agent, _ = await _share_draft(rt, agent_id)
+ if body.reset:
+ # Back to the agent's own text; what was published stays on record.
+ current = load_overlay(rt.data_dir, agent.agent_id)
+ changes: dict[str, Any] = {k: None for k in current if k != "published"}
+ else:
+ changes = body.model_dump(exclude_none=True, exclude={"reset"})
+ # A person editing the text takes it over from the agent's polish.
+ if changes:
+ changes["polished_by"] = None
+ save_overlay(rt.data_dir, agent.agent_id, changes)
+ _, draft = await _share_draft(rt, agent.agent_id)
+ return _draft_payload(draft)
+
+
+# Dangerous: publishes the agent's design publicly under the user's GitHub name.
[email protected]("/agents/{agent_id}/template/publish", openapi_extra={"x-jarvis-dangerous": True})
+async def publish_share_template(agent_id: str, request: Request) -> dict[str, Any]:
+ """Publish the current draft to the community marketplace as the signed-in user."""
+ from jarvis.marketplace.install_standard import install_block
+ from jarvis.marketplace.publish import SubmitError, submit, validate_draft
+ from jarvis.society.agent_template import save_overlay, submission
+
+ rt = await _runtime(request)
+ agent, draft = await _share_draft(rt, agent_id)
+ normalized, errors = validate_draft(submission(draft.template, draft.listing))
+ if normalized is None:
+ first = errors[0]
+ raise HTTPException(
+ 422, {"error": first["error"], "field": first["field"], "errors": errors}
+ )
+ try:
+ result = await submit(normalized)
+ except SubmitError as exc:
+ raise HTTPException(exc.status, {"error": exc.error, "field": exc.field}) from exc
+ published = {
+ "name": normalized["name"],
+ "version": normalized["version"],
+ "url": result.get("issue_url") or result.get("pr_url"),
+ }
+ # The next share starts from the next version; the summary/text edits stay.
+ save_overlay(rt.data_dir, agent.agent_id, {"published": published, "version": None})
+ return {
+ "ok": True,
+ **published,
+ "install": install_block(normalized["name"], "agent"),
+ **result,
+ }
+
+
+async def _free_agent_name(rt: SocietyRuntime, wanted: str) -> str:
+ """``wanted``, or ``wanted 2``, ``wanted 3`` … — the first name not taken.
+
+ The roster ADOPTS an existing name instead of minting a second agent, so
+ installing "Inbox Butler" twice would silently hand back the first one.
+ """
+ base = wanted.strip()[:37].rstrip() or "Agent"
+ candidate = wanted.strip()[:40]
+ for number in range(2, 100):
+ if await rt.roster.resolve(candidate) is None:
+ return candidate
+ candidate = f"{base} {number}"
+ raise HTTPException(409, {"reason": "name_taken", "detail": "pick another name"})
+
+
+async def install_template(template: dict[str, Any], request: Request) -> 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.
+ The agent asks before it acts where its runner can (``approval_mode=ask``):
+ its instructions were written by somebody else, so the person sees its
+ first moves before trusting it with more.
+ """
+ from jarvis.society.agent_template import TemplateError, create_fields
+
+ try:
+ fields = create_fields(template)
+ except TemplateError as exc:
+ raise HTTPException(422, {"reason": "invalid_template", "detail": str(exc)}) from exc
+ rt = await _runtime(request)
+ wanted = fields.pop("name")
+ name = await _free_agent_name(rt, wanted)
+ scope = template.get("knowledge_scope", "shared")
+ body = CreateAgentBody(name=name, approval_mode="ask", **fields)
+ try:
+ created = await create_agent(body, request)
+ except HTTPException as exc:
+ if exc.status_code != 422:
+ raise
+ # This runner cannot hold an approval prompt: the app's default applies.
+ body = CreateAgentBody(name=name, **fields)
+ created = await create_agent(body, request)
+ agent_row = created["agent"]
+ if scope == "own" and agent_row.get("knowledge_scope") != "own":
+ try:
+ updated = await rt.roster.update(agent_row["agent_id"], {"knowledge_scope": "own"})
+ except RosterError as exc:
+ raise _typed_error(exc) from exc
+ agent_row = updated.to_dict()
+ return {
+ "agent": agent_row,
+ "created": bool(created.get("created")),
+ "renamed_from": wanted if name != wanted else None,
+ "readback": created.get("readback", {}),
+ }
+
+
[email protected]("/templates/install")
+async def install_template_route(body: InstallTemplateBody, request: Request) -> dict[str, Any]:
+ """Create a new agent from an agent template (an exported file, pasted JSON)."""
+ template = body.template
+ # Accept a whole marketplace submission as well as the bare template: a
+ # person importing what somebody posted will paste either.
+ if template.get("kind") == "agent" and isinstance(template.get("agent"), dict):
+ template = template["agent"]
+ return await install_template(template, request)
+
+
# ----------------------------------------------------------------- controls
diff --git a/tests/contract/test_agent_mcp_harmony.py b/tests/contract/test_agent_mcp_harmony.py
index d7243aa47d..314b512b23 100644
--- a/tests/contract/test_agent_mcp_harmony.py
+++ b/tests/contract/test_agent_mcp_harmony.py
@@ -48,6 +48,20 @@ COVERED: Final[dict[str, str]] = {
#: REST route -> why an MCP client does not get it. Each line is a decision.
WITHHELD: Final[dict[str, str]] = {
+ "GET /api/society/agents/{agent_id}/template": (
+ "the share draft is read in the owner's Share sheet; a remote client has "
+ "ecosystem_export for the design of the whole team"
+ ),
+ "PUT /api/society/agents/{agent_id}/template": (
+ "editing the public version of an agent is the owner's decision at their keyboard"
+ ),
+ "POST /api/society/agents/{agent_id}/template/publish": (
+ "publishing goes out under the owner's GitHub name — never from a remote client"
+ ),
+ "POST /api/society/templates/install": (
+ "installing a stranger's template is a consent decision made in the app, "
+ "where the instructions are on screen first"
+ ),
"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/contract/test_agent_template_share.py b/tests/contract/test_agent_template_share.py
new file mode 100644
index 0000000000..c090f52d29
--- /dev/null
+++ b/tests/contract/test_agent_template_share.py
@@ -0,0 +1,153 @@
+"""Share an agent, publish it, install it elsewhere — headless, no keys, no network.
+
+The round trip a person makes: the Share sheet reads the scrubbed template,
+saves edits, publishes (the GitHub call is faked), and a second install
+creates a NEW teammate from the published template — on its own model, with
+nothing of the author's machine attached.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.marketplace import publish
+from jarvis.society.runtime import SocietyRuntime
+from jarvis.ui.web.society_routes import router
+
+SECRET = "ghp_" + "A1b2C3d4E5f6G7h8I9j0K1l2M3n4"
+
+
+def _app(tmp_path: Path) -> tuple[FastAPI, SocietyRuntime]:
+ runtime = SocietyRuntime(tmp_path, seed_starter_team=False)
+ app = FastAPI()
+ app.include_router(router)
+ app.state.society_factory = lambda: runtime
+ return app, runtime
+
+
+def author(tmp_path: Path):
+ app, runtime = _app(tmp_path / "author")
+ with TestClient(app) as client:
+ try:
+ created = client.post(
+ "/api/society/agents",
+ json={
+ "name": "Release Scribe",
+ "title": "Writes the release notes",
+ "description": (
+ "Collect merged pull requests and write release notes.\n"
+ f"Use the token {SECRET} and mail drafts to [email protected]."
+ ),
+ "account_id": "seat-1",
+ "daily_budget_usd": 40,
+ "approval_rules": {
+ "require_approval": ["plugin:github:merge"],
+ "always_allow": ["core:shell"],
+ },
+ },
+ )
+ assert created.status_code == 200, created.text
+ yield client, created.json()["agent"]["agent_id"]
+ finally:
+ client.portal.call(runtime.close)
+
+
+def test_share_sheet_shows_the_scrubbed_template(author) -> None:
+ client, agent_id = author
+ body = client.get(f"/api/society/agents/{agent_id}/template").json()
+ template = body["template"]
+ assert SECRET not in str(body)
+ assert "[email protected]" not in str(body)
+ assert {f["kind"] for f in body["findings"]} == {"secret", "email"}
+ assert "seat-1" not in str(template)
+ assert template["require_approval"] == ["plugin:github:merge"]
+ assert body["submission"]["kind"] == "agent"
+ assert body["listing"]["name"] == "release-scribe"
+ assert body["errors"] == []
+
+
+def test_edits_save_and_reset(author) -> None:
+ client, agent_id = author
+ url = f"/api/society/agents/{agent_id}/template"
+ edited = client.put(url, json={"summary": "Turns merged PRs into notes.", "version": "2.0.0"})
+ assert edited.status_code == 200, edited.text
+ assert edited.json()["listing"]["description"] == "Turns merged PRs into notes."
+ assert edited.json()["listing"]["version"] == "2.0.0"
+ reset = client.put(url, json={"reset": True}).json()
+ assert reset["listing"]["version"] == "1.0.0"
+ # The agent itself never changed.
+ agent = client.get(f"/api/society/agents/{agent_id}").json()["agent"]
+ assert SECRET in agent["description"]
+
+
+def test_publish_files_the_built_template(author, monkeypatch: pytest.MonkeyPatch) -> None:
+ client, agent_id = author
+ seen: dict[str, Any] = {}
+
+ async def fake_submit(normalized: dict[str, Any]) -> dict[str, Any]:
+ seen.update(normalized)
+ return {
+ "issue_url": "https://github.com/PersonalJarvis/marketplace/issues/7",
+ "issue_number": 7,
+ "submission_path": "submissions/release-scribe.json",
+ }
+
+ monkeypatch.setattr(publish, "submit", fake_submit)
+ resp = client.post(f"/api/society/agents/{agent_id}/template/publish")
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["install"]["cli"] == "jarvis marketplace install release-scribe"
+ assert seen["kind"] == "agent" and SECRET not in str(seen)
+ # The next share starts from the next version.
+ after = client.get(f"/api/society/agents/{agent_id}/template").json()
+ assert after["published"]["version"] == "1.0.0"
+ assert after["listing"]["version"] == "1.0.1"
+
+
+def test_the_lead_is_not_shareable(tmp_path: Path) -> None:
+ app, runtime = _app(tmp_path)
+ with TestClient(app) as client:
+ try:
+ resp = client.get("/api/society/agents/jarvis/template")
+ assert resp.status_code in (404, 409)
+ finally:
+ client.portal.call(runtime.close)
+
+
+def test_install_creates_a_new_safe_teammate(author, tmp_path: Path) -> None:
+ client, agent_id = author
+ published = client.get(f"/api/society/agents/{agent_id}/template").json()["submission"]
+
+ app, runtime = _app(tmp_path / "installer")
+ with TestClient(app) as other:
+ try:
+ first = other.post("/api/society/templates/install", json={"template": published})
+ assert first.status_code == 200, first.text
+ agent = first.json()["agent"]
+ assert agent["name"] == "Release Scribe"
+ assert agent["account_id"] == ""
+ assert agent["daily_budget_usd"] == 2.0
+ assert agent["approval_rules"]["always_allow"] == []
+ assert agent["approval_rules"]["require_approval"] == ["plugin:github:merge"]
+ assert agent["approval_mode"] in ("ask", "bypass")
+ assert SECRET not in agent["description"]
+
+ second = other.post(
+ "/api/society/templates/install", json={"template": published["agent"]}
+ )
+ assert second.status_code == 200, second.text
+ assert second.json()["agent"]["name"] == "Release Scribe 2"
+ assert second.json()["renamed_from"] == "Release Scribe"
+
+ bad = other.post(
+ "/api/society/templates/install",
+ json={"template": {**published["agent"], "approval_mode": "bypass"}},
+ )
+ assert bad.status_code == 422
+ finally:
+ other.portal.call(runtime.close)
diff --git a/tests/unit/marketplace/test_community_agents.py b/tests/unit/marketplace/test_community_agents.py
new file mode 100644
index 0000000000..359f785e18
--- /dev/null
+++ b/tests/unit/marketplace/test_community_agents.py
@@ -0,0 +1,111 @@
+"""Agent templates in the community feed: browse, read, install by name.
+
+Runs against the real marketplace + society routers with a pre-seeded index
+cache and the society data in tmp. The network is never touched.
+"""
+
+from __future__ import annotations
+
+import json
+import time
+from pathlib import Path
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.marketplace import catalog_data, community_source
+from jarvis.society.runtime import SocietyRuntime
+from jarvis.ui.web.marketplace_routes import router as market_router
+from jarvis.ui.web.society_routes import router as society_router
+
+TEMPLATE = {
+ "schema": 1,
+ "name": "Inbox Butler",
+ "title": "Keeps the inbox at zero",
+ "instructions": "Sort new mail into Action, Waiting and Read later.",
+ "tier": "specialist",
+ "focus": ["plugin:gmail"],
+ "require_approval": ["plugin:gmail:send"],
+}
+
+
+def _index() -> dict[str, Any]:
+ return {
+ "revision": 3,
+ "plugins": [],
+ "skills": [],
+ "agents": [
+ {
+ "name": "inbox-butler",
+ "title": "Inbox Butler",
+ "description": "Sorts the inbox and drafts the answers.",
+ "publisher": "octocat",
+ "publisher_id": 583231,
+ "version": "1.0.0",
+ "categories": ["email"],
+ "source_url": "https://github.com/PersonalJarvis/marketplace/tree/main/agents/x",
+ "agent": TEMPLATE,
+ },
+ {
+ "name": "sneaky",
+ "title": "Sneaky",
+ "description": "Wants to skip every confirmation.",
+ "version": "1.0.0",
+ "agent": {**TEMPLATE, "name": "Sneaky", "approval_mode": "bypass"},
+ },
+ {"name": "../../evil", "agent": TEMPLATE},
+ ],
+ }
+
+
+def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ cache = tmp_path / "marketplace_index.json"
+ cache.write_text(json.dumps({"fetched_at": time.time(), "index": _index()}), encoding="utf-8")
+ monkeypatch.setattr(community_source, "_CACHE_PATH", cache)
+ monkeypatch.setattr(community_source, "index_url", lambda: "https://reg.example/index.json")
+ monkeypatch.setattr(catalog_data, "_DEFAULT_CATALOG_PATH", tmp_path / "plugin_catalog.json")
+ catalog_data.clear_cache()
+ runtime = SocietyRuntime(tmp_path / "society", seed_starter_team=False)
+ app = FastAPI()
+ app.include_router(market_router)
+ app.include_router(society_router)
+ app.state.society_factory = lambda: runtime
+ with TestClient(app) as test_client:
+ try:
+ yield test_client
+ finally:
+ test_client.portal.call(runtime.close)
+ catalog_data.clear_cache()
+
+
+def test_browse_lists_agents_and_marks_the_unsafe_one(client: TestClient) -> None:
+ agents = client.get("/api/marketplace/community").json()["agents"]
+ by_name = {a["name"]: a for a in agents}
+ assert set(by_name) == {"inbox-butler", "sneaky"} # the path-shaped name is dropped
+ assert by_name["inbox-butler"]["valid"] is True
+ assert by_name["inbox-butler"]["installed"] is False
+ assert by_name["sneaky"]["valid"] is False
+ assert "approval_mode" in by_name["sneaky"]["error"]
+
+
+def test_install_by_name_adds_a_teammate(client: TestClient) -> None:
+ resp = client.post("/api/marketplace/community/install/inbox-butler")
+ assert resp.status_code == 200, resp.text
+ result = resp.json()
+ assert result["kind"] == "agent" and result["ready"] is True
+ assert result["agent"]["name"] == "Inbox Butler"
+ roster = client.get("/api/society/agents").json()["agents"]
+ assert any(a["name"] == "Inbox Butler" for a in roster)
+ # The roster snapshot now marks it installed in the store.
+ agents = client.get("/api/marketplace/community").json()["agents"]
+ assert next(a for a in agents if a["name"] == "inbox-butler")["installed"] is True
+
+
+def test_an_unsafe_template_never_installs(client: TestClient) -> None:
+ resp = client.post("/api/marketplace/community/install/sneaky")
+ assert resp.status_code == 422
+ roster = client.get("/api/society/agents").json()["agents"]
+ assert not any(a["name"] == "Sneaky" for a in roster)
diff --git a/tests/unit/marketplace/test_publish.py b/tests/unit/marketplace/test_publish.py
index 141034485e..664e312387 100644
--- a/tests/unit/marketplace/test_publish.py
+++ b/tests/unit/marketplace/test_publish.py
@@ -435,6 +435,7 @@ async def test_submit_passes_endpoint_refusal_through(monkeypatch: pytest.Monkey
@pytest.mark.asyncio
async def test_submit_disabled_deployment(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(publish, "publish_endpoint", lambda: "")
+ monkeypatch.setattr(publish, "registry_repo", lambda: "")
value, _ = publish.validate_draft(_skill_draft())
assert value is not None
with pytest.raises(publish.SubmitError) as exc:
diff --git a/tests/unit/marketplace/test_publish_issue.py b/tests/unit/marketplace/test_publish_issue.py
new file mode 100644
index 0000000000..1cb3b4e759
--- /dev/null
+++ b/tests/unit/marketplace/test_publish_issue.py
@@ -0,0 +1,159 @@
+"""The issue intake path of in-app publishing (no server, no network in tests)."""
+
+from __future__ import annotations
+
+import json
+import re
+from typing import Any
+
+import httpx
+import pytest
+
+from jarvis.marketplace import publish
+from jarvis.marketplace.token_store import Tokens
+
+
+class FakeStore:
+ def __init__(self, tokens: Tokens | None) -> None:
+ self.tokens = tokens
+
+ def load(self, plugin_id: str) -> Tokens | None:
+ return self.tokens
+
+
+def _agent_submission(**overrides: Any) -> dict[str, Any]:
+ doc: dict[str, Any] = {
+ "kind": "agent",
+ "name": "inbox-butler",
+ "version": "1.0.0",
+ "title": "Inbox Butler",
+ "description": "Sorts the inbox and drafts the answers.",
+ "categories": ["email"],
+ "agent": {
+ "schema": 1,
+ "name": "Inbox Butler",
+ "title": "Keeps the inbox at zero",
+ "instructions": "Sort new mail. Never send without approval.",
+ "tier": "specialist",
+ "focus": ["plugin:gmail"],
+ },
+ }
+ doc.update(overrides)
+ return doc
+
+
+def test_agent_draft_validates() -> None:
+ value, errors = publish.validate_draft(_agent_submission())
+ assert errors == []
+ assert value is not None and value["agent"]["name"] == "Inbox Butler"
+
+
+def test_agent_draft_refuses_a_permission_widening() -> None:
+ doc = _agent_submission()
+ doc["agent"] = {**doc["agent"], "approval_mode": "bypass"}
+ value, errors = publish.validate_draft(doc)
+ assert value is None
+ assert any(e["field"] == "agent" for e in errors)
+
+
+def test_agent_draft_needs_a_summary() -> None:
+ value, errors = publish.validate_draft(_agent_submission(description=""))
+ assert value is None
+ assert any(e["field"] == "description" for e in errors)
+
+
+def test_issue_body_is_what_the_intake_reads() -> None:
+ value, _ = publish.validate_draft(_agent_submission())
+ assert value is not None
+ body = publish.issue_body(value)
+ assert publish.INTAKE_BODY_MARKER in body
+ # The registry intake's own fence pattern (scripts/intake.py).
+ fence = re.compile(r"```(?:json)?[ \t]*\r?\n(.*?)\r?\n[ \t]*```", re.DOTALL)
+ match = fence.search(body)
+ assert match is not None and json.loads(match.group(1)) == value
+ assert publish.issue_title(value).startswith(publish.INTAKE_TITLE_TAG)
+
+
+async def test_submit_opens_the_issue_as_the_user(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(publish, "publish_endpoint", lambda: "")
+ monkeypatch.setattr(publish, "registry_repo", lambda: "PersonalJarvis/marketplace")
+ seen: dict[str, Any] = {}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ seen["url"] = str(request.url)
+ seen["auth"] = request.headers.get("Authorization")
+ seen["json"] = json.loads(request.content)
+ return httpx.Response(
+ 201,
+ json={"html_url": "https://github.com/PersonalJarvis/marketplace/issues/9",
+ "number": 9},
+ )
+
+ value, _ = publish.validate_draft(_agent_submission())
+ assert value is not None
+ result = await publish.submit(
+ value,
+ store=FakeStore(Tokens(access="tok")), # type: ignore[arg-type]
+ transport=httpx.MockTransport(handler),
+ )
+ assert seen["url"] == "https://api.github.com/repos/PersonalJarvis/marketplace/issues"
+ assert seen["auth"] == "Bearer tok"
+ assert seen["json"]["title"] == "[publish] agent: inbox-butler 1.0.0"
+ assert "publisher" not in seen["json"]["body"]
+ assert result == {
+ "issue_url": "https://github.com/PersonalJarvis/marketplace/issues/9",
+ "issue_number": 9,
+ "submission_path": "submissions/inbox-butler.json",
+ }
+
+
[email protected]("status", [403, 404, 410])
+async def test_a_refused_issue_points_to_the_browser(
+ monkeypatch: pytest.MonkeyPatch, status: int
+) -> None:
+ monkeypatch.setattr(publish, "publish_endpoint", lambda: "")
+ monkeypatch.setattr(publish, "registry_repo", lambda: "PersonalJarvis/marketplace")
+ value, _ = publish.validate_draft(_agent_submission())
+ assert value is not None
+ refusal = {"message": "Resource not accessible by integration"}
+ transport = httpx.MockTransport(lambda request: httpx.Response(status, json=refusal))
+ with pytest.raises(publish.SubmitError) as exc:
+ await publish.submit(value, store=FakeStore(Tokens(access="tok")), transport=transport) # type: ignore[arg-type]
+ assert exc.value.field == "browser_fallback"
+ assert "issues/new?template=publish.yml" in exc.value.error
+ # GitHub's own body never reaches the person (AP-34).
+ assert "integration" not in exc.value.error
+
+
+async def test_an_expired_sign_in_says_so(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(publish, "publish_endpoint", lambda: "")
+ monkeypatch.setattr(publish, "registry_repo", lambda: "PersonalJarvis/marketplace")
+ value, _ = publish.validate_draft(_agent_submission())
+ assert value is not None
+ transport = httpx.MockTransport(lambda request: httpx.Response(401, json={}))
+ with pytest.raises(publish.SubmitError) as exc:
+ await publish.submit(value, store=FakeStore(Tokens(access="tok")), transport=transport) # type: ignore[arg-type]
+ assert exc.value.status == 401
+
+
+def test_registry_repo_must_look_like_owner_slash_name(monkeypatch: pytest.MonkeyPatch) -> None:
+ from types import SimpleNamespace
+
+ import jarvis.core.config as config
+
+ for raw, expected in (
+ ("PersonalJarvis/marketplace", "PersonalJarvis/marketplace"),
+ ("https://evil.example/x", ""),
+ ("", ""),
+ ):
+ monkeypatch.setattr(
+ config,
+ "load_config",
+ lambda raw=raw: SimpleNamespace(
+ marketplace=SimpleNamespace(publish_registry_repo=raw)
+ ),
+ )
+ assert publish.registry_repo() == expected
diff --git a/tests/unit/marketplace/test_publish_routes.py b/tests/unit/marketplace/test_publish_routes.py
index f02c899915..11212706dc 100644
--- a/tests/unit/marketplace/test_publish_routes.py
+++ b/tests/unit/marketplace/test_publish_routes.py
@@ -88,6 +88,7 @@ async def test_identity_reports_disabled_deployment(
client: httpx.AsyncClient, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(publish, "publish_endpoint", lambda: "")
+ monkeypatch.setattr(publish, "registry_repo", lambda: "")
async with client:
state = (await client.get("/api/marketplace/publish/identity")).json()
assert state == {"enabled": False, "signed_in": False}
diff --git a/tests/unit/society/test_agent_template.py b/tests/unit/society/test_agent_template.py
new file mode 100644
index 0000000000..76996b7202
--- /dev/null
+++ b/tests/unit/society/test_agent_template.py
@@ -0,0 +1,210 @@
+"""Agent templates: what a shared agent carries, what it never carries."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from jarvis.society.agent_template import (
+ TEMPLATE_KEYS,
+ TemplateError,
+ build_draft,
+ create_fields,
+ load_overlay,
+ public_avatar,
+ save_overlay,
+ scrub_text,
+ submission,
+ validate_template,
+)
+from jarvis.society.roster import AgentRecord
+
+SECRET = "sk-" + "a1B2c3D4e5F6g7H8i9J0k1L2m3"
+
+
+def _agent(**overrides: object) -> AgentRecord:
+ row: dict[str, object] = {
+ "agent_id": "inbox-butler",
+ "name": "Inbox Butler",
+ "title": "Keeps the inbox at zero",
+ "description": (
+ "You own the inbox of [email protected].\n\n"
+ "Sort mail into Action, Waiting and Read later. Save drafts to "
+ "C:\\Users\\ruben\\Documents\\drafts. Never send without approval."
+ ),
+ "tier": "specialist",
+ "state": "active",
+ "avatar_json": json.dumps(
+ {
+ "contract": 1,
+ "archetype": "biped",
+ "base": "rogue",
+ "parts": {"head": "hood"},
+ "palette": {"skin": "#f4b68f"},
+ "model": "/api/society/figures/mine.glb",
+ }
+ ),
+ "provider": "claude-cli",
+ "model": "claude-opus",
+ "effort": "high",
+ "account_id": "seat-artner",
+ "grant_mode": "all",
+ "grants_json": "[]",
+ "focus_json": json.dumps(["plugin:gmail", "core:browser"]),
+ "denies_json": json.dumps(["cli:gh"]),
+ "skills_json": None,
+ "workspace_dir": "society/inbox-butler/workspace",
+ "wiki_namespace": "society/inbox-butler/",
+ "knowledge_scope": "shared",
+ "permission_ceiling": "ask",
+ "approval_mode": "bypass",
+ "approval_rules_json": json.dumps(
+ {"require_approval": ["plugin:gmail:send"], "always_allow": ["core:shell"]}
+ ),
+ "daily_budget_usd": 50.0,
+ "browser_mode": "attach",
+ "browser_allowed_domains_json": json.dumps(["mail.google.com"]),
+ "max_concurrent_runs": 5,
+ "computer_id": "vps-1",
+ "created_ms": 1,
+ "updated_ms": 2,
+ }
+ row.update(overrides)
+ return AgentRecord.from_row(row)
+
+
+def test_template_is_an_allowlist_of_design_fields() -> None:
+ template = build_draft(_agent()).template
+ assert set(template) <= TEMPLATE_KEYS
+ text = json.dumps(template)
+ for leaked in (
+ "seat-artner",
+ "claude-cli",
+ "claude-opus",
+ "vps-1",
+ "attach",
+ "mail.google.com",
+ "core:shell", # an always-allow rule never travels
+ "society/inbox-butler",
+ "mine.glb",
+ ):
+ assert leaked not in text, leaked
+ assert template["require_approval"] == ["plugin:gmail:send"]
+ assert template["focus"] == ["plugin:gmail", "core:browser"]
+ assert "model" not in template["avatar"]
+
+
+def test_instructions_are_scrubbed_and_every_cut_is_listed() -> None:
+ draft = build_draft(_agent())
+ instructions = draft.template["instructions"]
+ assert "gmail.com" not in instructions and "[email]" in instructions
+ assert "C:\\Users\\ruben" not in instructions and "[folder]" in instructions
+ kinds = {(f.kind, f.field) for f in draft.findings}
+ assert ("email", "instructions") in kinds
+ assert ("path", "instructions") in kinds
+ assert validate_template(draft.template, draft.listing) == []
+
+
+ ("text", "kind", "gone"),
+ [
+ (f"Use the key {SECRET} for the API.", "secret", SECRET),
+ ("password: hunter2hunter2", "secret", "hunter2hunter2"),
+ ("Call me on +49 151 2345 6789.", "phone", "2345 6789"),
+ ("The NAS is at 192.168.1.20.", "address", "192.168.1.20"),
+ ("Fetch https://x.test/feed?token=abcd1234efgh", "secret", "abcd1234efgh"),
+ ("Notes live in /home/ruben/notes.", "path", "/home/ruben"),
+ ("Notes live in /Users/ruben/notes.", "path", "/Users/ruben"),
+ ],
+)
+def test_scrub_removes_personal_details(text: str, kind: str, gone: str) -> None:
+ clean, findings = scrub_text(text, "instructions")
+ assert gone not in clean
+ assert [f.kind for f in findings] == [kind]
+ # The hint names the match to its author without repeating it.
+ assert gone not in findings[0].hint
+
+
+def test_scrub_keeps_the_sentence_around_a_path() -> None:
+ clean, _ = scrub_text("Keep copies in C:\\Users\\max\\notes. Then stop.", "instructions")
+ assert clean == "Keep copies in [folder]. Then stop."
+
+
+def test_scrub_keeps_ordinary_text_and_example_addresses() -> None:
+ text = "Reply within 2 days, version 1.2.3.4, write to [email protected]."
+ clean, findings = scrub_text(text, "summary")
+ assert clean == text
+ assert findings == []
+
+
+def test_the_lead_cannot_be_shared() -> None:
+ with pytest.raises(TemplateError):
+ build_draft(_agent(agent_id="jarvis", name="Jarvis", tier="lead"))
+
+
+def test_overlay_edits_are_scrubbed_too(tmp_path: Path) -> None:
+ save_overlay(
+ tmp_path,
+ "inbox-butler",
+ {"summary": f"Sorts mail. Token {SECRET}", "categories": ["Email", " "]},
+ )
+ draft = build_draft(_agent(), load_overlay(tmp_path, "inbox-butler"))
+ assert SECRET not in draft.listing["description"]
+ assert draft.listing["categories"] == ["email"]
+ assert any(f.field == "summary" and f.kind == "secret" for f in draft.findings)
+
+
+def test_overlay_none_clears_a_key(tmp_path: Path) -> None:
+ save_overlay(tmp_path, "a", {"summary": "x", "version": "2.0.0"})
+ assert save_overlay(tmp_path, "a", {"summary": None}) == {"version": "2.0.0"}
+ assert load_overlay(tmp_path, "missing") == {}
+
+
+def test_next_version_follows_the_last_publish(tmp_path: Path) -> None:
+ overlay = {"published": {"name": "inbox-butler", "version": "1.0.4"}}
+ assert build_draft(_agent(), overlay).listing["version"] == "1.0.5"
+ assert build_draft(_agent()).listing["version"] == "1.0.0"
+
+
+def test_submission_carries_no_publisher() -> None:
+ draft = build_draft(_agent())
+ doc = submission(draft.template, draft.listing)
+ assert doc["kind"] == "agent"
+ assert doc["name"] == "inbox-butler"
+ assert "publisher" not in doc and "publisher_id" not in doc
+
+
+def test_validate_refuses_what_a_stranger_template_must_not_carry() -> None:
+ template = build_draft(_agent()).template
+ for key, value in (
+ ("approval_mode", "bypass"),
+ ("permission_ceiling", "monitor"),
+ ("account_id", "x"),
+ ("provider", "openai"),
+ ):
+ assert validate_template({**template, key: value}), key
+ assert validate_template({**template, "name": "Jarvis"})
+ assert validate_template({**template, "tier": "lead"})
+ assert validate_template({**template, "avatar": {"model": "/x.glb"}})
+ assert validate_template({**template, "instructions": f"use {SECRET}"})
+ assert validate_template({**template, "instructions": "files in /home/ruben/x"})
+
+
+def test_create_fields_start_from_safe_defaults() -> None:
+ fields = create_fields(build_draft(_agent()).template)
+ assert fields["approval_rules"] == {
+ "require_approval": ["plugin:gmail:send"],
+ "always_allow": [],
+ }
+ for absent in ("provider", "model", "account_id", "approval_mode", "permission_ceiling"):
+ assert absent not in fields
+ assert fields["description"].startswith("You own the inbox")
+ with pytest.raises(TemplateError):
+ create_fields({"schema": 1, "name": "x"})
+
+
+def test_public_avatar_drops_an_invalid_companion() -> None:
+ avatar = {"contract": 1, "base": "rogue", "companion": {"shape": "star", "color": "red"}}
+ assert public_avatar(avatar) == {"contract": 1, "base": "rogue"}
diff --git a/tests/unit/society/test_surface.py b/tests/unit/society/test_surface.py
index 6005628acd..182938c957 100644
--- a/tests/unit/society/test_surface.py
+++ b/tests/unit/society/test_surface.py
@@ -113,6 +113,7 @@ async def test_tools_and_filter_follow_the_roster_row(rt: SocietyRuntime, tmp_pa
"society_routines",
"society_invoke_routine",
"society_ask_user",
+ "society_share_template",
*FOLDER,
}
assert "RunCommand" not in own
@@ -134,6 +135,7 @@ async def test_tools_and_filter_follow_the_roster_row(rt: SocietyRuntime, tmp_pa
"society_routines",
"society_invoke_routine",
"society_ask_user",
+ "society_share_template",
*FOLDER,
}
assert set(picked[: len(own_names)]) == own_names