Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions docs/app-kit/api-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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": "<key>"}
```

`bundle` is `{"crewmate": <crewmate.json>, "agent": <agent.json>, "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 `<name> 2` to `<name> 9`, and the owner can edit it.

The card is stored under the key `app:<name>` 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
Expand Down
2 changes: 2 additions & 0 deletions docs/app-kit/manifest-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -887,6 +887,7 @@ packages at all.
"sessionApproval": false,
"spawn": false,
"jobs": false,
"proposeCrewmate": false,
"exposeToApps": []
}
}
Expand All @@ -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
Expand Down
10 changes: 10 additions & 0 deletions docs/system-specs/modules/app-kit-platform.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<name>` 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/`
Expand Down
1 change: 1 addition & 0 deletions docs/system-specs/modules/crew-mode.md
Original file line number Diff line number Diff line change
Expand Up @@ -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=<encoded-name>&goal=<encoded-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.
Expand Down
16 changes: 16 additions & 0 deletions src/kiro_crew/apps/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.

Expand All @@ -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.
Expand Down Expand Up @@ -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,
Expand All @@ -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),
Expand Down
61 changes: 61 additions & 0 deletions src/kiro_crew/apps/crewmate_sdk.py
Original file line number Diff line number Diff line change
@@ -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:<name>``. 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
1 change: 1 addition & 0 deletions src/kiro_crew/apps/hooks_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions src/kiro_crew/apps/lifecycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
6 changes: 6 additions & 0 deletions src/kiro_crew/apps/manifest_sections.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:<this-app> / subagent:app:<this-app> declarations to observe
# this app's slots and subagents. Empty list = no cross-app visibility.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
)

Expand Down
Loading
Loading