From 76fc9f68224e13cd269f3e9a4e13aa204735a9b5 Mon Sep 17 00:00:00 2001 From: Joe Guo Date: Sat, 17 Oct 2026 23:03:08 +0000 Subject: [PATCH] feat(apps): crewmate.import owner card and ctx.crewmate for .crewmate bundles --- docs/app-kit/api-reference.md | 26 ++ docs/app-kit/manifest-reference.md | 2 + docs/system-specs/modules/app-kit-platform.md | 10 + docs/system-specs/modules/crew-mode.md | 1 + src/kiro_crew/apps/context.py | 16 ++ src/kiro_crew/apps/crewmate_sdk.py | 61 +++++ src/kiro_crew/apps/hooks_integration.py | 1 + src/kiro_crew/apps/lifecycle.py | 1 + src/kiro_crew/apps/manifest_sections.py | 6 + src/kiro_crew/change_card_catalog.py | 107 +++++++- src/kiro_crew/crewmate_bundle.py | 101 ++++++++ src/kiro_crew/dashboard/change_cards.py | 32 ++- .../dashboard/handlers/change_cards.py | 77 +++++- test/test_change_card_crewmate_import.py | 228 ++++++++++++++++++ website/src/api/cards.ts | 1 + website/src/cards/CardChanges.test.tsx | 15 ++ website/src/cards/CardChanges.tsx | 42 +++- website/src/cards/CardResultLine.tsx | 2 +- website/src/cards/ChangeCard.tsx | 12 +- website/src/cards/ConversationCard.test.tsx | 7 + website/src/cards/cardRegistry.ts | 4 + website/src/i18n/locales/bn.json | 17 ++ website/src/i18n/locales/de.json | 17 ++ website/src/i18n/locales/en-XA.json | 17 ++ website/src/i18n/locales/en.manual.json | 17 ++ website/src/i18n/locales/es.json | 17 ++ website/src/i18n/locales/fr.json | 17 ++ website/src/i18n/locales/hi.json | 17 ++ website/src/i18n/locales/it.json | 17 ++ website/src/i18n/locales/ja.json | 17 ++ website/src/i18n/locales/ko.json | 17 ++ website/src/i18n/locales/pt.json | 17 ++ website/src/i18n/locales/ru.json | 17 ++ website/src/i18n/locales/zh-CN.json | 17 ++ 34 files changed, 952 insertions(+), 21 deletions(-) create mode 100644 src/kiro_crew/apps/crewmate_sdk.py create mode 100644 src/kiro_crew/crewmate_bundle.py create mode 100644 test/test_change_card_crewmate_import.py diff --git a/docs/app-kit/api-reference.md b/docs/app-kit/api-reference.md index 25b93058600c..395d9d85c022 100644 --- a/docs/app-kit/api-reference.md +++ b/docs/app-kit/api-reference.md @@ -931,6 +931,32 @@ return. Only the SDK call takes `params`: the HTTP start route (`POST /api/apps/{app}/_jobs/{kind}/start`) accepts a `dedupe_key` and no parameters. +### Crewmate proposals (`ctx.crewmate`) + +> **Preview, switched off.** `ctx.crewmate` is `None` for every app, even one that declares the permission, until the dashboard view that lists an app's cards lands (#21718). The calls below describe the contract that view will switch on (`apps/crewmate_sdk.py::PREVIEW_ENABLED`). + +Once switched on, present when the manifest declares `permissions.proposeCrewmate: true`, and `None` otherwise. The app hands core one parsed `.crewmate` bundle ([rfc-crewmate-share.md](../request-for-change/rfc-crewmate-share.md) §5.2). Core checks it and raises one `crewmate.import` change card for the owner. The app creates nothing: only the owner's press creates the crewmate. + +```python +card_id = await ctx.crewmate.propose(bundle) # raises CrewmateProposalError(code, message) +state = await ctx.crewmate.status(card_id) # {"status": "pending"} ... {"status": "applied", "crew": ""} +``` + +`bundle` is `{"crewmate": , "agent": , "goals"?: {"longTerm", "keyResults"}, "rules"?: {"rules"}, "crons"?: [...], "avatar"?: {"type", "size"}}`. Core refuses it before any card exists when: + +| Code | Cause | +|---|---| +| `unknown_param` | an unknown key in the bundle, `crewmate`, `agent`, `goals`, `rules`, `sender` or `avatar` (`{"type", "size"}`); crons and key results are only counted | +| `invalid_bundle` | not `format: "kirocrew.crewmate"`, a bad shape, or a `dashboardTemplate` that is not a `builtin:` or `user:` id | +| `newer_format` | a `formatVersion` this version does not read | +| `grant_in_bundle` | `allowedTools`, `autoApprove` or `permissions` in `agent.json` | +| `needs_mate_config` | any `mcpServers` or `skills` entry, until the mate-owned agent file exists (RFC §5.7) | +| `rules_unsupported` | non-empty rules, which this version cannot import yet | + +The card creates the crewmate from the `kirocrew` template with a fresh member id, its own empty memory and workspace, and `approval_mode: "normal"` in the create. It writes the long-term goal when the bundle has one. It lists the crons, key results, picture or face, model or effort hints and dashboard template a bundle carries under "Not brought over", as codes the dashboard words, and memory, history, credentials and the sender's approval settings under "Stays with the sender". A taken name becomes the first free ` 2` to ` 9`, and the owner can edit it. + +The card is stored under the key `app:` with no conversation, so an app's open cards count against one per-app cap. `status` reads only this app's own cards. The dashboard view where the owner presses an app card is not built yet. + ### Gateway Application (`ctx.http_app`) The gateway's own aiohttp `Application`, for background work that must be anchored diff --git a/docs/app-kit/manifest-reference.md b/docs/app-kit/manifest-reference.md index a7f6e6aa29b5..c135cd7dc77f 100644 --- a/docs/app-kit/manifest-reference.md +++ b/docs/app-kit/manifest-reference.md @@ -887,6 +887,7 @@ packages at all. "sessionApproval": false, "spawn": false, "jobs": false, + "proposeCrewmate": false, "exposeToApps": [] } } @@ -904,6 +905,7 @@ packages at all. | `permissions.sessionApproval` | boolean | Controls existing local user sessions: send messages (including generated response-option choices, but not a change to the session's agent binding, persona settings, or a harness slash command), approve or deny pending tool requests, and change approval modes within the limits below | | `permissions.spawn` | boolean | May start a background agent through the host's subagent manager (`ctx.spawn`) | | `permissions.jobs` | boolean | May run durable background work through `ctx.job` and the app-owned `_jobs/*` routes | +| `permissions.proposeCrewmate` | boolean | **Preview, switched off**: `ctx.crewmate` stays `None` until the owner view that lists the cards lands (#21718). May propose one crewmate from a `.crewmate` bundle through `ctx.crewmate`. Gates a real capability like `spawn`: `ctx.crewmate` is absent unless the value is literally `true`. Each proposal is an owner change card; only the owner's press creates the crewmate ([api-reference](api-reference.md#crewmate-proposals-ctxcrewmate)) | | `permissions.exposeToApps` | string[] | App names (or `"*"`) allowed to request cross-app visibility into this app's slots/subagents | #### `permissions.spawn` — Background Agents diff --git a/docs/system-specs/modules/app-kit-platform.md b/docs/system-specs/modules/app-kit-platform.md index 3c1091d9a593..6f21cc310de0 100644 --- a/docs/system-specs/modules/app-kit-platform.md +++ b/docs/system-specs/modules/app-kit-platform.md @@ -1259,6 +1259,16 @@ surface that constructs an app context MUST pass a real broadcaster. Writer: `apps/lifecycle.py`; consumer: an app's `publish`/`_broadcast`. +## 8a. `ctx.crewmate` proposes; only the owner's press creates + +`build_app_context` builds `ctx.crewmate` (`apps/crewmate_sdk.py::CrewmateSDK`) only when `crewmate_sdk.PREVIEW_ENABLED` is on (off until the owner view below ships), the manifest's `permissions.proposeCrewmate` is literally `true` and the builder passed the gateway's Application as `crewmate_host`. Both builders pass it (`hooks_integration._build_app_context_from_info`, `LifecycleDispatcher._build_context`), whatever the app's `routes` hook says, because the SDK never hands the Application to the app. + +`propose(bundle)` runs `crewmate_bundle.crewmate_import_params`, which fails closed on an unknown key in the bundle, `crewmate`, `agent`, `goals`, `rules`, `sender` or `avatar` (crons, key results and `avatarTraits` are only counted), another format, a newer `formatVersion`, a grant, a non-template dashboard id, rules, and any MCP server or skill (rfc-crewmate-share.md §5.7). `handlers/change_cards.py::propose_app_card` then stores one `crewmate.import` card under `slot_key` `app:` with an empty `session_key`, and writes nothing else. `propose_for_caller` refuses that kind and any `app:` key from a chat caller, and `list_kinds` leaves the kind out, so no agent can raise it. The card's plan is `crewmate.create`'s: `POST /api/agents` with `approval_mode: "normal"`, then the long-term goal. It shares that kind's evidence, member-id-checked Undo and state reads through `CREWMATE_CREATING_KINDS`. The app token cannot run a plan step: `change_card_middleware` refuses it on every hooked route. + +Not built yet: the owner-facing view that lists `app:` cards (they are stored but no chat slot shows them), cancelling them when the app is disabled, re-consent when an update adds the permission, and a provenance stamp on the crew record. + +Writers: `apps/context.py::build_app_context`, `apps/crewmate_sdk.py`, `dashboard/handlers/change_cards.py::propose_app_card`. Pinned by `test/test_change_card_crewmate_import.py`. + ## 9. Desktop-shell (Electron main-process) code is a first-party-only exception App Kit apps are **renderer + backend** only. Mochi's `website/electron/mochi/` diff --git a/docs/system-specs/modules/crew-mode.md b/docs/system-specs/modules/crew-mode.md index 4376163620a7..e74c5d0ec701 100644 --- a/docs/system-specs/modules/crew-mode.md +++ b/docs/system-specs/modules/crew-mode.md @@ -1131,6 +1131,7 @@ proposed goal exactly as one created on the Crewmates page does (see the goal welcome below); the `/members?create=1&name=&goal=` link to an editable UI draft remains for a user who wants to fill it in; opening a draft never creates a member or starts a schedule. +An app's proposal of a crewmate from a `.crewmate` bundle is a `crewmate.import` card, raised only through `ctx.crewmate` ([app-kit-platform §8a](app-kit-platform.md#8a-ctxcrewmate-proposes-only-the-owners-press-creates)). Its create pins `approval_mode: "normal"` in the same write and sends no `first_greeting`; its evidence and Undo are `crewmate.create`'s (`change_card_catalog.CREWMATE_CREATING_KINDS`). Creating a crewmate is never a first-run chapter: neither the end of the tour nor a Crewmates visit opens anything by itself, and the page's New crewmate card is the one place a crewmate is created on the Crewmates page. diff --git a/src/kiro_crew/apps/context.py b/src/kiro_crew/apps/context.py index a1669e8664c4..004ec71c52a5 100644 --- a/src/kiro_crew/apps/context.py +++ b/src/kiro_crew/apps/context.py @@ -15,6 +15,7 @@ from kiro_crew.apps.app_storage import AppStorage from kiro_crew.apps.audit_sdk import AuditSDK +from kiro_crew.apps.crewmate_sdk import CrewmateSDK from kiro_crew.apps.cron_sdk import CronSDK from kiro_crew.apps.event_bus import EventBus from kiro_crew.apps.job_sdk import JobSDK @@ -68,6 +69,7 @@ class AppContext: storage: AppStorage | None = None spawn: SpawnSDK | None = None job: JobSDK | None = None + crewmate: CrewmateSDK | None = None health: AppHealthStatus = field(default_factory=AppHealthStatus) # NOT `| None`, unlike every SDK above: those grant a capability and stay None # until the manifest asks for it, while this one only removes sensitive data @@ -139,6 +141,7 @@ def build_app_context( spawn_impl: Any = None, app_config: dict[str, Any] | None = None, http_app: Any = None, + crewmate_host: Any = None, ) -> AppContext: """Factory that builds an AppContext based on app permissions. @@ -153,6 +156,8 @@ def build_app_context( through, NOT gated on a permission: the caller decides, because the decision is whether this app already reaches the object by another route (see ``AppContext.http_app``) and only the wiring knows that. + crewmate_host: The gateway's Application for ``ctx.crewmate``, built + only when the manifest declares ``proposeCrewmate``. Returns: AppContext with services populated based on permissions. @@ -197,6 +202,16 @@ def build_app_context( if perms.get("jobs"): job_sdk = JobSDK(app_name, data_dir) + crewmate_sdk = None + from kiro_crew.apps import crewmate_sdk as crewmate_mod + + if ( + crewmate_mod.PREVIEW_ENABLED + and perms.get("proposeCrewmate") is True + and crewmate_host is not None + ): + crewmate_sdk = CrewmateSDK(app_name, crewmate_host) + return AppContext( name=app_name, data_dir=data_dir, @@ -207,6 +222,7 @@ def build_app_context( storage=app_storage, spawn=spawn_sdk, job=job_sdk, + crewmate=crewmate_sdk, # Both unconditional: see the fields' comments on AppContext. scrub=ScrubSDK(), audit=AuditSDK(app_name), diff --git a/src/kiro_crew/apps/crewmate_sdk.py b/src/kiro_crew/apps/crewmate_sdk.py new file mode 100644 index 000000000000..b3882ab39abc --- /dev/null +++ b/src/kiro_crew/apps/crewmate_sdk.py @@ -0,0 +1,61 @@ +"""Crewmate SDK — an app proposes one crewmate; only the owner's press creates it. + +Declared as ``permissions.proposeCrewmate`` and injected as ``ctx.crewmate``, +``None`` otherwise (rfc-crewmate-share.md §5.5). ``propose`` hands core one +parsed ``.crewmate`` bundle. Core re-checks it (``crewmate_bundle. +crewmate_import_params``, fail closed) and raises one ``crewmate.import`` +change card keyed ``app:``. The SDK creates nothing and reads no crewmate: +the card's plan runs only on the owner's press, through owner routes that refuse +an app token. +""" + +from __future__ import annotations + +from typing import Any + +#: Off until the dashboard lists and cancels ``app:`` cards: until +#: then an app's card could only expire unpressed, so ``ctx.crewmate`` stays +#: ``None`` even for an app that declares the permission. +PREVIEW_ENABLED = False + + +class CrewmateProposalError(ValueError): + """Core refused the bundle or the card; ``code`` says why, as the card routes do.""" + + def __init__(self, code: str, message: str) -> None: + super().__init__(message) + self.code = code + + +class CrewmateSDK: + """``ctx.crewmate`` for one app. *http_app* is the gateway's Application.""" + + def __init__(self, app_name: str, http_app: Any) -> None: + self._app_name = app_name + self._http_app = http_app + + async def propose(self, bundle: dict[str, Any]) -> str: + """Raise the import card for *bundle*; returns its card id. Never a crew key.""" + from kiro_crew import change_card_catalog as catalog + from kiro_crew.crewmate_bundle import crewmate_import_params + from kiro_crew.dashboard.change_cards import CardError + from kiro_crew.dashboard.handlers.change_cards import propose_app_card + + try: + params = crewmate_import_params(bundle) + card = await propose_app_card(self._http_app, self._app_name, params) + except (catalog.CardCatalogError, CardError) as exc: + raise CrewmateProposalError(exc.code, exc.message) from None + return str(card["id"]) + + async def status(self, card_id: str) -> dict[str, Any]: + """``{"status": ...}`` of this app's own card, plus ``"crew"`` once applied.""" + from kiro_crew.dashboard.change_cards import CardError + from kiro_crew.dashboard.handlers.change_cards import app_card_status + + if not isinstance(card_id, str) or not card_id: + raise CrewmateProposalError("invalid_card_id", "card_id is required") + try: + return await app_card_status(self._http_app, self._app_name, card_id) + except CardError as exc: + raise CrewmateProposalError(exc.code, exc.message) from None diff --git a/src/kiro_crew/apps/hooks_integration.py b/src/kiro_crew/apps/hooks_integration.py index e816049434fa..063b7c712e0c 100644 --- a/src/kiro_crew/apps/hooks_integration.py +++ b/src/kiro_crew/apps/hooks_integration.py @@ -370,6 +370,7 @@ def _build_app_context_from_info( spawn_impl=spawn_impl, app_config=manifest.get("extra", {}), http_app=http_app, + crewmate_host=_route_registry.http_app if _route_registry else None, ) # The shared _jobs routes are mounted once for every app and resolve the app # from the URL, so they need a name -> SDK lookup. Publishing happens here, diff --git a/src/kiro_crew/apps/lifecycle.py b/src/kiro_crew/apps/lifecycle.py index 206eded6ed11..4a36e352dc1e 100644 --- a/src/kiro_crew/apps/lifecycle.py +++ b/src/kiro_crew/apps/lifecycle.py @@ -442,6 +442,7 @@ def _build_context(self, app_info: dict[str, Any], *, phase: str) -> AppContext: # The same shared predicate the enable/boot builder uses, so a # shutdown context carries the handle exactly when the startup one did. http_app=self._http_app if granted else None, + crewmate_host=self._http_app, ) async def _invoke(self, app_name: str, hook_path: str, ctx: AppContext, *, phase: str) -> bool: diff --git a/src/kiro_crew/apps/manifest_sections.py b/src/kiro_crew/apps/manifest_sections.py index 20c13170018f..52963f0d438d 100644 --- a/src/kiro_crew/apps/manifest_sections.py +++ b/src/kiro_crew/apps/manifest_sections.py @@ -508,6 +508,9 @@ class Permissions: #: same reason as ``spawn``: "which apps can start work that outlives the #: page that started it" must be answerable from the manifest. jobs: bool = False + #: May raise a ``crewmate.import`` owner card through ``ctx.crewmate``. The + #: card creates nothing until the owner presses it. + proposeCrewmate: bool = False # noqa: N815 # WS cross-app visibility opt-in: app names (or ["*"]) allowed to use # slots:app: / subagent:app: declarations to observe # this app's slots and subagents. Empty list = no cross-app visibility. @@ -535,6 +538,8 @@ def to_dict(self) -> dict[str, Any]: d["spawn"] = True if self.jobs: d["jobs"] = True + if self.proposeCrewmate: + d["proposeCrewmate"] = True if self.exposeToApps: d["exposeToApps"] = self.exposeToApps return d @@ -563,6 +568,7 @@ def from_dict(cls, data: dict[str, Any]) -> Permissions: sessionApproval=data.get("sessionApproval") is True, # noqa: N815 spawn=data.get("spawn") is True, jobs=data.get("jobs") is True, + proposeCrewmate=data.get("proposeCrewmate") is True, # noqa: N815 exposeToApps=_granted_list(data.get("exposeToApps")), # noqa: N815 ) diff --git a/src/kiro_crew/change_card_catalog.py b/src/kiro_crew/change_card_catalog.py index 53e3e12fcec0..e152d0f3a593 100644 --- a/src/kiro_crew/change_card_catalog.py +++ b/src/kiro_crew/change_card_catalog.py @@ -72,6 +72,21 @@ KIND_TRUST_APP = "trust.app" KIND_DENIED_COMMAND = "denied_command" KIND_FOLDER_STEERING = "folder.steering" +#: An app's proposal of one crewmate from a ``.crewmate`` bundle +#: (``docs/request-for-change/rfc-crewmate-share.md``). Only an app that +#: declares ``permissions.proposeCrewmate`` raises it, through ``ctx.crewmate``; +#: an agent cannot, so :func:`list_kinds` leaves it out. +KIND_CREWMATE_IMPORT = "crewmate.import" +#: The kinds whose apply step 0 creates a crewmate, so they share its evidence, +#: its identity-checked Undo (delete that crewmate) and its state reads. +CREWMATE_CREATING_KINDS = (KIND_CREWMATE_CREATE, KIND_CREWMATE_IMPORT) +APP_ONLY_KINDS = frozenset({KIND_CREWMATE_IMPORT}) +#: The ``.crewmate`` ``formatVersion`` values this version reads. Any added +#: field bumps the version, so a newer file is refused rather than guessed at. +CREWMATE_FORMAT_VERSIONS = (1,) +#: The parts a ``crewmate.import`` card names as left out, as codes the +#: dashboard words: the bundle carried them and this version does not write them. +NOT_IMPORTED_CODES = ("crons", "keyResults", "avatar", "model", "dashboardTemplate") #: The steps of a ``crewmate.create`` apply: the crewmate (0), its first goal #: in its goal record (1), and its optional work schedule (2). @@ -101,6 +116,7 @@ _TEXT_MAX = 4000 _CREWMATE_NAME_MAX = 24 _CREWMATE_GOAL_MAX = 200 +_CREWMATE_DESCRIPTION_MAX = 1000 #: A crewmate's goals and key results: the record's own bounds, so a #: validated card never fails on apply and the record accepts nothing a card #: could not propose. @@ -561,12 +577,28 @@ def _obj(props: dict[str, Any], required: list[str]) -> dict[str, Any]: ), ("steering_dirs",), ), + KindDef( + KIND_CREWMATE_IMPORT, + "Import one crewmate from a .crewmate bundle (apps only).", + _obj( + { + "name": {"type": "string", "maxLength": _CREWMATE_NAME_MAX}, + "description": _STR, + "goal": _STR, + "sender": _STR, + "format_version": {"type": "integer"}, + "not_imported": {"type": "array", "items": _STR}, + }, + ["name", "format_version"], + ), + ("name",), + ), ) } def list_kinds() -> list[dict[str, Any]]: - """The catalog as the ``list_change_kinds`` tool returns it.""" + """The catalog as the ``list_change_kinds`` tool returns it, app-only kinds left out.""" return [ { "id": k.id, @@ -575,6 +607,7 @@ def list_kinds() -> list[dict[str, Any]]: "editable": list(k.editable), } for k in KINDS.values() + if k.id not in APP_ONLY_KINDS ] @@ -823,6 +856,26 @@ def validate_params(kind: str, params: Any) -> dict[str, Any]: expr, tz = _clean_cron(schedule, required=True) out["schedule"] = {"cron_expr": expr, **({"timezone": tz} if tz else {})} return out + if kind == KIND_CREWMATE_IMPORT: + _only(p, set(KINDS[kind].params_schema["properties"])) + if p.get("format_version") not in CREWMATE_FORMAT_VERSIONS: + raise _fail("invalid_param", "'format_version' is not one this version reads") + out = { + "name": _member_name(p, "name", max_len=_CREWMATE_NAME_MAX), + "format_version": p["format_version"], + } + for key, max_len in (("description", _CREWMATE_DESCRIPTION_MAX), ("sender", 64)): + text = _clean_str(p, key, required=False, max_len=max_len, allow_empty=True) + if text: + out[key] = text + if p.get("goal") is not None: + out["goal"] = _goal_text(p, "goal", max_len=_LONG_TERM_GOAL_MAX, multiline=True) + left_out = _str_list(p.get("not_imported", []), "not_imported", max_len=32) + if not set(left_out) <= set(NOT_IMPORTED_CODES): + raise _fail("invalid_param", "'not_imported' names a part this version does not know") + if left_out: + out["not_imported"] = left_out + return out if kind == KIND_CREWMATE_UPDATE: _only(p, {"name", "fields"}) name = _member_name(p, "name") @@ -1504,6 +1557,52 @@ def build_preview( ) apply.append(_create_schedule_step(p)) out["apply"] = apply + elif kind == KIND_CREWMATE_IMPORT: + if snapshot.get("exists"): + raise _fail("already_exists", f"a crewmate named '{p['name']}' already exists") + out["title"] = f"Import crewmate “{p['name']}”" + out["changes"] = [ + {"field": "name", "label": "Name", "after": p["name"]}, + {"field": "sender", "label": "From", "after": p.get("sender", "")}, + ] + for key in ("description", "goal"): + if p.get(key): + out["changes"].append({"field": key, "label": key.title(), "after": p[key]}) + # Trust is the receiver's to grant: the mode rides on the create itself, + # because an unset mode opens in MEMBER_APPROVAL_MODE_UNSET_EFFECTIVE. + inherited = [s for s in snapshot.get("inherited_auto_approve") or () if isinstance(s, str)] + # ``import_approval`` only when a row of inherited grants follows: its + # hint says the crewmate asks like the owner's other crewmates do. + mode = "import_approval" if inherited else "approval_mode" + out["changes"].append({"field": mode, "label": "Approval", "after": "normal"}) + if inherited: # granted by the template, so the press widens (as crewmate.create) + reach = [r for r in snapshot.get("inherited_reach") or () if isinstance(r, dict)] + row = { + "field": "template_auto_approve", + "label": "Your crewmates use these without asking", + } + out["changes"].append({**row, "after": reach or ", ".join(inherited)}) + out["risk"] = RISK_WIDEN + out["changes"].append( + {"field": "not_included", "label": "Stays with the sender", "after": "private"} + ) + if p.get("not_imported"): + out["changes"].append( + {"field": "not_imported", "label": "Not brought over", "after": p["not_imported"]} + ) + body = { + "name": p["name"], + "kiro_agent": DEFAULT_CREWMATE_TEMPLATE, + "source": "kirocrew", + "description": p.get("description", ""), + "approval_mode": "normal", + } + out["apply"] = [step("POST", "/api/agents", body)] + if p.get("goal"): # crewmate.create's goal step, addressed by step 0's member_id + fills = [_step_path_fill("slug", 0, "member_id"), _step_fill("member", 0, "name")] + path = f"/api/members/{placeholder(fills[0])}/goals/long-term" + body = _with_fills({"long_term": p["goal"], "expected": ""}, fills[1:]) + out["apply"].append(step("PUT", path, body, fill=fills)) elif kind == KIND_CREWMATE_UPDATE: if not snapshot.get("exists"): raise _fail("not_found", f"no crewmate named '{p['name']}'") @@ -2161,7 +2260,7 @@ def pick(*keys: str) -> dict[str, Any]: and step_index in (LEGACY_CREWMATE_CREATE_SCHEDULE_STEP, CREWMATE_CREATE_SCHEDULE_STEP) ): return pick("id") - if kind == KIND_CREWMATE_CREATE and step_index == 0: + if kind in CREWMATE_CREATING_KINDS and step_index == 0: return pick("member_id", "name") if kind == KIND_CREWMATE_GOAL and op == OP_APPLY: # The goal the write added or changed, so the Undo of an added goal can @@ -2280,7 +2379,7 @@ def _build_undo( if not job_id: return None, "identity_unknown" return [step("DELETE", f"/api/crons/{_q(str(job_id))}")], None - if kind == KIND_CREWMATE_CREATE: + if kind in CREWMATE_CREATING_KINDS: plan = [] at = _create_schedule_index(evidence) job_id = ev(at).get("id") @@ -2449,7 +2548,7 @@ def result_summary( if status == "applied": return f"Done: {title}" if status == "partial": - if kind == KIND_CREWMATE_CREATE: + if kind in CREWMATE_CREATING_KINDS: name = params.get("name") if failed_step == CREWMATE_CREATE_GOAL_STEP: # A failed step stops the plan, so a schedule after it never ran. diff --git a/src/kiro_crew/crewmate_bundle.py b/src/kiro_crew/crewmate_bundle.py new file mode 100644 index 000000000000..b29139f033db --- /dev/null +++ b/src/kiro_crew/crewmate_bundle.py @@ -0,0 +1,101 @@ +"""The ``.crewmate`` bundle reader (``docs/request-for-change/rfc-crewmate-share.md`` §5.2). + +Pure: turns one parsed bundle an app hands ``ctx.crewmate.propose`` into the +``crewmate.import`` change-card params, failing closed on anything this version +does not read. +""" + +from __future__ import annotations + +import re +from typing import Any + +from kiro_crew import change_card_catalog as catalog + +CREWMATE_FORMAT = "kirocrew.crewmate" +_BUNDLE_KEYS = {"crewmate", "agent", "rules", "goals", "crons", "avatar"} +_MANIFEST_HINTS = ("modelHint", "reasoningEffortHint", "dashboardTemplate") +_MANIFEST_KEYS = { + *"format formatVersion name description avatarTraits skills".split(), + *_MANIFEST_HINTS, +} +_MANIFEST_KEYS |= {"sender", "exportedAt"} +_TEMPLATE_ID_RE = re.compile(r"^(?:builtin|user):[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$") + + +def _bundle_part(bundle: dict[str, Any], key: str, kind: type, *, required: bool = False) -> Any: + value = bundle.get(key) + if value is None and not required: + return kind() + if not isinstance(value, kind): + raise catalog._fail( + "invalid_bundle", f"'{key}' must be a{'n object' if kind is dict else ' list'}" + ) + return value + + +def crewmate_import_params(bundle: Any) -> dict[str, Any]: + """The ``crewmate.import`` params for one parsed ``.crewmate`` bundle. + + Fails closed on anything this version does not read: an unknown key in the + bundle, ``crewmate.json``, ``agent.json``, ``goals.json``, ``rules.json``, the + sender or the avatar marker, another format or a newer version, a grant, page HTML, and, until the + mate-owned agent file exists (RFC §5.7), any MCP server or skill. Rules are + refused too: importing without them would give the crewmate fewer limits + than its sender set, and a rules file outlives its crewmate, so the card's + Undo could not take them back. Crons and key results are only counted for + the card's "Not brought over" row; their entries are not read. + """ + if not isinstance(bundle, dict): + raise catalog._fail("invalid_bundle", "the bundle must be an object") + catalog._only(bundle, _BUNDLE_KEYS, "bundle") + m = _bundle_part(bundle, "crewmate", dict, required=True) + catalog._only(m, _MANIFEST_KEYS, "crewmate.json") + if m.get("format") != CREWMATE_FORMAT: + raise catalog._fail("invalid_bundle", "this is not a .crewmate file") + version = m.get("formatVersion") + if type(version) is not int or version < 1: + raise catalog._fail("invalid_bundle", "'formatVersion' must be a whole number") + if version not in catalog.CREWMATE_FORMAT_VERSIONS: + raise catalog._fail("newer_format", "this file needs a newer Kiro Crew") + agent = _bundle_part(bundle, "agent", dict, required=True) + grant = sorted(set(agent) & {"allowedTools", "autoApprove", "permissions"}) + if grant: + raise catalog._fail("grant_in_bundle", f"a bundle never carries '{grant[0]}'") + catalog._only(agent, {"mcpServers", "skills"}, "agent.json") + if agent.get("mcpServers") or agent.get("skills") or m.get("skills"): + raise catalog._fail( + "needs_mate_config", "this version cannot import MCP servers or skills yet" + ) + rules = _bundle_part(bundle, "rules", dict) + catalog._only(rules, {"rules"}, "rules.json") + if rules.get("rules"): + raise catalog._fail("rules_unsupported", "this version cannot import rules yet") + goals = _bundle_part(bundle, "goals", dict) + catalog._only(goals, {"longTerm", "keyResults"}, "goals.json") + avatar = _bundle_part(bundle, "avatar", dict) + catalog._only(avatar, {"type", "size"}, "avatar") + sender = _bundle_part(m, "sender", dict) + catalog._only(sender, {"label"}, "sender") + for key in (*_MANIFEST_HINTS, "exportedAt"): + catalog._clean_str(m, key, required=False, max_len=72, allow_empty=True) + template = m.get("dashboardTemplate") + if template and not _TEMPLATE_ID_RE.fullmatch(template): + raise catalog._fail("invalid_bundle", "'dashboardTemplate' must be a builtin: or user: id") + carried = { + "crons": _bundle_part(bundle, "crons", list), + "keyResults": _bundle_part(goals, "keyResults", list), + "avatar": avatar or _bundle_part(m, "avatarTraits", dict), + "model": (m.get("modelHint") or "").strip() or (m.get("reasoningEffortHint") or "").strip(), + "dashboardTemplate": (template or "").strip(), + } + left_out = [code for code, part in carried.items() if part] + params = { + "name": m.get("name"), + "format_version": version, + "description": m.get("description"), + "goal": goals.get("longTerm") or None, + "sender": sender.get("label"), + "not_imported": left_out, + } + return catalog.validate_params(catalog.KIND_CREWMATE_IMPORT, params) diff --git a/src/kiro_crew/dashboard/change_cards.py b/src/kiro_crew/dashboard/change_cards.py index 69e4e227b6ea..9704b3081752 100644 --- a/src/kiro_crew/dashboard/change_cards.py +++ b/src/kiro_crew/dashboard/change_cards.py @@ -63,6 +63,7 @@ import re import secrets import time +import urllib.parse from collections import OrderedDict from pathlib import Path from typing import Any, Callable @@ -1907,6 +1908,18 @@ def _mcp_global_entry(name: str) -> tuple[bool, dict[str, Any] | None]: return (name in known), None +def _server_reach(name: str) -> dict[str, str]: + """What MCP server *name* reaches, for a card row: a URL's host or a command's name.""" + _exists, entry = _mcp_global_entry(name) + entry = entry or {} + if isinstance(entry.get("url"), str): + host = urllib.parse.urlsplit(entry["url"]).hostname or "" + return {"name": name, "host": host} if host else {"name": name} + if isinstance(entry.get("command"), str) and entry["command"].strip(): + return {"name": name, "command": os.path.basename(entry["command"].strip())} + return {"name": name} + + def _mcp_exists(name: str) -> bool: from kiro_crew.dashboard.handlers.mcp import _find_server_spec_anywhere @@ -2024,7 +2037,7 @@ def same(a: Any, b: Any) -> bool: if not isinstance(fields, dict): return False return all(same(fields.get(k), v) for k, v in (p.get("fields") or {}).items()) - if kind == catalog.KIND_CREWMATE_CREATE: + if kind in catalog.CREWMATE_CREATING_KINDS: # Undo deletes the crewmate this card made. The only safe baseline is the # IMMUTABLE member_id the card's own create returned (step 0's evidence): # a name is reusable, so an owner who deleted and recreated the same name @@ -2281,11 +2294,11 @@ def _sync_read_state( "label": target["label"], "value": read_setting_value(target), } - if kind in (catalog.KIND_CREWMATE_CREATE, catalog.KIND_CREWMATE_UPDATE): + if kind in (*catalog.CREWMATE_CREATING_KINDS, catalog.KIND_CREWMATE_UPDATE): from kiro_crew.config.loader import KiroCrewConfig agents = KiroCrewConfig.load().agents - if kind == catalog.KIND_CREWMATE_CREATE: + if kind in catalog.CREWMATE_CREATING_KINDS: key = ev0.get("name") if isinstance(ev0.get("name"), str) else None if key: agent = agents.get(key) @@ -2298,12 +2311,11 @@ def _sync_read_state( taken = taken or any( getattr(a, "display_name", "") == p["name"] for a in agents.values() ) - return { - "exists": bool(taken), - "inherited_auto_approve": template_auto_approved_servers( - catalog.DEFAULT_CREWMATE_TEMPLATE - ), - } + inherited = template_auto_approved_servers(catalog.DEFAULT_CREWMATE_TEMPLATE) + out = {"exists": bool(taken), "inherited_auto_approve": inherited} + if kind == catalog.KIND_CREWMATE_IMPORT: + out["inherited_reach"] = [_server_reach(name) for name in inherited] + return out agent = agents.get(p["name"]) if agent is None: return {"exists": False} @@ -2505,7 +2517,7 @@ async def resumed_undo_is_stale(rec: dict[str, Any], index: int, *, state: Any, only what is still there to remove. """ kind, params, after = rec["kind"], rec["params"], rec.get("after") or {} - if kind == catalog.KIND_CREWMATE_CREATE: + if kind in catalog.CREWMATE_CREATING_KINDS: current = await read_state(kind, params, rec["evidence"][:1], state=state, app=app) keys = ("exists", "member_id", "revision") return canonical({k: current.get(k) for k in keys}) != canonical( diff --git a/src/kiro_crew/dashboard/handlers/change_cards.py b/src/kiro_crew/dashboard/handlers/change_cards.py index 39c134767558..c3620d0d36d9 100644 --- a/src/kiro_crew/dashboard/handlers/change_cards.py +++ b/src/kiro_crew/dashboard/handlers/change_cards.py @@ -188,6 +188,10 @@ def is_open(key: str) -> bool: async def _settle(request: web.Request) -> None: + await _settle_app(request.app) + + +async def _settle_app(app: web.Application) -> None: """Expire / prune, persist, then broadcast what changed. Raises :class:`CardError`. Persist-before-you-publish, for reads too: when the write fails, every @@ -197,8 +201,8 @@ async def _settle(request: web.Request) -> None: follow from the clock and the open conversations, so the next settlement whose write succeeds derives them again and announces them then. """ - state = request.app["state"] - store = _store(request) + state = app["state"] + store = card_store_for(state) await store.warm() # Retirement cancels a proposal nobody can confirm, so it must fire ONLY on # a slot the user actually closed -- never on one merely absent, and never @@ -501,6 +505,10 @@ async def propose_for_caller( preview, same store, same row in the conversation. """ try: + # An app's kind and an app's card key are never a chat caller's: see + # propose_app_card. + if kind in catalog.APP_ONLY_KINDS or slot_key.startswith(APP_SLOT_PREFIX): + raise CardError(403, "app_only", "only an app can propose this change") params = catalog.validate_params(kind, params) params = await cards.resolve_params(kind, params) cards.check_param_text(params) @@ -549,6 +557,69 @@ async def api_cards_agent_status(request: web.Request) -> web.Response: return web.json_response(store.public(rec)) +# ── app half (``ctx.crewmate``, apps/crewmate_sdk.py) ── + +#: The card key of an app's cards, ``app:``. No chat slot key carries it +#: (``propose_for_caller`` refuses one that does), so the store's per-slot cap +#: counts per app, and no conversation can list, report or retire the card. +APP_SLOT_PREFIX = "app:" +_FREE_NAME_TRIES = 9 + + +async def propose_app_card(app: web.Application, app_name: str, params: Any) -> dict[str, Any]: + """Raise one ``crewmate.import`` card for app *app_name*; returns the stored card. + + Writes nothing but the card. Only the owner's press applies its plan, through + owner routes ``change_card_middleware`` refuses to an app token. A taken name + becomes the first free `` 2`` .. `` 9``; the owner may edit it. + Raises :class:`CardError` or :class:`catalog.CardCatalogError`. + """ + kind = catalog.KIND_CREWMATE_IMPORT + params = await cards.resolve_params(kind, catalog.validate_params(kind, params)) + cards.check_param_text(params) + base = params["name"] + for n in range(2, _FREE_NAME_TRIES + 2): + try: + preview, before, context = await cards.build(kind, params, state=app["state"], app=app) + break + except catalog.CardCatalogError as exc: + if exc.code != "already_exists" or n > _FREE_NAME_TRIES: + raise + suffix = f" {n}" + name = base[: catalog._CREWMATE_NAME_MAX - len(suffix)].rstrip() + suffix + params = catalog.validate_params(kind, {**params, "name": name}) + await _settle_app(app) + store = card_store_for(app["state"]) + rec = store.propose( + slot_key=APP_SLOT_PREFIX + app_name, + session_key="", + kind=kind, + params=params, + reason="", + preview=preview, + before=before, + context=context, + ) + try: + await store.flush(strict=True) + except CardError as exc: + store.discard(rec["id"]) + raise CardError(exc.status, exc.code, "the change card could not be saved") from None + _audit(APP_SLOT_PREFIX + app_name, "cards.propose", "ok") + return store.public(rec) + + +async def app_card_status(app: web.Application, app_name: str, card_id: str) -> dict[str, Any]: + """``{status, crew?}`` of app *app_name*'s own card; ``crew`` only once applied.""" + await _settle_app(app) + rec = card_store_for(app["state"]).status_for_caller(APP_SLOT_PREFIX + app_name, card_id) + out: dict[str, Any] = {"status": rec["status"]} + evidence = rec.get("evidence") or [] + if rec["status"] == "applied" and evidence and isinstance(evidence[0].get("name"), str): + out["crew"] = evidence[0]["name"] + return out + + # ── browser half ── @@ -944,7 +1015,7 @@ def _arm_card_undo_cron_guard( request[REQ_CARD_UNDO_CRON_EXPECT] = ( revision if isinstance(revision, str) and revision else _CRON_FINGERPRINT_MISSING ) - elif path.startswith("/api/agents/") and kind == catalog.KIND_CREWMATE_CREATE: + elif path.startswith("/api/agents/") and kind in catalog.CREWMATE_CREATING_KINDS: from kiro_crew.dashboard.handlers.undo_identity_guard import ( REQ_CARD_UNDO_CREWMATE_EXPECT, ) diff --git a/test/test_change_card_crewmate_import.py b/test/test_change_card_crewmate_import.py new file mode 100644 index 000000000000..653db808924c --- /dev/null +++ b/test/test_change_card_crewmate_import.py @@ -0,0 +1,228 @@ +"""The ``crewmate.import`` card and ``ctx.crewmate`` (rfc-crewmate-share.md Phase 1). + +A bundle is checked fail-closed before any card exists; the card lands under the +app's own ``app:`` key and writes nothing; only the owner's press creates +the crewmate, pinned to ``normal`` in the create itself. +""" + +from __future__ import annotations + +import asyncio +import copy +from pathlib import Path + +import change_cards_helpers +import pytest +from aiohttp import web +from aiohttp.test_utils import TestClient, TestServer +from change_cards_helpers import AGENT, _card_headers, _run + +from kiro_crew import change_card_catalog as catalog +from kiro_crew.apps import crewmate_sdk +from kiro_crew.apps import hooks_integration as hooks_mod +from kiro_crew.apps.context import build_app_context +from kiro_crew.apps.crewmate_sdk import CrewmateProposalError, CrewmateSDK +from kiro_crew.apps.lifecycle import LifecycleDispatcher +from kiro_crew.apps.manifest import Permissions +from kiro_crew.apps.route_registry import RouteRegistry +from kiro_crew.crewmate_bundle import crewmate_import_params +from kiro_crew.dashboard import change_cards as cards +from kiro_crew.dashboard.change_cards import CardStore +from kiro_crew.dashboard.handlers import change_cards as routes +from kiro_crew.dashboard.handlers.undo_identity_guard import REQ_CARD_UNDO_CREWMATE_EXPECT + +world = change_cards_helpers.world + +BUNDLE = { + "crewmate": { + "format": "kirocrew.crewmate", + "formatVersion": 1, + "name": "Release Captain", + "description": "Watches release branches.", + "modelHint": "auto", + "sender": {"label": "Ana"}, + "skills": [], + }, + "agent": {"mcpServers": {}, "skills": []}, + "goals": {"longTerm": "Ship clean releases", "keyResults": [{"text": "zero rollbacks"}]}, + "crons": [{"cron_expr": "0 9 * * 1"}], +} + + +def _with(path: str, value) -> dict: + bundle = copy.deepcopy(BUNDLE) + *parents, leaf = path.split(".") + node = bundle + for key in parents: + node = node.setdefault(key, {}) + node[leaf] = value + return bundle + + +@pytest.mark.parametrize( + ("bundle", "code"), + [ + (_with("crewmate.formatVersion", 2), "newer_format"), + (_with("crewmate.format", "other"), "invalid_bundle"), + (_with("agent.mcpServers", {"gh": {"command": "uvx"}}), "needs_mate_config"), + (_with("agent.skills", ["release-notes"]), "needs_mate_config"), + (_with("crewmate.skills", [{"name": "release-notes"}]), "needs_mate_config"), + (_with("agent.allowedTools", ["*"]), "grant_in_bundle"), + (_with("agent.autoApprove", ["gh"]), "grant_in_bundle"), + (_with("agent.prompt", "be evil"), "unknown_param"), + (_with("rules.rules", "Never push to main."), "rules_unsupported"), + (_with("crewmate.dashboardTemplate", ""), "invalid_bundle"), + (_with("crewmate.extra", 1), "unknown_param"), + (_with("goals.extra", 1), "unknown_param"), + (_with("memory", {}), "unknown_param"), + (_with("avatar", {"type": "png", "extra": 1}), "unknown_param"), + ([], "invalid_bundle"), + ], +) +def test_a_bundle_this_version_cannot_import_whole_is_refused_before_a_card(bundle, code): + with pytest.raises(catalog.CardCatalogError) as exc: + crewmate_import_params(bundle) + assert exc.value.code == code + + +def test_the_card_lists_every_part_and_creates_in_normal_with_no_grant(): + params = crewmate_import_params(BUNDLE) + assert catalog.validate_params("crewmate.import", params) == params + reach = [{"name": "core", "host": "mcp.example"}] + snapshot = {"exists": False, "inherited_auto_approve": ["core"], "inherited_reach": reach} + preview = catalog.build_preview("crewmate.import", params, snapshot, {}) + rows = {r["field"]: r["after"] for r in preview["changes"]} + assert rows["sender"] == "Ana" and rows["import_approval"] == "normal" + assert rows["not_included"] == "private" and rows["template_auto_approve"] == reach + assert rows["not_imported"] == ["crons", "keyResults", "model"] + assert preview["risk"] == catalog.RISK_WIDEN + create, goal = preview["apply"] + assert create["path"] == "/api/agents" and create["body"]["approval_mode"] == "normal" + assert not {"allowedTools", "autoApprove", "mcpServers", "skills"} & set(create["body"]) + assert goal["body"]["long_term"] == "Ship clean releases" + bare = catalog.build_preview("crewmate.import", params, {"exists": False}, {}) + assert "import_approval" not in {r["field"] for r in bare["changes"]} + with pytest.raises(catalog.CardCatalogError) as exc: + catalog.build_preview("crewmate.import", params, {"exists": True}, {}) + assert exc.value.code == "already_exists" + + +def test_an_agent_can_neither_see_nor_propose_the_app_kind(world, tmp_path): + assert "crewmate.import" not in {k["id"] for k in catalog.list_kinds()} + + async def go(c): + r = await c.post( + "/api/cards/agent/propose", + json={"kind": "crewmate.import", "params": {"name": "X", "format_version": 1}}, + headers=AGENT, + ) + return r.status, (await r.json())["code"] + + assert _run(world, CardStore(tmp_path / "c.json"), go) == (403, "app_only") + + +@pytest.mark.parametrize( + ("grant", "built"), [(None, False), ("true", False), (1, False), (True, True)] +) +def test_ctx_crewmate_exists_only_for_a_literal_true_grant(grant, built, tmp_path, monkeypatch): + monkeypatch.setattr(crewmate_sdk, "PREVIEW_ENABLED", True) + perms = {} if grant is None else {"proposeCrewmate": grant} + ctx = build_app_context("share", tmp_path, permissions=perms, crewmate_host=object()) + assert isinstance(ctx.crewmate, CrewmateSDK) is built + + +def test_ctx_crewmate_stays_off_until_the_owner_view_ships(tmp_path): + ctx = build_app_context( + "share", tmp_path, permissions={"proposeCrewmate": True}, crewmate_host=object() + ) + assert crewmate_sdk.PREVIEW_ENABLED is False and ctx.crewmate is None + + +def test_both_context_builders_hand_ctx_crewmate_to_a_lifecycle_only_app(tmp_path, monkeypatch): + monkeypatch.setattr(crewmate_sdk, "PREVIEW_ENABLED", True) + monkeypatch.setenv("KIROCREW_HOME", str(tmp_path)) + gateway = web.Application() + monkeypatch.setattr(hooks_mod, "_route_registry", RouteRegistry(gateway)) + info = {"name": "share", "enabled": True, "manifest": {"name": "share", "version": "1.0.0"}} + info["manifest"]["permissions"] = {"proposeCrewmate": True} + for ctx in ( + hooks_mod._build_app_context_from_info(info), + LifecycleDispatcher(http_app=gateway)._build_context(info, phase="startup"), + ): + assert isinstance(ctx.crewmate, CrewmateSDK) and ctx.http_app is None + assert Permissions.from_dict({"proposeCrewmate": "true"}).proposeCrewmate is False + assert Permissions.from_dict({"proposeCrewmate": True}).to_dict() == {"proposeCrewmate": True} + + +@pytest.mark.parametrize( + ("entry", "reach"), + [ + ({"url": "https://mcp.example/sse"}, {"name": "s", "host": "mcp.example"}), + ({"command": "/usr/bin/uvx", "args": ["x"]}, {"name": "s", "command": "uvx"}), + (None, {"name": "s"}), + ], +) +def test_an_inherited_server_row_says_what_the_server_reaches(entry, reach, monkeypatch): + monkeypatch.setattr(cards, "_mcp_global_entry", lambda name: (entry is not None, entry)) + assert cards._server_reach("s") == reach + + +def test_import_shares_the_create_state_read_and_partial_line(): + state = cards._sync_read_state("crewmate.import", {"name": "Nobody Here"}, []) + assert state["exists"] is False and "inherited_auto_approve" in state + assert [r["name"] for r in state["inherited_reach"]] == state["inherited_auto_approve"] + line = catalog.result_summary("crewmate.import", {"name": "Q"}, "partial", "t", failed_step=1) + assert line == "Created crewmate “Q”, but its goal was not saved" + + +def test_propose_writes_only_a_card_under_the_app_key_and_the_press_creates( + world, monkeypatch, tmp_path: Path +): + store, created, guarded, modes = CardStore(tmp_path / "c.json"), [], [], [] + real = cards.read_state + + async def read_state(kind, params, evidence, *, state, app): + if kind != "crewmate.import": + return await real(kind, params, evidence, state=state, app=app) + if evidence: # after the create: the crewmate it made, by its member id + return {"exists": bool(created), "member_id": "m1", "revision": "r1"} + return {"exists": params["name"] == "Release Captain", "inherited_auto_approve": []} + + async def create(request: web.Request) -> web.Response: + created.append(await request.json()) + modes.append(created[-1].get("approval_mode")) + return web.json_response({"member_id": "m1", "name": created[-1]["name"]}) + + async def delete(request: web.Request) -> web.Response: + # The Undo deletes only the crewmate this card made (undo_identity_guard). + guarded.append(request.get(REQ_CARD_UNDO_CREWMATE_EXPECT)) + created.clear() + return web.json_response({"ok": True}) + + async def main(): + app = change_cards_helpers._app(world, store) + app.router.add_post("/api/agents", create) + app.router.add_delete("/api/agents/{name}", delete) + async with TestClient(TestServer(app)) as c: + sdk = CrewmateSDK("share", app) + card = store.public(store.get(await sdk.propose(_with("goals", {})))) + seen = (list(created), await sdk.status(card["id"])) + with pytest.raises(CrewmateProposalError): + await CrewmateSDK("other", app).status(card["id"]) + body = card["plan"]["apply"][0]["body"] + for auth in ("app", "owner"): + r = await c.post("/api/agents", json=body, headers=_card_headers(card, auth=auth)) + seen += (r.status,) + applied = store.public(store.get(card["id"])) + undo = applied["plan"]["undo"] + r = await c.delete(undo[0]["path"], headers=_card_headers(applied, op="undo")) + return card, seen + (undo[0]["path"], r.status) + + monkeypatch.setattr(cards, "read_state", read_state) + card, seen = asyncio.run(main()) + rec = store.get(card["id"]) + assert rec["slot_key"] == routes.APP_SLOT_PREFIX + "share" and rec["session_key"] == "" + # The bundle's name is taken, so the card proposes the first free one. + assert rec["params"]["name"] == "Release Captain 2" + assert seen == ([], {"status": "pending"}, 403, 200, "/api/agents/Release%20Captain%202", 200) + assert modes == ["normal"] and guarded == ["m1"] and rec["status"] == "undone" diff --git a/website/src/api/cards.ts b/website/src/api/cards.ts index 5fbcc00825f8..cf4dbc4c154e 100644 --- a/website/src/api/cards.ts +++ b/website/src/api/cards.ts @@ -20,6 +20,7 @@ export const CARD_KINDS = [ 'schedule.create', 'schedule.update', 'crewmate.create', + 'crewmate.import', 'crewmate.update', 'crewmate.capabilities', 'crewmate.goal', diff --git a/website/src/cards/CardChanges.test.tsx b/website/src/cards/CardChanges.test.tsx index 7240e4b9b4d3..1a02dba403d6 100644 --- a/website/src/cards/CardChanges.test.tsx +++ b/website/src/cards/CardChanges.test.tsx @@ -71,6 +71,21 @@ describe('CardChanges', () => { expect(screen.getByTestId('change-card-hint')).toHaveTextContent(L('approval_mode_hint_normal')) }) + it("shows an import card's sender and what it leaves out in the reader's language", () => { + render() + expect(screen.getByText(`${L('reach_remote', { name: 'gh', host: 'api.example' })}; ${L('reach_local', { name: 'fs', command: 'uvx' })}`)).toBeTruthy() + expect(screen.getByTestId('change-card-template-link').getAttribute('href')).toBe('/capabilities?tab=templates') + for (const k of ['field_sender', 'field_not_included', 'not_included_private', 'field_not_imported', 'approval_hint_import']) expect(screen.getByText(L(k))).toBeTruthy() + expect(screen.getByText(fmtList([L('left_crons'), L('left_model')]))).toBeTruthy() + expect(screen.queryByText('private')).toBeNull() + }) + it("shows a reasoning effort in the editor's words, and an unset one as inherited", () => { render() const value = screen.getByTestId('change-card-value').textContent ?? '' diff --git a/website/src/cards/CardChanges.tsx b/website/src/cards/CardChanges.tsx index 21df099d1675..a5aadfdae6e9 100644 --- a/website/src/cards/CardChanges.tsx +++ b/website/src/cards/CardChanges.tsx @@ -28,6 +28,37 @@ export const FIELD_LABELS: Record string> = { model: () => i18nT('components.changeCards.field_model'), reasoning_effort: () => i18nT('components.changeCards.field_reasoning_effort'), approval_mode: () => i18nT('components.changeCards.field_approval_mode'), + sender: () => i18nT('components.changeCards.field_sender'), + not_included: () => i18nT('components.changeCards.field_not_included'), + not_imported: () => i18nT('components.changeCards.field_not_imported'), + template_auto_approve: () => i18nT('components.changeCards.field_template_auto_approve'), +} + +/** One inherited MCP server, said as what it reaches: a service's host or a local program. */ +function reachText(r: unknown): string { + const o = (r && typeof r === 'object' ? r : {}) as { name?: unknown; host?: unknown; command?: unknown } + const name = String(o.name ?? '') + if (typeof o.host === 'string' && o.host) return i18nT('components.changeCards.reach_remote', { name, host: o.host }) + if (typeof o.command === 'string' && o.command) return i18nT('components.changeCards.reach_local', { name, command: o.command }) + return name +} + +/** The servers a widen row names, for the warning above the rows. */ +export function reachNames(v: unknown): string { + if (Array.isArray(v)) return fmtList(v.map(r => String((r as { name?: unknown })?.name ?? r))) + return typeof v === 'string' ? v : '' +} + +/** Where the owner changes which servers new crewmates use unasked. */ +export const TEMPLATES_HREF = '/capabilities?tab=templates' + +/** The parts an import card says it leaves out, sent as codes. */ +const LEFT_OUT_LABELS: Record string> = { + crons: () => i18nT('components.changeCards.left_crons'), + keyResults: () => i18nT('components.changeCards.left_key_results'), + avatar: () => i18nT('components.changeCards.left_avatar'), + model: () => i18nT('components.changeCards.left_model'), + dashboardTemplate: () => i18nT('components.changeCards.left_dashboard'), } /** The approval modes a crewmate's own chat can be set to, in the picker's words. */ @@ -49,12 +80,14 @@ const APPROVAL_MODE_HINTS: Record string> = { /** A line under a row's value explaining what the new value means, when the field has one. */ export function changeHint(c: CardChange): string | null { if (c.field === 'approval_mode' && typeof c.after === 'string' && APPROVAL_MODE_HINTS[c.after]) return APPROVAL_MODE_HINTS[c.after]() + if (c.field === 'import_approval') return i18nT('components.changeCards.approval_hint_import') return null } /** A row's label: the localized field name when known, else the gateway's. */ export function changeLabel(c: CardChange): string { if (c.field === 'goal' && typeof c.number === 'number') return i18nT('pages.membersPage.goals_goal_number', { number: c.number }) + if (c.field === 'import_approval') return FIELD_LABELS.approval_mode() return (c.field && FIELD_LABELS[c.field]?.()) || c.label } @@ -67,7 +100,11 @@ function changeValue(c: CardChange, v: unknown): string { if (c.field === 'reasoning_effort' && typeof v === 'string') return v === '' ? i18nT('pages.kiroCrewAgentsPage.inherited') : effortLabel(v) // An approval mode is a code identifier on the wire; the card shows the word // the picker shows for it, so "trust" reads as the same thing in both places. - if (c.field === 'approval_mode' && typeof v === 'string' && APPROVAL_MODE_LABELS[v]) return APPROVAL_MODE_LABELS[v]() + if ((c.field === 'approval_mode' || c.field === 'import_approval') && typeof v === 'string' && APPROVAL_MODE_LABELS[v]) return APPROVAL_MODE_LABELS[v]() + // Codes on the wire, so the words are in the reader's language. + if (c.field === 'not_included' && v === 'private') return i18nT('components.changeCards.not_included_private') + if (c.field === 'template_auto_approve' && Array.isArray(v)) return v.map(reachText).join('; ') + if (c.field === 'not_imported' && Array.isArray(v)) return fmtList(v.map(code => LEFT_OUT_LABELS[String(code)]?.() ?? String(code))) return formatCardValue(v) } @@ -122,6 +159,9 @@ export function CardChanges({ changes }: { changes: CardChange[] }) { {changeHint(c) && ( {changeHint(c)} )} + {c.field === 'template_auto_approve' && ( + {i18nT('components.changeCards.template_link')} + )} )} diff --git a/website/src/cards/CardResultLine.tsx b/website/src/cards/CardResultLine.tsx index a4b846f3bb11..0b14c588875c 100644 --- a/website/src/cards/CardResultLine.tsx +++ b/website/src/cards/CardResultLine.tsx @@ -56,7 +56,7 @@ function appliedSummary(card: Card, title: string): string { return i18nT('components.changeCards.result_schedule_created', { name, schedule: fmtCardCron(card.params.cron_expr) }) } } - if (card.kind === 'crewmate.create' && name) return i18nT('components.changeCards.result_crewmate_created', { name }) + if ((card.kind === 'crewmate.create' || card.kind === 'crewmate.import') && name) return i18nT('components.changeCards.result_crewmate_created', { name }) if (card.kind === 'setting.change') { const row = cardChanges(card)[0] const label = row ? changeLabel(row) : '' diff --git a/website/src/cards/ChangeCard.tsx b/website/src/cards/ChangeCard.tsx index 23d45fdeb280..5edb8c6b1585 100644 --- a/website/src/cards/ChangeCard.tsx +++ b/website/src/cards/ChangeCard.tsx @@ -17,7 +17,7 @@ import ErrorNotice from '../components/ErrorNotice' import { i18nT } from '../i18n/t' import { fmtRelative, toDate } from '../i18n/format' import { cardsApi, CARD_FINISHED_STATUSES, type Card } from '../api/cards' -import { CardChanges } from './CardChanges' +import { CardChanges, reachNames } from './CardChanges' import { cardChanges, cardTitle, FALLBACK_ICON, specFor } from './cardRegistry' import { oneShotRunAt } from './oneShot' import { CardRow, UserInputs } from './kindBodies' @@ -52,6 +52,14 @@ function safeHttpUrl(value: string): string { } +/** The widen warning; an import card names the servers it would run unasked. */ +function widenText(card: Card): string { + const row = card.kind === 'crewmate.import' ? card.changes.find(c => c.field === 'template_auto_approve') : undefined + const servers = row ? reachNames(row.after) : '' + if (servers) return i18nT('components.changeCards.risk_widen_import', { servers }) + return i18nT('components.changeCards.risk_widen') +} + interface ChangeCardProps { card: Card store: (c: Card | null) => void @@ -300,7 +308,7 @@ export default function ChangeCard({ card, store, refresh, remove }: ChangeCardP
{widen && (