Files
gabrielvidal 94f808d34a Merge branch 'fresh-context-plugin': feat(plugins): move fresh context out of core with provider.cache and composer hooks (#52)
# Conflicts:
#	CLAUDE.md
#	backend/settings/routes.py
#	backend/telemetry/features.json
#	frontend/openapi.json
#	frontend/src/api.ts
#	frontend/src/business/settings/lazy.tsx
#	frontend/src/business/settings/redirects.test.tsx
#	frontend/src/business/settings/redirects.tsx
#	frontend/src/business/settings/registry.test.ts
#	frontend/src/business/settings/rows.test.ts
#	frontend/src/business/settings/rows.ts
#	frontend/src/generated/api.ts
#	frontend/src/lib/queries.ts
#	frontend/src/lib/telemetry/features.ts
#	frontend/src/root.tsx
2026-12-01 17:15:19 +01:00

2946 lines
193 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Live User Plugins (`v1 + v2 + v3`)
Live plugins let **anyone** with permission (`plugins.install` / `plugins.create`) build, install, reload, and share self-contained extensions for `ai-agent` **without rebuilding the Docker image or running untrusted code inside the hub process**.
## Storage layout
Runtime state never lives in git; plugin sources live outside `ai-agent` core.
- **Hub / owner plugins repo:** `~/projects/ai-agent-plugins` (private Gitea repo `gabrielvidal/ai-agent-plugins`), one folder per plugin under `plugins/<id>/`.
- **User-created plugins:** created inside the app (`Settings → Plugins → + New plugin`), living in their own folder/Gitea repo (or any local path / git URL).
- **Hub runtime data** (under `PLUGINS_DIR`, default `/data/plugins`):
- `installed.json` — per-user installs, capability approval fingerprint, enabled flag, non-secret config, webhook tokens, schedule status, plus the operator's **hub catalog**.
- `secrets/<uid>/<id>.json` (`0600`) — write-only per-user secrets (`secrets/_hub/<id>.json` for hub-scoped secrets set by the operator). Never returned by any GET API.
- `data/<uid>/<id>/` — per-user plugin storage and scheduled snapshots (quota-enforced).
- `live-skills/<uid>/<id>/` — materialized copy of each enabled plugin's `skill/` folder, injected live into lab runs (`shared_skills.py`) and synced to paired computers (`labsync.py`).
- `repos/<hash>/` — shallow git clones for plugins installed by git URL.
## Plugin folder layout
```text
<plugin-dir>/
├── plugin.json # required manifest (schema: 1)
├── skill/ # optional — live-injected skill for agent runs + workers
│ ├── SKILL.md
│ └── scripts/... # calls AIA_TOOLS_URL/plugins/<id>/...
├── ui/ # optional — v2 sandboxed HTML documents (/sandbox-frame.html)
├── jobs/ # optional — v1/v2 non-LLM scheduled scripts
└── handlers/ # optional — v3 sandboxed action scripts
```
## Manifest (`plugin.json`)
```json
{
"schema": 1,
"id": "meta",
"name": "Meta Business",
"version": "1.0.0",
"description": "Read-only Meta ads, Instagram & Page insights",
"category": "data",
"icon": "megaphone",
"color": "#545e91",
"illustration": "illustration.webp",
"readme": "README.md",
"skill": { "dir": "skill", "name": "meta" },
"secrets": [
{
"key": "token",
"label": "System-user token",
"placeholder": "EAA...",
"help": "Stored write-only on the hub.",
"scope": "user",
"required": true
}
],
"settings": {
"subtitle": "Read-only ads, Instagram and Page insights",
"instructions": "## Setup\n1. Create a read-only system user token…",
"fields": [
{ "key": "timezone", "label": "Timezone", "type": "text", "default": "Europe/Paris" }
],
"links": [
{ "label": "Business settings", "url": "https://business.facebook.com/settings/system-users?tz={{config.timezone}}" }
],
"testAction": "inspect",
"statusAction": "status"
},
"proxy": {
"baseUrl": "https://graph.facebook.com/v27.0",
"internal": false,
"stream": false,
"auth": { "in": "header", "name": "Authorization", "prefix": "Bearer ", "secret": "token" },
"headers": { "X-Example": "guest-{{user.id}}" },
"allow": [
{ "method": "GET", "path": "^me(/(adaccounts|accounts|permissions))?$" }
],
"denyParams": ["access_token", "method"],
"stripResponseKeys": ["access_token"],
"scrubSecrets": true,
"maxBytes": 20971520,
"inspect": {
"method": "GET",
"path": "me/permissions",
"requireOnlyScopes": ["ads_read", "read_insights"]
},
"wake": null
},
"managed": {
"defaultForGuests": false,
"allowUserSecretOverride": false,
"metered": false,
"grantFields": [
{ "key": "allowPro", "label": "Allow Pro models", "type": "checkbox", "default": false }
],
"limits": { "inFlight": 4, "jobsPerDay": 40, "defaultMonthlyBudgetUsd": 5.0 },
"keyHealth": { "alertLimit": 20.0, "currency": "EUR", "pushAtPct": 80, "pushOnBreak": true,
"secretKey": "token", "legacyLedgerTool": null }
},
"storage": { "maxMb": 50 },
"schedules": [
{ "id": "daily-snapshot", "cron": "0 7 * * *", "script": "jobs/snapshot.py", "timeoutSec": 180 }
],
"ui": {
"settingsHtml": "ui/settings.html",
"pages": [
{ "id": "board", "label": "Board", "nav": "dashboards", "html": "ui/board.html" }
],
"toolCards": [
{ "id": "card", "match": { "tool": "shell", "commandRegex": "\\bmytool\\b" }, "label": "My Tool", "html": "ui/card.html" }
],
"slots": [
{ "id": "proj", "where": "project.detail", "html": "ui/slot.html", "height": 140 }
],
"fences": [
{ "id": "chart-fence", "lang": "chart", "html": "ui/chart.html", "height": 330 }
]
},
"events": [
{ "id": "done-hook", "on": ["conversation.finished"], "url": "https://example.com/hook", "secret": "hook_secret" }
],
"webhooks": [
{ "id": "inbound", "mode": "notify", "titleTemplate": "Update: {{title}}" }
],
"actions": {
"inspect": { "script": "handlers/inspect.py", "timeoutSec": 30 },
"status": { "script": "handlers/status.py", "timeoutSec": 20 }
},
"resources": [
{ "id": "jira", "label": "Jira issue", "urlRegex": "^https://[a-z0-9-]+\\.atlassian\\.net/browse/(?P<key>[A-Z]+-\\d+)",
"idTemplate": "{key}", "color": "#0052CC", "priority": 10, "hueRole": "hue" }
],
"capabilities": ["conversations.read"]
}
```
## Art and the info page (since 2026-11-25)
Every plugin has a card in Settings → Plugins (a catalog with categories —
see "Categories and the Plugins page" below) and its own page: the illustration, its
settings, then its **info** — the README, what it can access (the capability
list), what runs on its own (schedules, webhooks), its pages, version, author
and source. A catalog entry's page is the info and an Install button.
| Field | What | Default when not declared |
|---|---|---|
| `icon` | a lucide name, **or** a path to an `.svg` (≤ 32 KB, 24×24, strokes in `currentColor`) | `icon.svg` at the root, else `puzzle` |
| `illustration` | `.webp` / `.png` / `.jpg` / `.svg`, ≤ 1 MB, about 16:9 (cropped to a banner) | `illustration.{svg,webp,png,jpg}` at the root |
| `color` | hex accent of the icon's tile (the illustration's background) | a neutral tile |
| `readme` | a `.md` (≤ 64 KB) — the info page's text, for people, not agents | `README.md` at the root |
- The icon is drawn as a CSS mask, so it follows the tile's colour; no plugin
markup reaches the DOM. An SVG with scripts, event handlers, `foreignObject`,
external or `data:` references is refused at install, and refused again when
served if it changed on disk.
- `GET /api/plugins/{id}/asset/{icon|illustration}` serves them sandboxed
(`CSP: sandbox`, `nosniff`), for an install of the caller, a managed plugin
granted to them, or a catalog entry they can see; the URLs carry
`?v=<artVersion>`. `GET /api/plugins/{id}/info` returns the info page.
- Art is not in the approval fingerprint: changing it never asks for
re-approval. A record installed before art existed gets it from its source
once, on the next list.
- Hub plugins use soft-clay 3D illustrations (Nano Banana Pro, 16:9, a muted
gradient background, the tile colour sampled from its darker edge).
## Categories and the Plugins page (`category`, since 2026-11-28)
Settings → Plugins is one catalog (Orca's layout, the app's own look; form
`plugins-page-rework_rhce3j`): a **category sidebar** with counts on the left
(a horizontal chip row on a phone), search, an **All / Installed / Available**
segmented filter and a **sort** (Installed first — the default —, Name,
Recently updated) on top, and the plugins as **cover cards** (illustration
banner, the tile overlapping its edge, author · category) or compact rows —
the grid / list toggle is kept (`settings.pluginsView`), and so is the sort
(`settings.pluginsSort`), per person. *Installed* = an install of yours or a
managed plugin provided to you (a guest); *Available* = a catalog entry you
haven't installed. One card per plugin: an installed one opens its settings, a
catalog one its info and Install.
The manifest's `category` (`plugins/categories.py`) is one of:
| `category` | Label | Who may use it |
|---|---|---|
| `dev` | Dev and code | app plugins |
| `data` | Data and costs | app plugins |
| `agents` | Agents and context | app plugins |
| `chat` | Chat and mail | app plugins |
| `scheduling` | Scheduling | app plugins |
| `media` | Media and fun | app plugins |
| `other` | Other | app plugins — **the default** when an app declares none |
| `providers` | Providers | `kind: "provider"` only (its default) |
| `harnesses` | Harnesses | `kind: "harness"` only (its default) |
| `translations` | Translations | `kind: "translation"` only (its default) |
- Checked strictly at install: an unknown value, a kind shelf on an app, or a
typed plugin outside its kind's shelf is refused. Not in the approval
fingerprint.
- Every row of `GET /api/plugins` (`installed`, `catalog`, a guest's `managed`)
carries the resolved `category`. A record installed or promoted before the
field reads it off its source's `plugin.json` (cached on its mtime), else
takes its kind's default — no re-install, no re-approval.
- A category with no plugin under the current filter is hidden from the
sidebar (except the one selected), so *Translations* shows up as soon as a
translation plugin exists.
- The frontend's labels and icons: `frontend/src/business/plugins/categories.ts`
— keep it in step with `CATEGORIES`.
- Addresses: `?cat=<category>`, `?show=installed|available`. The old ones
still land: `?tab=providers|harnesses|translations` → that category, `?tab=catalog` →
Available, `?tab=catalog&kind=harness` → Available harnesses (the
composer's "no harness installed" link). For the operator, *Available* is now
the `plugin-catalog` plugin's page (next section).
## The public catalog and the `plugin-catalog` plugin (`plugins.manage`, since 2026-11-28)
The catalog of what *isn't* installed left Settings → Plugins for a website
and a plugin (Gabriel's form `plugin-catalog-and-public-plugins-repo_al2ibd`):
- **The public site** — `ai-agent.plugins.gabvdl.xyz`, built by the plugins
repo's `scripts/build-catalog.py` (stdlib) into `site/dist/`: a static card
grid (categories, kinds, search, a page per plugin with its README and what
it declares) and **`catalog.json`** (`{schema: 1, generatedAt, commit, repo,
plugins: [{id, name, version, description, kind, category, author, color,
icon, iconSvg, illustration, readme, languages, capabilities, declares,
schedules, webhooks, pages, skill, seed, requires, optionalRequires,
source}]}`, art under `art/<id>/`). Only the ids of `catalog/public.json`
are published; `source` is `<public repo>#plugins/<id>`. Deployed from the
Homelab with `site/deploy.sh` (zipgo).
- **The plugin** — `plugin-catalog` (seeded, the operator's only): a
`nav: "settings"` page (`tools`, after Plugins, `perm: plugins.manage`,
`opens: ["plugin-catalog"]` with `{cat, show}`) that draws the same data with
**Install / Update / Uninstall**. Its `catalog` action reads the
`catalogUrl` setting (the public site by default; `https://`, or `http://`
to this machine for a preview) and keeps the last copy for when the site is
down; `art` returns one picture as a `data:` URL (the frame has no network).
Not the plugin proxy: a proxy's `baseUrl` is fixed in the approved manifest
and can't follow a setting.
- **The install bridge** (`frontend/src/business/plugins/catalogBridge.tsx`):
`aiAgentPlugin.plugins.list()` → `{installed: [{id, name, version, enabled,
needsApproval, fromCatalog, source, seed}], catalogRepo}`;
`.install({source})` and `.uninstall({id})` → `{ok: true, id, version?,
purged?}` | `{ok: false, cancelled: true}`. The frame only **asks**: the host
checks the caller is the operator (not read-only, not impersonating) and the
asking plugin is theirs, enabled, approved and holds the **`plugins.manage`
capability** (operator-only, in the approval fingerprint); a source must be
`<catalogRepo>#plugins/<id>` exactly. Then the **host draws the
confirmation**: for an install, what `POST /api/plugins/validate` (refreshed
clone) says — name, version, source, every capability, a warning when it
needs the operator, what an update replaces — and only *Install* sends the
owner's own `POST /api/plugins/install` (the folder must hold the plugin its
path names); for an uninstall, **keep or delete its data and secrets**, asked
each time (`DELETE /api/plugins/{id}[?purge=true]`). A plugin can't uninstall
itself. Anyone else gets a refusal (an error from the call), never a dialog.
- **`catalogRepo`** on `GET /api/plugins` (the operator's only, else null):
`PLUGIN_CATALOG_REPO` (`plugins/catalog_repo.py`), default
`https://git.gabvdl.xyz/gabrielvidal/ai-agent-plugins-public.git` — the
one-way public mirror; the builder's `PUBLIC_REPO` must say the same.
- **Settings → Plugins** keeps what is installed. The operator's page has no
All / Installed / Available switch: *Browse the catalog* opens the plugin's
page (`usePluginOpener("plugin-catalog")`), the hub catalog's entries
promoted for guests wear a *For guests* pill, and an old *Available* link
(`?show=available`, `?tab=catalog&kind=harness` — the composer's "no harness
installed") redirects to the plugin's page on that shelf. With the plugin off
or uninstalled, a note says so and offers *Install the plugin catalog* (from
`<catalogRepo>#plugins/plugin-catalog`). A guest's page is unchanged: their
*Available* is still the hub catalog the operator promoted for them.
## Host data and slots (since 2026-11-25, the Services plugin)
- `ui.slots[]` render: `conversation.details` in a conversation's Details drawer (init
`{sessionId, conversationId}`, one `pluginSlots` card for all of them) and
`machine.detail` on a machine page's Tools tab (init `{machineId, name,
kind: "lab"|"worker"}`, the owner's machines only — see "Machines, relays
and attention"),
through `PluginSlots` (`frontend/src/business/plugins/components/`) — a
borderless sandboxed frame sized by `aiAgentPlugin.resize(px)`; a slot with
nothing to show calls `resize(0)` and folds to no height. Every plugin
frame (pages, slots, settings, tool cards) now gets the app's theme tokens on
`:root` (`--background`, `--foreground`, `--card`, `--border`, `--primary`…,
`lib/sandboxTheme.ts`), so `hsl(var(--card))` follows light / dark and the
accent.
- `provides`: data the **host** asks a plugin for — in the fingerprint.
`{"services.index": "<action>"}` (since 2026-11-28, the Services plugin,
which now owns the **whole** catalogue — `backend/services/`,
`/api/services`, `/api/service`, the `service.cards` merge, the
`service.card` / `service.detail` slot places, the core `/services*` pages,
`ai-agent services` and MCP `browse services` are gone): every service the
plugin indexes (`dir`, `name`, `description`, `goal {done,total}`,
`updatedAt`, `icon`, `group`, `urls`, `containers`, `containerCount`,
`images`, `profiles`, `auth`, `hasCompose`, `hasTraefik`, `routerCount`),
newest commit first. `backend/plugins/services_bridge.py` runs it as the
owner, whitelists the fields, caches 30 s stale-while-revalidate (keyed on
the provider and the store's version: a plugin write re-reads in the
background) and hands it to the core's readers — the Goals board's service
goals, the Graph's service nodes, and **`GET /api/plugins/services-index`**
(owner only, `lab.read`), which the tag registry, the composer's service
chips and `ai-agent tags` read (the frontend only while
`usePluginProvides("services.index")`). No plugin: `[]` everywhere, no
`service:` chips in the composer, and `service:` pills are plain.
- `services.read` (capability, operator-approved): the owner's handler runs
get `AIA_SERVICES_DIR` (the host's services dir, read-only); a guest's never.
It also opens **`GET …/hub/services/commits`** (owner only):
`{services: {<dir>: {updatedAt, commits: [{hash, date, subject}]}}}` off one
bucketed `git log` of the repo's `services/` (cached on HEAD,
`backend/servicesdir.py` — never a fork per service), or `{updatedAt,
commits}` for `?slug=<dir>` (404 for a dir that isn't one).
- `conversations.read`'s `hub/conversations` rows carry `services` (the dirs
a conversation is tagged with — its meta's, else the parser's
`servicesAuto`), and `?service=<dir>` returns, from the whole archive, the
conversations tagged with it (with `model`; `metrics=1` adds cost and
tokens) — the Services plugin's *Linked conversations*.
- `provides: {"plans.index": "<action>"}` (since 2026-11-25, the Plans
plugin — `data/plans` left the core): the plan summaries, read by
`backend/plugins/plans_bridge.py` as the owner for the Graph's plan nodes
(`graph.read`); `plans_bridge.get_plan` runs the same plugin's `get`. The
CLI (`ai-agent plugin plans ls|show`) and the MCP tools `plugin_plans_ls` /
`plugin_plans_show` are the plugin's own `commands` (below, "Commands").
No plugin, no plans: every
reader gets `[]` / 404. The old `/plans` and `/plans/<slug>` routes
redirect to `/plugins/plans/plans[/<slug>]`.
- `provides: {"memories.index": "<action>"}` (since 2026-11-26, the
Memories plugin — `backend/memories/` and `core/filecache.py` left the
core): the memory summaries (`slug`, `name`, `description`, `type`,
`originSessionId`, `projects`, `services`, `links`, `words`, `bytes`,
`updatedAt`), read by `plugins/memories_bridge.py` for the Graph's memory
nodes. The CLI (`ai-agent plugin memories ls|show`) and the MCP tools
`plugin_memories_ls` / `plugin_memories_show` are the plugin's own
`commands`. The conversation Details
drawer's memories card is the plugin's `conversation.details` slot (a
service's memories are its exported `for_service` action, which the
Services plugin's page calls — `optionalRequires: ["memories"]`);
`ConversationDetail` no
longer carries `memoriesRead` / `memoriesCreated` (the indexer still
records the slugs a transcript read — the plugin reads them through
`hub/conversations?memories=1`). `/memories[/<slug>]` redirect to
`/plugins/memories/memories[/<slug>]`.
- `provides: {"notify.channel": "<action>"}` (since 2026-11-25, the Home
Assistant push plugin): the plugin **delivers its installer's pushes** — run
as that person for every push, question and clear they get, stdin
`{"event": "notify"|"ask"|"clear", "push": {id, title, message, question,
options, url, image, type, importance, channel, actions, tag, spoken…}}`,
stdout `{"ok": bool, "status"?: int, "error"?: str}`. Tried once (a notify /
ask on the request thread, a clear off it), never retried; the app and
browser push still reach the person without one. Buttons answer the hub
(`/api/ask/{id}/answer`, `/api/notify/{id}/action`). An ask's `options` are
2 to 8 labels (≤ 80 characters) and its `question` up to 4 000 characters:
a channel that can't draw them all shows none as buttons — the list, and a
link to `url` where the app has them — never the first few. Host side:
`backend/notifications/channels.py`; example: `home-assistant-push`.
- **Plugin dependencies (`requires`, `optionalRequires`, `exports`, `emits`, `plugin:<dep>:<event>`):**
(`optionalRequires`: optional peers — see "Keyboard shortcuts" below.)
a plugin can declare `"requires": ["ask-form"]` (checked at install / enable /
disable / uninstall; in the approval fingerprint). A base plugin opts actions
into cross-plugin calls with `"exports": ["create", "get"]` (a dependent
plugin's handler token `aiah1` can then POST to
`/proxy/tools/plugins/<base>/actions/<act>`, capped at call depth 4, with
`AIA_USER_CONTEXT.callerPlugin` set) and declares events in `"emits": […]`
(fired via `POST /proxy/tools/plugins/<base>/hub/emit` and delivered to
enabled dependents subscribing to `"plugin:<base>:<event>"`).
- **Declarative Claude subagents (`agents[]`) & `default+override` prefs:**
a plugin can declare `"agents": [{name, description, promptFile, tools,
omitClaudeMd?, enabledPref?, modelPref?, effortPref?}]` loaded in-process by
`backend/runs/extras.py` (0 ms overhead). `ui.prefs[]` supports
`"scope": "default+override"` (operator's setting is everyone's default;
guests can override or reset to default) and
`"optionsFrom": "user.modelFamilies"` (clamped to each user's allowed Claude
model families). First user: the `clarifier` plugin.
- `provides: {"composer.shortcuts": "<action>"}`: prompt shortcuts rendered
natively by the core composer's `RichInput` (`GET
/api/plugins/composer-shortcuts`, cached and invalidated on plugin mutations)
— since 2026-11-27 the composer's only source of chips (the
`prompt-shortcuts` plugin's library, ask-form's Form chip). The answer is
`{"shortcuts": [...], "position"?: "first"}`: `"first"` puts its chips
before the other providers' (of two with one id the first wins); up to 64
chips; a chip keeps `runners: []` (no runner offers it — guests only) and
`hidden: true` (a guest hid it: out of the composer, still named by the
thread's prompt pills). Any POSTed action of a plugin that provides it drops
its cached chips — every caller's — and publishes SSE
`{"type": "composer-shortcuts"}` (guests too): every composer refetches.
## Commands: the `ai-agent` CLI and the MCP server (since 2026-11-26)
A plugin adds its own commands to the `ai-agent` CLI and, opt-in, tools to
the hub's MCP server (Claude.ai, ChatGPT — itself the `hub-mcp` plugin since
2026-11-28) with a `commands` block — no core edit, no plugin id in core. Gabriel's choices
(form `ai-agent-cli-and-mcp-for-live-plugins_fevcts`): manifest-declared
commands, **namespaced** under `plugin`, MCP **opt-in** per command, guests
**follow their plugin grants**. Code: `backend/plugins/commands.py`
(validation + catalogue), `cli/plugin_commands.py` (parser, printing, MCP
tool specs — `tool_specs` / `call_tool`, which the hub-mcp plugin's
`handlers/hubmcp_tools.py` `plugin_tools` calls). Before this, each move from core
hard-coded its plugin's id in `cli/ai_agent.py` + `cli/mcp_tools.py`
(`plans_call`, `memories_call`): gone, and `ai-agent goals` / MCP
`work_on_goal` / `browse plans|goals|memories` / `read_document` with them.
```json
"commands": {
"ls": { "action": "index", "summary": "Every plan, newest first: slug, status, title",
"output": { "rows": "plans", "columns": ["slug", "status", "title"] },
"mcp": true },
"show": { "action": "get", "summary": "One plan's markdown",
"description": "Longer text for --help and the MCP tool description.",
"args": [ { "name": "slug", "positional": true, "required": true,
"help": "The plan's slug, as `ls` lists it." },
{ "name": "conversations", "type": "boolean", "default": false } ],
"output": { "text": "content" }, "mcp": true }
}
```
- **A command = one declared action** (`action`), a one-line `summary`
(required: the `--help` line and the MCP description), an optional
`description`, its `args` and `output`. At most 16 commands, 12 args each.
Names: commands `[a-z][a-z0-9-]{0,31}`, args `[a-z][a-z0-9_]{0,31}` (not
`json`, not `query`).
- **`args[]`**: `type` `string` (default) · `integer` · `number` · `boolean` ·
`array` (of strings); `positional` (a boolean can't be; only the last
positional may be an array; a required positional never follows an
optional one), `required`, `enum` (strings), `default` (sent when the
argument isn't given — how `memories show` asks for no conversations by
default), `help`. Flags are `--kebab-case` of the name; a boolean is a
switch (`--no-x` when its default is `true`); an array flag repeats.
**`conversation: true`** (a plain string, since 2026-11-28 — Send later's
`add --to`): the argument names a conversation, and the CLI and the MCP
resolve whatever was given (a session id, a ≥ 6-char prefix, a
conversation id, a viewer link) to its **session id** before the action
sees it; the CLI takes `.` for the run it is called from
(`$CLAUDE_SESSION_ID`), the MCP refuses `.` (no run behind the call).
An older hub ignores the key and passes the value as typed.
- **`output`**: `{"text": "<field>"}` prints that field of the answer,
`{"rows": "<list field>", "columns": [...]}` prints the rows as an aligned
table (MCP: one JSON line per row with only those columns, and an implicit
`query` argument that keeps the rows containing every word), absent = the
JSON answer. `--json` always prints the raw answer.
- **`mcp: true`** offers it as the tool `plugin_<id>_<command>` (≤ 64
characters, refused at validation otherwise). Group `read` when the action
is `readOnly`, else `run` (a read-only connection sees only the read ones);
`destructive: true` sets the hint. The MCP server itself is the `hub-mcp`
plugin (since 2026-11-28): it lists these from `GET /api/plugins/commands`
as the connection's caller.
- **Calls**: a `readOnly` action goes by `GET …/actions/{action}?payload=`
(8 KB), anything else by POST — the same route the plugin's pages use, so
the caller's grants, `ownerOnly` and `runAs` apply unchanged. That is why
`commands` is **not** in the approval fingerprint: it adds no reach.
The consent card / info page lists them (`kind: "commands"`).
- **Catalogue**: `GET /api/plugins/commands` (`plugins.use`) — the commands of
the plugins active for the caller: the owner's installs; a guest's own
installs plus the owner's `managed` plugins granted to them, minus any
`ownerOnly` action. A guest's CLI (the guard's broker) and AI-app
connection get exactly those.
- A plugin whose id is a core `ai-agent plugin` verb (`ls`, `install`,
`commands`, `call`, …) can't declare commands.
On the CLI:
```bash
ai-agent plugin commands # every command you have, with its MCP tool
ai-agent plugin plans ls # a plugin's command
ai-agent plugin memories show SLUG --json # raw answer
ai-agent plugin plans --help # that plugin's commands
ai-agent plugin call movies op --payload '{"op":"status","id":7}' [--get] # any action, raw
ai-agent memories # → "is the Memories plugin's — ai-agent plugin memories <command>"
```
## Batch 1 platform hooks (since 2026-11-26)
Shared hooks for the templates, memories, desk-phone, activity, project-env,
ship and blue-green-deploy plugins (the legacy core modules stay until each
plugin replaces them).
- **Owner-only capabilities** (operator approval; a guest's run never gets
them): `templates.read` → `AIA_TEMPLATES_DIR` (`TEMPLATES_DIR`),
`memories.read` → `AIA_MEMORIES_DIR` (`MEMORIES_DIR`), `projects.env` →
`AIA_PROJECTS_DIR` (`projects.catalog.PROJECTS_DIR`), set in the owner's
handler env only (`plugins/runner.py`); `activity.read`, `usage.read`,
`usage.calibrate` and `ship.run` are hub bridges (below).
- **`provides` keys:** `memories.index` (`plugins/memories_bridge.py`, the
`plans_bridge` twin: `list_memories`, `get_memory` via the plugin's `get`,
`has_provider`; the Graph's only source of memory nodes since the
`memories` plugin, below),
`notify.audio` (a push's spoken audio — the `desk-phone` plugin: the
owner's provider gets `{spoken, type, title, message, audio}` and answers
`{ok, wavBase64, contentType}`; `POST /api/notifications/audio` decodes it,
503 without one — `notifications/channels.render_audio`), `app.banner` (below).
`GET /api/plugins` (and its `ui`) carries `provides: [...]`, the sorted keys
active for the caller (`usePluginProvides(key)` in the frontend); a guest's
list never has `app.banner`.
- **`app.banner`** (`plugins/banner.py`): the owner's plugin answers
`{active, title, label, status: running|done|failed|info, phaseNum,
totalPhases, phase, steps: [{n, label, state?}], startedAt, updatedAt,
sessionId?, maintenance?}` (a missing step `state` is derived from
`phaseNum` + `status`); `GET /api/app-banner` (owner only, `lab.read`)
serves it cached 5 s with `sessionId` resolved to `conversationId` /
`convTitle` / `convUrl`; `frontend/src/technical/StatusBanner.tsx` draws it
while `active`. Any webhook or (non-GET) action of the providing plugin
drops the cache and publishes SSE `{"type": "banner"}`; while a banner shows,
the app also polls it (6 s once done/failed, 1 min while running), so a
provider can let a snapshot expire with no webhook (`blue-green-deploy`
hides done/failed after 10 s, a silent `running` after 30 min).
`banner.is_maintenance(deps)` (`maintenance: true` or `status: "running"`)
pauses guest-job push delivery (`runs/guestjob.py`).
- **Webhooks, `mode: "action"`**: runs the named action as the installer with
`{"trigger": "webhook", "hookId", "body"}` on stdin; `internalOnly` → 404 on
the public guest host.
- **`hub/conversations`**: `memories=1` adds `memoriesRead` (slugs) and
`model` to each row; `memory=<slug>` scans the whole archive (no `days`
window) for the conversations that read it.
- **`activity.read`** — `GET …/hub/activity?account=<scope>&tzOffset=<min>`:
the Activity rollup (`days`, `binsByDay`, `models`, `totals`,
`account`, `byAccount`) plus `profiles` (`plugins/activitydata.py`). Read by
the `activity` plugin since 2026-11-26, which replaced core's
`/api/activity` and `/dashboards/activity` (that path is gone since
2026-11-27 — the core names no plugin page). Local-day helpers live in
`dashboards/timebins.py`. Home's usage tile reads the slim
`GET …/hub/activity/daily?days=&scope=&tzOffset=` (`{days: [{date, cost,
tokens, conversations}]}`, 1–90 days, owner only — `usage/routes.py`
`daily_usage`; the core `/api/usage/daily` route is gone).
- **`home.read`** (since 2026-11-29, not operator-only) — `GET …/hub/home?scope=&profileScope=&tzOffset=`
(`plugins/hubbridge.py`): the caller's own home page as data — `{tiles,
running, waiting}`: every active plugin's `provides: home.tiles` exactly as
`GET /api/plugins/home-tiles` answers them (sanitized, each with its
`pluginId`; `profileScope` defaults to `all`), the count of their
conversations running now (archived ones left out) and their *Waiting for
feedback* count (`provides: inbox.waiting`). A guest's plugin reads that
guest's own. It is how a tile reaches a surface outside the app: the
`android-push` plugin draws them in its live notification, so a plugin that
gives a home tile is in the notification with no change of its own.
- **`usage.read`** — `GET …/hub/usage/overview?scope=<all|profile:id>&days=<1–120>`:
one scope's Plan usage in one answer (`plugins/usagedata.py`) — `accounts`
(the scope's accounts with a /usage source, `/api/accounts`' rows plus the
live plan's `planWindows` / `planLabel` / `planTier` and `subscription`:
Settings → Logins' plan, monthly price and start date, or null), and per
account `limits` (`/api/usage/limits`' entry), `history`
(`calibrate.history`), `plans` (`/api/usage/plans`) and `calibration`
(the stored fits; no core route reads either any more), plus the scope switch's `profiles`. `all` =
every account; a profile = its ★ seats; the Guests profile = the default
profile's. **`usage.calibrate`** — `POST …/hub/usage/calibrate {backfill?}`:
`POST /api/usage/calibrate`'s fit (`{calibrations, shifted}`), then an SSE
`usage`. Read by the `plan-usage` plugin since 2026-11-26, which replaced
core's `/dashboards/plan` page (`PlanUsage.tsx` + `planViz.tsx`; that path
is gone since 2026-11-27 — the plugin's page is `/plugins/plan-usage/board`). `usage/` itself — poller, store, calibration, budget, burn and
every `/api/usage/*` route — stays core: Home's strip and burn tile, the
composer's rings, `ai-agent usage` / `budget` and the rate-shift pushes
read it. Home's half-ring gauge is `dashboards/components/ArcGauge.tsx`.
- **`perf.read`** / **`perf.act`** (`plugins/hubperf.py`, since 2026-11-26,
the `performance` plugin): the Performance and Storage dashboards' data.
`perf.read` — GET `…/hub/perf/live?account=` (+ `profiles`, `guestNames`),
`history?range=&runner=&account=`, `conversations`, `commands?kind=`,
`conversation/{sid}?series=10m,life` (`{perf, series}` — one call per
refresh of a Details card), `conversation/{sid}/storage`, `storage`
(+ `profiles`, `guestNames`), `storage/history`, `storage/writers`,
`storage/config?runner=`, `settings`: the `/api/perf/*` answers. `perf.act`
— POST `…/hub/perf/kill`, `keep`, `settings` (a partial patch),
`storage/rm`, `storage/scan`, `storage/config`, the bodies of their
`/api/perf/*` twins, **the plugin's own handlers only**. Both owner-only,
operator-approved; refusals `{error: {message, kind}}` (`bad_request`,
`handler_only`, `capability`). `telemetry.read` also serves
`…/hub/telemetry/hub?range=24h|7d|30d` (`/api/telemetry/hub`: the hub's own
latency, loop lag, routes, web vitals, JS errors). The plugin replaced
core's `/dashboards/performance` and `/dashboards/storage` (gone since
2026-11-27: the core names no plugin page), the conversation's five CPU & RAM cards and *On disk* card, and
(2026-11-27) the header's CPU and On-disk chips (`PerfChip`, `StorageChip`
and the *Performance* eye switch — now its `conv-chips`
`conversation.header` slot, reading `conversation/{sid}` without `series`
and `conversation/{sid}/storage`, with its own *Performance chips* switch);
`backend/perf/` and every `/api/perf/*` route stay (the Bash cards' cost
strip, the guest Stats). A `conversation.details` slot's `update` also
carries `drawerOpen` and `prompts` (each prompt's epoch s).
- **`ship.run`** (owner's handler token only — a guest reaches it through a
`runAs: "owner"` action, whose `AIA_USER_CONTEXT.requester` carries `uid`,
`isOwner`, `name`, `lang`, `domains`, `sessionId`, `grant`):
`POST …/hub/ship/deploy {project, host, dir?, actor?, sessionId?}` (host
sidecar `/ship/deploy`, `dir` defaulting to `package.json`
`zipgo.deploy[host]` else `dist`, then a `ship_deploy` security event naming
`actor`), `POST …/hub/ship/audit {kind: guard_block|ship_deploy, actor,
project?, host?, detail?, sessionId?}`, `GET …/hub/ship/scan?project=` →
`{hosts, buildDirs}`. The plugin enforces who may deploy where. Since
2026-11-26 the `ship` plugin (`ai-agent-plugins`) is the only broker:
`backend/ship/`, `/api/ship/*`, the guard's `ship-deploy` catch and the
guest prompt's deploy line are gone; `carryover.ship` copies
`/data/deploy-hosts.json` into its shared dir once.
- `GET …/hub/scaffold/templates` no longer imports `backend/templates/`.
- **Templates** is the `templates` plugin (owner-only, `templates.read`):
core `backend/templates/`, `/api/templates`, `/api/template`,
`/api/template-file` and the Projects panel's Templates tab are gone;
`/templates[?t=<name>]` redirects to `/plugins/templates/templates[/<name>]`.
- Slots: `project.detail` is mounted on a project's page (init `{slug,
isRoot, isWorker}`). Its first user is the owner-only `project-env` plugin
(since 2026-11-26): the `.env` editor (`get` / `save` actions over
`AIA_PROJECTS_DIR`, the `# --- secrets ---` section write-only) — the core
`GET|PUT /api/project-env`, `projects/envfile.py` and `EnvEditor.tsx` are
gone; the slot folds to 0 px on the root and worker projects. Frames get `aiAgentPlugin.copy(text)` (the host writes
the clipboard; a string ≤ 100 000 chars).
## Machines, relays and attention (since 2026-11-26, the MCP servers plugin)
What the `mcp-servers` plugin (`~/projects/ai-agent-plugins/plugins/mcp-servers`)
builds on — generic, nothing MCP-specific but the sidecar routes it reaches.
Contract: homelab spec `data/log/2026-11-26-ai-agent-mcp-plugin-spec.md` §4.
Both capabilities are owner only, operator-approved, and reach only the
plugin's **own handlers** (`aiah1` handler token, else 403 `handler_only`).
- **`machines.mcp`** (`plugins/hubmachines.py`):
- `GET …/hub/machines` → `[{id: "local", name: "Homelab", kind: "lab",
status, toolsUrl}, {id, name, kind: "worker", status, platform, account,
toolsUrl}]` — `local` first, then the owner's paired workers (never a
guest's computer, never a pending one); `status` `online`|`offline` (the
lab: the host sidecar's `/health`, cached 15 s). `toolsUrl` is the
`AIA_TOOLS_URL` that machine's runs get (the lab `TOOLS_PROXY_LAB_URL`,
default `http://127.0.0.1:8096/proxy/tools`; a worker
`core/state.tool_hub_url`) — where it reaches a relay.
- `GET|POST|DELETE …/hub/machines/{machine}/mcp[/{rest}]` → that machine's
sidecar `/mcp-servers[/{rest}]` (the host sidecar for `local`), the JSON
body and query passed through, **the sidecar's status and JSON passed back
as they are** (its errors: `{"detail": {message, kind}}`). The bridge's
own refusals carry the same `detail` (and `error`): offline or pending 409
`worker_offline`, a guest's computer 403 `forbidden`, unknown 404
`unknown_machine`, a machine refusing the hub's token 502 `worker_auth`,
one that doesn't answer in time 504 `timeout`.
Timeouts: POST `/mcp-servers` 300 s, `login` 60 s, `login/callback` 90 s,
else 30 s.
- **`relay.serve`** (`plugins/relay.py`) — authenticated streaming relays to
upstreams whose credentials the plugin manages (the hub gateway: sign in
once on the hub, every harness and machine goes through it). Stored in
`PLUGINS_DIR/relay/<pluginId>.json` (0600; a purged uninstall deletes it).
- `PUT …/hub/relay/routes/{name}` `{upstream: "https://…", headers: {…}}`
(header values are secrets: stored, never returned; hop-by-hop names,
`Host` and `Accept-Encoding` refused) → `{ok, route}`; `DELETE
…/hub/relay/routes/{name}` → `{ok}`; `GET …/hub/relay/routes` →
`[{name, upstream (no query, no userinfo), headerNames, updatedAt,
lastUsedAt, lastStatus}]`.
- `POST …/hub/relay/tokens {label, routes: [name]}` → `{id, token}` —
`aiar1.<id>.<secret>`, shown once, stored as a SHA-256; `PUT
…/hub/relay/tokens/{id} {routes?, label?}` → `{ok, token}`; `DELETE
…/hub/relay/tokens/{id}` → `{ok}`; `GET …/hub/relay/tokens` →
`[{id, label, routes, createdAt, lastUsedAt}]`.
- **The public route** — `GET|POST|DELETE /proxy/tools/relay/{pluginId}/{name}`
and `…/{name}/{path}`, `Authorization: Bearer aiar1…`. A token that isn't
the plugin's or doesn't list `name` → 403 `relay_auth` (and counts toward
the address's bad-token lock); a plugin not the owner's, disabled,
unapproved or without `relay.serve`, or a route nobody made → 404;
**404 on the owner's internet address**, and **404 on the guest host
except for a `public` token** — machines come over the tailnet, but a
dial-out worker (`link`, off the tailnet: the Orus devbox) reaches the hub
only on the guest host, like its link. `POST …/hub/relay/tokens
{label, routes, public: true}` mints such a token (`PUT` can flip it);
`GET hub/machines` marks those machines `public: true` and gives them the
guest host's tools URL (`GUEST_PUBLIC_URL/proxy/tools`). A wrong token on
the guest host is a 404 as well.
- Forwards to `upstream` (+ `/{path}`, + the caller's query after the
upstream's own) with only `Content-Type`, `Accept`, `Mcp-Session-Id`,
`MCP-Protocol-Version` and `Last-Event-ID` from the caller, plus the
route's headers and `Accept-Encoding: identity`. Answers the upstream's
status with only `Content-Type`, `Mcp-Session-Id`, `MCP-Protocol-Version`
and `Cache-Control` (+ `X-Accel-Buffering: no` on an event stream). The
answer body is streamed as it comes — an SSE event reaches the caller
when the upstream sends it; no read timeout on an event stream, a JSON
answer may idle 300 s between chunks (`RELAY_IDLE_TIMEOUT_S`) and take
600 s to start (`RELAY_RESPONSE_TIMEOUT_S`); connect 15 s. A request body
with a `Content-Length` (≤ 16 MB) is read and sent whole, a chunked one
streamed.
- An upstream **401/403 becomes the relay's own 403** `{"error":
"relay_unauthorized", "message": "signed out on the hub — sign in again
in MCP servers"}`, **without `WWW-Authenticate`**: a harness must not
start an OAuth flow of its own against the hub. Every refusal of the
relay is a 403, never a 401 — a 401 sends an MCP client looking for the
hub's own `/.well-known/oauth-protected-resource` (the hub's MCP server).
- `lastUsedAt` / `lastStatus` are kept at once in memory and written at
most once per route per 60 s, or when the status changes.
- The owner's plugin: no egress filter (like the owner's proxies); https or
http upstreams.
- **`provides: {"machine.attention": "<action>"}`**
(`plugins/machine_attention.py`) — what waits for the owner on each of his
machines. The owner's providers run as the owner (stdin `{"trigger":
"machine.attention"}`, ≤ 20 s) and answer `{"items": [{machine, key,
title, detail?, tone: "warn"|"error"}]}` (`machine` = `local` or a worker
id; ≤ 200). `GET /api/machines/attention` (owner, `lab.read`) →
`{items: [{pluginId, machine, key, title, detail?, tone}]}`, cached 30 s.
A provider's action that isn't `readOnly`, its webhook or scheduled job, and
any install / reload / enable / disable / uninstall by the owner drop the
cache and publish SSE `{"type": "machine-attention"}`. The machine page's
*Needs you* strip draws each item of its machine (*Open* → the Tools tab,
scrolled to the plugin's slot: `?slot=<pluginId>` /
`#plugin-slot-<pluginId>` — `PluginSlots anchors`); a worker's Setup
checklist gets one row per provider ("2 MCP servers need a sign-in +1": the
first item's title, `+N` for the others). The frontend fetches it only
while `/api/plugins` lists the key in `provides`.
- **`machines.wake`** (`plugins/hubwake.py`, the `wake-on-lan` plugin) —
owner only, operator approval, handler only; each route answers at
`…/hub/…` and at the alias `…/bridge/…`:
- `POST …/hub/wol` (= `…/bridge/wol`) `{mac, broadcast = "192.168.1.255",
port = 9}` → the host sidecar's `POST /wol` (`sidecar/routes_wol.py`: a
UDP magic packet with `SO_BROADCAST` — the container can't broadcast on
the LAN) → `{ok, mac (normalised aa:bb:…), broadcast, port}`. The MAC
(`aa:bb:cc:dd:ee:ff`, `:` or `-`), a literal IPv4 broadcast and 1–65535
are checked in both places (400 `bad_request`).
- `POST …/hub/workers/{wid}/probe` (= `…/bridge/workers/{wid}/probe`) → one
`workers.probe` now (SSE `workers` when it moved) → `{online, status,
lastSeen}`; a guest's, pending or unknown worker 404 `unknown_machine`.
- `GET …/hub/wake/workers` (= `…/bridge/workers`) → `{workers: [{id, name,
host, hostname, status, running, lastSeen}]}` — the owner's paired
workers, no token, no URL (`workers.read`'s `GET …/hub/workers` stays
the harness view).
- **`provides: {"runs.limits": "<action>"}`** (`plugins/run_limits.py`, since
2026-11-29 — the `agent-limits` plugin) — how many agents each machine runs
at once. The owner's first provider runs with `{"trigger": "runs.limits",
"op": "limits"}` → `{limits: {<runner id>: n}}` (a worker's id, `local` =
the lab; unlisted or 0 = no limit; cached 30 s, dropped when the provider
runs a write or comes and goes). The core enforces it (`runs/queue.py`):
- **The budget** of a machine: every live hub-launched run counts 1, and
so does each native subagent its transcript shows in flight.
- **A launch over it waits**: a new conversation, or a turn that restarts a
session with no live process, goes into the hub's queue instead of the
sidecar — the send answers `{sessionId, queued: {worker, name, position,
limit, running}}` with no `pid`, `meta.queued` is stamped, and the start
replays the whole send path (pinned to that machine) when it is back
under its limit: on a run's exit, on a limits change, every 5 s. First
in, first out per machine; a follow-up into a live run never waits; a
fork isn't queued. The queue is `/data/run-queue.json` (it survives a
restart); a start that fails stays listed with its error.
- `GET /api/runs/queue` → `{items, machines}` (a guest: their own items),
`POST /api/runs/queue/{sid}/start` (owner: start now, over the limit —
also the retry), `DELETE /api/runs/queue/{sid}`; SSE `{"type":
"run-queue"}`. A plugin reaches them with `hub.api`.
- **The limit rides every launch** (`agentLimit` on `/spawn`, `/resume`,
`/fork`): the sidecar gives the run `AIA_AGENT_LIMIT` and
`AIA_RUN_PIDS_DIR` (its live runs' pidfiles) and lowers Claude Code's own
per-session caps to fit (`CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS`,
`CLAUDE_CODE_WORKFLOW_MAX_CONCURRENT_AGENTS`). What caps **native
subagents** against the machine's budget is the provider's own
`harnessHooks` (a `PreToolUse` gate on `Agent|Task|Workflow`, a ledger fed
by `SubagentStart` / `SubagentStop`), since only code on the machine sees
a subagent before it starts. A harness driver reads `body.agentLimit`
(harness-opencode denies its subagent tool on a limited machine).
No provider: no limit, nothing queues; a provider that fails is no limit.
- **`provides: {"machine.wake": "<action>"}`** (`plugins/machine_wake.py`) —
the owner's first provider runs with `{"trigger": "machine.wake", "op":
"list"}` → `{machines: {<workerId>: {configured, mac, broadcast, autoWake,
timeoutSec, lastWokenAt}}}` (cached 30 s, dropped like attention's, SSE
`{"type": "machine-wake"}`) and `{"op": "wake", "machineId"}` → `{ok, sent,
configured, autoWake, timeoutSec, …}`. A run **pinned** to an offline
worker (`route_new_run`'s `worker`) and a resume of a session living on one
call `maybe_wake_and_wait`: an `autoWake` worker is woken and probed every
2.5 s for its `timeoutSec` (clamped 10–120 s, default 60) before the 409
`worker_offline`; an unpinned run never waits — it takes the profile's
next runner up. `GET /api/machines/wakeable` (owner, `lab.read`) →
`{machines}`; `POST /api/machines/{id}/wake` (owner, `workers.manage`) wakes
it and probes it every 3 s for 60 s (the card flips on SSE `workers`).
Settings → Machines draws *⚡ Wake* on an offline worker the plugin has
`configured` (`business/machines/components/WakeButton.tsx`).
- **Carry-over** — `carryover.mcp_servers`: once `mcp-servers` is installed
and enabled for the owner (at start, and right after its install /
enable), an old `/data/mcp-servers.json` (`MCP_SERVERS_PATH`) becomes its
shared `_private/servers.json` (`accounts: ["x"]` → `["claude:x"]`,
`mode: "direct"`) and `_private/overrides.json` (`lab.overrides` →
`"local"`, each owner worker's `mcpServerOverrides` → its id), merged under
what the plugin already has, then `.carried-over`. The old file is never
deleted.
## Cron jobs: a guest's run as that guest, `runs.cron`, pages `unless` (since 2026-11-28, the Cron jobs plugin)
The core's cron jobs (`backend/cron/`, `/api/cron*`, `/api/me/cron*`,
Settings → Cron, the guests' « Tâches planifiées », `ai-agent cron`, MCP
`run_cron_job` / `set_cron_job` / `browse cron`) are the `cron-jobs` plugin's
(form `move-ai-agent-cron-jobs-into-a-plugin_u0wa6b`). What it needed:
- **`runs.guest`** (owner-only, operator approval, `plugins/hubruns.py` →
`runs/guestjob.py`): `POST …/hub/runs/guest {guest, prompt, model:
"sonnet"|"qwen", job: {id, name}, project?, email?, mailHtml?, allow?,
effort?, probe?}` runs a guest's scheduled job **as that guest**. The body
only *names*; the confinement — `meta.owner`, their scope (writes in the
project they still hold `chat` on, else their jobs folder; reads narrowed),
the lean allowlist (`BASE_ALLOW` + `allow`), their budget / own login, the
EVOX2 probe and the Sonnet fallback of a `qwen` job — is built by the core
from their record; a body's `scope`, `cwd` or `lean` is ignored. It stamps
`meta.cron {id, name, guest, firedAt, project, email, mailHtml, plugin,
fallback?}`, which is all the core's delivery (push, mail from a page of
the project) and « Discuter » (`POST /api/cron-runs/discuss`) read. Answers
`{sessionId, account, fallback, harness, model}`; a refusal (guest gone or
locked, budget, live runs) is its HTTP error.
- **`runs.start`'s `cron: {id, name}`** stamps `meta.cron` on an owner job's
run (+ `fallback` when the EVOX2 couldn't take it).
- **`provides: {"runs.cron": "<action>"}`** (`plugins/cron_bridge.py`), asked
as the owner with `{op}`: `index` — every job with `promptFile`, `owner`,
`enabled`, `schedule`, `archiveOnSuccess`, `history` (auto-archive, the
agents catalog's cron runs, an agent page's "its cron job"); `list` — the
same + `runConfig`, `nextRun` (the week's budget); `get {id}`; `create
{name, schedule, promptFile}` (the agents page's *Schedule* through
`agents.run`). Cached 30 s, refreshed off the caller's thread; no plugin ⇒
`[]`.
- **`context.write`'s `create: true`**: a missing `.claude/agents/<name>.md`
may be made (a new owner job's stub) — no other path.
- **`ui.pages[].unless`** (a known permission): the page is hidden from
whoever holds it — the guests' *Scheduled jobs* page (`unless:
automation.manage`) beside the owner's *Cron jobs* (`perm:
automation.manage`), both `nav: "settings"`.
- **`seed: true`** + `managed.defaultForGuests`: on for every guest; the
grant fields `maxJobs` / `defaultModel` override the plugin's settings for
one guest. The carry-over (`carryover.cron_jobs`) moves `/data/cron-jobs.json`
→ `jobs.json` and `guestDefaults.cronLimits` → `limits.json` in the plugin's
shared dir, once, without needing the install (and the guests' `qwen` jobs
to `sonnet`, PR #23's decision, unless that PR's marker says it ran).
- **Commands**: every one `mcp: true` (`ls`, `show`, `prompt`, `add`, `edit`,
`pause`, `resume`, `run`, `rm` — `rm` `destructive`). The actions run
`runAs: owner` and tell a guest by `AIA_USER_CONTEXT.requester`, so a
guest's CLI / AI app reaches their own jobs only; `prompt_save` and the
`cron` provider are `ownerOnly`. A worker-bound connection (Read / Run) has
no `plugins.use`: no cron there, only on the owner's full CLI.
- **The plugin scheduler's `_fired` set is per process**: the tick claims each
job's minute in its own store (`flock` + compare-and-set) before firing, as
the core's store did, so the blue-green window never fires a job twice.
## Scheduled conversations: drawer, send menu, app modal (since 2026-11-26)
What the `scheduled-conversations` plugin (*Send later* — the core's
`backend/scheduled/` and `frontend/src/business/scheduled/` are gone) builds
on. Every piece is generic; the plugin id appears in the core only in the
legacy `?scheduled=<id>` link and the CLI's door below.
- **Slot places** (`ui.slots[].where`), each optional key written only when set:
- `conversations.drawer` — a toggle in the conversations drawer's count row
(`icon`: a lucide name; `label`: its tooltip; `badge`: a `readOnly`
action answering `{count}` for `{scope}`, drawn on the icon). Toggled on,
the drawer's body is a slim header row (the frame's
`setHeader({subtitle})`, the toggle) and the frame filling the rest.
init / update `{scope}` (the profile scope: `all` | `profile:<id>`).
The choice is the drawer filter store's `drawerSlot` (`plugin:<pid>:<slot>`).
- `composer.send` — one more item (`label`, `icon`) in both composers' send
menus (not a guest's, not a New project). A tap freezes the payload the
send would have made and opens the slot in the app's modal with `init
{send, spec, followUp}` — `send`: `{prompt, text, model, harness,
thinking, effort, account, projects, worker, profile}` (a reply box's:
`{prompt, text, targetSessionId, cwd, model, harness, thinking,
effort}`); `spec`: what the chips show (`account` / `worker` as
routing would pick them, `workerName`, `target` = the conversation's
title). Its result `{sent: true}` clears the composer like a send;
anything else gives the draft back; `drawer: true` opens the plugin's
drawer slot.
- `app.modal` — a document in the app's modal (no host title; the close X
sits top-right, keep ~40 px clear). Opened by `aiAgentPlugin.openModal
(slotId, init?)` from any of the plugin's frames, or by the address
`?modal=<pluginId>:<slotId>` (the other params → `init.query`; a push's
link). Closing drops those params from the address as it is then.
- **Bridge**: `openModal(slotId, init)`, and in a modal frame
`modal.setResult(obj)` / `modal.close(obj?)` (no object: the last
`setResult`); elsewhere they reject.
- **`POST …/hub/changed`** (no capability) — "my data changed": SSE
`{"type": "plugin-data", id}` to the installer, and the app refetches every
read of that plugin (frames' `query`, the drawer badge). Call it after a
write a job or another device made.
- **`notify.action`** (event, the owner's installs): a push button was tapped
— `{notifyId, index, title}`. `hub/notify` takes `actions` (≤ 3 button
titles), `spoken`, and an app path as `url` (`/…` → the viewer's address),
and answers `{ok, id}`. The buttons are on the phone (Home Assistant) **and
on the owner's browsers' web push** (`push-sw.js` draws them); the first
tap wins (a later one on another device goes nowhere) and clears the push
off the others. For the app, list the open question from your
`inbox.waiting` action with `kind: "ask"`, its `options` and
**`notifyId`** (the push's id): the Waiting for feedback card and the bell
then tap the push's buttons (`/api/notify/{id}/action`, owner only), not an
ask — and leave the list once your state says it's answered (call
`hub/changed`: a `plugin-data` event also refetches the inbox). Auto-ship's
*Merge & deploy N PRs?* does all three (2026-11-27: a phone off the tailnet
couldn't reach Home Assistant, so its tap went nowhere).
- **`conversations.title`** (capability, owner only, operator approval) —
`POST …/hub/title {text, kind?, ref?, account?}` → the `conversation.title`
provider's `{title, summary}`, `{}` when there is none.
- **`runs.start`**, more of the composer's payload: `worker: "auto"` (+
`profile`: routed when it starts, like an unpinned prompt), `account`,
`projects`, `cwd`, `newProject`, `scheduled` (`{id, scheduledAt,
shouldStartAt, manual?}` → `meta.scheduled`, the card's pill); the answer
adds where it went (`worker`) and who it bills (`account`).
`POST …/hub/runs/resolve {runners: [{key, harness, account, worker,
profile, model, mode: "freeze"|"now"}], sessions: [sid], workers: true}` →
what routing would pick (or its refusal), each session's conversation id,
title, runner and harness, the owner's machines (name, online, profile)
and the profiles' labels. **`conversations.send`** takes `model`,
`harness`, `thinking`, `effort`, `cwd`.
- **`provides: {"runs.schedule": "<action>"}`** — `{op: list | get | create
| edit | cancel | start | title | upcoming, …}` (`plugins/schedule_bridge.py`):
the week's budget asks `upcoming` (30 s cache), and the stopped-run card's
*Resume at…* calls it from the app. (The core's `/api/scheduled*` door
went on 2026-11-28: the CLI and the hub-mcp plugin use the plugin's
commands.)
`GET /api/plugins/ui` names each key's plugin and action:
`providers: {key: {pluginId, action}}` (`usePluginProvider`).
- **`runScript(..., context=)`**: host-vouched `AIA_USER_CONTEXT` keys (never
`uid` / `isOwner`) — `plugins/launch.py`'s.
- **Carry-over** `carryover.scheduled`: `/data/scheduled.json` → the
plugin's shared `scheduled.json`, once, then `.migrated`.
- **Commands**: the plugin declares `ai-agent plugin scheduled-conversations
ls | show | add | cancel | start`, every one `"mcp": true` — the only way
in from a shell or an AI app since 2026-11-28 (the core's `ai-agent later`
/ `scheduled` / `unschedule`, `/api/scheduled*` and the MCP
`schedule_conversation` / `cancel_scheduled` / `browse scheduled` are gone).
`add --to` is a `conversation` argument (`.` = the calling run, below).
A worker's CLI under *Read* / *Read + run here* has no plugin commands (no
`plugins.use`), so it can't schedule (Gabriel's call: Full only).
- The plugin scheduler wakes a second past each half minute: a
`* * * * *` job fires at :01.
## Websockets, the lab browser and a full modal (since 2026-11-26, the Lab Chrome plugin)
What the `lab-chrome` plugin (`~/projects/ai-agent-plugins/plugins/lab-chrome`)
is built on — the core's `backend/chrome/` (Settings → Browser, the noVNC proxy,
the on-demand life, the idle reaper) and the frontend's Browser dock are gone.
Every piece is generic but `chrome.lab`, which is the core's own *Chrome chip*
(the harness capability `chrome`) asking who runs the browser a lab `--chrome`
run drives.
- **`sockets[]`** (`plugins/sockets.py`) — a websocket a plugin's frames open
through the host, to a target the plugin declares (≤ 4):
```json
"sockets": [{ "id": "vnc", "url": "ws://chrome:6080/websockify",
"subprotocols": ["binary"], "label": "The lab Chrome's screen" }]
```
`url` is `ws://` / `wss://` host, port and path — no query, no credentials.
A declared socket reaches the host's network: **operator approval**, in the
approval fingerprint (only when declared), a consent line per socket.
- **The frame**: `aiAgentPlugin.openSocket(id, {protocols?})` returns a
WebSocket-like channel at once (`send(ArrayBuffer | typed array |
string)`, `close(code?, reason?)`, `onopen` / `onmessage` (`e.data` an
ArrayBuffer, or a string) / `onclose` (`code`, `reason`, `wasClean`) /
`onerror`, `readyState` `connecting|open|closing|closed`, `protocol`,
`binaryType`) — what noVNC's `RFB` takes as its channel. ≤ 4 open per
frame; a bad id closes it at once (4400), a fifth too (4429).
- **The host** (`frontend/src/business/plugins/frameSockets.ts`, wired in
`PluginSandboxFrame`) opens the real websocket, with the reader's cookies,
and relays it over postMessage (`aia-plugin-socket-open|send|close` in,
`aia-plugin-socket` out — binary as transferred ArrayBuffers); a frame
that goes away closes its sockets.
- **The route**: `WS /api/plugins/{pid}/sockets/{sid}` bridges to the
declared `url` and nothing else. **Owner only** — the gate's rules on the
handshake (`sockets.ws_caller`, formerly the chrome proxy's: same origin,
the owner's Authelia user, never a read-only account, never the guest
host; on the owner's internet address the session is re-checked every
5 s and the socket closed when it ends); the owner's enabled, approved
install only. Refusals close before accepting (the browser sees a 403):
4403 who, 4404 an undeclared socket, 4502 the upstream is down.
- **Its life**: `GET /proxy/tools/plugins/{pid}/sockets/{sid}/probe` (the
plugin's own handlers, the owner's) → `{up, open, lastActiveAt}` — a TCP
connect to the upstream now, the relays open, when one last carried a
frame (epoch seconds, in memory: 0 since the hub started). The lab Chrome
reads it for "reachable" and for its idle job ("someone is watching").
- **`provides: {"chrome.lab": "<action>"}`** (`plugins/chrome_bridge.py`) —
the browser a lab `--chrome` run drives. The host asks the owner's provider:
- `{op: "status"}` → `{reachable, chipDefault: off|running|always, guests}`
(cached 10 s, dropped when the plugin runs a non-read action or any owner
plugin changes): `runs/routes.py _guest_chrome` keeps a guest's
`--chrome` only with `guests: true`; the composer's chip default reads
the same action itself (`usePluginProvider("chrome.lab")` +
`usePluginRead`, payload `{op: "status"}`), so the action is `readOnly`.
- `{op: "ensure", sessionId, resume}` — before a lab claude run launches
with `--chrome` (`runs/service.py`, spawn and resume): bring it up and
wait (≤ 120 s; a failure is logged, the run launches anyway).
No provider: no guest keeps `--chrome`, nothing is started, the chip
starts off.
- **`ui.slots[].size`** on an `app.modal` slot: `sm` · `md` (default, not
written) · `lg` · `full` — the app modal's width; `full` is near the whole
screen and the frame fills its height (`fill`, its `resize` ignored): a
live view, a canvas.
- **`conversation.gizmos`' update** adds how the run was launched: `chrome`
(`meta.chrome`) and `worker` (null = the lab).
- **`hub/conversations` rows** carry `chrome` (launched with `--chrome`).
- **A module script in a frame**: a frame's document is written with
`document.write`, which never runs a `<script type="module">` it parses.
Keep a module (noVNC has a top-level await) as text and run it with
`createElement("script")` + `type = "module"` (the lab Chrome's
`loadRFB`).
- **Carry-over** `carryover.chrome`: `/data/chrome.json` → the plugin's shared
`legacy-settings.json` at once (read under its saved config), and into the
owner's config once installed (at the install — `_plugin_changed` — or the
next start; a key still at its field's default takes the old value), then
`….migrated`.
## Resources: conversation pills from data (since 2026-11-26)
A plugin declares **resource kinds** — what a conversation can be *about*
(a PR, an issue, a thread) — as pure data in `resources[]`. The host's
in-process registry (`backend/plugins/resources.py`) matches them; no code of
the plugin runs for it, ever. The core itself knows only `branch` and `url`:
every link in a transcript is stored raw, so installing a plugin lights up
every past conversation at view time with **no re-parse**. The reference
manifests are the `github` / `linear` / `slack` fixtures in
`backend/fixtures/resource_plugins/` (the shapes the hub plugins ship).
| Field | What |
|---|---|
| `id` | the kind (`pr`, `linear`, `slack`, `jira`…; not `branch` / `url`); one plugin per kind |
| `label` | its noun (`Pull request`) — tooltips |
| `urlRegex` | a link → this kind; its named groups feed the templates (`(?P<repo>…)`, `(?P<num>…)`) |
| `idRegex` | an id → its groups (a stored / recorded id, `conv add 13722`); `urlRegex` or `idRegex` required |
| `idTemplate` | the canonical id from the groups — a template or up to 4 tried in order: `["{repo\|config.githubRepo}#{num}", "#{num}"]` |
| `urlTemplate` | the link of a record named by id only: `https://linear.app/{workspace\|config.linearWorkspace}/issue/{team:upper}-{num}` |
| `labelTemplate` / `titleToken` | the pill text / how it reads in a composite title — a template, or rules `[{"match": "<regex on the id>", "template"}]` (first hit wins; `""` = none) |
| `slugTitleGroup` | a group that is the title, slugged (`separate-tenant` → *Separate tenant*) |
| `bareKeyRegex` + `bareKeyTeamGroup` | keys typed in prose (`INS-2229`) — kept only for teams seen in a real link (`UTF-8` never) |
| `branchKeyPattern` | what a git branch / a PR's head / what a PR body closes names (`ins-2229-slug` → `INS-2229`): cross-links between plugins that never import each other |
| `ignoreUrlRegex` | this vendor's other links, dropped instead of shown as plain links (a repo's blob URLs) |
| `namesGroup` / `dateGroup` | a group whose display name is learned (`channelMap`, `channelMapRegex`) — `{name}` in the label; a group holding an epoch (several pills of one label get their date) |
| `needles` | templates `ai-agent past` searches excerpts for (`pull/{num}`) |
| `toolExtractors[]` | `{tool, commandRegex?, inputTemplate?, tagOnCall?, kind?, itemsPath?, idFields?, urlFields?, titleFields?, stateFields?, stateFlags?, metaFields?, xrefFields?, channelMapRegex?, textHint?}` — `tool` is `shell`, a glob (`mcp__*__get_issue`) or `*`; field paths `a.b`, `labels[].name`; `metaFields` (`labels`, `project`, `team`; a group's `icon`, `color`) draw the card's work icon and Settings → Tags; a long `xrefFields` text contributes what it closes / fixes / resolves; `itemsPath` (`projects[]`) reads each item of a listing as one result — it teaches the archive (titles, looks) without tagging the conversation with every item |
| `icon`, `color` | a lucide name (`linear` = Linear's mark), a tone key (`sky`, `violet`…) or a hex |
| `stateTones` | `{"open": "emerald", "merged": "violet"…}` — the pill by its state (*Resource state* switch) |
| `clickAction` | `open` (default) or `copy` (its id) |
| `priority` | lower = the primary first (`linear` 10, `pr` 20, `slack` 30; default 100) |
| `hueRole` | `hue` / `shade`: the card colour's subject (issue hue, its PRs shades — conversations/look.py); `group`: what a hue belongs to (a Linear project) — its own icon / colour from its lookups' `icon` / `color`, its pill beside the issue |
| `groupBy` | on a `hue` kind: the `metaFields` name its lookups name the group by (`project`), matched to the `group` kind by name |
Templates: `{group}`, `{a|b|config.key}` (first non-empty), `{{config.key}}`,
filters `:upper` `:lower` `:nodot` `:title`. Every regex is compiled at
install and refused with nested quantifiers (`(a+)+` — they run over every
prompt and tool result). Only `(id, urlRegex)` enter the approval
fingerprint.
**Scope is the plugin's settings** (declare the fields in `settings.fields`):
`workers` (runner ids; `local` = the lab) and `cwdGlobs` — empty = every
conversation — `notifPills` (pills on its conversations' pushes),
`channelMap` (`C0123=name` lines); any other text setting is
`{config.<key>}`. A setting never saved reads as its field's `default`.
The plugin that declares the `group` kind also sets the **look**
(`plugins/resources.LookPrefs`): `cardColour` (`group` — the card wears its
issue's group colour, each issue a shade; `hue` — one colour per issue, its
PRs shades), `iconOrder` (`group` — group › label › team; `label`),
`groupPills` (the group's pill beside its issue) and `groupLooks` (the
vendor's own icon and colour, from lookups) — all on / `group` by default.
`GET /api/plugins` → `ui.resources` lists the display descriptors
(`id, label, icon, color, stateTones, clickAction, priority, hueRole,
pluginId`) the app draws pills with; a kind whose plugin is gone still draws
as a link. `conv add <url|key>` sends links and keys raw — the hub's registry
reads them.
## Harness hooks (`harnessHooks[]`, since 2026-11-26)
A plugin hooks into the agent harness's own hook points (Claude Code's
`--settings` hooks) on the lab and on paired workers — the first user is the
`gcloud-reauth` plugin, which replaced the core's `sidecar/gcloud_reauth.py`.
Validation, scope and materialization: `backend/plugins/harness_hooks.py`;
the sidecar's side: `sidecar/plugin_hooks.py`.
```json
"harnessHooks": [
{ "id": "gcloud-expired", "harness": "claude", "event": "PostToolUse", "matcher": "Bash",
"excludeCommandRegex": "gcloud\\s+auth\\b",
"outputRegex": "invalid_rapt|reauthentication failed|gcloud\\s+auth\\s+login",
"message": "Google sign-in expired on this machine: use the gcloud-login skill, then retry." },
{ "id": "custom", "harness": "claude", "event": "PostToolUse", "matcher": "Bash",
"script": "hooks/my_hook.py", "timeoutSec": 10 }
]
```
- **Declarative** (`message` + `commandRegex` / `excludeCommandRegex` /
`outputRegex`, `ignoreCase` default true; `PreToolUse` / `PostToolUse`): the
sidecar's stdlib runner evaluates it — a match adds `message` as the call's
`additionalContext`. No plugin code runs anywhere, so the owner may approve
it. Output is scanned on its last 200 KB; the runner always exits 0.
- **Script** (`script`: a `.py` file inside the plugin, ≤ 256 KB; `timeoutSec`
1–60; also `UserPromptSubmit` / `Stop` / `SessionStart` / `SubagentStart` /
`SubagentStop`): the harness runs it
as the hook (`python -I`). Code on every machine it reaches: **operator
approval** (`requires_operator`).
- `matcher` (a tool-name regex) is required on tool events. Every regex is
compiled at install and refused with nested quantifiers, as `resources[]`;
paths can't leave the plugin dir; at most 16 hooks. The whole declaration
(regexes, message, script, `guestAllowed`) is in the approval fingerprint —
a plugin without the key keeps its old one.
- **Where** — the plugin's settings (declare the fields): `where`
(`workers` | `lab` | `all`, default `all`), `profiles` (profile ids; empty =
any), `workers` (runner ids, `local` = the lab; non-empty overrides the
other two). A value never saved reads as its field's default. Only the
owner's enabled, approved installs count.
- **Guests** — a guest's computer, and a guest's scoped run on the lab, get a
hook only with `guestAllowed: true` (default false; a guest's computer is in
no profile, so a `profiles` filter leaves it out too).
- **Delivery** — the lab: `PluginStore.sync_hooks()` writes
`/data/plugins/live-hooks/` (`index.json` with the rules that apply to
`local`, + script copies under `<plugin>/<path>`) on every owner plugin
change and at the backend's start; the host sidecar reads it at each launch
(`SIDECAR_LIVE_HOOKS_DIR`). A worker: its `/sync` bundle carries `hooks`
(`{hash, rules, files}`, filtered by its runner id and profile — the bundle
hash moves with it, `{}` clears), written to `~/.ai-agent-worker/hooks`.
`SIDECAR_PLUGIN_HOOKS=0` turns them off on a machine.
## Commits and diffs as plugins (since 2026-11-27, `diff-viewer` + `commits`)
The Changes tab, the commit cards, the Details *Commits* card and every diff
view left the core for two live plugins: **`diff-viewer`** (diff rendering,
the Changes tab, full-page diffs, Viewed ticks, comments, Send review) and
**`commits`** (`requires: ["diff-viewer"]`: capture, the feed card, the Details
card). Core keeps the data engines (`backend/diff/*`,
`conversations/commits.py` — legacy `gitCommits` parsing included) and gives
plugins five generic points. Form `commits-diff-viewer-plugins_zr3l5s`.
**A1 — `conversation.tab` slots.** `ui.slots[] = {id, where: "conversation.tab",
label (1–24, required), icon? (lucide), html, legacyView? ("changes"), vis?,
events?}`, at most 2 per plugin. The conversation header's switch becomes
`Thread | <label> <badge>`; the frame is mounted hidden once the thread has
painted, stays mounted, and reports with `aiAgentPlugin.setTab({hidden?, badge?,
label?})` (the button shows after its first `hidden: false`). Active, it fills
the pane. URL `?view=<pluginId>:<slotId>[&tp=<JSON>]`; `legacyView: "changes"`
also answers `?view=changes&c=<sel>` (params `{c: sel}`). init `{sessionId,
conversationId, lang, theme, active, params}`, update `{sessionId,
conversationId, running, active, params, pluginData}`. Any frame on a
conversation page may call `openTab({plugin?, slot, params?})`, `closeTab()`,
`reply({text, send?})`.
**A2 — tool cards.** `match.hasReport: true` (tool `shell` only): claimed only
when this plugin filed a report (A3) during the call. `stackable: true` (with
`inThread`): consecutive items claimed by the same plugin + card are one frame
(init = the first call's + `stack: [init…]`; update `{stack: [… + toolUseId],
running}`). `pullOut: true` (with `inThread`): in Summary it stands after its
fold. A card's init/update add `commits` (the item's legacy field or null) and
`reports` (this plugin's summaries during the call, `[]` when none) — the
thread item carries them as `reports: {<pluginId>: [{id, ts, event, cwd,
summary, hasBlob}]}`. Written into the normalized manifest only when set.
**A3 — path shims and out-of-band reports.** Top-level, **operator approval**
(code on every machine), in the approval fingerprint only when declared:
```json
"pathShims": [ { "id": "git", "command": "git", "script": "shim/git_shim.py",
"triggers": ["commit","merge","cherry-pick","rebase","revert","am","push","pull"],
"guestAllowed": true } ]
```
- ≤ 4 shims; `command` `^[a-z][a-z0-9_-]{0,31}$` (one plugin per command on a
machine — the first by id); `script` a `.py` in the plugin (≤ 256 KB);
1–32 `triggers` `^[a-z][a-z0-9-]{0,31}$`. Validation:
`backend/plugins/path_shims.py`.
- **Delivery** as harness-hook scripts: the lab's `live-hooks/index.json`
(`shims: [{plugin, id, command, script, triggers, guestAllowed, scope}]`,
the script copied under `<plugin>/<path>`), a worker's `/sync` bundle
(`hooks.shims` + `hooks.files`). Same `where` / `profiles` / `workers`
settings; a guest's computer and a guest's scoped run get `guestAllowed`
ones only; `SIDECAR_PLUGIN_HOOKS=0` turns them off.
- **Every run, every harness** (`sidecar/path_shims.py`, from `launch._launch`
after the driver's env): `~/.cache/ai-agent/shims/bin[-guest]/<command>`, a
POSIX-sh wrapper, first on `PATH`. An argument equal to a trigger →
`exec <sidecar python> -I <script> "$@"` with `AIA_SHIM_REAL` (the command the
run would have run — the run's PATH minus the shim dir; re-searched if it
went), `AIA_SHIM_PLUGIN`, `AIA_SESSION_ID`, `AIA_REPORT_PY`,
`AIA_SHIM_ACTIVE=1` (a nested call — a git hook's own `git` — takes the fast
path). Else `exec "$AIA_SHIM_REAL" "$@"`: no python for read-only git, and
the exit code, stdio and signals are the real command's. The script must
keep them too (and work under `guest_git.py`'s `GIT_CONFIG_*`).
- **`aia_report.py`** (core, stdlib, copied next to the wrappers): the shim
loads it from `AIA_REPORT_PY` and calls `report(event, summary, blob=None) ->
bool` — `summary` ≤ 8 KB JSON (refused past it), `blob` ≤ 160 KB (dropped,
`summary.blobDropped = true`); adds `ts` (epoch ms), `cwd`, `pid`; never
raises or prints, ≤ 2 s. Transport: on the lab `POST /api/plugin-reports
{id, sessionId, plugin, report, token}` — `token` is the run's
`AIA_REPORT_TOKEN` (HMAC of its session id under the sidecar's bearer, which
the hub checks: a run reports on its own conversation only); on a worker a
one-shot `report` outbox item (`rpt_` + 12 hex) the `OutboxMirror` collects
(a guest's computer: its own sessions only; the blob leaves the worker's
outbox file once acked). A failed send appends to `AIA_REPORT_SPOOL`, which
the sidecar drains every 20 s.
- **Hub** (`plugins/reports.py`, `plugins/hubreports.py`): the plugin must be
one of the owner's active plugins with `pathShims`. Stored in
`/data/plugin-reports/<sessionId>/<pluginId>.jsonl` + `<pluginId>.blobs/`
(2 000 reports, 16 MB per conversation × plugin; a known id is a no-op);
SSE `{type: "transcript", ids: [<conversation id>]}`; each summary joins
the shell item whose `[ts − 1.5 s, ts + durationMs + 3 s]` window (now while
it runs) holds it — the latest-starting call on overlap.
- Capability **`conversations.reports`** (no operator approval — it reads what
the plugin itself wrote; the caller's own conversations, a guest's theirs):
`GET …/hub/conversations/{cid}/reports?since=<ts>` → `{sessionId,
conversationId, worker, reports: [{id, ts, event, cwd, summary, hasBlob}]}`
(the calling plugin's only, oldest first); `GET
…/hub/conversations/{cid}/reports/{rid}/blob` → the blob (404 none).
**A4 — `diff.read`.** The diff engines as bridges (`plugins/hubdiff.py`) — the
very `diff/routes.py` functions run as the caller, so a guest is held exactly
as there (`_viewed_by`, `_repo_allowed`). `cid` is a conversation or session id.
| Bridge (`AIA_TOOLS_URL/plugins/<id>/hub/diff/…`) | Answer |
|---|---|
| `GET conversations/{cid}/commits` | `ConversationCommits` (`/api/conversation-commits`) |
| `GET conversations/{cid}/commit?sha=&root=` | one commit's `DiffResult`: lab git, the transcript's patch, or the worker; `root` (a shim report's repo root) finds a commit the transcript never showed — a guest: their project's lab repo or their own computer only |
| `GET conversations/{cid}/uncommitted?stats=0\|1` | `/api/conversation-uncommitted-diff` |
| `GET conversations/{cid}/aggregate` | `/api/conversation-diff` (the whole conversation) |
| `GET commit?repo=<project:x\|service:x\|super:_>&sha=` | `/api/commit-diff` |
Diff images: `aiAgentPlugin.mediaUrl("/api/diff-blob?repo=&path=&sha=&wt=")`.
The `/api/*` diff routes stay (nothing in the app calls them; the CLI may).
**A5 — links by kind.** `ui.pages[].opens: ["commit", "conversation-diff"]`
(≤ 8 kinds `^[a-z][a-z0-9-]{0,31}$`, written only when set). The app's
`pluginOpenHref(kind, params)` → `/plugins/<id>/<page>?<params>` of the first
active page that opens it (`commit` `{repo, sha}` — Project / Service *Recent
commits*; `conversation-diff` `{id}`), else no link. Old `/diff/…` addresses
redirect there (or to `?view=changes&c=…`).
## A phone app as a channel: `notify.respond`, webhooks that answer (since 2026-11-28, the Android push plugin)
The `android-push` plugin (`ai-agent-plugins`) is a `notify.channel` whose
other end is a native app (`gabrielvidal/ai-agent-android`, contract in its
`docs/PROTOCOL.md`): pushes go out to each paired phone's UnifiedPush
endpoint, and the app talks back to **one webhook** with the token it got from
a QR code. Three generic things the core gained for it:
- **`webhooks[i].respond: "result"`** (mode `action` only; default
`"envelope"` = `{ok, mode, result}`): the action's JSON **is** the HTTP
body — an API of the plugin's own (`{"ok": false, "error": "answered"}`
with a 200, or `_error` for a status). A result
`{"_file": {"path", "in": "shared" | "data", "filename"?, "contentType"?}}`
is answered as that file — from the plugin's hub-scoped dir (default) or the
installer's data dir, never outside (`proxyroutes._webhook_result`).
**`webhooks[i].methods`** (`["POST"]` by default, `GET` and / or `POST`): a
GET's body is its query without `token` — a download link. Both keys are
written, and join the approval fingerprint, only when set.
- **`notify.respond`** (not an operator capability: a guest's own install
answers their own asks), **the plugin's handler token only**, acting for the
token's user — a push or ask that isn't theirs (`notifications.routes.push_is_for`:
sent to them, or their conversation's audience) is a 404:
- `GET …/hub/notify/pairing` → `{user, uid, isOwner, addresses: [{id, label,
hub, hooks: {<webhook id>: <url?token=…>}}], origins}`. The owner:
`public` (`https://<OWNER_HOSTS[0]>` as the app's address, the webhooks on
`GUEST_PUBLIC_URL` — the owner's host serves no `/proxy/`) then `tailnet`
(`AI_AGENT_VIEW_URL` for both); a guest: the guest host. `origins`: the
hub's own origins, to make a link relative.
- `GET …/hub/notify/push/{id}` → `{ok, push}`: the recorded push or ask,
whole (`body`, `options`, `actions`, `status`…), its link on the reader's host.
- `GET …/hub/notify/push/{id}/image` → that push's picture as bytes
(`image/*`, ≤ 5 MB; 404 otherwise) — what lets the channel give the phone
a link of its own (a `methods: ["GET"]` webhook answering a `_file`) for a
picture **on the hub itself**, which a notification can't load with no
session. Not a proxy: only the image recorded on the person's own push; a
hub path is read through the file route it names (`/api/host-file/raw`,
`/api/artefact`, `/api/project-asset`; `/api/screenshot` and
`/api/data-asset` for the owner) with that route's own check for this
person; a public address goes through `notifications/image_proxy.fetch`;
a lab address is never fetched.
- `POST …/hub/notify/answer {id, index}` → `{ok, label}`; 409 `answered` /
`expired` once it is no longer pending (first answer wins — the route
`/api/ask/{id}/answer` still overwrites); then the usual clear everywhere.
- `POST …/hub/notify/action {id, action | index}` (`action`: the button's
own id, `<push id>__<i>`) → `{ok, index, title, already}`; first tap wins.
- `POST …/hub/notify/dismissed {tags}` → `{ok, dismissed}`: the owner's go
to *dismissed* in the read ledger (`by: plugin:<id>`, SSE `notif-state`);
anyone's leave their web push devices and their **other** channels
(`deliver.clear(skip_channel=…)` / `channels.clear_async(exclude=…)` —
Home Assistant in parallel is cleared, the channel it was swiped on isn't).
- **`GET /.well-known/assetlinks.json`** (`core/routes.py`): the app's Trusted
Web Activity — unauthenticated, every host; `ANDROID_APP_FINGERPRINTS`
(SHA-256 of the signing certificates, comma / space separated; empty → 404)
and `ANDROID_APP_PACKAGE` (default `xyz.gabvdl.aiagent`).
Which host serves the webhook: `/proxy/tools/plugins/<id>/webhook/<hook>` is
answered on the admin host (tailnet) and on the guest host (internet) — the
token names the install, so the owner's works on the guest host too; the
owner's internet host (`OWNER_HOSTS`) refuses every `/proxy/` path at Traefik.
A handler has no egress filter: a plugin that POSTs where a *user* says
(a device's endpoint) checks the address itself, as `android-push/lib/ap.py`
`check_endpoint` does (https, port 443, every resolved address public, the
connection pinned to the checked address, no redirects; the owner's trusted
servers excepted).
## Handlers vs callers (since 2026-11-25)
A plugin has two doors: its **actions** (handler scripts, where its rules —
ownership, quotas, pricing, Pro gating — live) and its **raw proxy**. A
handler subprocess gets a *handler token* (`AIA_TOOLS_TOKEN = aiah1.<uid>.<pid>.<exp>.<sig>`,
`toolproxy/access.mint_handler`), valid only for its own plugin's routes and
never on the public guest host; a guest's run keeps its `aiat1` token. So
the proxy can tell the plugin's code from a guest calling upstream directly:
- `proxy.handlerOnly` (default for every rule) / per-rule `handlerOnly` —
refuse callers (403 `handler_only`); open only the rules a skill must
stream itself (uploads, big downloads).
- per rule: `query` (param → regex, matched on the query string or a form
body; rules are first-match, so a narrow rule goes first), `forcedParams`
(set server-side for callers: `{{user.id}}`, `{{user.tag}}` = `owner` /
`guest-<uid>`, `{{user.domains}}`, `{{config.k}}`), `noAuth` (no secret
injected), `units` (ledger units), `creates` (checks and counts
`jobsPerDay`), `owned` (`{group, file, key}`: the path's named group must be
in `json(<data dir>/<file>)[key]` for a guest).
- Data paths under `_private/` are written only by handlers.
- Handler calls to their own proxy skip the limits, the in-flight slot and the
ledger row — the outer action did all three (its `_meter`).
- Streams enforce `proxy.maxBytes` both ways.
- Handler env adds `AIA_PLUGIN_SHARED_DIR` (one hub-scoped dir per plugin,
never on the data API — use it instead of reading other users' dirs) and
`AIA_USER_CONTEXT.{name, lang, email, sessionId}` (`email` = the guest's
account address, `""` for the owner; `requester.email` likewise). A handler may answer
`{"_error": {"status", "kind", "message"}}` to choose its HTTP status.
Action `timeoutSec` ≤ 900.
- An action marked `"readOnly": true` (it only reads: `list`, `get`, `health`…)
also answers `GET /api/plugins/{id}/actions/{name}?payload=<json>` (≤ 8 KB).
A read-only account (the screenshot skills' bot) may only use safe methods,
so its plugin pages send every action as a GET: a `readOnly` one runs, any
other gets 405. Mark every action a page calls on load.
- Hub events a plugin can subscribe to (`events[].on`, the owner's installs):
`conversation.started` — `{sessionId, prompt (≤ 4 000 chars), projects,
worker ("local" = the lab), owner, origin}`, when a new run launches
(`runs/service._dispatch_started`; Plans links the run its *Implement*
opened) — and `conversation.finished` — `{sessionId, state, exitedAt}`
(`runs/sidecar_client._mark_run_exited`).
- `hub/notify` takes `session` (push in that conversation; a guest only their
own), `i18n` (`{"fr": {title, message}}`) and `to` (a user, when no session).
- `webhooks[i].internalOnly` → 404 on the public guest host.
- UI bridge: `window.aiAgentPlugin.navigate(path)` opens an app path.
## Waking a sleeping service (`proxy.wake`, since 2026-11-26)
A plugin whose `internal: true` proxy calls a container the homelab's
services-manager stops when idle (a **Dynamic** service — a call on its name
fails with a `ConnectError`: a stopped container has no Docker DNS entry)
declares the service to wake:
```json
"proxy": {
"baseUrl": "http://music-dl:8080",
"internal": true,
"wake": { "service": "music-dl", "holdMinutes": 15 },
"allow": [{ "method": "GET", "path": "^api/.*$" }]
}
```
- `service` — the services-manager name, `^[a-z0-9][a-z0-9_.-]{0,62}$`;
`holdMinutes` — an integer 1..240 (default 15): services-manager won't put
it back to sleep before then. Refused without `internal: true`.
- Before each `forward` / `open_stream` (so `proxy.inspect` too), the proxy
POSTs `$SERVICES_MANAGER_URL/api/services/<service>/wake?hold=<holdMinutes>&wait=60&trigger=cli`
(default `http://services-manager:8080`, 70 s timeout). At most one wake
per service per 60 s (a 2xx answer is cached; concurrent calls share one
wake); on an awake service it only extends the hold, so it keeps sliding
while the plugin is used.
- A call that still gets a `ConnectError` forces a wake (past the cache) and
is retried once — a streamed upload only if none of its body was read.
- services-manager down or refusing (e.g. a service set to Always on → 400)
is logged and the call goes ahead; a failed wake isn't cached.
- In the approval fingerprint only when declared: plugins without it keep
theirs. The install screen's proxy line adds "wakes service `<name>`".
## Tool cards that stand in the chat (`inThread`, since 2026-11-26)
By default a plugin tool card (`ui.toolCards[]`) renders inside the expanded
body of the call it matches — so it folds away with the tools (the summary's
"3 tools", a "Ran 2 commands" group). A card the reader comes back for (the
Music plugin's download card) declares:
```json
{ "id": "music-card", "match": { "tool": "shell", "commandRegex": "\\bmusic\\s+(get|status)\\b" },
"html": "ui/music-card.html", "height": 110,
"inThread": true, "keyRegex": "\\bjob ([a-f0-9]{12})\\b|\\bmusic\\s+status\\s+([a-f0-9]{12})\\b" }
```
- `inThread: true` — the card stands in the chat where its call happened,
**in place of the call's row**, never folded into a tool group or the
summary; a small *details* toggle under it opens the call's command and
output (without drawing the card twice). Behind the *Rich widgets* switch.
- `keyRegex` (only with `inThread`; needs a capture group) — one card per key:
the key is the first non-empty group, matched over the command **and** the
output (a job id is often only in what the call printed). A later call on
the same key is a plain row that folds away with the tools; a call with no
key yet (still running) is its own card.
The frontend marks the calls before grouping the thread
(`planPluginThread`, `business/plugins/components/PluginToolCard.tsx`); the
Conversation page renders them with `PluginThreadCard` (`ToolUse.tsx`). The
fields join the manifest's `ui` only when set (existing fingerprints don't
move). Form `music-card-placement-in-the-chat_e3rhec`.
## Fenced blocks in messages (`ui.fences`, since 2026-11-26)
A plugin can draw a fenced block of an **agent's message** — ```` ```chart ````
→ the Charts plugin's frame, inside the message, where the agent talks
about it (form `charts-plugin-how-the-agent-draws-it_aveht1`):
```json
"ui": { "fences": [
{ "id": "chart-fence", "lang": "chart", "label": "Chart", "html": "ui/chart.html", "height": 330,
"vis": { "key": "charts", "label": "Charts", "hint": "the charts agents draw in the thread" } }
] }
```
- `lang` is the block's info string (2–32 of `a-z 0-9 _ + -`). A language
people write code in (`python`, `json`, `sh`, `csv`, `sql`…) and `notify`
(the closing push) are refused (`_FENCE_RESERVED`); at most 8 per plugin,
one per language. Two active plugins on one language: the first keeps it.
- The frame's `init` is `{fence, code, sessionId, conversationId, lang}` —
`code` is the block's text without its fences. It has no `update`: a block
never changes once written. Drawn with the tool cards' border, sized by
`resize(px)` (`height` is the first paint's).
- Only **assistant** messages in the thread (`PluginFenceScope` around
`AnimatedMessage`, `business/plugins/components/PluginFences.tsx`); a
user's message, a tool output and a subagent's report keep their code
blocks. While the block is still being typed (no closing fence yet) a
dashed placeholder holds its room, so the frame loads once.
- Behind the *Rich widgets* switch and the fence's own `vis` switch (a tool
card of the same plugin may share the key: one switch for both).
- Host side: `technical/Markdown.tsx`'s `pre` renderer asks the
`FenceRendererProvider` (null → the code block as before), `fenceOf` reads
the language, the code and whether the closing fence is there (the `pre`
node's source offsets). `GET /api/plugins` → `ui.fences` (no `html`),
the document is `/api/plugins/{id}/ui/fence/{fenceId}`. An older hub
ignores the key, so a plugin can ship it before the hub does.
## The widget platform: slots, live updates, home tiles (since 2026-11-26)
The core widgets of the home page and the conversation page move into plugins
through these points (`backend/plugins/manifest.py`, `home_tiles.py`;
`frontend/src/business/plugins/` — `PluginSandboxFrame`, `PluginSlots`,
`hostBridges`, `ConversationPluginPlaces`). Every optional key below is only
written into the normalized manifest when set, so a plugin that doesn't use it
keeps its approval fingerprint.
**More slot places** (`ui.slots[].where`): `home.section` (a full-width
section of the home feed, above *Waiting for feedback*; init/update
`{profileScope, scope, guests}`), `conversation.pinned` (a slim bar above the
composer; update `{sessionId, conversationId, running, thread: {commands}}` —
the last 200 shell calls, results cut at 800 chars), `conversation.threadFooter`
(the strip under the last message; update `{sessionId, running, genProgress,
motionOn}`), `conversation.gizmos` (a pill in the thread's corner row, sized
both ways by `resize(h, w)`; update `{sessionId, running, deployedUrl,
deploys}`), `conversation.header` (since 2026-11-27, the performance plugin's
chips: an inline chip at the end of the header's meta line — model · project
· when —, sized both ways by `resize(h, w)` and **hidden until its first
non-zero resize** (or `setEmpty(false)`), so a frame that never finds anything
to show takes no room; keep it ≤ 16 px tall; init `{sessionId,
conversationId}`, update `{sessionId, conversationId, running}`; the
frame polls while `running` itself), `conversation.threadHeader` / `conversation.threadEnd` (the
thread's first and last line; update `{sessionId, conversationId, running,
pluginData}` — see "Menu items, thread places and conversation data"). A typed (`kind: "provider"`) plugin may declare slots too.
**Optional slot keys**: `label` (≤ 48 chars — its card's name in the Details
drawer; default the plugin's name), `defaultStashed` (starts benched),
`vis: {key, label, hint, defaultOff?}` (a switch under *Plugins* in the
conversation's eye popover, stored as `plugin:<pluginId>:<key>`; off = the slot
isn't drawn), `events` (a subset of `askform`, `meta`, `transcript`, `usage`:
the host forwards those SSE events — `{type, id?, ids?}` only — to
`aiAgentPlugin.onEvent`).
**The Details drawer in two requests** (since 2026-11-28,
`backend/plugins/batch.py`). Two more optional slot keys:
`query: {action, payload?}` — a declared **`readOnly`** action (no new
capability, no approval of its own) and a JSON object ≤ 2 KB whose string
values may hold `$conversationId` / `$sessionId`, which the app fills in; the
app reads every visible slot's query in one batch and hands the answer to the
frame, so it paints without a round trip of its own — and `reuseFrame: true`
(the app keeps one frame of the slot and sends it the next conversation as an
`update` instead of a fresh document). Both come back on the slot in
`GET /api/plugins/ui`. The two routes behind them (`plugins.use`):
- `POST /api/plugins/batch-read {items: [{key, pluginId, action, payload?,
fresh?}], fresh?}` (≤ 32 items, ≤ 32 KB; a payload ≤ 8 KB) — or
`GET …?items=<JSON array>&fresh=` (≤ 16 KB) for a safe-methods-only caller —
→ `{results: {<key>: {ok: true, data, cached} | {ok: false, status,
error}}}`. Each item is authorized exactly as
`/api/plugins/{pid}/actions/{action}` would (a non-`readOnly` action is its
own `405`), answered on its own (one failure never fails the batch), run
5 at a time and shared with an identical read already in flight. A success
is kept 30 s when its payload names a finished conversation
(`conversationId` / `sessionId` / `sid`), 3 s a running one, 5 s with no
conversation, keyed on a stamp of the conversation's summary and meta (a new
turn misses); `fresh` skips it, and any install / reload / config / secret /
grant change, a non-readOnly action, or `hub/changed` drops the plugin's.
- `GET /api/plugins/ui-bundle?where=<slot place>` → `{where, version, docs:
{"<pid>:<slotId>": html}}`: every active slot document of that place
(512 KB each, the per-document route's containment), `ETag: "<version>"`
and `304` on `If-None-Match` (`Cache-Control: private, no-cache`).
The frame page itself is cacheable: `/sandbox-frame.html?v=<the first 12 hex
of its sha256>` answers `Cache-Control: public, max-age=31536000, immutable`
(any other request still `no-cache`; the sandbox CSP either way).
**Tool cards** also take `vis` and `events`, and `match.hasField` (`deploy`,
`commits`, `subagent`, `bashDiff`: the thread item must carry that field — e.g.
`{"tool": "shell", "hasField": "deploy"}` is every call the backend's
`deploycmd` recognised). A card's `init` is the call (`tool, toolUseId, mi, ts,
sessionId, conversationId, input, result, isError, deploy, deployedUrl, lang`);
its `update` is what moves (`result, isError, deployedUrl, running`). A call an
`inThread` card claims is the plugin's.
**`conversation.details`: one card per slot.** Each slot is its own
rearrangeable card (`plugin:<pid>:<slotId>`); the retired core cards' ids map
onto the plugin cards that replaced them (`DETAIL_CARD_RENAMES` in
`Conversation.tsx`), so a saved arrangement keeps its slots. Every such slot
gets the conversation's compact snapshot as `update` (cost, tokens, usage,
models, byModel, byTool, plan units / %, fast calls, the price book, `local`,
artefacts, per-turn `turns`, the reader's currency and language) — enough to
draw without a subprocess.
**The bridge** (`window.aiAgentPlugin`), besides the v2 calls:
`onUpdate(cb)` (the latest `update` is replayed to a late subscriber; a new
one never reloads the frame), `setEmpty(bool)` (a bare slot's `resize(0)` means
the same — the slot then takes no room but stays mounted, so a later update
brings it back), `onEvent(cb)`, `scrollTo({formId | toolUseId | mi})`,
`openMediaViewer({slides, index})` (hub media paths or `https://`),
`openPreview({url, title})` (http(s)), `mediaUrl(url)` → a `blob:` URL of a hub
media file (`/api/artefact`, `/api/screenshot`, `/api/upload-file`,
`/api/data-asset`, `/api/scratchpad-asset`; image or video, ≤ 25 MB) fetched
by the host with the reader's cookies — the frame's `"null"` origin can't.
**`provides: {"home.tiles": "<action>"}`** → `GET /api/plugins/home-tiles?scope=
&profileScope=&composerHarness=&tzOffset=` (`app.read`). The action gets
`{trigger: "home.tiles", scope, profileScope, composerHarness, tzOffset}` and
answers `{tiles: [...]}`; each tile is `{id, kind, label, stashLabel?, fixed?,
defaultBench?, to?, title?, stale?, sub?}` plus its kind's fields — `arc` (pct,
resetsAt, goal), `burn` (usdPerHour, pctPerHour, neededUsdPerHour,
neededPctPerHour, projected, goal, windowMinutes, noReading — "no reading"
instead of a $0 dial), `stat` (value, or valueUsd /
subUsdPerDay formatted in the reader's currency), `sparkline` (days
`[{date, value, label?}]`, isCost), `bar` (value, max, text, over). Sanitized
server-side; cached 5 s and on any plugin change. `to` is the tile's link —
the plugin's own page (`/plugins/<id>/<page>`), every kind, the burn gauge
included; without one the tile links nowhere (since 2026-11-27: the core
names no plugin page, so it has no default). `stashLabel` (≤ 48 chars) names
it on the bench when that differs from the label (`$ today` for *Today*,
2026-11-27). The home strip draws them
natively; reusing a retired core tile's id (`h5:<acct>`, `week:<acct>`,
`fable:<acct>`, `burn:<acct>`, `billing:<acct>`, `spark`, `today`,
`week_cost`, `convs`, `tokens` — `tokens` starts benched) keeps its saved
slot. Two read-only owner bridges feed such an action:
`GET /proxy/tools/plugins/{pid}/hub/usage/home` (`usage.read`: `{limits, burn,
accounts, profiles}`) and `GET …/hub/activity/daily?days=&scope=&tzOffset=`
(`activity.read`: `{days: [{date, cost, tokens, conversations}]}`).
### The core widgets this retired (2026-11-26)
With the nine plugins built on these points, the core copies are gone — no
plugin installed means no such widget (the data stays: `deploycmd` still stamps
`deploy` / `deployedUrl`, the backend routes are unchanged):
| was core | now |
|---|---|
| home strip: the owner's plan gauges, burn rate, renewal, sparkline, $ today / 7 days, conversations, tokens | `plan-usage` + `activity` home tiles (the core keeps a guest's own Claude gauges + budget and the Guests profile's budget bars) |
| *Waiting for feedback* / the bell / `]` `u`: pending ask-forms read from `/api/ask-form/forms` | the `ask-form` plugin's `inbox.waiting` (`usePluginInboxWaiting`) |
| Details: Footprint, Plan usage, EVOX2 time, Forms, Artefacts, Cost by activity, Cost growth | `environment`, `plan-usage`, `provider-evox2`, `ask-form`, `artefacts`, `cost-charts` detail slots |
| thread: movie cards + pinned films, screenshot card, deploy card + corner gizmo, `ask-form` CLI card, the EVOX2 generation strip | `movies`, `artefacts`, `deploy-preview`, `ask-form` tool cards / pinned / gizmo slots, `provider-evox2` thread footer |
| Details: *Now*, *Consumption*, *Over its life*, *Heaviest commands*, *Left running*, *On disk* (2026-11-26, a later move) | the `performance` plugin's `conv-perf` and `conv-storage` slots |
| header: the CPU chip and the On-disk chip, and their *Performance* eye switch (2026-11-27) | the `performance` plugin's `conv-chips` `conversation.header` slot (its *Performance chips* switch) |
| Details: *Lifecycle checks* — the committed / pushed / merged / deployed / notified / completed row (2026-11-27) | the `lifecycle` plugin's `conv-checks` slot, read through `conversations.checks` (the list cards keep `StatusChecks`) |
| Details: *Related conversations* (2026-11-27; `GET /api/conversations/{id}/related` and its eye-popover switch went with it) | the `graph` plugin's `conv-related` slot, over `graph.read`'s `hub/graph/related` |
| Details: *Background shells* card, header *N shells running* chip, and thread background-work tool cards (`Monitor`, `ScheduleWakeup`, `TaskOutput`, `TaskStop`, `BashTaskStrip`; `runs/bgtasks.py` `/api/conversation-task-*` retired, 2026-11-27) | the `background-shells` plugin (`seed: true`, `managed.defaultForGuests: true`), over `conversations.tasks` (`plugins/hubtasks.py`), `openDetails(slotId)`, `match.hasInput`, `match.hasField: "taskId"`, `bare`, and `inThreadWhile: "active"` |
Kept core: `ArcGauge` / `BurnGauge` / `PluginTile`, `ImageWidget` / `VideoWidget`,
`FormDock` + `AskFormFrame`, the hoisted subagent forms (`AgentFormCard` →
`AskFormCard`), `lib/footprint.ts` (a guest's Stats), and the host-side
`previewSandbox` / `threadDeployUrl` (`lib/previewSandbox.ts`). The eye
popover's *Footprint*, *Movie cards* and *Deploy preview* switches went with
their widgets (the plugins' own `vis` switches replace them).
## Keyboard shortcuts: the keymap, commands, optional peers (since 2026-11-27, the Keyboard shortcuts plugin)
What the `keyboard-shortcuts` plugin builds on. The app keeps the key layer
(one keydown listener, the commands and their handlers — a sandboxed frame
can't see the app's keys); which keys run which command is the plugin's.
Nothing here knows about that plugin: any plugin may provide the keymap, bind
a key to its own modal, or be someone's optional peer.
- **`provides: {"app.keymap": "<action>"}`** — `GET /api/plugins/keymap`
(`backend/plugins/keymap.py`, every role's `self` permission) runs the first
active provider's action **as the caller** (a guest: the owner's `managed`
install granted to them) on `{"trigger": "app.keymap"}`; it answers
`{"enabled": bool, "bindings": [{"command": "go.home", "keys": ["g h"]}]}`.
Served as `{enabled, bindings, pluginId}`, sanitized: a `command` matches
`^[a-z][a-zA-Z0-9._:-]{0,119}$`, ≤ 400 of them, ≤ 4 keys each; a key is
one chord or two space-separated, a chord `mod+ctrl+alt+shift+<key>` in
that order (`<key>`: one lowercase printable character, `space` `escape`
`enter` `tab` `backspace` `delete` `arrowup|down|left|right` `home` `end`
`pageup` `pagedown`, `f1`–`f24`) — the spelling of
`frontend/src/lib/keyboard/keys.ts`. No provider: `enabled: false`, no
bindings — no shortcuts. Cached per caller + fingerprint
(stale-while-revalidate); any plugin change drops every cache, and a
non-read action of the provider drops its caller's and publishes SSE
`{"type": "keymap"}` to them (their tabs refetch) — a save takes at once.
- **Commands** a binding runs: the app's (`frontend/src/lib/keyboard/actions.ts`:
`sidebar`, `search`, `settings.search`, `conv.new`,
`conv.reply`, `conv.nextActive`, `conv.prevActive`, `conv.nextUnread`,
`list.next`, `list.prev`, `composer.guidelines`, `composer.chip.1…9`,
`go.home|dashboards|files|projects|settings`, `profile.cycle`,
`profile.1…9` — the owner's), **`composer.shortcut:<chip id>`** (toggle
that guideline chip in the focused composer) and
**`modal:<pluginId>:<slotId>`** (open that plugin's `app.modal` slot;
pressed again while it is the one open, close it). The app skips a command
it doesn't know.
- **Frame bridges**: `aiAgentPlugin.commands()` → `{commands: [{id, group,
label, context?, repeat?, owner?}], groups: [{id, label}], fixed: [{keys,
label}], mac}` — the app commands this person may run, in the app's
language (`profile.N` as many as they can switch to, labelled with the
profile's name); `fixed` the composer's own keys. `aiAgentPlugin.keyChord
({key, code, ctrlKey, metaKey, altKey, shiftKey})` → the host's chord for
that key press (or null) — record keys with it, so they match what the app
listens for on any layout.
- **More bridges** (the `command-palette` plugin's): `commands()` rows also
carry `available` (something answers it now), `keys` (its keymap keys) and
`current` (the profile on screen's `profile.N`); `runCommand(id)` → `{ok}`
runs an available app command as its key would (a modal frame's modal
closes first, the command runs on the next frame); `places()` →
`{places: [{to, label, hint?, keywords?, plugin?, icon?}]}` (Home, the
sections and their sub-pages, every Settings page and row the person's
role opens, plugin pages, each plugin active for them — `plugin` its id,
`to` its `/settings/plugin/<id>`, `icon` its glyph as a
`data:image/svg+xml;base64,…` URI the host fetched, drawn as a CSS mask —
Add machine); `conversations()` → `{conversations: [{id, title, hint}]}`
(the app's loaded list in the profile on screen, no archived).
- **Switching plugins** (since 2026-12-01, the palette's *Turn … off / on*;
`business/plugins/switchBridge.tsx`): `pluginSwitches()` →
`{switches: [{id, name, on}]}`, the caller's own installs, on and switched
off (`GET /api/plugins/ui` marks them `own` and lists `off`) — not a plugin
provided to a guest, none for a read-only credential or an impersonation;
`switchPlugin(id, on)` → `{ok: true, id, on}` | `{ok: false, cancelled}`.
A frame never switches by itself: the **host** draws the confirmation
(Enter confirms, *Open its page* goes there instead) and only its button
sends the person's own `PUT /api/plugins/{id}`; a refusal (a plugin others
need) shows in the dialog. Anything outside the list is refused before a
dialog shows; one at a time; a modal frame's modal closes first.
- **`ui.slots[].preload: true`** (`app.modal` only, written only when set):
the app loads the document hidden ~2.5 s after start and keeps it
(`PluginWarmModals` — a frame can't move in the DOM without reloading, so
it has its own fixed layer instead of the app's `Modal`); opening only
shows it. Each opening reaches the frame as an update `{open: true, seq,
init}`, each closing as `{open: false, seq}`; it closes on `modal.close()`,
Escape outside the frame and the scrim.
- **Unused keys reach the app**: every frame's bridge passes on each keydown
it didn't `preventDefault()` — not plain typing in a field, never Esc — and
the host takes it only while that frame has the focus. A frame that
records keys must `preventDefault()` them.
- **`optionalRequires: ["<plugin id>", …]`** (top-level, in the approval
fingerprint only when set): optional peers. Never checked at install /
enable / disable / uninstall (unlike `requires`); while one is active for
the user, this plugin's handlers may call its `exports`
(`/proxy/tools/plugins/<peer>/actions/<act>`, 404 while it is off) and
subscribe to its `plugin:<peer>:<event>` events. A handler sees which are on
in `AIA_ACTIVE_PLUGINS`; `GET /api/plugins/{id}/info` lists them
(`optionalRequires`) with the ones active for the caller (`peersActive`),
and the info page shows them under *Works with*. An id can't be in both
`requires` and `optionalRequires`.
- **Carry-over** `carryover.keyboard`: each person's core `state.keyboard`
(`{enabled, bindings}` — action id → keys, `[]` = unbound) → the
`keyboard-shortcuts` plugin's per-user `keymap.json`, where they have none;
once (a `.carried-over` marker), whether or not the plugin is installed yet.
## Composer hooks, provider cache and conversation feeds (since 2026-12-01, the fresh-context plugin)
What the `fresh-context` plugin (the reply box's expired-cache nudge, its
estimate, *Auto fresh*, Settings → Fresh context — all formerly core:
`runs/fresh.py`, `lib/freshContext.ts`, `/api/fresh-context`, `users.autoFresh`)
builds on. Nothing below knows about fresh context:
- **`provider.cache`** (typed provider plugins, optional — written only when
declared, so a manifest without it keeps its fingerprint):
`{defaultTtlSeconds, tiers: [{key, ttlSeconds, writeMult}] (≤ 8),
expiryMarginSeconds (default 120), warmPrefixTokens (default 0)}`. Served as
each vendor's `cache` on `/api/providers`; `ProviderRegistry.cache_for(model)`
→ `{vendor, cache}` or None. provider-anthropic: 1 h default, 5m ×1.25 / 1h
×2.0, 120 s margin, 24K warm prefix; openai 600 s; google 300 s; openrouter
and evox2 declare none.
- **`GET …/hub/providers`** (`models.read`, `plugins/hubruns.py`) — the
registry as `/api/providers` serves it, **owner and guests** (a guest gets no
accounts and only guest harnesses).
- **`GET …/hub/conversations/{sid}/feed?tail=20`** (`conversations.read`,
`plugins/proxyroutes.conversation_feed`) — `{id, sessionId, harness, model,
running, codeMode, contextTokens, firstContextTokens, cacheTtl, lastCallAt,
messages: [{mi, role, kind, ts, model}]}` (tail 1–100), never text; `sid` = a
session id or the conversation's id; a guest's own conversations only.
- **The thread places' `update.feed`** (`conversation.threadHeader` /
`threadEnd` / `threadFooter`): `{harness, model, codeMode, contextTokens,
firstContextTokens, cacheTtl, lastCallAt, echoesPending, tail}` — `tail` the
last 10 items `{role, kind, ts, model}` (`threadFeedUpdate` in
`ConversationPluginPlaces.tsx`).
- **`provides: {"composer.beforeSend": "<action>"}`** —
`POST /api/plugins/composer/before-send` (`self`; `plugins/composer_bridge.py`)
runs it **as the caller** (a guest: the owner's managed plugins granted to
them) on an idle, non-switched, non-Code-Mode reply, with what the reply box
sends (`{mode, sessionId, conversationId, harness, model, switched, running,
codeMode, terminal, contextTokens, firstContextTokens, cacheTtl, lastCallAt,
lastMessages}` — never the prompt). First non-`proceed` answer wins:
`{verdict: "proceed"}`, `{verdict: "modify", resume: {compact: {model,
instructions}}}` or `{verdict: "modal", slot: <its app.modal slot>, init}`
(≤ 16 KB). The modal's result `{verdict: "cancel"}` hands the draft back,
`{verdict: "proceed", resume?}` sends. Anything broken = `proceed`.
- **`provides: {"runs.compact": "<action>"}`** — `{sessionId, ownModel}` →
`{model, instructions}`: what `/api/resume` `fresh: true` compacts with
(`ai-agent send --fresh`, a guest continuing a terminal session). No
provider ⇒ 400. `/api/resume` also takes `compact: {model, instructions}`
directly; either needs the harness's `fresh_context` cap.
- **`composer.send` slots' new keys** (each written only when set):
`contexts` (`spawn` / `resume`), `guestAllowed` (guests get only these from
`/api/plugins/ui`), `requiresHarnessCap` (a `harness.caps` word; the item also
hides while running or in Code Mode), `directAction` (a declared action run
instead of a document — `html` then optional; its answer's `resume.compact`
rides on the send, through the un-send window).
- **Carry-over** `carryover.fresh_context`: `/data/fresh-context.json` → the
owner's `settings.json` in the plugin's data; each guest's raw
`users.json` `autoFresh` → their grant's `{autoFresh}` once the plugin is
installed; a `.carried-over` marker. `/settings/fresh-context` redirects to
`/plugins/fresh-context/settings`.
## App launch: a modal on opening the app (`app.launch`, since 2026-11-26, the What's new plugin)
What the `whats-new` plugin (the guests' feature carousel — the core's
`backend/whatsnew/` and `business/whatsNew/` are gone) builds on. Nothing in
it knows about What's new.
- **`provides: {"app.launch": "<action>"}`** — asked by `GET
/api/plugins/app-launch?reason=load|foreground&path=` (`plugins.use`;
`backend/plugins/launch.py`), which the app calls once per **opening**: a
load, or the app back in the foreground (a phone reopening the PWA) — never
mid-use (`PluginLaunchHost`, mounted in `App.tsx`; it asks only when an
active plugin provides the key). Each enabled, approved plugin active for
the caller (their installs; for a guest, the owner's `managed` plugins
granted to them) runs the action **as the caller**, with their grant, on
`{"trigger": "app.launch", "reason", "path"}`, at most 10 s, and answers
`{}` or `{"modal": {"slot": "<one of its app.modal slot ids>", "init": {…}
(≤ 16 KB), "closeAction"?: "<one of its actions>"}}`. Anything else is
dropped; one broken plugin never hides another's. Not cached.
- The app opens the answers **one after the other** in its plugin modal
(`openPluginModal` — host-drawn, so it shows on an iPhone, where plugin
overlays are off). Nothing opens over a modal already showing, nor with a
`?modal=` / `?form=` link in the address: that opening is skipped.
- **`closeAction`** runs as the caller once the modal closes, whichever way —
the host's ✕, Escape, the scrim, or the frame's `modal.close(obj)` — with
`{"trigger": "app.launch.closed", "init", "result"}` (`result`: the frame's
`modal.close` object, else its last `modal.setResult`, else `null`).
- **`impersonatedBy`**: while the owner looks through a guest's eyes
(Settings → Users → Impersonate), every action call and launch check runs
with `AIA_USER_CONTEXT.impersonatedBy` = the owner — a plugin keeps a
preview from counting as the guest's own visit.
- **`init.lang`**: every frame's init carries the app's language (`en` | `fr`;
a tool card's own `lang` wins), so a guest-facing frame speaks French. A
page's manifest `label` goes through the app's dictionary (`What's new` →
*Nouveautés*).
- **`users.read`** rows carry `createdAt` (when the account was made).
- **`hub/grants`** (`users.read`, owner's handler token of a **managed**
plugin only — else 403 `handler_only` / `capability`, 400 not managed): a
plugin's own Settings page reads and writes its own per-guest grants, the
same `PluginStore` records Settings → Users → <guest> → Managed plugins
edits. `GET …/hub/grants` → `{grants: [{uid, name, email, active, grant,
usage}], managed}`; `PUT …/hub/grants/{uid} {enabled?, config?,
monthlyBudgetUsd?}` (config merges over `grantFields` keys; an omitted
budget is left alone, `null` clears it; 404 unknown user) → `{ok, uid,
grant}`, publishing `plugins` + `users`. Both doors go through
`plugins/routes.apply_managed_grant`. The Users page draws every
`grantFields` type (checkbox, select, number, text, textarea, list).
- **`provides: {"whatsnew.index": "<action>"}`** (`plugins/whatsnew_bridge.py`,
the owner's run, 30 s cache): `{entries: [{id, title, publishedAt, seen}]}` —
App usage's announcement → adoption (`telemetry/views.py` → `whatsNew`).
None without the plugin.
- **What's new and its editor are the plugin's own Settings pages** (since
2026-11-27: `nav: "settings"`, *You* after Extras and *Workspace* after
Fresh context, the editor `perm: "users.manage"`) — the core's registry
names neither any more.
- **Carry-over** `carryover.whats_new`: the core's `whats_new` /
`whats_new_seen` tables (`ai-agent.db`, left unread) → the plugin's shared
`entries.json` / `seen.json` where it has none; each `users.json`
`whatsNew: false` → the plugin's grant `autoOpen: false` once it is
installed; a `.carried-over` marker makes it run once.
## Menu items, thread places and conversation data (since 2026-11-26, the Handoff plugin)
Handoffs left the core for the `handoff` plugin (`~/projects/ai-agent-plugins/plugins/handoff`);
these generic points are what it is built on — nothing in them knows about handoffs.
- **`ui.menuItems[]`** — `{id, where: "conversation.menu", label (1–40), icon?, html,
height? (80–900), title? (1–60)}`, at most 8 (`manifest._menu_items`, only written
when set). The conversation list's right-click / long-press menu (`ConversationMenu`)
draws one row per active plugin's item after its own rows; a click closes the menu and
opens a Modal holding the item's sandboxed frame (`PluginMenuItems.tsx`, html at
`GET /api/plugins/{pid}/ui/menuItem/{id}`), init `{where, itemId, conversationId,
sessionId, title, harness, worker, running, archived}`. `GET /api/plugins/ui` →
`ui.menuItems` lists them (with `pluginId` / `pluginName`).
- **Frame bridges**: `aiAgentPlugin.close()` closes the dialog the frame is in (answers
`{ok: false}` elsewhere); `aiAgentPlugin.toast(message, tone)` shows the app's toast
(`tone` `success` / `error` / `info`, ≤ 300 chars).
- **Thread places**: `conversation.threadHeader` (the thread's first line, under the fork
banner) and `conversation.threadEnd` (its last, after the summary) —
`ThreadPluginSlots` in `ConversationPluginPlaces.tsx`. init `{sessionId,
conversationId}`; each slot's **update** is `{sessionId, conversationId, running,
pluginData}`, `pluginData` being **its own plugin's** `meta.plugins.<id>` on the
conversation (null when it wrote none) — so a slot draws with no call when there is
nothing, and `resize(0)` folds it away. `vis` / `events` work as on the other slots.
- **`ConversationDetail.pluginData`** — `{<pluginId>: object}`, `meta.plugins` as it is,
for the owner only (null for a guest: only the owner's bridges write it).
- **`conversations.data`** (capability, operator approval, the plugin's own handlers,
owner only — `plugins/hubconvdata.py`): `GET …/hub/conversations/{sid}/data` →
`{sessionId, data}`; `POST` the same path `{data: {…} | null, merge = true}` (≤ 16 KB)
sets `meta.plugins.<id>` — `merge` merges the top-level keys (a `null` value drops
one), `data: null` without merge clears it — then publishes SSE `meta` for the
conversation (its page refetches; the slots get the new `pluginData`). `sid` is a
session or a conversation id; 404 `not_found` when the hub knows neither its
transcript nor its meta (a run just spawned has its meta); a guest's conversation 403.
A `runs.start` run's `data` lands in the same key.
- **`runs.start`** also takes `test: true` (stamped `meta.test`: archived once its turn
ends — the Handoff plugin's cold-path writer).
- **`hub/conversations` rows** carry `model` (the context model, else the model) and
`harness` (meta, else the transcript's, else `claude`).
- **Carry-over**: `carryover.handoffs` copies the core's old `meta.handoffFrom` /
`meta.handoffTo` stamps (2026-11-24 → 26) into `meta.plugins.handoff.from` / `.to` at
start, where they aren't yet; the old keys stay, unread.
## Pages: full-height and themed (since 2026-11-25, the Graph plugin)
- A `ui.pages[i]` with `"fill": true` takes the whole area under the page
header (a canvas, a map) instead of growing with its content; its
`resize()` calls are ignored. The key is only written when true, so pages
installed before keep their approval fingerprint.
- Every sandboxed frame gets the app's palette: `aiAgentPlugin.init.theme`
(`{scheme: "dark"|"light", tokens: {"--primary": "24 95% 53%", …}}`), the
tokens set on its `<html>` (use `hsl(var(--card))`…) with the `dark` class,
and `aiAgentPlugin.onTheme(cb)` when the app switches theme or accent.
- The frame has no network and no app CSS: keep the page self-contained
(inline script and style, no CDN) and get data through an action.
- A frame no longer reloads when its host re-renders (its `init` is compared
by value).
- A page's `init.scope` is the app's profile scope as the dashboards send
it (`profile:<id>` | `all`, since 2026-11-25, the Environment plugin), so a
dashboard page opens on the profile the app is on.
- `init.query` is the page address's search params as an object (a
repeated key keeps its last value) and `init.origin` the app's
`window.location.origin` (since 2026-11-26, the MCP servers plugin's OAuth
callback: `/plugins/mcp-servers/callback?code=…&state=…`).
- `ui.pages[].nav` is `dashboards` (default), `tools`, `main`, `files`,
**`projects`** (since 2026-11-28, the Services plugin: a shortcut row above
the project list — the Projects panel and the Projects bottom-bar drawer —
and an open page lights the Projects tab; `/projects` itself is Projects
only), **`none`** — routable at `/plugins/<id>/<page>`, listed in no nav nor on the
plugin's info page: a page a flow opens (an OAuth redirect target) — or
**`settings`** (since 2026-11-27, the prompt-shortcuts plugin): a Settings
entry, routed at `/settings/p/<id>/<page>` and listed in the Settings panel,
the bottom bar's drawers, the settings search and the command palette, in
its `group` (`you` default, `tools`, `workspace`, `people`, `machine`),
right after the entry `after` names (a core entry id, or another plugin
Settings page's page id; none found: the end of the group). A page label the
app's dictionary knows reads in the app's language. A `tools` page is also a
target of the settings search (under Settings → Plugins). Open, a
`files` page keeps the Files drawer and lights the Files tab (since
2026-11-27 — Forms, Plans, Memories, Templates used to switch to
Dashboards); a `dashboards`, `tools` or `main` page sits in Dashboards
(`nav.ts` `sectionOf`).
- **The core names no plugin page** (since 2026-11-27): every link to one
comes from its manifest. A `files` page is a card on the Files landing, a
row of the Files panel and a link of the bottom bar's Files drawer; a
`dashboards` / `tools` / `main` page a card on the Dashboards landing
(`/dashboards`, since 2026-11-28 — every dashboard is a plugin's; an empty
grid points at the catalogue), a row of the Dashboards panel and a
link of its drawer (past the drawer's five slots, into its stash; key
`<section>/p:<plugin>:<page>`, `nav.ts` `pluginSubLinks`). The old core
addresses (`/goals`, `/skills`, `/dashboards/plan`, `/whats-new`…) are
gone, and so are the core cards' links into plugin pages. Beyond its nav
entry a page may claim, each only written when set (`ui` is in the approval
fingerprint):
- `perm` — a permission the caller must hold to be shown the page at all
(`/api/plugins/ui` leaves it out otherwise): the What's new editor's
`users.manage`.
- `header: "home"` — a button with the plugin's glyph in the head of the
home page and the conversation list (`PluginHeaderButtons`): Analytics.
- `tag` — a tag kind the core does not route itself (not `project`): its
pills open the page at `<page>/<slug>` (needs `subpath: true`; `lib/tags`
`tagHref`, `usePluginTagPages`): the skills-agents plugin's `skill` and
`agent`, the services plugin's `service` (since 2026-11-28 — every
`service:<slug>` pill: conversations, Settings → Tags, Goals, Graph,
Memories). A kind no page claims is no link (a plain pill).
- `feature` — the App usage id its visits count under: the id it had as a
core page (`page.forms`, `dash.plan`…), so its history carries on.
Without one, `plugin.<plugin>.<page>`. The frontend records it
(`lib/telemetry` `setPluginPages` / `pageOf`) and the registry the App
usage plugin reads lists it (`telemetry/views.plugin_features`).
- A page's `init.lang` is the app's language (`en` | `fr`, since
2026-11-27): a page with its own strings follows it.
- **Links into other plugins' pages without naming them** (since 2026-11-28,
the Services plugin): every frame's init carries `tagPages` (`{<tag kind>:
<page route>}` — `{service: "/plugins/services/services", skill: …}`) and
`openers` (`{<kind>: <page route>}` for each kind an active page `opens`,
`{commit: …}`), so a frame knows synchronously whether a chip or a row is a
link. `aiAgentPlugin.openTag(kind, slug)` navigates to the claiming page at
`<page>/<slug>`, `aiAgentPlugin.open(kind, params)` to the page that opens
`kind` with `params` as its query (`open("commit", {repo: "service:traefik",
sha})` → the diff viewer); both answer `{ok, href}` (`ok: false`, nothing
claims it: style it plain).
## Files as plugins: pages that route themselves, downloads (since 2026-11-28)
The host file browser + viewer and the context tree + editor left the core for
two live plugins (form `migrate-files-context-dashboard-to-plugins_imhucu`):
**`file-explorer`** (seeded, managed `defaultForGuests` — every guest has it;
page `files`, `nav: "projects"`, `fill`, `opens: ["host-file"]` `{path:
"~/…"}`; slot `project-files` in `project.detail`) and **`context-editor`**
(seeded, the operator's only; page `editor`, `nav: "files"`, `fill`, `opens:
["context-file"]` `{path: ".claude/…"}`). The bridges are in the capability
table (`hostfiles.read`, `context.read`, `context.write`). What the core gained
for them, generic:
- **A page that routes itself.** `aiAgentPlugin.onRoute(cb)` registers for
address changes — `cb({subpath, query})` on Back / Forward or a link into the
page — and is the opt-in: from then on the page's `init.subpath` / `init.query`
stay the ones it booted on and a new address is *posted*, never a frame
reload. `aiAgentPlugin.setRoute({subpath?, query?}, {replace?})` changes the
address (`/plugins/<id>/<page>/<subpath>?<query>`) the same way: a folder or a
file is a real address (Back works, a link can be shared) and the tree, the
scroll and an unsaved draft stay put. A page's only (a slot gets an error);
`cleanRoute` refuses `..`, empty segments, `?` / `#` / a backslash, non-string or > 16
query params. `PluginCustomPage` keeps it (`routed` / `shown`).
- **`aiAgentPlugin.download(url, filename?)`** — a same-origin download of a hub
media / file path (`/api/host-file/raw?path=…` joined `MEDIA_PREFIXES`) from
the host, with the reader's cookies (a `"null"`-origin frame can't).
`aiAgentPlugin.mediaUrl("/api/host-file/raw?path=…")` shows an image or video
(≤ 25 MB; past it, `openMediaViewer` streams it).
- **`aiAgentPlugin.back(fallback?)`** — the app's history back when there is
one (back to the conversation a file chip was tapped in), else `fallback`.
- **A plugin page's foot clears the phone's floating composer**: the page area
pads by `--spawn-drawer-h` (a `fill` frame stops above it).
- `/file/*` and `/_/*` redirect through `opens` (`LegacyFileRedirect`,
`legacyFileTarget`); none active: a note naming the plugin, with a link to
the catalogue. The core's links follow the same openers: a message's file
chips (`FileLinksProvider`, plain text without the explorer), a skill card's
SKILL.md, the Context & skills dashboard's rows.
- A `host-file` link follows the file's extension to a **viewer page** when
one takes it (`ui.pages[].fileTypes`) — see "File viewers" below.
## File viewers: pages by type, fetchFile, previews (since 2026-11-28)
A plugin can be the viewer of some file types — a PDF, a 3D model, a video,
an archive, a font, office files, code — without file-explorer knowing it
exists (form `viewers-for-pdf-media-and-3d-files_jl74lk`). Three pieces:
**V1** a page picked by the file's extension, **V2** `fetchFile` to read the
bytes, **V3** a preview card under an agent's message naming such a file.
Guests get a viewer the way they get file-explorer: make it `managed` with
`defaultForGuests: true`; what a guest may *read* is always the endpoint's
call (their projects only), never the plugin's.
A complete viewer's manifest:
```json
{
"schema": 1, "id": "pdf-viewer", "name": "PDF viewer", "version": "1.0.0",
"managed": { "defaultForGuests": true },
"ui": {
"pages": [
{ "id": "view", "label": "PDF", "nav": "none", "icon": "file-text", "fill": true,
"html": "ui/view.html", "opens": ["host-file"], "fileTypes": ["pdf"] }
],
"filePreviews": [
{ "id": "card", "label": "PDF preview", "html": "ui/card.html", "fileTypes": ["pdf"], "height": 220,
"vis": { "key": "pdf-previews", "label": "PDF previews", "hint": "a card under messages naming a .pdf" } }
]
}
}
```
### V1 — a page by file type: `ui.pages[].fileTypes`
- `fileTypes`: 1..32 extensions, lowercase, **without the dot**, each
`^[a-z0-9]{1,10}$` (`["glb", "gltf"]`); duplicates are dropped. Only on a
page whose `opens` includes `"host-file"` — anywhere else the manifest is
refused (`fileTypes needs "opens": ["host-file"]`), as are an empty list,
`".pdf"`, `"PDF"`, an 11-char extension or 33 entries. Written to the
normalized manifest (and `/api/plugins`, `/api/plugins/ui` → `ui.pages[]`)
only when set, so a page without it keeps its approval fingerprint.
- **How a `host-file` link resolves** (`pluginOpenHref(pages, "host-file",
{path})`, `frontend/src/business/plugins/opener.ts`): the path's
extension (`fileExt`: the last segment's, lowercased, a `:line[:col]`
suffix ignored; a trailing slash, no dot or a dotfile = a folder) →
the **first active page whose `fileTypes` has it** (plugin order: by
plugin id) → else **the first `host-file` page with no `fileTypes`** (the
generic one: file-explorer) → else no link. A folder always goes to the
generic page. With no generic page active, a viewer still gets its own
types' links and everything else is plain text.
- Everything that links a host file follows it: a message's file chips, an
old `/file/*` address (`LegacyFileRedirect`), a frame's
`aiAgentPlugin.open("host-file", {path})`, the preview cards' `href`.
- **The page's address** is `/plugins/<id>/<page>?path=<~/… path>` (`to` +
`?path=` + `encodeURIComponent(path)`), so the page reads
**`init.query.path`** — `"~/projects/calamite/notes/brief.pdf"`. That
spelling is what every hub file route takes. A page that navigates
between files itself can use `setRoute({query: {path}})` / `onRoute`
("Files as plugins" above).
- **The header** is the page's: `setHeader({subtitle: <file name>, actions:
[{id: "download", label: "Download", icon: "download"}]})`, then
`onHeaderAction(id => aiAgentPlugin.download(rawUrl, name))`; a *Back* is
`aiAgentPlugin.back("/plugins/file-explorer/files?path=" + <its folder>)`
— back to the conversation the chip was tapped in when there is one. Use
`fill: true` for a canvas (a PDF, a 3D view) and `nav: "none"` (a viewer is
reached by its files, it needs no nav entry). The raw URL of a file is
`/api/host-file/raw?path=` + `encodeURIComponent(path)`.
- **Every plugin frame's `init`** carries, beside `openers` (kind → route),
**`fileOpeners: {ext: route}`** — every extension an active viewer page
takes → that page's route (the first page per extension). A typed page is
never `openers["host-file"]`: that stays the generic page (or is absent).
So the explorer (or any page listing files) sends a `.pdf` row to its
viewer:
```js
var ext = (name.match(/\.([^./]+)$/) || [])[1];
var route = ext && init.fileOpeners && init.fileOpeners[ext.toLowerCase()];
if (route) aiAgentPlugin.navigate(route + "?path=" + encodeURIComponent(path));
```
A page that forwards a file it was *opened on* (an old link, Back) passes
`aiAgentPlugin.navigate(url, {replace: true})` (since 2026-11-28): the
viewer takes the current history entry's place, so Back doesn't land on
the forwarding page again. file-explorer ≥ 1.1.0 does both.
- Icons: the app's `fileIcon` draws 3D models (`glb gltf obj stl fbx ply usdz
3mf`), archives (`zip tar tgz gz bz2 xz 7z rar zst`), fonts (`ttf otf woff
woff2`) and audio (`mp3 wav ogg oga flac m4a aac opus`) with their own
glyphs.
### V2 — the bytes: `aiAgentPlugin.fetchFile(url)` → `Promise<Blob>`
```js
const url = "/api/host-file/raw?path=" + encodeURIComponent(init.query.path);
const blob = await aiAgentPlugin.fetchFile(url); // rejects with an Error
const buf = await blob.arrayBuffer(); // pdf.js, a glb parser, JSZip…
const src = URL.createObjectURL(blob); // <img>, <video>, <audio>, @font-face
```
- The host's same-origin read (`fetchFileBlob`, `hostBridges.tsx`) of a
**hub media / file path** — the `mediaUrl` list: `/api/host-file/raw`,
`/api/artefact`, `/api/screenshot`, `/api/upload-file`, `/api/data-asset`,
`/api/scratchpad-asset`, `/api/diff-blob` (no `//`, `..`, backslash or
control character). **Any content type**, **≤ 100 MB** (`MAX_FILE_BYTES`:
refused on the `Content-Length` before reading, and on the size after);
the reader's cookies ride along. A refusal of the endpoint (a guest asking
for a file outside their projects, a secret, a missing file) is a 404 and
the promise rejects with `file fetch failed: 404`.
- The Blob keeps the endpoint's content type when it gives one
(`application/pdf`, `model/gltf-binary`, `font/woff2`…); otherwise
`blob.type` is `""` — sniff by extension.
- `mediaUrl` / `fetchMedia` keep their own rule (images and videos, ≤ 25 MB).
For a big video, prefer `openMediaViewer` (it streams); `fetchFile` holds
the whole file in memory.
- **What a frame can do with the bytes** (checked on a live hub, Chromium,
2026-11-28 — the frame is `sandbox="allow-scripts allow-popups
allow-popups-to-escape-sandbox"`, opaque origin, no CSP beyond `sandbox`):
a `blob:` URL it makes in `<img>`, `<video>`, `<audio>`, `@font-face` and
`new FontFace(name, buffer)`; a **`Worker` from a `blob:` URL** (what
pdf.js's worker needs: `pdfjsLib.GlobalWorkerOptions.workerPort = new
Worker(URL.createObjectURL(new Blob([src], {type: "text/javascript"})))`
— fetch the worker's source from the CDN as text first, a worker URL on
another origin is refused); **WebGL** (`canvas.getContext("webgl2")`);
a **`<script src="https://cdn.jsdelivr.net/…" integrity="sha384-…"
crossorigin="anonymous">`** (`crossorigin` is required for SRI; jsDelivr
answers `Access-Control-Allow-Origin: *`). ES modules from jsDelivr
(`import … from "https://cdn.jsdelivr.net/npm/…/+esm"`) load too.
Not available: cookies / `localStorage` / IndexedDB of the app (opaque
origin — `localStorage` throws), forms submitting (`allow-forms` is off),
top navigation (use `navigate`).
### V3 — previews in the thread: `ui.filePreviews[]`
```json
{ "id": "card", "label": "PDF preview", "html": "ui/card.html", "fileTypes": ["pdf"],
"height": 220, "vis": { "key": "pdf-previews", "label": "PDF previews", "hint": "…" } }
```
- At most **4** per plugin; `id` (`^[a-zA-Z_][a-zA-Z0-9_-]{0,47}$`, unique),
`fileTypes` (the V1 rule — but no `opens` needed here), `html` (inside the
plugin), `height` 40..1200 (default 240: the placeholder's and the first
paint's), `label` (≤ 60, default the id), `vis` as for fences (a switch
under *Plugins* in the conversation's eye popover, `plugin:<pid>:<key>`;
a page / tool card / fence of the same plugin may share the key). Written
only when set. The install screen lists "Previews .pdf files agents'
messages name (sandboxed)".
- **When a card is drawn**: under an **assistant** message of the thread
(never a user's or the app's message, a tool output or a subagent report)
that names host files — the same detection the file chips use
(`messageHostPaths`, `lib/hostPaths.ts`: an inline-code span that is a
path, a path in running text, a markdown link target; never inside a fenced
code block; `/home/<u>/…`, `~/…`, `$HOME/…` under `projects/<slug>`,
`homelab`, `worktrees/<dir>`). One card per **distinct** file (by its `~/…`
spelling), in reading order, **at most 4 per message**; folders and files
the reader can't open (a guest: other projects, every non-project root)
get none. For each extension the **first active plugin** (plugin order)
whose preview lists it wins.
- Behind the *Rich widgets* switch and the preview's own `vis`.
- **Mounted only once visible**: until the card comes within 200 px of the
viewport it is a dashed placeholder of `height` showing the file name; the
document is fetched then (`GET /api/plugins/{id}/ui/preview/{previewId}`,
`usePluginUiHtml(pid, "preview", id)`) and the frame mounts.
- **The frame's `init`**: `{preview, path, name, ext, href, sessionId,
conversationId}` (+ the usual `lang`, `theme`, `openers`, `fileOpeners`,
`tagPages`) — `preview` its id, `path` the `~/…` spelling
(`"~/projects/calamite/notes/brief.pdf"`), `name` the last segment
(`"brief.pdf"`), `ext` lowercased (`"pdf"`), `href` the V1 link for the
file (the viewer page, else the generic page, else `null`). Its *Open* is
`aiAgentPlugin.navigate(init.href)`. No `update`: a card never changes.
- **Size**: drawn **bare** inside a card with the tool cards' border
(rounded, `border-border`); `aiAgentPlugin.resize(px)` sets its height
(any value — no 80 px floor); **`resize(0)` (or `setEmpty(true)`)
collapses the card** — the file is gone, or isn't one you draw after all.
Read the bytes with `fetchFile` (V2); a 404 is the cue for `resize(0)`.
- An older hub ignores both keys, so a plugin can ship them first.
### Host side, for reference
- Backend: `plugins/manifest.py` (`_file_types`, `_file_previews`, the page
check), `plugins/routes.py` (`_ui_descriptors` → `ui.filePreviews`
without `html`, every active plugin's in plugin order; the document route's
`kind == "preview"`). Tests: `backend/test_plugin_file_viewers.py`.
- Frontend: `opener.ts` (`fileExt`, `pluginOpenHref`, `pluginOpeners`,
`pluginFileOpeners`), `hostBridges.tsx` (`fetchFileBlob`,
`MAX_FILE_BYTES`), `components/PluginFilePreviews.tsx` (`pickFilePreviews`,
the card), mounted by `Conversation.tsx` under the message. Mock: a
`pdf-viewer` page + preview (`mock/fileViewers.ts`), the kitchen-sink
thread names `notes/brief.pdf`.
## Pages that feel native: reads, header, kit (since 2026-11-26)
A plugin page is drawn as one of the app's own pages: the app's header
carries its title, **subtitle and buttons**; the frame is **borderless across
the content area**; a **skeleton** holds its place until it has painted, then
it fades in. Three bridge calls make that happen, and one stylesheet.
### `aiAgentPlugin.query(action, payload, onData)` — reads that paint at once
```js
const q = aiAgentPlugin.query("list", { scope: init.scope }, (data, meta) => {
if (meta.error && !data) return showError(meta.error);
render(data); // called again when a fresher answer lands
});
// q.refresh() — this read again · q.stop() — unsubscribe
```
- `onData(data, meta)` runs **at once with the last answer** this device kept
(`meta.fromCache: true`, `meta.fetching: true`) and again with the fresh one
(`fetching: false`). `meta.at` is when the answer was made; `meta.error` is
set when the last fetch failed (`data` is then the last good answer, or
`null`). An identical answer isn't delivered twice.
- The host keeps the answers (memory, then its own IndexedDB store —
`frontend/src/business/plugins/pluginData.ts`, **not** busted by app
deploys; at most 150 answers, least recently used dropped). The same read
from two frames (a page and its slot) is one request.
- **Learned preload:** the reads a page makes in its first 8 s are remembered
per page; the next visit starts them as the route mounts — in parallel with
the page's document loading and its frame booting — so the frame's `query`
usually finds its answer already there or in flight.
- The header's **refresh button** (shown once the page has a read; hide it
with `setHeader({refresh: false})`) runs every read of the page again and
**spins while any of them runs** — a page drops its own refresh button.
- Use it for what a page reads on load and on filter changes; keep
`action()` for writes (save, delete, run). Mark the action `"readOnly": true`
in the manifest (the screenshot bot's GETs need it, and the hub then shares
identical calls in flight — below).
### `ready()`, `setHeader(h)`, `onHeaderAction(cb)`, `onRefresh(cb)`
- **Readiness:** the skeleton goes when the frame's first read has answered
and its callback has run (automatic), when the page calls
`aiAgentPlugin.ready()`, or when it booted without any read (an older page
that loads with `action()` shows at once with its own "Loading…"). 8 s at
most.
- `aiAgentPlugin.setHeader({subtitle, actions, refresh})` — the page's line in
the **app's** header: `subtitle` (≤ 140 chars: a count, the scope —
`"302 memories"`), `actions` (≤ 4: `{id, label, icon?, primary?,
disabled?}`, `icon` a lucide name), `refresh` (`false` hides the refresh
button). Call it again whenever it changes. A page that sets a header
**drops its own title row**: the app's header already names the page.
- `aiAgentPlugin.onHeaderAction(id => …)` — one of those buttons was pressed.
- `aiAgentPlugin.onRefresh(() => …)` — the refresh button was pressed (reads
made with `query` are re-run by the host on their own; this is for the rest).
### The UI kit (`aia-*` classes)
Every plugin frame gets the kit before its own styles
(`frontend/src/business/plugins/pluginKit.ts`): the app's font and colours, and
classes a page opts into — nothing changes under a page that uses none.
| Class | What |
|---|---|
| `aia-page` (+ `aia-narrow`) | the page's container: centred, 1080 px (768 px) wide, 16 px padding, border-box inside |
| `aia-stack` · `aia-row` · `aia-toolbar` · `aia-spacer` · `aia-grid` (`--aia-col: 260px`) | layout |
| `aia-card` (+ `aia-link`, `aia-active`) | a card in the app's look; `aia-link` = clickable |
| `aia-title` · `aia-subtitle` · `aia-section` · `aia-muted` · `aia-small` · `aia-mono` · `aia-truncate` | text |
| `aia-btn` (+ `aia-btn-primary`, `-danger`, `-ghost`, `-sm`, `-icon`) | buttons |
| `aia-input` · `aia-select` · `aia-textarea` | fields |
| `aia-seg` (buttons inside; `aia-active` / `aria-pressed`) · `aia-chip` (+ `aia-count`) | segmented control, filter chips |
| `aia-badge` (`data-tone="primary|success|warn|danger|info"`) | small labels |
| `aia-table` (+ `aia-num` cells) | tables |
| `aia-empty` (with a `<strong>`) · `aia-error` · `aia-note` | empty state, error, callout |
| `aia-skeleton` · `aia-spin` · `aia-hidden` | placeholders, a spinning icon |
A page's own loading state is the host's skeleton: don't draw a "Loading…"
line for the first paint (draw `aia-skeleton` blocks for a later, partial
load).
### The hub side
- `GET /api/plugins/ui` — what every app page reads: the live UI descriptors,
the `provides` keys and each active plugin's `{id, name, kind, description,
icon, iconUrl, color, config}` (a few KB; `GET /api/plugins`, ~250 KB with
every manifest and the catalog, is for Settings → Plugins only). A page's
descriptor carries its plugin's `description` — the Dashboards / Files nav
subtitle; plugin pages sit in the same rearrangeable list as the app's.
- Identical `readOnly` actions in flight (same caller, plugin, action and
payload) run once and share the answer (`backend/plugins/singleflight.py`).
- `composer.shortcuts` / `composer.mode` providers are stale-while-revalidate
(`backend/plugins/swr.py`): past their TTL (60 s / 30 s) the last answer is
served while the plugin runs again behind it (up to 1 h / 10 min old);
`inbox.waiting` is always asked fresh but concurrent calls share one run.
## Overlays: drawing over a page (since 2026-11-25, the Pets plugin)
`ui.overlays[]` puts a **transparent sandboxed frame over a whole page** — the
app's content area, everything above the navbar — for a plugin that draws on
top of it (the pets plugin's hamsters). Decided with Gabriel in forms
`pets-as-an-overlay-plugin_wl2w72` and `how-the-pet-moves-on-the-page_6k4gry`.
```json
"ui": {
"overlays": [
{ "id": "conversation", "where": "conversation", "html": "ui/overlay.html", "pointer": "hits", "cursor": true },
{ "id": "home", "where": "home", "html": "ui/overlay.html", "pointer": "hits" }
],
"prefs": [
{ "key": "enabled", "type": "switch", "label": "Pets", "default": true },
{ "key": "size", "type": "range", "label": "Size", "min": 28, "max": 96, "step": 2, "default": 46, "unit": "px" },
{ "key": "color", "type": "color", "label": "Your hamster", "default": "#f4b66a", "swatches": ["#f4b66a"],
"labels": { "fr": { "label": "Ton hamster" } } }
]
}
```
- **Places** (`where`, one overlay per place and plugin): `conversation` (a
conversation page) and `home` (the home page). The host
(`frontend/src/business/plugins/overlay/`) mounts the frame fixed over
`[data-overlay-world]`, z 30 (popovers stay above), only while the
**Animations** switch is on (reduced motion counts) and the eye menu's
**Plugin overlays** switch is on.
- **Never on an iPhone or iPad** (`overlaysSupported()`, since 2026-11-26).
iOS hit-tests a swipe against the frame's own document, not against the
page under it. So a frame over a scroller swallows every scroll gesture,
even at `pointer-events: none`, while taps still go through. Guests on
iPhone (pets on by default; off for the owner) couldn't scroll a
conversation. The plugin's *Your preferences* says it isn't shown there.
Bringing them back needs a test in the iOS Simulator first (Mac perso).
- **What the frame gets — and nothing else** (`aiAgentPlugin.overlay.on(kind, cb)`;
the last value of each kind is replayed to a late subscriber):
- `layout` — `{w, h, surfaces: [{id, x, y, w, h, anchor?}], anchors: {key: box}}`:
the outlines of the page's solid boxes (cards, code blocks, buttons, the
composer — pet-pet's own "solid" rule) near the screen, frame px, ≤ 400;
rescanned on DOM changes, re-measured on scroll and 4×/s, posted only
when it changed. A home Running card carries its conversation id
(`data-overlay-anchor` → `anchor`). Never text.
- `members` — the page's conversations: `{id, color (#rrggbb), state, mood,
ending?}`; `mood` = `busy` | `waiting` (a form waits) | `error` | `done` |
`free` (`feed.ts`). The conversation page has one; home has the running
cards (`ending` while a card leaves the rail).
- `event` — `{type: "stamp", id, stamp}` (committed / pushed / merged /
deployed / notified, as they land) and `{type: "message", id}` (Claude
wrote a new message — conversation page).
- `prefs` — the person's `ui.prefs` values; `pointer` — `{x, y}` while the
page has the pointer (`cursor: true` only; replayed in the frame as a
synthetic `pointermove`).
- `aiAgentPlugin.init` = `{where, lang, theme}`.
- **Clicks** (`pointer`): `none` — the frame never takes the pointer.
`hits` — the frame reports the boxes it draws (`overlay.setHits([{x, y, w, h}])`);
the host keeps ≤ 16 boxes, ≤ 240 px a side, ≤ 15 % of the frame together
(`hits.ts`), and flips the frame to `pointer-events: auto` only while the
pointer is inside one, or a press that started there is down. The bridge
reports that itself from the frame's own events; a frame that goes quiet
for 1.5 s, or holds a press past 60 s, loses the pointer. Every other click
reaches the page.
- **Preferences** (`ui.prefs[]`: `switch` · `range` · `color` · `select`, ≤ 12):
per person, kept in their own settings blob (`settings.pluginPrefs[<id>]`,
server-side ui-state, so guests have theirs), drawn as *Your preferences* on
the plugin's page (a guest's provided-plugin page too). A `switch` named
`enabled` is the overlay's off switch. Not in the approval fingerprint.
- The consent card says what each overlay sees and whether it takes clicks.
- The frame has no network: inline everything (the pets plugin's
`build.sh` inlines pet-pet's IIFE build).
## Typed plugins: providers and harnesses (since 2026-11-26, Wave 1A)
A plugin's `"kind"` says what it is: `"app"` (the default — every plugin
before this), `"translation"` (a language — see "Translations" below),
`"provider"` (a model vendor: its models, pricing, plan meter,
accounts, an optional sidecar usage reader) or `"harness"` (an agent CLI the
sidecar drives: knobs, caps, login, the vendors it runs with their `--model`
templates, its sidecar driver). The contract is the homelab spec
`data/log/2026-11-26-ai-agent-typed-plugins-spec.md`; the validators are
`backend/plugins/typed_manifest.py`.
- **Operator only**: `requires_operator()` is true for both kinds, the id must
start with `provider-` / `harness-`, and only the owner installs one (a
guest's install is refused). Their kind and what their block can reach
(sidecar dirs, URLs, accounts, caps, login) are in the capability
fingerprint — an app plugin's fingerprint is unchanged.
- **Live bundles** (`PluginStore.sync_typed`, after every install / reload /
enable / disable / config change / uninstall of one): the enabled harnesses'
`sidecar/` (+ `runner/`) and `plugin.json` into
`PLUGINS_DIR/live-harnesses/<id>/`, the providers' usage reader, `plugin.json`
and non-secret `config.json` into `live-providers/<id>/`, each with an
`index.json` (`{version, hash, harnesses|providers: {…, hash}}`). A change
asks the host sidecar for `POST /harnesses/reload` (best effort, off the
request thread). `live_harness_bundle(guest_only=True)` keeps the
`guestAllowed` harnesses (what a guest's computer gets).
- **Accounts are editable** from the provider's settings: `PUT
/api/plugins/<id> {config: {accounts: [{id, …}]}}` — an override of a
declared account, a new one, or `{id, removed: true}`
(`store.clean_provider_accounts`, a 400 on anything invalid).
- **`ProviderRegistry`** (`backend/plugins/providers.py`, cached on
`PluginStore.version`, bound in `build_state` so `providers.current()` works
without deps): ids, accounts (aliases: `opencode-lab` → `evox2`; `guest-<uid>`),
canonical models (Anthropic / APPE discovery in a background thread, 6 h,
disk copy under `PLUGINS_DIR/discovery/`), `catalog_entries()` (the
`/api/models` list, synthesized from provider models × harness `supports`),
`rates_for` / `usage_cost` / `price_call` / `plan_units` / `local_call` —
the same floats as `conversations/pricing.py` (`test_typed_plugins` checks
every book row) — and the pricing of a provider since disabled
(`PLUGINS_DIR/pricing-snapshot.json`). `GET /api/providers` is its
`api_payload()` (`app.read`; a guest gets the guest-allowed harnesses and no
accounts).
- **Pricing reads only the registry** (Wave 3B): `conversations/pricing.py`
holds no table — it is a facade over `plugins/seed_registry.effective()`:
the bound store's registry when it has ever known a provider (strict), else
the seed dir's (`PLUGINS_SEED_DIR`, the plugins checkout, then
`backend/fixtures/typed_plugins/`) — for standalone parses, scripts and
unit tests. The usage poller reads each `usageReader` vendor at
`GET /usage/{vendor}` (legacy `/claude|opencode|agy/usage` on a 404).
- **`provider.quotaWindows`** (optional, since 2026-11-29): which of an
account's usage windows each model draws on — `[{"models": "<regex on the
model id>", "windows": ["five_hour", "seven_day", …]}]`, first match wins
(≤ 32 rows, ≤ 8 window names each, the regex checked like every manifest
regex). The presets with a ladder read it (`backend/models/ladders.py`): a
route is full when one of its windows is. Without it: the windows with no
model suffix, plus `<window>_<family>` when the account reports one. Not in
the fingerprint (data only).
- **Seeding**: at start `carryover.seed_typed_plugins` installs (and promotes
to the catalog) every `provider-*` / `harness-*` plugin of
`PLUGINS_SEED_DIR` (else `~/projects/ai-agent-plugins/plugins`) the owner
doesn't have, once each — an uninstalled one is never seeded again
(`installed.json` → `seeded`). `PLUGINS_SEED_DIR=""` turns it off.
- **No harness or no provider** (since 2026-11-27): once `/api/providers`
has answered with no harness (for a guest: none `guestAllowed`) or no
vendor, `lib/providers` `useAgentGap()` names the gap and no composer is
drawn — home's docked box, the floating one and its launcher, a
conversation's reply box and the model-bound context ring give way to
`NoAgentNotice` (`business/composer/components/`): what is missing, and for
the owner a link to Settings → Plugins → Available, on that kind's category
(`?tab=catalog&kind=harness|provider`); a guest is told to ask the owner.
Nothing shows before the first payload (no flash of the empty state).
- Reference plugins mirroring the hard-coded tables of 2026-11-26:
`backend/fixtures/typed_plugins/`. Until the Wave 3 cutover,
`conversations/pricing.py`, `models/catalog.py` and `accounts/profiles.py`
still answer every caller.
### The sidecar hooks of a typed plugin (2026-11-26, Workstream A)
What the sidecar core leaves to its typed plugins, and the names it calls
them by (``sidecar/harness_base.py``, ``usage_loader.py``,
``routes_harnesses.py``) — every one optional, a plugin that lacks it is
simply skipped:
- **`provider.sidecar`** `{dir, entry}` — a provider's sidecar module that is
*no* usage reader (one module per provider: declare this or
`usageReader`, not both; `typed_manifest.py`). Materialized and synced like
a reader, loaded by `usage_loader`; the hub never polls `/usage/<vendor>` for
it. **provider-evox2** ships one: `sidecar/driver.py` + `gen_progress.py` /
`local_room.py` / `local_ready.py` (they were the core's).
- `live_progress(sid) -> dict | None` — `GET /sessions`' `progress` of a run
(`usage_loader.live_progress`, first non-empty answer);
- `before_launch(harness, model)` — called by `launch._launch` before every
launch (`usage_loader.before_launch`; the EVOX2: free the other server's
idle model);
- `extra_routers()` — mounted like a harness driver's (`/local-ready`, host
only: the module returns `[]` on a worker).
- **Harness driver hooks** beside the spec's §3.2 methods:
- `health_meta()` is merged into `/health` — harness-claude adds `agentsMax`,
`agentKeys`, `codeMode` and, on a worker, `ownLogin` (they were the core's);
- `session_meta(sid, rec) -> dict` — merged into the run's `GET /sessions`
row (harness-claude: `codeMode`, the Code Mode banner);
- `extra_routers()` — harness-claude: `POST /tasks/output` / `/tasks/stop`
(`bgtasks.py`); `startup(ctx)` installs its account-wide hooks
(`turn_hook.py`, `conv_ref_hook.py`);
- `setup_check(tc) -> dict` — the harness CLI's row of a worker's Setup
checklist; `tc` is the core's `tools_check` module (`_run`, `_which`,
`_first_line`, `_own`, `_status`, `harness_row`). No hook: a bare
"on PATH" row (`tools_check.check_plain`).
- **`harness.workerSetup`** `{tool, order, guestAllowed, update,
enablesHarness, installerEnv, recipe}` — what a worker's Setup checklist may
install for this harness, by name only. Exactly one of: `recipe` (a bash
file in the plugin's sidecar dir, sourced by the core's `worker/tools.sh` —
its helpers `say`, `fetch`, `verify`, `older`, `latest_tag`, `arch_of`,
`mine` and `$ACTION`, `$BIN_DIR`, `$SHARE`, `$OS`, `$ARCH`, `$PY` in scope —
then its `tool_main`: harness-claude, harness-pi) or `enablesHarness` +
`installerEnv` (`install.sh update` with `WORKER_<X>=1`, one restart:
harness-opencode, harness-agy). `guestAllowed` needs `harness.guestAllowed`
(only those harnesses reach a guest's computer — pi left a guest's checklist
with this). `update`: the hub may ask for an update. In the capability
fingerprint. Core keeps `gh` and `ask-form`.
- **Claude's own argv** is harness-claude's `sidecar/claude_launch.py` (the
`--settings` hooks, scope rules + sandbox, extras, lean flags, `/compact`,
`--remote-control`, Code Mode); the core's `launch.py` keeps `valid_scope`,
`valid_lean` / `lean_prompt`, `_launch` (now `extra_env=` instead of
`code_mode=`) and `_stop_run`. Its `stop_guard.py` hook ships in the plugin
too.
- The OpenRouter catalogue (`GET /api/models/openrouter`) is the
`openrouter_appe` discovery of the registry (`providers.appe_catalogue`,
the plugin's `catalogueUrl` setting) — `backend/models/openrouter.py` is gone.
## Translations: every language but English (since 2026-11-28, `translation-fr`)
The core speaks **English only**. Every other language is a plugin of
`"kind": "translation"` — one per language, id `translation-<lang>`
(`translation-fr` in `ai-agent-plugins`, seeded at start like the providers
and harnesses: once, an uninstall sticks). Validated strictly by
`typed_manifest.parse_translation`:
```json
{
"id": "translation-fr", "kind": "translation", "languages": ["en", "fr"],
"translation": {
"lang": "fr", "name": "Français", "englishName": "French", "flag": "🇫🇷",
"locale": "fr-FR",
"promptLine": "- **Language: {name} reads French.** Write everything meant for them in French…",
"ui": "i18n/ui.json", "backend": "i18n/backend.json"
}
}
```
- `lang` a base code (`^[a-z]{2,3}$`, never `en`), `locale` a BCP 47 locale
of it, `name` its own name, `flag` an emoji. `ui` / `backend` are JSON
objects in the plugin (English text → translation, strings only, ≤ 20 000
entries / 4 MB each); at least one. `promptLine` (`{name}` = the reader's)
is the system-prompt line every run of a person reading that language gets
(`users/runs.language_line`).
- **Operator only** (`requires_operator`): its prompt line reaches guests'
runs. A guest can't install, reload, disable or remove one. The fingerprint
carries `lang` + `promptLine`.
- **One per language**: two enabled translations of one code — the first by
id holds it; the other's page says which one does.
- **Read by** `plugins/translations.py` (`current()`, cached on
`PluginStore.version` and the dictionary files' mtimes, bound in
`build_state`): `core.i18n.tr` (its `backend` table), `langs()` /
`lang_prefs()` (what a person may pick: `auto`, `en`, an installed code),
`localized()` (a notice's variants, one per installed language),
`effective_lang` (a stored pick whose translation is gone reads English and
is kept), `prompt_line`.
- **Public routes** (`plugins/translation_routes.py`, `PUBLIC` in the authz
table — the sign-in page is translated before anyone signs in, on the guest
host too): `GET /api/i18n/languages` (`{default: "en", languages: [{code,
name, englishName, flag, locale, etag}]}`) and `GET /api/i18n/{lang}` (the
`ui` dictionary, `ETag`, `If-None-Match` → 304). The PWA keeps a copy on the
device and revalidates it in the background (`frontend/src/i18n/README.md`).
- **Coverage**: the core lists its English keys in
`backend/core/i18n_keys/ui.json` (kept by `frontend/src/i18n/i18n.test.tsx`)
and `backend.json` (kept by `backend/test_i18n.py`; `UPDATE_I18N_KEYS=1`
rewrites either). A translation's page (Settings → Plugins → Translations)
shows, per dictionary, how many it has, how many are missing (with the
list), the entries no longer used and the ones whose `{placeholders}`
differ (`translations.coverage`, `typed.coverage` on
`/api/plugins/{id}/settings|info`). A new English string never blocks a core
change: it shows in English until the translation catches up, and the
plugins repo's test for that translation flags it.
- **Settings → Plugins** has a fourth kind, *Translations* (tab, catalog
filter and group); Settings → Display → *Language* lists English and the
enabled translations (name and flag from the manifest), hidden while none
is installed.
### `languages`: what a plugin's own texts speak
Any plugin may say which languages its own UI and messages speak:
`"languages": ["en", "fr"]` (base codes; English always first and always
there — absent = `["en"]`; a translation's own code is added). Shown on the
plugin's page (*Languages*). Frames still get the app's language in
`init.lang` and pick their own strings; this field is what the page tells
people. Not part of the approval fingerprint. A plugin on the `i18n` contract
(below) gets every language it has a file for added to it.
### A plugin's own strings: `i18n` (since 2026-11-28, the auto-translate plugin)
A plugin's own words in other languages live **in that plugin**, the same way
for everyone, in one folder named by the manifest: `"i18n": "i18n"`.
- **`i18n/en.json`**: the English source list, a JSON array of every string
the plugin translates. It is generated, never written by hand. The plugins
repo's `scripts/plugin_i18n.py keys <plugin>` builds it from the manifest's
labels (`name`, `description`, `ui.pages[].label`/`description`,
`settings.subtitle`, `settings.fields[].label`/`help`). It also reads the
frames' `t("…")` / `msg("…")` / `tn(n, "…", "…")` literals (`ui/`, or
`ui-src/` when the plugin builds its documents) and the Python handlers'
`t(lang, "…")` / `tr(lang, "…")` / `caller.t("…")` / `msg("…")`. Write each
string as one literal; use `msg("…")` for a string that reaches `t()`
through a variable.
- **`i18n/<lang>.json`**: `{English: translation}` (the shape of a
translation plugin's dictionaries; a context key `verb|Open` translates
the text after the bar). `{placeholders}` must match the English.
- **`languages`**: the validator adds every language a file exists for
(`plugins/plugin_i18n.validate`). The plugins repo's test wants the field to
list exactly English plus one language per file.
- **Frames**: the host hands the plugin's dictionary for the page's language
as `init.i18n` (`{}` for English), with `init.locale`.
`aiAgentPlugin.t(s, vars)` and `aiAgentPlugin.tn(n, one, other, vars)`
(the language's own plural rules, `{n}` filled) read it. A missing entry,
or an older hub, gives the English back. The PWA gets every active
plugin's dictionary in one body, `GET /api/plugins/i18n/{lang}`
(`{lang, plugins: {pid: dict}}`, ETag'd; a guest's own installs plus the
managed plugins granted to them). It keeps a copy in `localStorage` and
revalidates it when `/api/me` or the plugin list changes
(`frontend/src/i18n/plugins.ts`). An English page never asks.
- **Manifest labels**: a page's label in the drawers, the header, Files,
Projects and Dashboards, plus the settings page's subtitle and field
labels and help, go through `pluginT(pid, s)`. That means the plugin's own
dictionary first, then the core's `t()` (which a translation plugin may
still carry, as before), then the English.
- **Handlers** read `$AIA_PLUGIN_DIR/<i18n>/<lang>.json` themselves. The
reader's language is `AIA_USER_CONTEXT.lang`. `AIA_LANGS` lists the hub's
languages (English plus every enabled translation), for a notice worded
once per reader.
- **Coverage**: `/api/plugins/{id}/info` and `…/settings` carry `i18n`:
`{dir, source, langs: {<lang>: {total, translated, missing, missingSample,
stale, staleSample, placeholderMismatch}}}`. The plugin's page shows one
row per language (*Its strings in français*), next to *Languages*.
- **Without the field nothing changes**: a plugin that carries its French
inline keeps working (`init.lang`, its own table).
The references are `cron-jobs` (documents built from `ui-src/`, plus its
handlers' errors), `file-explorer` (plain `ui/*.html`) and `ship` (handler
messages only).
**`i18n.read`** (operator approval, owner only, `plugins/hubi18n.py`):
`GET …/hub/i18n` returns `{languages, translations, plugins}`. That is the
enabled translations' languages, each translation install's coverage
against the core's English, and each other install's `i18n` coverage per
language (None off the contract) with its `repoPath` in an
`ai-agent-plugins` checkout. It reads files only. The **auto-translate**
plugin uses it: a daily check, a Sonnet run when something is missing, one
PR that auto-ship merges.
## One-shot completions and conversation labels (since 2026-11-26)
The hub's own small model calls — a conversation's **action badge**, a long
title's **short header title**, a *Send later* prompt's **title** — are a
plugin's job now, on any model. First user: the `conversation-labels` plugin
(`~/projects/ai-agent-plugins/plugins/conversation-labels`). The sidecar's
Haiku-only `/title` and `/look` and the core's `look_labeler.py` thread are
gone.
- **Host sidecar `POST /complete`** (`sidecar/complete.py`, host only):
`{system, prompt, model, harness?, account?, fallbackModel?,
fallbackHarness?, fallbackAccount?, wakeLocal?: false, timeout?: 30}` →
`{text, model, harness, account, usage?, costUsd?, fallbackUsed,
primaryError?, seconds}`. A model the EVOX2 serves (named under `pi`,
`opencode`, `evox2` or no harness) goes straight to its llama-server's
`/v1/chat/completions` — with `wakeLocal: false` an asleep box or an
unloaded model fails at once (never a Wake-on-LAN, never a model load that
would evict a live run's) and the fallback answers. A `vendor/model` id
(`pi` or no harness) goes to OpenRouter on pi's key. Any other harness asks
its driver's optional **`SidecarHarness.complete(system, prompt, model,
account, timeout)`** → `{text, model, account, usage?, costUsd?}`:
`harness-claude` (`claude -p --no-session-persistence --tools ""
--setting-sources "" --strict-mcp-config --output-format json`, the
account's login), `harness-agy` (`agy --print --output-format json`; the
mirror held off and the conversation deleted after), `harness-opencode`
(`opencode run` on a throwaway database — a ChatGPT-login model is a 409:
its rotating refresh token can't be copied), `harness-pi` (the EVOX2 /
OpenRouter directly). A driver without it is a 409 `unsupported`. `usage`
comes back in Anthropic's shape.
- **`complete.run`** (capability, owner only, operator approval) —
`POST …/hub/complete {system, prompt, model, harness, account, fallback…,
wakeLocal, timeout, kind, ref}` calls `/complete` and books the spend in the
side-call ledger (`usage_store.add_side_call(kind, ref, account, model, cost,
units, usage)`): claude / agy / opencode priced from their tokens with the
provider book, OpenRouter at its own figure, the EVOX2 at 0
(`plugins/hubcomplete.py`).
- **`conversations.label`** (capability, owner only, operator approval):
- `GET …/hub/labels/pending?days=&limit=&sid=` → `{items: [{sessionId,
title, firstPrompt, labels, account, profile, isolated, startedAt}],
actions, system}` — top-level conversations with a user turn and neither
`lookAuto` nor a set `look.action` nor `cron` (`conversations/look_pending.py`);
`account` is the Claude login the conversation bills (a Work run's is the
Work seat), `isolated` = not the default login. `sid` answers one
conversation from its meta even before its transcript is indexed.
- `POST …/hub/labels/look {sessionId, action, model}` → `meta.lookAuto =
{action, at, model, source}` (an action outside `look.ACTIONS` is stored
as `null` — never asked again) and SSE `{"type": "meta", "id"}`.
- `POST …/hub/labels/short-title {id, title, source}` → the `short_titles`
cache (`source` = the long title it stands for) and SSE
`{"type": "short-title", id, title}`.
- **`provides: {"conversation.title": "<action>"}`** — run as the owner with
`{text, kind: "scheduled-title"|"short-title", ref, account?, isolated?}`,
answers `{title, summary}` (`plugins/labels_bridge.py`). Called by
the scheduled-conversations plugin's `hub/title` (*Send later*) and
`conversations/short_title.py`. No
provider, a failure or `{}`: the scheduled title is the prompt's first words
and no short title is asked or stored.
- **`provides: {"conversation.look": "<action>"}`** — `{sessionId?}`: label
that conversation (or what is pending) now (`labels_bridge.look`). The
plugin also subscribes to `conversation.started` and runs a 2-minute
catch-up schedule for the terminal and worker sessions no start event names.
- `GET /api/look/pending` (`scripts/look-backfill.py`) reads the same list.
## HTTP endpoints, the hub's API and asks (since 2026-11-28, the hub-mcp plugin)
What the `hub-mcp` plugin (`~/projects/ai-agent-plugins/plugins/hub-mcp` — the
hub as an MCP server for Claude.ai, ChatGPT…, core's `backend/mcpserver/`
until then) builds on. Nothing here is MCP-specific: a plugin that serves a
protocol on the hub's own address (an OAuth callback, a Slack events URL, a
status page) uses the same four contracts. All four are the **owner's install
only** and need **operator approval**; the three bridges answer only the
plugin's **own handlers** (`aiah1` token, else 403 `handler_only`).
### `endpoints[]` — HTTP the plugin answers on the hub's address
```json
"endpoints": [
{ "id": "mcp", "path": "/mcp", "methods": ["POST", "GET", "DELETE"],
"action": "http_mcp", "maxBodyKb": 2048, "surfaces": ["public"] },
{ "id": "oauth", "path": "/oauth/*", "methods": ["GET", "POST"], "action": "http_oauth" },
{ "id": "connect", "path": "/oauth/connect/*", "methods": ["GET", "POST"],
"action": "http_connect", "browser": true }
]
```
- **`path`**: under the plugin's own prefix `/x/<pluginId>/…`, or a
**protocol path** — `/mcp`, `/oauth/…`, `/.well-known/…` (the standards
give those no choice). Exact, or a prefix when it ends in `/*`
(`/oauth/*` answers `/oauth/token`, not `/oauth`). Characters
`A-Z a-z 0-9 . _ ~ - /`, no `..`, no `//`. At most 16 endpoints. Nothing
else on the host can be claimed: `/api`, `/proxy`, the app's pages and
assets stay the hub's. Two plugins claiming one path: the one whose id
sorts first answers; the other's claim is ignored and listed under
`shadowedEndpoints` in its `GET /api/plugins/{id}/info`.
- **`methods`**: any of `GET` `POST` `PUT` `PATCH` `DELETE` (a `HEAD` is
answered as its `GET`, without the body). Another method is a 405 with
`Allow`.
- **`action`**: a declared action — the endpoint's handler. It runs **as the
owner** (the install's user), whoever sent the request. **It answers HTTP
and nothing else**: the action routes refuse it (403 `endpoint_only` on
`POST /api/plugins/{id}/actions/{action}` and on the tool proxy's), and the
manifest may not also make it a command, a webhook's, an event's, a
provider's, an exported or a settings action. Its payload carries the host's
word on who is asking (`request.caller`); through an action route that
would be the caller's own word — a guest granted the plugin posting "the
caller is the owner" to a consent handler.
- **`maxBodyKb`** (default 64, ≤ 4096): a larger body is a 413, read no
further. **`perIpPerMin`** (default 120, ≤ 6000): requests one address may
make a minute, then 429 with `Retry-After`.
- **`surfaces`** (default both): `"admin"` (the admin host and host-side
callers) and/or `"public"` (the guest host — the internet). Never on the
owner's internet address (`OWNER_HOSTS`): 404 there.
- **`browser: true`**: a page people open. A state-changing request from
another origin is refused by the host (403, a `cross_site` line in the
Security log) before the handler runs — the gate's rule, for a path the
gate never sees.
- At most 16 endpoint runs at once per hub (past that 503 `busy`, with
`Retry-After: 2`); they run on their own threads and never take a page's
plugin-script slots.
The handler reads on stdin:
```json
{"trigger": "endpoint", "endpoint": "mcp",
"request": {"method": "POST", "path": "/mcp", "rest": "", "query": "a=1&b=2",
"headers": {"authorization": "Bearer …", "content-type": "application/json"},
"body": "{…}", "ip": "203.0.113.7", "host": "ai-agent.gabvdl.xyz",
"origin": "https://ai-agent.gabvdl.xyz", "surface": "public", "sameOrigin": true,
"caller": null}}
```
- `rest`: what a `/*` path matched after the prefix (`"token"`); `query`: the
raw query string.
- `headers`: lower-case names, only `authorization`, `content-type`, `accept`,
`accept-language`, `user-agent`, `origin`, `mcp-session-id`,
`mcp-protocol-version`, `last-event-id`. Never a cookie, `Remote-User` or a
host token.
- `body`: the text (UTF-8); bytes that aren't come as `bodyBase64` instead.
- `ip`: the client's address as the Security log has it. `origin`: this
surface's **configured** address — `GUEST_PUBLIC_URL` on the public host,
`AI_AGENT_VIEW_URL` on the admin host; the request's own scheme and host
only when none is configured (a standalone hub). Build links back to the
surface from it, never from a header. Every handler run of a plugin that
declares endpoints also has both in `AIA_HUB_URLS` (`{"admin": "https://…",
"public": "https://…"}`, `""` for one that isn't configured) — what a
settings page shows as the address to paste.
- `caller`: **who this browser is signed in as on this host, vouched by the
host** — `null`, or `{"uid", "isOwner", "name", "lang", "active"}`: the
owner (Authelia on the admin host, a host-side caller) or the guest whose
session cookie it is (`active`: this plugin is theirs — granted; guests
locked reads as `null`; `impersonatedBy` is set when it is the owner
looking through that guest's eyes — not the guest's own act). The gate's own rules (`core/auth.identify`); the
handler never sees the credential.
and answers on stdout:
```json
{"status": 401, "headers": {"WWW-Authenticate": "Bearer resource_metadata=\"…\""},
"json": {"error": "unauthorized"}}
```
- `status` (default 200); one of `json` (any JSON value), `body` (text) or
`bodyBase64`; `headers`: only `Content-Type`, `Cache-Control`, `Pragma`,
`WWW-Authenticate`, `Location`, `Allow`, `Retry-After`, `Vary`,
`Access-Control-Allow-Origin`, `Mcp-Session-Id`, `MCP-Protocol-Version` are
kept. The body is at most 4 MB.
- The host adds `X-Content-Type-Options: nosniff` and `Referrer-Policy:
no-referrer`. A body goes out as `application/json`, `text/plain` or
`text/html`; any other type is sent as a download.
- **HTML never runs a script**: a `text/html` answer always carries
`Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline';
img-src data:; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`
— the page is on the app's own origin, so it is forms, links and a
`<meta http-equiv="refresh">`, nothing else. (That is how the hub-mcp consent
page polls.)
- A handler `_error` (`{"_error": {"status", "kind", "message"}}`), a crash or
a timeout is the host's JSON error (`{"error": {message, kind}}`), 5xx
without the script's own words.
- In the approval fingerprint (id, path, methods, action, surfaces, browser);
the consent card lists every path. A disabled or unapproved plugin answers
404 on all of them. Code: `backend/plugins/endpoints.py`.
- The service worker never answers these paths with the app shell
(`vite.config.ts` `navigateFallbackDenylist`: `/x/`, `/mcp`, `/oauth/`,
`/.well-known/`). `/x/` is excluded from the 2026-11-28 build on: a page
that must open in a browser still holding an older worker sits under a
path that one already left alone — hub-mcp's consent page is
`/oauth/connect/<id>` for that reason.
### `hub.api` — the hub's API, as a person
`ANY {AIA_TOOLS_URL}/plugins/{pid}/hub/api/{path}` → the hub's own
`/api/{path}`, the query and JSON body passed through, the status and JSON
answer passed back (≤ 130 s). What the `ai-agent` CLI is built on — a handler
gets the CLI as a library to drive it: `AIA_CLI_DIR` (the hub's `cli/`, on no
`sys.path` by itself) and `ai_agent.Hub(base=AIA_TOOLS_URL + "/plugins/<id>/hub",
headers={"Authorization": "Bearer " + AIA_TOOLS_TOKEN, …})`.
- No header: **the owner**, as his CLI is.
- `X-AIA-As-User: <uid>`: **that guest**, through the `cli` credential scope
(`authz/scopes.py` — their own conversations and granted projects, no
settings, devices or sharing), and only while the plugin is theirs (granted),
they are active and guests aren't locked: else 403, `kind` `guest_gone`
(deleted — for good), `guest_disabled`, `guests_locked` or `not_granted`.
The header sent empty is a 400, never the owner. Only ever a downgrade: the handler runs as
the owner.
- `X-AIA-Read-Only: 1`: safe methods only (a 403 `read_only` otherwise).
- `POST …/hub/via {"sessionId", "app", "connection"?}` stamps a conversation
the plugin just started with where it came from: `meta.via = {kind:
"plugin", plugin: <id>, app, connection}` — the card's "via Claude.ai" pill,
the analytics' origin. Once per conversation.
- The names of `cli/ai_agent.py`, `cli/plugin_commands.py` and
`cli/conv_ref.py` a plugin may lean on are pinned by
`cli/test_library_surface.py`.
### `notify.ask` — a tappable question to the owner
- `POST …/hub/ask {"question", "options": [2–3 labels], "url"?, "type"?,
"timeoutSecs"?}` → `{id}`: a push with those buttons (and the feed's card).
- `GET …/hub/ask/{id}` → `{id, status: "pending"|"answered"|"expired",
"answer"}` — only an ask this plugin raised (404 otherwise).
- `POST …/hub/ask/{id}/close {"note"?}`: answered elsewhere — the push leaves
the phone, the card shows the note.
How many pushes go out is the plugin's to bound (hub-mcp: per address, per ten
minutes, per day).
### `security.record` — a line in the Security log
`POST …/hub/security {"event", "detail", "who"?, "ip"?, "push"?}` → `{ok}`: a
`plugin_event` line (`data: {plugin, event}`, the detail prefixed with the
plugin's name; `event` `[a-z][a-z0-9_]{0,31}`, `detail` ≤ 400 characters).
`push: true` also pushes the owner when *Plugin events* is among the kinds he
is pushed about (Settings → Security).
## Hub capabilities
| Capability | Bridge (`AIA_TOOLS_URL/plugins/<id>/hub/…`) | Who |
|---|---|---|
| `conversations.read` | `GET conversations?days&limit`, `GET conversations/<sid>` | the caller's own |
| `conversations.spawn` | — | operator approval |
| `goals.read` / `goals.work` | `GET goals`, `POST goals/work` | owner only |
| `graph.read` | `GET graph` — projects, services, conversations, subagents, plans and memories as small node lists (`plugins/graphdata.py`) plus `prefs`, the Graph page's settings from before it was a plugin; `GET graph/related?id=<conversation or session id>` — the other conversations sharing a resource with it, most shared first, then newest (`{id, related: [{id, sessionId, title, endedAt, state, shared: [resource]}], kinds: {<kind>: {label, icon, color}}}`, `conversations/related.py`; the Details drawer's *Related conversations* card) | owner only |
| `footprint.read` | `GET footprint?account=<scope>&range=24h\|7d\|30d\|90d\|sub\|all` — each conversation's estimated carbon, water and energy (`id`, `t`, `family`, `projects`, `co2eKg`, `waterL`, `energyKwh`) in a profile scope and range, plus the scope switch's `profiles` and `subscriptionStart` (`plugins/footprintdata.py`, the twin of `lib/footprint.ts`, checked by `test_plugin_footprint.py`) | owner only |
| `telemetry.read` | `GET telemetry/usage?range=7d\|30d\|90d&who=all\|owner\|guests\|guest:<uid>` — `telemetry/views.usage` (feature use by person and device, What's new seen, where conversations start) plus `registry`, the app's feature registry (`telemetry/features.json`, generated from `lib/telemetry/features.ts`) | owner only |
| `analytics.read` | `GET analytics?account=<scope>&range=24h\|7d\|30d\|90d\|sub\|all&tzOffset=<min>&cron=0\|1` — one row per top-level conversation (no `spawnedBy` children; cron / Run now / test runs only with `cron=1`): `start`, `t`, `workMin` (distinct 5-minute active bins, subagents included) and `byDay`, `wallSec`, `turns`, `model`, `harness`, `projects`, `machine`, `person`, `guest`, `origin` — usage, never cost (`plugins/analyticsdata.py`) | owner only |
| `activity.read` | `GET activity?account=<scope>&tzOffset=<min>` — the Activity rollup plus `profiles` (`plugins/activitydata.py`) | owner only |
| `usage.read` | `GET usage/overview?scope=<all\|profile:id>&days=<1–120>` — the scope's accounts and, per account, limits, history, plans and calibration, plus `profiles` (`plugins/usagedata.py`) | owner only |
| `usage.calibrate` | `POST usage/calibrate {backfill?}` — refit every account now (`{calibrations, shifted}`) | owner only |
| `ship.run` | `POST ship/deploy`, `POST ship/audit`, `GET ship/scan?project=` (handler only) | owner only |
| `notify.send` | `POST notify` | the caller, the owner, a named user |
| `notify.respond` | `GET notify/pairing`, `GET notify/push/<id>`, `GET notify/push/<id>/image`, `POST notify/answer`, `POST notify/action`, `POST notify/dismissed` (handler only) — a phone channel's way back: answer an ask, tap a push's button, mark pushes dismissed, read one back, and the addresses its webhooks answer on (`plugins/hubnotify.py`; see "A phone app as a channel") | the handler's user, their own pushes only |
| `complete.run` | `POST complete` — one short answer from any model through the host sidecar's `/complete`, booked in the side-call ledger | owner only |
| `conversations.label` | `GET labels/pending`, `POST labels/look`, `POST labels/short-title` | owner only |
| `machines.mcp` | `GET machines`, `GET\|POST\|DELETE machines/<id>/mcp[/<rest>]` — the owner's machines and each one's sidecar `/mcp-servers` (handler only) | owner only |
| `conversations.title` | `POST title` — a prompt's title from the `conversation.title` provider | owner only |
| `catalog.read` | `GET skills?account=`, `GET skills/<name>/prompt`, `GET agents?account=`, `GET agents/<name>?account=` — `/api/skills` / `/api/agents`' answers plus the scope switch's `profiles` (`plugins/hubcatalog.py`; the `skills-agents` plugin) | owner only |
| `runs.guest` | `POST runs/guest` — a guest's scheduled job, run as that guest and confined by the core (`runs/guestjob.py`; see "Cron jobs") | owner only, operator approval |
| `contextcost.read` | `GET context-cost` — what the Claude context costs to load: `pricing`, `totals` (files, tokens, cost, estimated, skills, invocations, skillSpend), `skills` (calls, last used, context tokens / cost, estSpend, `path` of its SKILL.md), `topFiles` — the old `/api/dashboard` body (`plugins/hubcontextcost.py`; the `context-skills` plugin) | owner only |
| `skills.share` | `POST skills/share {ref, on}` — a catalog skill handed to every guest run (`sharedSkills`), or not | owner only |
| `agents.run` | `POST agents/<name>/run {prompt?}`, `POST agents/<name>/schedule {schedule}` — run a definition now, or the cron job that keeps running it — created in the cron-jobs plugin (handler only) | owner only |
| `machines.wake` | `POST wol`, `POST workers/<id>/probe`, `GET wake/workers` (each also under `bridge/` — `bridge/wol`, `bridge/workers/<id>/probe`, `bridge/workers`) — Wake-on-LAN through the host sidecar (handler only) | owner only |
| `relay.serve` | `GET relay/routes`, `PUT\|DELETE relay/routes/<name>`, `GET\|POST relay/tokens`, `PUT\|DELETE relay/tokens/<id>` (handler only); machines connect to `/proxy/tools/relay/<plugin>/<name>` with an `aiar1` token | owner only |
| `conversations.data` | `GET\|POST conversations/<sid>/data` — the plugin's own `meta.plugins.<id>` on a conversation (`{data, merge}`; handler only — see "Menu items, thread places and conversation data") | owner only |
| `conversations.checks` | `GET conversations/<cid>/checks` — one conversation's lifecycle stamps as its card has them (`committed`, `pushed`, `merged`, `deployed`, `notified`: an ISO time or null) and its resolved `state` (`finished` = *Completed*; a subagent's own), by conversation or session id (`plugins/hubchecks.py`; the `lifecycle` plugin) | the caller's own (a guest: theirs and those shared with them) |
| `conversations.reports` | `GET conversations/<cid>/reports?since=<ts>`, `GET conversations/<cid>/reports/<rid>/blob` — what the plugin's own path shims reported on a conversation (`plugins/hubreports.py`; see "Commits and diffs as plugins") | the caller's own (a guest: theirs) |
| `diff.read` | `GET diff/conversations/<cid>/commits`, `…/commit?sha=&root=`, `…/uncommitted?stats=`, `…/aggregate`, `GET diff/commit?repo=&sha=` — core's diff engines (`plugins/hubdiff.py`; a guest held as `diff/routes.py` holds them) | the caller's own (a guest: their projects') |
| `conversations.tasks` | `GET conversations/<cid>/tasks`, `GET …/tasks/<tid>/output?lines=`, `POST …/tasks/<tid>/stop` (handler only) — a conversation's background shells and Monitors, their output tail and stop on the runner (`plugins/hubtasks.py`; the `background-shells` plugin) | the caller's own (a guest: theirs; stop checks `can_send(stop=True)`) |
| `hub.api` | `ANY api/<path>` — the hub's own API as the owner, or as a guest with `X-AIA-As-User` (the `cli` scope); `POST via` stamps where a conversation came from (handler only; see "HTTP endpoints, the hub's API and asks") | owner only |
| `notify.ask` | `POST ask`, `GET ask/<id>`, `POST ask/<id>/close` — a 2–3-button question to the owner and its answer (handler only) | owner only |
| `security.record` | `POST security` — a `plugin_event` line in the Security log, pushed when asked and allowed (handler only) | owner only |
| `hostfiles.read` | `GET host-file?path=`, `GET host-files?path=`, `GET host-files/recent?project=&limit=`, `GET host-files/roots` — the host files the caller may read (`files/hostfiles.py`; secrets, noise dirs and the lab's runtime state 404 for everyone; `plugins/hubfiles.py`; the `file-explorer` plugin) | operator approval; answers as the caller (a guest: their granted projects) |
| `i18n.read` | `GET i18n` — the enabled translations' languages, each translation's coverage against the core's English, each plugin's own `i18n/<lang>.json` coverage (`plugins/hubi18n.py`; the `auto-translate` plugin — see "A plugin's own strings") | owner only, operator approval |
| `context.read` / `context.write` | `GET context/bundle`, `GET context/file?path=`; `PUT context/file {path, content, create?}` (handler only; `data/` read-only; `create` makes a missing `.claude/agents/<name>.md` only) — the Claude context catalog with real token counts and cost, one file, a save that re-indexes at once (`plugins/hubfiles.py`; the `context-editor` plugin) | owner only, operator approval |
## Security model
- **Capability consent & fingerprint:** installing a plugin computes a deterministic SHA-256 fingerprint over its declared capabilities (secrets, outbound host/methods/paths, internal flag, skill, schedules, UI, events, webhooks, actions, harness hooks, path shims, hub capabilities). Reloading keeps approval automatically if the fingerprint did not change; widening capabilities requires re-approval.
- **No SSRF:** non-owner proxy and event webhook requests pass through `plugins/egress.py` (public globally-routable IPs only, redirects re-validated). `proxy.internal: true` requires operator approval.
- **Write-only secrets:** stored `0600`, injected server-side by the proxy, scrubbed from responses/errors, never returned to the browser or agent run.
- **Sandboxed UI:** custom HTML renders inside `/sandbox-frame.html` (opaque `"null"` origin) with a scoped `postMessage` bridge (`aia-plugin-req` / `aia-plugin-res`).
- **Sandboxed jobs & actions:** run in a stripped environment with only `AIA_TOOLS_URL`, `AIA_TOOLS_TOKEN`, `AIA_PLUGIN_ID`, `AIA_PLUGIN_DATA_DIR`, `AIA_PLUGIN_CONFIG`, and `AIA_USER_CONTEXT` — never host tokens or other users' secrets.
## Runtime APIs
### Tool proxy (used by skills, jobs & actions via `AIA_TOOLS_URL` + `AIA_TOOLS_TOKEN`)
- `ALL /proxy/tools/plugins/{id}/proxy/{path}` — allowlisted outbound HTTP proxy (wakes the `proxy.wake` service first — see "Waking a sleeping service")
- `GET /proxy/tools/plugins/{id}/data` — list files in caller's plugin data dir
- `GET|PUT|DELETE /proxy/tools/plugins/{id}/data/{path}` — read/write/delete a file in plugin data dir
- `GET /proxy/tools/plugins/{id}/config` — read caller's non-secret plugin config
- `POST /proxy/tools/plugins/{id}/actions/{action}` — run a v3 sandboxed action
- `POST /proxy/tools/plugins/{id}/webhook/{hook_id}` — inbound webhook (`?token=…` or `X-Plugin-Webhook-Token`); `GET` too when the webhook's `methods` say so, and the action's own JSON or file with `respond: "result"`
- `GET|POST|DELETE /proxy/tools/relay/{id}/{name}[/{path}]` — a `relay.serve` plugin's streaming relay (`aiar1` token; never on the public hosts)
### Hub bridges (declared in `capabilities`)
- `conversations.read` — `GET /proxy/tools/plugins/{id}/hub/conversations?days=&limit=` (≤ 2000; the owner's own conversations, a guest's theirs): `id` (what `/conversation/<id>` takes), `sessionId`, `title`, `startedAt`, `endedAt`, `state`, `projects`, `isSidechain`, `archived`, `userTurns`, `turnEnded`, `cron`, `agentRun`, `test`, `spawnedBy`, `worker` (`"local"` = the lab); `GET …/hub/conversations/{sid}` adds `finalAnswer` (the newest transcript's last assistant text, ≤ 32 000 chars).
- `conversations.checks` — `GET /proxy/tools/plugins/{id}/hub/conversations/{cid}/checks`
(`cid` a conversation or a session id): `{sessionId, conversationId, state,
committed, pushed, merged, deployed, notified}` — the Details drawer's
lifecycle row, without the transcript's text (404 for a conversation the
caller can't open).
- `goals.read` / `goals.work` (owner) — `GET …/hub/goals`, `POST …/hub/goals/work`.
- `notify.send` — `POST …/hub/notify`.
- `notify.respond` — `…/hub/notify/pairing|push/{id}|answer|action|dismissed`
(the plugin's handlers, for the user they run as — "A phone app as a channel").
- Run bridges (owner only, operator approval; `plugins/hubruns.py`, first used by
`mail-agents`):
- `runs.start` — `POST …/hub/runs {prompt, model, harness, effort, thinking,
worker, lean, fallback: {model, harness, effort, wait}, title, services, data}`
starts a conversation through the composer's send path. A local (pi /
opencode) model with a `fallback` on the lab is probed first (the EVOX2 woken,
`/local-ready`, ≤ 30 min); when it can't take the run it goes to the
fallback and the answer's `fallback` says why. `data` lands on
`meta.plugins.<id>`. Answers `{sessionId, fallback, harness, model}`.
- `conversations.send` — `POST …/hub/conversations/{sid}/send {prompt, inboxOnly?}`:
a turn into the owner's conversation (its live run's inbox, else a resume).
- `models.read` — `GET …/hub/models`: `/api/models`' owner shape (models + presets),
plus `ladders: [{id, name, now: {i, model, label, harness, account} | null}]` —
the owner's presets with a ladder (Settings → Models). `preset:<id>` goes
wherever a model does (`run.model`, `fallback` aside): the hub takes the
preset's first route with quota left; `hub/runs/resolve` answers where it
lands now (`preset`, `harness`, `model`). A run that names no model,
harness or account gets the plugin's default preset when the owner set one.
- `workers.read` — `GET …/hub/workers`: `local` first, the owner's machines,
status, `lastSeen`, the harnesses each runs, and `autoWake` /
`wakeTimeoutSec` when the `machine.wake` plugin (wake-on-lan) will wake it:
a `runs.start` pinned to an offline machine with `autoWake` wakes it and
waits up to that many seconds before answering 409 `worker_offline`
(`runs.service.route_new_run`) — give the call that long.
- `machines.mcp` / `machines.wake` / `relay.serve` (owner only, operator approval, handler only)
— see "Machines, relays and attention".
### App API (`/api/plugins/*`)
- `GET /api/plugins` — caller's installed plugins, hub catalog, and UI/resource/tool-card descriptors (Settings → Plugins)
- `GET /api/plugins/ui` — the slim list every page reads: UI descriptors, `provides`, active plugins' glyph + config
- `POST /api/plugins/validate` — inspect a path or git URL before installing (returns manifest, capabilities, fingerprint)
- `POST /api/plugins/install` — install/approve a plugin live
- `POST /api/plugins/{id}/reload` — reload from source
- `PUT /api/plugins/{id}` — toggle enabled, update config, or (operator) manage catalog promotion
- `DELETE /api/plugins/{id}` — uninstall (`?purge=1` also removes data & secrets)
- `GET /api/plugins/{id}/settings` — declarative Settings model + secret presence + schedules + webhooks
- `GET /api/plugins/{id}/info` — the info page (README, capabilities, schedules, webhooks, actions, pages, source)
- `GET /api/plugins/{id}/asset/{icon|illustration}` — the plugin's art
- `PUT|DELETE /api/plugins/{id}/secrets/{key}` — set/delete write-only secret
- `POST /api/plugins/{id}/test` — run `testAction` or `proxy.inspect` (for a `managed.keyHealth` plugin, as the owner: the verdict is recorded as the hub key's health)
- `GET /api/plugins/{id}/spend` — operator only, a `managed.keyHealth` plugin's hub key: health + last-4 hint, alert settings, this month, by caller / model, 30 days, recent calls, `settings.links` filled in (see "The hub key" below)
- `PUT /api/plugins/{id}/key-settings` — operator only: `alertLimit`, `currency` (`EUR`|`USD`), `pushAtPct`, `pushOnBreak`
- `POST /api/plugins/{id}/actions/{action}` — run a v3 action from the UI / sandbox bridge (identical `readOnly` calls in flight share one run); `GET` with `?payload=` for a `readOnly` one
- `GET /api/plugins/commands` — the caller's plugin commands (the `ai-agent plugin <id> <command>` CLI and the `plugin_<id>_<command>` MCP tools; "Commands" above)
- `GET /api/plugins/{id}/ui/{kind}/{sub_id}` — fetch sandboxed HTML document
- `GET /api/machines/attention` — the owner's `machine.attention` items (owner only)
- `GET /api/machines/wakeable`, `POST /api/machines/{worker_id}/wake` — the `machine.wake` provider's list, and a wake now (owner only)
- `GET /api/runs/queue`, `POST /api/runs/queue/{sid}/start`, `DELETE /api/runs/queue/{sid}` — the starts waiting behind a machine's agent limit (the `runs.limits` provider): list, start now (owner only), cancel
- `POST /api/plugins/create-session` — scaffold a plugin folder and open a conversation with `create-plugin`
## The hub key (`managed.keyHealth`)
A managed plugin that pays for its callers with **one hub key** (`scope: "hub"`
secret — Nano Banana's Gemini key) declares `managed.keyHealth`, and its
Settings page gets a **Hub key** section for the owner (what Settings → API keys
was until 2026-11-26): the key's state and last four characters, Test and
Replace, the month against the alert line, by caller and by model, 30 days and
the recent calls (`GET /api/plugins/{id}/spend`, `plugins/keyspend.py`).
- **Manifest**: `alertLimit` + `currency` (`EUR`|`USD`; `alertLimitEur` is the
older spelling), `pushAtPct`, `pushOnBreak` — the defaults, which the owner
overrides at runtime (`PUT …/key-settings`, kept in `installed.json` →
`keySettings`); `secretKey` (default: the first hub secret);
`legacyLedgerTool` — a core ledger tool the plugin took over, whose rows count
as the plugin's spend (`nanobanana` → `plugin:nanobanana`).
- **`settings.links`**: `[{label, url}]`, `https://` only, with
`{{config.<field>}}` placeholders (URL-quoted; a link whose field is empty is
left out) — the provider's console, billing…
- **Health**: an action's `_meter.keyHealth: {status, message}` — `ok`, or a
broken state `no-credit` / `invalid` / `denied` / `capped` — moves the key's
state; any other status (a rate limit, an outage) is listed as a failure only.
A move into a broken state pushes the owner once (`type: error`), the way back
to `ok` once (`✅ <Plugin> key works again`, `type: success`). The monthly
spend pushes once at `pushAtPct` and once at 100 % (an alert only).
- **Test** (`POST …/test`, `settings.testAction`): its `_meter` is billed (via
`test`) and its `keyHealth` recorded; a handler `_error` whose `kind` is a
key state is recorded too.
- **Replace** (`PUT …/secrets/<secretKey>` by the owner): the new key is checked
with `testAction` **before** it is saved — the run's handler token carries the
candidate in memory (`plugins.proxy.register_candidate`), so that run's proxy
calls use it. `invalid` / `denied` → 400, nothing saved; `no-credit` /
`capped` → saved (the key is right, the billing isn't); anything else → 502,
nothing saved. The secret's last four characters are kept beside it as a
non-secret hint (`installed.json` → `secretHints`).
## Seeded app plugins and icons for frames (since 2026-11-27, the prompt-shortcuts plugin)
- **`"seed": true`** (top level): an *app* plugin of the seed dir
(`PLUGINS_SEED_DIR`, else the plugins repo checkout) that the hub installs
once for the owner at start, approved and promoted to the catalog, like
the `provider-*` / `harness-*` plugins (`carryover.seed_typed_plugins`). The
store remembers it (`seeded`): an uninstall sticks. For a plugin that
replaced a core feature every user leans on — the prompt-shortcuts plugin,
whose `managed.defaultForGuests` then gives it to every guest. Only `true`
is written to the validated manifest.
- **`aiAgentPlugin.pickIcon({value?})`** → `Promise<string | null>`: the app's
glyph picker (the whole lucide set and the user's own icons) in a host
dialog; the picked key (`"GitBranch"`, `"svg:<id>"`), or null when
dismissed.
- **`aiAgentPlugin.iconSvg(keys)`** → `Promise<Record<string, string>>`: each
key's glyph as markup (24×24 lucide `<svg>` in `currentColor`, a user's own
SVG, or an `<img>` for a raster one; an unknown key gets Sparkles), ≤ 100
keys a call — what a frame draws chips with. Both live in
`frontend/src/business/plugins/iconBridge.tsx`.