A resource plugin can declare a `hueRole: group` kind — what an issue belongs to (a Linear project); its issue kind names it with `groupBy`. The linear plugin's `linear-project` uses it (plugin 1.1.0, ai-agent-plugins branch linear-projects). Decided in form linear-projects-icons-colour_yfnahd. - Lookups only: get_project and list_projects (a new extractor field, `itemsPath: projects[]`, reads each item of a listing without tagging the conversation) teach Linear's icon and colour; `vendor_icons` turns `Brush` / `:heavy_plus_sign:` into glyph keys (`brush`, `emoji:➕`, gemoji table vendored). PARSER_VERSION 47 re-mines past lookups. - Colour (`cardColour: group`, the default): a card wears its issue's project colour, each issue of the project a shade (`LookColors.group_color`, `shade_hex` ≡ the PWA's `shadeHex`); a palette hue when Linear's is unknown; an issue with no known project keeps issue + PR colours. A Settings → Tags colour on `linear:project/<name>` wins (the PWA re-shades it with `colorGroup` / `colorShade`); *Colour…* on such a card writes that tag. - Icon (`iconOrder: group`): project › label › team; the project's tag icon, else Linear's own. - Pill (`groupPills`): the issue's project beside it, in its own icon and colour (`Resource.icon` / `color`; the glyph is tinted, not the pill). - `groupLooks` off: only what Settings → Tags sets. - Emoji tag icons (`emoji:<char>`), Linear's look as a project tag's derived default in Settings → Tags, the mock seeds two projects. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2735 lines
141 KiB
Python
2735 lines
141 KiB
Python
"""Plugin manifest parsing, strict validation (v1 + v2 + v3), capability
|
||
summaries and deterministic approval fingerprints.
|
||
|
||
Every field is checked before a plugin can be installed or reloaded:
|
||
* relative paths must stay inside the plugin directory (no ``..`` or symlinks
|
||
escaping the root);
|
||
* regex patterns must compile cleanly;
|
||
* ``proxy.baseUrl`` must be ``https://`` unless ``internal: true`` (which only
|
||
the operator may approve);
|
||
* unknown top-level keys are refused so typos fail loudly instead of silently
|
||
doing nothing.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import hashlib
|
||
import json
|
||
import pathlib
|
||
import re
|
||
from typing import Any
|
||
from urllib.parse import urlsplit
|
||
|
||
SCHEMA_VERSION = 1
|
||
|
||
_ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,47}$")
|
||
_KEY_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_-]{0,47}$")
|
||
_SKILL_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,47}$")
|
||
_METHODS = frozenset({"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"})
|
||
_AUTH_INS = frozenset({"header", "query", "basic"})
|
||
_SECRET_SCOPES = frozenset({"user", "hub"})
|
||
_WAKE_SERVICE_RE = re.compile(r"^[a-z0-9][a-z0-9_.-]{0,62}$")
|
||
_FIELD_TYPES = frozenset({"text", "textarea", "number", "checkbox", "select", "list"})
|
||
# ``none``: routable at ``/plugins/<id>/<page>`` and shown in no nav (an
|
||
# OAuth callback page). ``settings``: a Settings entry (the panel, the bottom
|
||
# bar's drawers, the settings search), routed at ``/settings/p/<id>/<page>``,
|
||
# in the page's ``group`` (default ``you``), after the core entry ``after``
|
||
# names — the prompt-shortcuts plugin's editor. ``projects``: a shortcut row
|
||
# above the project list (the Projects panel and the Projects bottom-bar
|
||
# drawer) — the services plugin's Services catalogue.
|
||
_NAV_GROUPS = frozenset({"dashboards", "tools", "main", "files", "none", "settings", "projects"})
|
||
# The Settings groups a ``nav: "settings"`` page may sit in (the frontend's
|
||
# ``SETTINGS_GROUPS``, business/settings/registry.ts).
|
||
_SETTINGS_GROUPS = frozenset({"you", "tools", "workspace", "people", "machine"})
|
||
# Where a page may put a button of its own in a page head (``ui.pages[].header``):
|
||
# the home page and the conversation list — the Analytics plugin's chart icon.
|
||
_PAGE_HEADERS = frozenset({"home"})
|
||
# The tag kinds the core routes itself (lib/tags.ts ``tagHref``): a page's
|
||
# ``tag`` claims any other (skill, agent, service — the services plugin's
|
||
# catalogue since 2026-11-28).
|
||
_CORE_TAG_KINDS = frozenset({"project"})
|
||
# An App usage feature id (frontend lib/telemetry/features.ts): ``page.forms``.
|
||
_FEATURE_RE = re.compile(r"^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9-]+){1,3}$")
|
||
# ``machine.detail``: a machine page's Tools tab (init ``{machineId, name, kind}``).
|
||
_SLOT_PLACES = frozenset({"project.card", "project.detail",
|
||
"conversation.header", "conversation.details", "machine.detail",
|
||
# widget-platform places: a full-width home section, a
|
||
# bar above the composer, the strip under the last
|
||
# message, a pill in the thread's corner row.
|
||
"home.section", "conversation.pinned",
|
||
"conversation.threadFooter", "conversation.gizmos",
|
||
# the thread's first line (under the fork banner) and
|
||
# its last (after the summary) — the Handoff plugin's
|
||
# "Continued from" / "Continued in".
|
||
"conversation.threadHeader", "conversation.threadEnd",
|
||
# the conversations drawer's body behind a toggle in
|
||
# its count row; an item of both composers' send
|
||
# menus (the frozen payload, in the app's modal); a
|
||
# document in the app's modal (``openModal`` /
|
||
# ``?modal=<pid>:<slot>``) — the scheduled-conversations
|
||
# plugin's drawer, Send later… and edit view.
|
||
"conversations.drawer", "composer.send", "app.modal",
|
||
# a tab of the conversation header's switch
|
||
# (``Thread | <label> <badge>``): the frame fills
|
||
# the thread's pane while it is active — the
|
||
# diff-viewer plugin's Changes tab.
|
||
"conversation.tab"})
|
||
# ``ui.menuItems[].where``: the conversation list's right-click / long-press
|
||
# menu — a row that opens the item's sandboxed dialog.
|
||
_MENU_PLACES = frozenset({"conversation.menu"})
|
||
_MENU_ITEMS_MAX = 8
|
||
# Slot places whose host draws a control of its own (a toggle, a menu item):
|
||
# they name a lucide ``icon`` (and the drawer's toggle a ``badge`` read).
|
||
_ICON_SLOTS = frozenset({"conversations.drawer", "composer.send", "conversation.tab"})
|
||
# ``conversation.tab`` slots: at most this many per plugin, a label of at most
|
||
# 24 characters, and ``legacyView`` — an old ``?view=`` value the tab answers
|
||
# (``changes``: today's ``?view=changes&c=<sel>`` → params ``{c: sel}``).
|
||
_TAB_SLOTS_MAX = 2
|
||
_TAB_LABEL_MAX = 24
|
||
_TAB_LEGACY_VIEWS = frozenset({"changes"})
|
||
# ``ui.pages[].opens``: the kinds of link into the app the page answers
|
||
# (``pluginOpenHref(kind, params)`` — ``commit`` {repo, sha} from Project &
|
||
# Service *Recent commits*, ``conversation-diff`` {id}). The core names no
|
||
# plugin page: the first active page that opens a kind gets its links.
|
||
_PAGE_OPEN_RE = re.compile(r"^[a-z][a-z0-9-]{0,31}$")
|
||
_PAGE_OPENS_MAX = 8
|
||
# ``ui.pages[].fileTypes`` / ``ui.filePreviews[].fileTypes``: the file
|
||
# extensions (lowercase, no dot) a viewer page / an inline preview card takes —
|
||
# docs/plugins.md → "File viewers". A typed page must open ``host-file``.
|
||
_FILE_TYPE_RE = re.compile(r"^[a-z0-9]{1,10}$")
|
||
_FILE_TYPES_MAX = 32
|
||
_FILE_PREVIEWS_MAX = 4
|
||
_LUCIDE_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,39}$")
|
||
# ``ui.slots[].size`` on an ``app.modal`` slot: the app modal's width (``full``
|
||
# also fills its height — a live view, a canvas).
|
||
_MODAL_SIZES = frozenset({"sm", "md", "lg", "full"})
|
||
# Host SSE event types a slot / tool card frame may ask to be forwarded.
|
||
_UI_EVENTS = frozenset({"askform", "meta", "transcript", "usage"})
|
||
# ThreadItem fields a tool card's ``match.hasField`` may require.
|
||
_HAS_FIELDS = frozenset({"deploy", "commits", "subagent", "bashDiff", "taskId"})
|
||
# ``ui.toolCards[].inThreadWhile``: stand in the chat only while the call is
|
||
# still active (its task has no terminal state / its timer hasn't fired); once
|
||
# inactive, fold into its normal collapsible tool row.
|
||
_IN_THREAD_WHILE = frozenset({"active"})
|
||
# ``match.hasReport: true``: the call is claimed only when this plugin filed a
|
||
# report (``aia_report.py`` — a ``pathShims`` script) during it; shell only.
|
||
_HAS_REPORT_TOOLS = frozenset({"shell"})
|
||
# ``ui.fences[].lang``: the info string of a fenced block in an agent's message
|
||
# that the plugin draws (```chart → its frame). A language people write code in
|
||
# stays a code block, and ``notify`` is the closing push the parser cuts out.
|
||
_FENCE_LANG_RE = re.compile(r"^[a-z][a-z0-9_+-]{1,31}$")
|
||
_FENCE_RESERVED = frozenset({
|
||
"notify", "text", "txt", "plain", "plaintext", "md", "markdown", "diff", "patch", "log",
|
||
"sh", "bash", "zsh", "fish", "shell", "console", "powershell", "ps1", "bat", "cmd",
|
||
"js", "jsx", "javascript", "ts", "tsx", "typescript", "json", "jsonc", "json5", "yaml", "yml",
|
||
"toml", "ini", "xml", "html", "css", "scss", "sass", "less", "svg", "csv", "tsv", "sql",
|
||
"py", "python", "rb", "ruby", "go", "rs", "rust", "java", "kt", "kotlin", "swift", "c", "cpp",
|
||
"c++", "cs", "csharp", "php", "lua", "r", "dart", "scala", "ex", "elixir", "erl", "hs",
|
||
"dockerfile", "makefile", "nginx", "graphql", "proto", "env", "vue", "svelte",
|
||
})
|
||
# A transparent sandboxed frame over a whole page (docs/plugins.md → "Overlays"):
|
||
# ``conversation`` = a conversation page, ``home`` = the home page. What each
|
||
# place hands the frame is fixed by the host (lib/overlay/feed.ts), never more.
|
||
_OVERLAY_PLACES = frozenset({"conversation", "home"})
|
||
# Clicks: ``none`` = every click goes to the page; ``hits`` = the frame takes
|
||
# the pointer only inside the small boxes it reports (a pet to pat or throw).
|
||
_OVERLAY_POINTER = frozenset({"none", "hits"})
|
||
# Per-person preferences the host keeps for a plugin (in the person's
|
||
# own settings, guests included) and draws on the plugin's page.
|
||
_PREF_TYPES = frozenset({"switch", "range", "color", "select"})
|
||
_PREF_SCOPES = frozenset({"user", "default+override"})
|
||
_PREF_OPTIONS_FROM = frozenset({"user.modelFamilies"})
|
||
# ``notify.action``: a button of a push was tapped (``/api/notify/{id}/action``)
|
||
# — ``{notifyId, index, title}``; a plugin's push buttons (``hub/notify``
|
||
# ``actions``) come back to it this way.
|
||
_EVENT_TYPES = frozenset({"conversation.finished", "conversation.started", "notify", "deploy",
|
||
"notify.action"})
|
||
_EVENT_NAME_RE = re.compile(r"^[a-z][a-z0-9._-]{0,63}$")
|
||
_PLUGIN_EVENT_RE = re.compile(r"^plugin:([a-z0-9][a-z0-9-]{0,47}):([a-z][a-z0-9._-]{0,63})$")
|
||
_WEBHOOK_MODES = frozenset({"notify", "spawn", "action"})
|
||
_WEBHOOK_RESPONDS = frozenset({"envelope", "result"})
|
||
_WEBHOOK_METHODS = frozenset({"GET", "POST"})
|
||
_CAPABILITIES = frozenset({
|
||
"conversations.read", "conversations.spawn", "conversations.reply", "notify.send",
|
||
# A phone channel's way back (plugins/hubnotify.py): answer an ask, run a
|
||
# push's button, mark pushes dismissed, read one push back, and the
|
||
# addresses its own webhooks answer on — the installer's own pushes only,
|
||
# the plugin's handlers only — the android-push plugin.
|
||
"notify.respond",
|
||
"goals.read", "goals.work", "graph.read", "footprint.read", "telemetry.read", "analytics.read",
|
||
# The host's services dir, for this plugin's handlers (AIA_SERVICES_DIR):
|
||
# the owner's runs only — the Services catalogue plugin.
|
||
"services.read",
|
||
# Owner-only run bridges (plugins/hubruns.py) — the mail-agents plugin.
|
||
"runs.start", "conversations.send", "models.read", "workers.read",
|
||
# A guest's scheduled job, run as that guest — the confinement is the
|
||
# core's (runs/guestjob.py) — the cron-jobs plugin.
|
||
"runs.guest",
|
||
# Hub bridges for ask-form, approvals, new-project and plans plugins.
|
||
"askform.bridge", "users.read", "scaffold.run", "plans.read", "plans.write",
|
||
# Batch 1 owner-only host data (AIA_TEMPLATES_DIR / AIA_MEMORIES_DIR /
|
||
# AIA_PROJECTS_DIR for the owner's handler runs; activity + ship bridges).
|
||
"templates.read", "memories.read", "projects.env", "activity.read", "ship.run",
|
||
# Plan usage (plugins/usagedata.py) — the plan-usage plugin.
|
||
"usage.read", "usage.calibrate",
|
||
# The caller's own home page as data (plugins/hubbridge.py hub/home) — the
|
||
# android-push plugin's live notification.
|
||
"home.read",
|
||
# One-shot completions on any model + writing conversation labels
|
||
# (plugins/hubcomplete.py) — the conversation-labels plugin.
|
||
"complete.run", "conversations.label",
|
||
# The owner's machines and their sidecar's /mcp-servers routes
|
||
# (plugins/hubmachines.py), and authenticated streaming relays to
|
||
# upstreams the plugin holds the credentials of (plugins/relay.py) — the
|
||
# mcp-servers plugin.
|
||
"machines.mcp", "relay.serve",
|
||
# Wake-on-LAN through the host sidecar's /wol and a worker probe
|
||
# (plugins/hubwake.py) — the wake-on-lan plugin.
|
||
"machines.wake",
|
||
# A plugin's own data on a conversation (``meta.plugins.<id>``, read and
|
||
# written through hub/conversations/{sid}/data — plugins/hubconvdata.py)
|
||
# — the handoff plugin's links.
|
||
"conversations.data",
|
||
# A prompt's title from the ``conversation.title`` provider (hub/title)
|
||
# — the scheduled-conversations plugin.
|
||
"conversations.title",
|
||
# The skills and agents catalogs, sharing a skill with guests, running or
|
||
# scheduling an agent (plugins/hubcatalog.py) — the skills-agents plugin.
|
||
"catalog.read", "skills.share", "agents.run",
|
||
# The Performance / Storage dashboards' data and their Kill / Keep /
|
||
# Remove / Measure (plugins/hubperf.py) — the performance plugin.
|
||
"perf.read", "perf.act",
|
||
# One conversation's lifecycle stamps and state, the caller's own
|
||
# (hub/conversations/{cid}/checks — plugins/hubchecks.py) — the
|
||
# lifecycle plugin's Details card.
|
||
"conversations.checks",
|
||
# The reports the plugin's own path shims filed on a conversation
|
||
# (hub/conversations/{cid}/reports — plugins/hubreports.py) and the diff
|
||
# engines (hub/diff/… — plugins/hubdiff.py): the caller's own
|
||
# conversations — the commits and diff-viewer plugins.
|
||
"conversations.reports", "diff.read",
|
||
# One conversation's background shells and Monitors: list, output tail,
|
||
# and stop on the runner (hub/conversations/{cid}/tasks… —
|
||
# plugins/hubtasks.py) — the background-shells plugin.
|
||
"conversations.tasks",
|
||
# The hub's own API as the owner or, narrowed, as a guest the plugin is
|
||
# granted to (plugins/hubapi.py), a tappable question to the owner and a
|
||
# line in the Security log (plugins/hubsignals.py) — the hub-mcp plugin.
|
||
"hub.api", "notify.ask", "security.record",
|
||
# Host file explorer & viewer (hub/host-file*, caller-scoped —
|
||
# plugins/hubfiles.py) and workspace Claude context tree & editor
|
||
# (hub/context/*, owner-only) — the file-explorer and context-editor plugins.
|
||
"hostfiles.read", "context.read", "context.write",
|
||
# The context files' token cost, the skills' usage and estimated spend
|
||
# (hub/context-cost — plugins/hubcontextcost.py) — the context-skills
|
||
# plugin's dashboard.
|
||
"contextcost.read",
|
||
# Install / uninstall plugins from the public catalog through host-drawn
|
||
# confirmations (aiAgentPlugin.plugins.* — business/plugins/catalogBridge)
|
||
# — the plugin-catalog plugin.
|
||
"plugins.manage",
|
||
# Every translation's and every plugin's own coverage, per language
|
||
# (hub/i18n — plugins/hubi18n.py) — the auto-translate plugin.
|
||
"i18n.read",
|
||
})
|
||
# Capabilities only the operator may approve (and shown as privileged).
|
||
_OPERATOR_CAPS = frozenset({
|
||
"conversations.spawn", "conversations.reply",
|
||
"goals.read", "goals.work", "services.read", "graph.read", "footprint.read", "telemetry.read",
|
||
"analytics.read", "runs.start", "conversations.send", "models.read", "workers.read",
|
||
"runs.guest", "askform.bridge", "users.read", "scaffold.run", "plans.read", "plans.write",
|
||
"templates.read", "memories.read", "projects.env", "activity.read", "ship.run",
|
||
# Plan usage (plugins/usagedata.py) — the plan-usage plugin.
|
||
"usage.read", "usage.calibrate",
|
||
"complete.run", "conversations.label",
|
||
"machines.mcp", "relay.serve", "machines.wake", "conversations.data",
|
||
"conversations.title", "perf.read", "perf.act",
|
||
"catalog.read", "skills.share", "agents.run",
|
||
"hub.api", "notify.ask", "security.record",
|
||
# the host's files (~/homelab, ~/worktrees for the owner): a plugin of the
|
||
# operator's only — a guest reaches them through the owner's managed one
|
||
"hostfiles.read", "context.read", "context.write",
|
||
"contextcost.read", "i18n.read",
|
||
"plugins.manage",
|
||
})
|
||
# Data a plugin hands the host itself: name → the action the host runs (as the
|
||
# owner) and merges into its own answer. ``services.index``: the homelab
|
||
# services catalogue (every services/<dir>: name, README line, goal, URLs,
|
||
# containers, auth…) for core integrations — the tag registry, the composer's
|
||
# service chips, goals, the graph (plugins/services_bridge.py).
|
||
# ``notify.channel``: delivers its installer's pushes, asks and clears
|
||
# (notifications/channels.py) — run as that user, not the owner.
|
||
# ``composer.shortcuts``: additive prompt shortcuts rendered natively in the
|
||
# composer (plugins/shortcuts.py).
|
||
# ``inbox.waiting``: pending questions surfaced in Waiting for feedback,
|
||
# FeedbackBell, ConversationWaiting and auto-archive (plugins/waiting.py).
|
||
# ``composer.mode``: composer mode descriptor (e.g. New project).
|
||
# ``plans.index``: plan metadata consumed by core integrations (e.g. graph).
|
||
# ``memories.index``: memory metadata for core integrations (plugins/memories_bridge.py).
|
||
# ``notify.audio``: renders a push's spoken audio (the desk-phone replay button).
|
||
# ``app.banner``: an owner-only floating status banner (plugins/banner.py).
|
||
# ``conversation.title``: a scheduled prompt's title and a long title's short
|
||
# header stand-in; ``conversation.look``: label a conversation's action badge
|
||
# now (plugins/labels_bridge.py).
|
||
# ``machine.attention``: what on each of the owner's machines waits for him —
|
||
# the Needs-you rows and the Setup checklist (plugins/machine_attention.py).
|
||
# ``machine.wake``: which of the owner's workers can be woken (Wake-on-LAN),
|
||
# and the wake itself — before a run pinned to a sleeping one, and the Wake
|
||
# button on its card (plugins/machine_wake.py).
|
||
# ``runs.schedule``: scheduled conversations — ``{op: list|get|create|edit|
|
||
# cancel|start|title|upcoming, …}`` (plugins/schedule_bridge.py).
|
||
# ``runs.cron``: cron jobs — ``{op: index|list|get|create, …}``
|
||
# (plugins/cron_bridge.py).
|
||
_PROVIDES = frozenset({
|
||
"services.index", "notify.channel", "composer.shortcuts",
|
||
"inbox.waiting", "composer.mode", "plans.index",
|
||
"memories.index", "notify.audio", "app.banner",
|
||
"conversation.title", "conversation.look",
|
||
# declarative native tiles for the home usage strip (plugins/home_tiles.py)
|
||
"home.tiles",
|
||
"machine.attention", "machine.wake",
|
||
# Scheduled conversations ("Send later"): the week's budget and the
|
||
# stopped-run card's Resume at… ask it
|
||
# (plugins/schedule_bridge.py).
|
||
"runs.schedule",
|
||
# Cron jobs (owner and guests'): the week's budget, auto-archive's
|
||
# archiveOnSuccess, the agents catalog's cron runs and the agent page's
|
||
# Schedule ask it (plugins/cron_bridge.py).
|
||
"runs.cron",
|
||
# On opening the app (a load, back to the foreground): one of the
|
||
# plugin's ``app.modal`` slots to open, or nothing (plugins/launch.py).
|
||
"app.launch",
|
||
# The guests' What's new entries and who saw them — App usage's
|
||
# announcement → adoption (plugins/whatsnew_bridge.py).
|
||
"whatsnew.index",
|
||
# The browser a lab ``--chrome`` run drives (the lab-chrome plugin):
|
||
# ``{op: status}`` — the composer chip's default, whether guests' runs may
|
||
# launch with --chrome — and ``{op: ensure}`` before such a run launches
|
||
# (plugins/chrome_bridge.py).
|
||
"chrome.lab",
|
||
# The caller's keyboard shortcuts — which keys run which app command
|
||
# (plugins/keymap.py); none provided = no shortcuts.
|
||
"app.keymap",
|
||
# How many agents each machine runs at once — ``{op: limits}`` →
|
||
# ``{limits: {<runner id | local>: n}}``; the core queues the starts
|
||
# over it and hands the limit to each run (plugins/run_limits.py,
|
||
# runs/queue.py).
|
||
"runs.limits",
|
||
})
|
||
_TOP_KEYS = frozenset({
|
||
"schema", "id", "name", "version", "description", "icon", "author",
|
||
"skill", "secrets", "settings", "proxy", "storage", "schedules",
|
||
"ui", "events", "webhooks", "actions", "resources", "capabilities",
|
||
"managed", "illustration", "color", "readme", "provides",
|
||
# an app plugin of the seed dir installed once at start (carryover.py)
|
||
"seed",
|
||
"requires", "optionalRequires", "exports", "emits", "agents",
|
||
# typed plugins (plugins/typed_manifest.py): what a plugin *is* — an app
|
||
# (the default), a model provider or an agent harness.
|
||
"kind", "provider", "harness", "translation",
|
||
# the languages its own UI speaks (``["en", "fr"]``; default ``["en"]``)
|
||
"languages",
|
||
# the plugin's own strings in other languages (plugins/plugin_i18n.py)
|
||
"i18n",
|
||
# hooks into the agent harness's own hook points (plugins/harness_hooks.py)
|
||
"harnessHooks",
|
||
# ai-agent CLI commands + MCP tools over declared actions (plugins/commands.py)
|
||
"commands",
|
||
# websockets its frames open through the host (plugins/sockets.py)
|
||
"sockets",
|
||
# commands it wraps on every agent run's PATH (plugins/path_shims.py)
|
||
"pathShims",
|
||
# the shelf Settings → Plugins files it under (plugins/categories.py)
|
||
"category",
|
||
# HTTP it answers on the hub's own address (plugins/endpoints.py)
|
||
"endpoints",
|
||
})
|
||
|
||
|
||
class ManifestError(ValueError):
|
||
"""Raised when ``plugin.json`` or its referenced files are invalid."""
|
||
|
||
def __init__(self, errors: list[str]):
|
||
self.errors = errors
|
||
super().__init__("; ".join(errors))
|
||
|
||
|
||
def _overlays(root: pathlib.Path, raw: Any, errors: list[str]) -> list[dict[str, Any]]:
|
||
"""``ui.overlays[]``: one transparent frame per page place. Only keys that
|
||
are set are written (``ui`` is in the approval fingerprint)."""
|
||
if raw is None:
|
||
return []
|
||
if not isinstance(raw, list):
|
||
errors.append("ui.overlays must be a list")
|
||
return []
|
||
out: list[dict[str, Any]] = []
|
||
seen: set[str] = set()
|
||
for i, ov in enumerate(raw):
|
||
if not isinstance(ov, dict):
|
||
errors.append(f"ui.overlays[{i}] must be an object")
|
||
continue
|
||
oid = str(ov.get("id") or "").strip()
|
||
where = str(ov.get("where") or "")
|
||
if not _KEY_RE.match(oid) or where not in _OVERLAY_PLACES:
|
||
errors.append(f"ui.overlays[{i}]: invalid id or where ({sorted(_OVERLAY_PLACES)})")
|
||
continue
|
||
if where in seen:
|
||
errors.append(f"ui.overlays[{i}]: one overlay per place ('{where}' twice)")
|
||
continue
|
||
seen.add(where)
|
||
pointer = str(ov.get("pointer") or "none")
|
||
if pointer not in _OVERLAY_POINTER:
|
||
errors.append(f"ui.overlays[{i}].pointer must be one of {sorted(_OVERLAY_POINTER)}")
|
||
continue
|
||
_safe_rel(root, ov.get("html"), f"ui.overlays[{i}].html", errors)
|
||
item: dict[str, Any] = {"id": oid, "where": where, "html": str(ov.get("html") or ""), "pointer": pointer}
|
||
if ov.get("cursor") is True:
|
||
item["cursor"] = True
|
||
out.append(item)
|
||
return out
|
||
|
||
|
||
def _prefs(raw: Any, errors: list[str]) -> list[dict[str, Any]]:
|
||
"""``ui.prefs[]``: switch / range / color / select fields, per person."""
|
||
if raw is None:
|
||
return []
|
||
if not isinstance(raw, list):
|
||
errors.append("ui.prefs must be a list")
|
||
return []
|
||
out: list[dict[str, Any]] = []
|
||
for i, f in enumerate(raw[:12]):
|
||
if not isinstance(f, dict):
|
||
errors.append(f"ui.prefs[{i}] must be an object")
|
||
continue
|
||
key = str(f.get("key") or "")
|
||
typ = str(f.get("type") or "")
|
||
if not _KEY_RE.match(key) or typ not in _PREF_TYPES:
|
||
errors.append(f"ui.prefs[{i}]: invalid key or type ({sorted(_PREF_TYPES)})")
|
||
continue
|
||
item: dict[str, Any] = {"key": key, "type": typ, "label": str(f.get("label") or key)[:60]}
|
||
if f.get("help"):
|
||
item["help"] = str(f["help"])[:300]
|
||
if isinstance(f.get("labels"), dict): # {"fr": {"label", "help"}}
|
||
item["labels"] = {str(k)[:5]: {kk: str(vv)[:300] for kk, vv in v.items() if kk in ("label", "help")}
|
||
for k, v in f["labels"].items() if isinstance(v, dict)}
|
||
scope = str(f.get("scope") or "user")
|
||
if scope not in _PREF_SCOPES:
|
||
errors.append(f"ui.prefs[{i}].scope must be one of {sorted(_PREF_SCOPES)}")
|
||
continue
|
||
if scope != "user":
|
||
item["scope"] = scope
|
||
d = f.get("default")
|
||
if typ == "switch":
|
||
item["default"] = bool(d) if d is not None else True
|
||
elif typ == "range":
|
||
try:
|
||
lo, hi = float(f.get("min", 0)), float(f.get("max", 100))
|
||
step = float(f.get("step", 1))
|
||
dv = float(d if d is not None else lo)
|
||
except (TypeError, ValueError):
|
||
errors.append(f"ui.prefs[{i}]: range needs numeric min / max / step / default")
|
||
continue
|
||
if not lo < hi or not lo <= dv <= hi or step <= 0:
|
||
errors.append(f"ui.prefs[{i}]: range needs min < default ≤ max")
|
||
continue
|
||
item.update({"min": lo, "max": hi, "step": step, "default": dv})
|
||
if f.get("unit"):
|
||
item["unit"] = str(f["unit"])[:8]
|
||
elif typ == "color":
|
||
dv = str(d or "#888888")
|
||
if not re.fullmatch(r"#[0-9a-fA-F]{6}", dv):
|
||
errors.append(f"ui.prefs[{i}]: color default must be #rrggbb")
|
||
continue
|
||
item["default"] = dv.lower()
|
||
sw = [str(c).lower() for c in (f.get("swatches") or []) if re.fullmatch(r"#[0-9a-fA-F]{6}", str(c))]
|
||
if sw:
|
||
item["swatches"] = sw[:12]
|
||
else:
|
||
opt_from = f.get("optionsFrom")
|
||
if opt_from is not None:
|
||
opt_from = str(opt_from)
|
||
if opt_from not in _PREF_OPTIONS_FROM:
|
||
errors.append(f"ui.prefs[{i}].optionsFrom must be one of {sorted(_PREF_OPTIONS_FROM)}")
|
||
continue
|
||
item["optionsFrom"] = opt_from
|
||
opts = [str(o)[:40] for o in (f.get("options") or [])][:20]
|
||
if not opts and opt_from == "user.modelFamilies":
|
||
opts = ["haiku", "sonnet", "opus"]
|
||
if not opts or str(d if d is not None else opts[0]) not in opts:
|
||
errors.append(f"ui.prefs[{i}]: select needs options and a default among them")
|
||
continue
|
||
item.update({"options": opts, "default": str(d if d is not None else opts[0])})
|
||
if isinstance(f.get("optionLabels"), dict):
|
||
item["optionLabels"] = {str(k)[:40]: str(v)[:60] for k, v in f["optionLabels"].items()}
|
||
out.append(item)
|
||
return out
|
||
|
||
|
||
def _safe_rel(root: pathlib.Path, rel: str, label: str, errors: list[str],
|
||
*, must_exist: bool = True, want_dir: bool = False) -> pathlib.Path | None:
|
||
if not isinstance(rel, str) or not rel.strip() or rel.startswith("/") or "\\" in rel:
|
||
errors.append(f"{label}: must be a relative POSIX path")
|
||
return None
|
||
parts = pathlib.PurePosixPath(rel).parts
|
||
if not parts or any(p in ("", ".", "..") for p in parts):
|
||
errors.append(f"{label}: path must not contain '..' or '.' segments")
|
||
return None
|
||
resolved_root = root.resolve()
|
||
target = (resolved_root / rel).resolve()
|
||
try:
|
||
target.relative_to(resolved_root)
|
||
except ValueError:
|
||
errors.append(f"{label}: path escapes plugin directory")
|
||
return None
|
||
if must_exist:
|
||
if want_dir and not target.is_dir():
|
||
errors.append(f"{label}: directory '{rel}' not found")
|
||
return None
|
||
if not want_dir and not target.is_file():
|
||
errors.append(f"{label}: file '{rel}' not found")
|
||
return None
|
||
return target
|
||
|
||
|
||
# ── art: SVG icon, illustration, accent colour, README ───────────────────────
|
||
_ICON_MAX = 32 * 1024
|
||
_ILLUSTRATION_MAX = 1024 * 1024
|
||
_README_MAX = 64 * 1024
|
||
_ILLUSTRATION_EXTS = (".svg", ".webp", ".png", ".jpg", ".jpeg")
|
||
_COLOR_RE = re.compile(r"^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$")
|
||
_LUCIDE_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,39}$")
|
||
# An SVG is served sandboxed and drawn through <img> / CSS masks, where
|
||
# scripts never run — but a plugin anyone can write must not ship active
|
||
# content at all: refused at install instead of trusting the serving path.
|
||
_SVG_FORBIDDEN = re.compile(
|
||
r"<\s*(script|foreignObject|iframe|embed|object|audio|video|use\b[^>]*href\s*=\s*(?![\"']?#))"
|
||
r"|\bon[a-z]+\s*="
|
||
r"|javascript:"
|
||
r"|<!ENTITY|<!DOCTYPE"
|
||
r"|(?:xlink:)?href\s*=\s*[\"']?\s*(?:https?:|data:|//)"
|
||
r"|@import|url\(\s*[\"']?\s*(?:https?:|data:|//)",
|
||
re.IGNORECASE,
|
||
)
|
||
|
||
|
||
def svg_problem(data: bytes) -> str | None:
|
||
"""Why an SVG can't be used as plugin art, or ``None`` when it is inert."""
|
||
try:
|
||
text = data.decode("utf-8")
|
||
except UnicodeDecodeError:
|
||
return "is not UTF-8"
|
||
if "<svg" not in text.lower():
|
||
return "is not an SVG"
|
||
m = _SVG_FORBIDDEN.search(text)
|
||
if m:
|
||
return f"contains active or external content ({m.group(0)[:30]!r})"
|
||
return None
|
||
|
||
|
||
def _art_file(root: pathlib.Path, rel: Any, label: str, errors: list[str], *,
|
||
exts: tuple[str, ...], max_bytes: int) -> str | None:
|
||
target = _safe_rel(root, rel, label, errors)
|
||
if target is None:
|
||
return None
|
||
if target.suffix.lower() not in exts:
|
||
errors.append(f"{label}: must be one of {', '.join(exts)}")
|
||
return None
|
||
size = target.stat().st_size
|
||
if size > max_bytes:
|
||
errors.append(f"{label}: {size // 1024} KB is over the {max_bytes // 1024} KB limit")
|
||
return None
|
||
if target.suffix.lower() == ".svg":
|
||
why = svg_problem(target.read_bytes())
|
||
if why:
|
||
errors.append(f"{label}: SVG {why}")
|
||
return None
|
||
return str(rel)
|
||
|
||
|
||
def _parse_art(root: pathlib.Path, raw: dict[str, Any], errors: list[str]) -> dict[str, Any]:
|
||
"""``icon`` (a lucide name, or a path to an ``.svg``), ``illustration``,
|
||
``color`` and ``readme``. Without a declaration, ``icon.svg``,
|
||
``illustration.{svg,webp,png,jpg}`` and ``README.md`` at the plugin root
|
||
are picked up by name. ``artVersion`` changes whenever one of the files
|
||
does, so the asset URLs can be cached for good."""
|
||
icon_raw = str(raw.get("icon") or "puzzle").strip()
|
||
icon_name = "puzzle"
|
||
icon_svg_rel: Any = None
|
||
if icon_raw.lower().endswith(".svg"):
|
||
icon_svg_rel = icon_raw
|
||
elif _LUCIDE_RE.match(icon_raw):
|
||
icon_name = icon_raw
|
||
else:
|
||
errors.append("icon must be a lucide icon name or a path to an .svg")
|
||
if icon_svg_rel is None and (root / "icon.svg").is_file():
|
||
icon_svg_rel = "icon.svg"
|
||
icon_svg = (_art_file(root, icon_svg_rel, "icon", errors, exts=(".svg",), max_bytes=_ICON_MAX)
|
||
if icon_svg_rel else None)
|
||
|
||
ill_rel: Any = raw.get("illustration")
|
||
if ill_rel is None:
|
||
ill_rel = next((f"illustration{e}" for e in _ILLUSTRATION_EXTS if (root / f"illustration{e}").is_file()), None)
|
||
illustration = (_art_file(root, ill_rel, "illustration", errors,
|
||
exts=_ILLUSTRATION_EXTS, max_bytes=_ILLUSTRATION_MAX)
|
||
if ill_rel else None)
|
||
|
||
color = raw.get("color")
|
||
if color is not None and (not isinstance(color, str) or not _COLOR_RE.match(color.strip())):
|
||
errors.append("color must be a hex colour like #3a2f7d")
|
||
color = None
|
||
|
||
readme_rel: Any = raw.get("readme")
|
||
if readme_rel is None and (root / "README.md").is_file():
|
||
readme_rel = "README.md"
|
||
readme = (_art_file(root, readme_rel, "readme", errors, exts=(".md",), max_bytes=_README_MAX)
|
||
if readme_rel else None)
|
||
|
||
h = hashlib.sha256()
|
||
for rel in (icon_svg, illustration, readme):
|
||
if rel:
|
||
h.update(rel.encode())
|
||
h.update((root / rel).read_bytes())
|
||
return {
|
||
"icon": icon_name,
|
||
"iconSvg": icon_svg,
|
||
"illustration": illustration,
|
||
"color": color.strip().lower() if isinstance(color, str) else None,
|
||
"readme": readme,
|
||
"artVersion": h.hexdigest()[:12],
|
||
}
|
||
|
||
|
||
def _check_regex(pattern: Any, label: str, errors: list[str]) -> str | None:
|
||
if not isinstance(pattern, str) or not pattern or len(pattern) > 512:
|
||
errors.append(f"{label}: regex must be a non-empty string (<= 512 chars)")
|
||
return None
|
||
try:
|
||
re.compile(pattern)
|
||
except re.error as e:
|
||
errors.append(f"{label}: invalid regex ({e})")
|
||
return None
|
||
return pattern
|
||
|
||
|
||
# A quantified group that itself ends on a quantifier — `(a+)+`, `(\w*)*`,
|
||
# `(x{1,3})+`: the shape behind catastrophic backtracking. Resource regexes
|
||
# run over every prompt and tool result of every transcript, so they are
|
||
# held to it (a heuristic, not a proof: it refuses the classic shapes).
|
||
_REDOS_RE = re.compile(r"\((?:[^()\\]|\\.)*(?:[+*]|\{\d*,?\d*\})\??\)(?:[+*]|\{\d*,\d*\})")
|
||
|
||
|
||
def _check_safe_regex(pattern: Any, label: str, errors: list[str]) -> str | None:
|
||
pat = _check_regex(pattern, label, errors)
|
||
if pat and _REDOS_RE.search(pat):
|
||
errors.append(f"{label}: nested quantifiers (catastrophic backtracking) are not allowed")
|
||
return None
|
||
return pat
|
||
|
||
|
||
# ── resources[] (conversation resource kinds, plugins/resources.py) ─────────
|
||
_CORE_RESOURCE_KINDS = frozenset({"branch", "url"})
|
||
_GROUP_RE = re.compile(r"^(?:[A-Za-z_][A-Za-z0-9_]{0,31}|\d)$")
|
||
_CLICK_ACTIONS = frozenset({"open", "copy"})
|
||
_HUE_ROLES = frozenset({"hue", "shade", "group"})
|
||
_FIELD_PATH_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,47}(?:\[\])?(?:\.[A-Za-z_][A-Za-z0-9_]{0,47}(?:\[\])?){0,3}$")
|
||
_TPL_MAX = 300
|
||
|
||
|
||
def _tpl(v: Any, label: str, errors: list[str]) -> str | None:
|
||
if v is None:
|
||
return None
|
||
if not isinstance(v, str) or not v.strip() or len(v) > _TPL_MAX:
|
||
errors.append(f"{label}: a template string (<= {_TPL_MAX} chars)")
|
||
return None
|
||
return v
|
||
|
||
|
||
def _tpl_rules(v: Any, label: str, errors: list[str]) -> list[dict[str, str]] | None:
|
||
"""A template, or rules ``[{"match": "<regex on the id>", "template"}]``
|
||
— the first whose ``match`` hits (none = always) wins; ``""`` = nothing."""
|
||
if v is None:
|
||
return None
|
||
if isinstance(v, str):
|
||
t = _tpl(v, label, errors)
|
||
return [{"template": t}] if t else None
|
||
if not isinstance(v, list) or not v or len(v) > 8:
|
||
errors.append(f"{label}: a template or 1-8 rules")
|
||
return None
|
||
out = []
|
||
for i, rule in enumerate(v):
|
||
if not isinstance(rule, dict) or not isinstance(rule.get("template"), str) \
|
||
or len(rule["template"]) > _TPL_MAX:
|
||
errors.append(f"{label}[{i}]: {{match?, template}}")
|
||
continue
|
||
item = {"template": rule["template"]}
|
||
if rule.get("match") is not None:
|
||
m = _check_safe_regex(rule["match"], f"{label}[{i}].match", errors)
|
||
if m:
|
||
item["match"] = m
|
||
out.append(item)
|
||
return out or None
|
||
|
||
|
||
def _paths(v: Any, label: str, errors: list[str]) -> list[str] | None:
|
||
if v is None:
|
||
return None
|
||
if isinstance(v, str):
|
||
v = [v]
|
||
if not isinstance(v, list) or len(v) > 6 or not all(
|
||
isinstance(x, str) and _FIELD_PATH_RE.match(x) for x in v):
|
||
errors.append(f"{label}: 1-6 field paths (a.b, labels[].name)")
|
||
return None
|
||
return list(v) or None
|
||
|
||
|
||
def _tool_extractors(raw: Any, label: str, errors: list[str]) -> list[dict[str, Any]]:
|
||
if raw is None:
|
||
return []
|
||
if not isinstance(raw, list) or len(raw) > 10:
|
||
errors.append(f"{label} must be a list (10 max)")
|
||
return []
|
||
out: list[dict[str, Any]] = []
|
||
for i, ex in enumerate(raw):
|
||
lb = f"{label}[{i}]"
|
||
if not isinstance(ex, dict):
|
||
errors.append(f"{lb} must be an object")
|
||
continue
|
||
tool = ex.get("tool")
|
||
if not isinstance(tool, str) or not tool.strip() or len(tool) > 120:
|
||
errors.append(f"{lb}.tool: a tool name or glob (\"shell\", \"mcp__*__get_issue\", \"*\")")
|
||
continue
|
||
item: dict[str, Any] = {"tool": tool.strip()}
|
||
if ex.get("kind") is not None:
|
||
if not isinstance(ex["kind"], str) or not _ID_RE.match(ex["kind"]):
|
||
errors.append(f"{lb}.kind invalid")
|
||
continue
|
||
item["kind"] = ex["kind"]
|
||
if ex.get("commandRegex") is not None:
|
||
pat = _check_safe_regex(ex["commandRegex"], f"{lb}.commandRegex", errors)
|
||
if pat:
|
||
item["commandRegex"] = pat
|
||
inp = _tpl(ex.get("inputTemplate"), f"{lb}.inputTemplate", errors)
|
||
if inp:
|
||
item["inputTemplate"] = inp
|
||
for f in ("idFields", "urlFields", "titleFields", "stateFields", "xrefFields"):
|
||
p = _paths(ex.get(f), f"{lb}.{f}", errors)
|
||
if p:
|
||
item[f] = p
|
||
# A result that lists several (``list_projects`` → ``projects[]``):
|
||
# each item is read as one result.
|
||
ip = ex.get("itemsPath")
|
||
if ip is not None:
|
||
if not isinstance(ip, str) or not _FIELD_PATH_RE.match(ip) or not ip.endswith("[]"):
|
||
errors.append(f"{lb}.itemsPath: a list field path (projects[])")
|
||
else:
|
||
item["itemsPath"] = ip
|
||
mf = ex.get("metaFields")
|
||
if mf is not None:
|
||
if not isinstance(mf, dict) or len(mf) > 8 or not all(
|
||
isinstance(k, str) and _KEY_RE.match(k) and isinstance(v, str)
|
||
and _FIELD_PATH_RE.match(v) for k, v in mf.items()):
|
||
errors.append(f"{lb}.metaFields: up to 8 name → field path")
|
||
else:
|
||
item["metaFields"] = dict(mf)
|
||
sf = ex.get("stateFlags")
|
||
if sf is not None:
|
||
if not isinstance(sf, dict) or len(sf) > 4 or not all(
|
||
isinstance(k, str) and _FIELD_PATH_RE.match(k) and isinstance(v, str)
|
||
and 0 < len(v) <= 40 for k, v in sf.items()):
|
||
errors.append(f"{lb}.stateFlags: up to 4 field path → state")
|
||
else:
|
||
item["stateFlags"] = dict(sf)
|
||
cm = ex.get("channelMapRegex")
|
||
if cm is not None:
|
||
pats = [cm] if isinstance(cm, str) else cm
|
||
ok = []
|
||
if not isinstance(pats, list) or len(pats) > 4:
|
||
errors.append(f"{lb}.channelMapRegex: a regex or up to 4")
|
||
else:
|
||
for j, pat in enumerate(pats):
|
||
pat = _check_safe_regex(pat, f"{lb}.channelMapRegex[{j}]", errors)
|
||
if pat and not {"id", "name"} <= set(re.compile(pat).groupindex):
|
||
errors.append(f"{lb}.channelMapRegex[{j}]: needs (?P<id>…) and (?P<name>…)")
|
||
elif pat:
|
||
ok.append(pat)
|
||
if ok:
|
||
item["channelMapRegex"] = ok
|
||
th = ex.get("textHint")
|
||
if th is not None:
|
||
th = [th] if isinstance(th, str) else th
|
||
if not isinstance(th, list) or len(th) > 4 or not all(
|
||
isinstance(x, str) and 0 < len(x) <= 60 for x in th):
|
||
errors.append(f"{lb}.textHint: up to 4 substrings")
|
||
else:
|
||
item["textHint"] = list(th)
|
||
if ex.get("tagOnCall"):
|
||
item["tagOnCall"] = True
|
||
if not any(k in item for k in ("commandRegex", "inputTemplate", "idFields", "urlFields",
|
||
"channelMapRegex")):
|
||
errors.append(f"{lb}: extracts nothing (commandRegex / inputTemplate / idFields / "
|
||
"urlFields / channelMapRegex)")
|
||
continue
|
||
out.append(item)
|
||
return out
|
||
|
||
|
||
def _resources(raw: Any, errors: list[str]) -> list[dict[str, Any]]:
|
||
"""``resources[]``: the conversation resource kinds a plugin declares —
|
||
pure data the host's in-process registry (``plugins/resources.py``)
|
||
matches; no code of the plugin ever runs for it. The v3 shape
|
||
``{id, label, urlRegex, color}`` stays valid."""
|
||
if raw is None:
|
||
return []
|
||
if not isinstance(raw, list) or len(raw) > 8:
|
||
errors.append("resources must be a list (8 max)")
|
||
return []
|
||
out: list[dict[str, Any]] = []
|
||
seen: set[str] = set()
|
||
for i, r in enumerate(raw):
|
||
lb = f"resources[{i}]"
|
||
if not isinstance(r, dict):
|
||
errors.append(f"{lb} must be an object")
|
||
continue
|
||
rid = str(r.get("id") or "").strip()
|
||
if not _ID_RE.match(rid) or rid in seen:
|
||
errors.append(f"{lb}.id invalid or duplicate")
|
||
continue
|
||
if rid in _CORE_RESOURCE_KINDS:
|
||
errors.append(f"{lb}.id: '{rid}' is a core kind")
|
||
continue
|
||
n_err = len(errors)
|
||
item: dict[str, Any] = {"id": rid, "label": str(r.get("label") or rid)[:40]}
|
||
for f in ("urlRegex", "idRegex", "bareKeyRegex", "branchKeyPattern", "ignoreUrlRegex"):
|
||
if r.get(f) is not None:
|
||
pat = _check_safe_regex(r[f], f"{lb}.{f}", errors)
|
||
if pat:
|
||
item[f] = pat
|
||
if not item.get("urlRegex") and not item.get("idRegex"):
|
||
if len(errors) == n_err:
|
||
errors.append(f"{lb}: needs a urlRegex or an idRegex")
|
||
continue
|
||
# idTemplate: a template, or up to 4 tried in order (the first whose
|
||
# placeholders all resolve) — `["{repo|config.githubRepo}#{num}", "#{num}"]`.
|
||
idt = r.get("idTemplate")
|
||
if idt is not None:
|
||
idts = [idt] if isinstance(idt, str) else idt
|
||
if not isinstance(idts, list) or not 0 < len(idts) <= 4:
|
||
errors.append(f"{lb}.idTemplate: a template or up to 4")
|
||
else:
|
||
ok = [t for j, x in enumerate(idts) if (t := _tpl(x, f"{lb}.idTemplate[{j}]", errors))]
|
||
if ok:
|
||
item["idTemplate"] = ok
|
||
t = _tpl(r.get("urlTemplate"), f"{lb}.urlTemplate", errors)
|
||
if t:
|
||
item["urlTemplate"] = t
|
||
for f in ("labelTemplate", "titleToken"):
|
||
t = _tpl_rules(r.get(f), f"{lb}.{f}", errors)
|
||
if t:
|
||
item[f] = t
|
||
for f in ("slugTitleGroup", "bareKeyTeamGroup", "namesGroup", "dateGroup"):
|
||
v = r.get(f)
|
||
if v is None:
|
||
continue
|
||
if not isinstance(v, (str, int)) or not _GROUP_RE.match(str(v)):
|
||
errors.append(f"{lb}.{f}: a capture group name or index")
|
||
else:
|
||
item[f] = str(v)
|
||
if item.get("bareKeyRegex") and not item.get("bareKeyTeamGroup"):
|
||
errors.append(f"{lb}.bareKeyRegex needs bareKeyTeamGroup (bare keys are gated on "
|
||
"the teams seen in real links)")
|
||
nd = r.get("needles")
|
||
if nd is not None:
|
||
if not isinstance(nd, list) or len(nd) > 8 or not all(
|
||
isinstance(x, str) and 0 < len(x) <= 80 for x in nd):
|
||
errors.append(f"{lb}.needles: up to 8 templates")
|
||
else:
|
||
item["needles"] = list(nd)
|
||
item["toolExtractors"] = _tool_extractors(r.get("toolExtractors"),
|
||
f"{lb}.toolExtractors", errors)
|
||
if r.get("icon") is not None:
|
||
if not isinstance(r["icon"], str) or not re.match(r"^[A-Za-z0-9:_-]{1,64}$", r["icon"]):
|
||
errors.append(f"{lb}.icon: a lucide name")
|
||
else:
|
||
item["icon"] = r["icon"]
|
||
item["color"] = str(r.get("color") or "")[:32]
|
||
st = r.get("stateTones")
|
||
if st is not None:
|
||
if not isinstance(st, dict) or len(st) > 12 or not all(
|
||
isinstance(k, str) and 0 < len(k) <= 40 and isinstance(v, str) and 0 < len(v) <= 32
|
||
for k, v in st.items()):
|
||
errors.append(f"{lb}.stateTones: up to 12 state → tone")
|
||
else:
|
||
item["stateTones"] = {k.lower(): v for k, v in st.items()}
|
||
ca = r.get("clickAction", "open")
|
||
if ca not in _CLICK_ACTIONS:
|
||
errors.append(f"{lb}.clickAction must be one of {sorted(_CLICK_ACTIONS)}")
|
||
item["clickAction"] = ca if ca in _CLICK_ACTIONS else "open"
|
||
pr = r.get("priority", 100)
|
||
if not isinstance(pr, int) or isinstance(pr, bool) or not 0 <= pr <= 1000:
|
||
errors.append(f"{lb}.priority: an integer 0-1000 (lower = the primary first)")
|
||
pr = 100
|
||
item["priority"] = pr
|
||
hr = r.get("hueRole")
|
||
if hr is not None:
|
||
if hr not in _HUE_ROLES:
|
||
errors.append(f"{lb}.hueRole must be one of {sorted(_HUE_ROLES)}")
|
||
else:
|
||
item["hueRole"] = hr
|
||
# A hue kind's lookup field that names its group (an issue's
|
||
# ``project``) — matched by name to the ``hueRole: group`` kind.
|
||
gb = r.get("groupBy")
|
||
if gb is not None:
|
||
if not isinstance(gb, str) or not _KEY_RE.match(gb):
|
||
errors.append(f"{lb}.groupBy: a metaFields name (project)")
|
||
else:
|
||
item["groupBy"] = gb
|
||
item["statusAction"] = str(r.get("statusAction") or "")
|
||
if len(errors) == n_err:
|
||
seen.add(rid)
|
||
out.append(item)
|
||
for item in out:
|
||
for ex in item["toolExtractors"]:
|
||
if ex.get("kind") and ex["kind"] not in seen:
|
||
errors.append(f"resources.{item['id']}.toolExtractors: kind '{ex['kind']}' "
|
||
"is not one of this plugin's resources")
|
||
return out
|
||
|
||
|
||
def _check_cron(expr: Any, label: str, errors: list[str]) -> str | None:
|
||
if not isinstance(expr, str) or len(expr.strip().split()) != 5:
|
||
errors.append(f"{label}: cron must be a 5-field expression")
|
||
return None
|
||
try:
|
||
from core.cronexpr import parse_schedule
|
||
parse_schedule(expr.strip())
|
||
except Exception as e:
|
||
errors.append(f"{label}: invalid cron expression ({e})")
|
||
return None
|
||
return expr.strip()
|
||
|
||
|
||
_PARAM_RE = re.compile(r"^[A-Za-z0-9_.\[\]-]{1,64}$")
|
||
_UNIT_RE = re.compile(r"^[a-z][a-zA-Z0-9_]{0,31}$")
|
||
|
||
|
||
def _clean_rule(rule: dict[str, Any], method: str, pat: str, label: str,
|
||
errors: list[str]) -> dict[str, Any]:
|
||
"""One ``proxy.allow`` rule: method + path, plus the optional per-rule
|
||
policy (handlerOnly, query, forcedParams, noAuth, units, creates, owned)."""
|
||
out: dict[str, Any] = {"method": method, "path": pat}
|
||
if rule.get("handlerOnly") is not None:
|
||
out["handlerOnly"] = bool(rule["handlerOnly"])
|
||
q = rule.get("query")
|
||
if q is not None:
|
||
if not isinstance(q, dict) or not q:
|
||
errors.append(f"{label}.query must be a non-empty object of param → regex")
|
||
else:
|
||
qo = {}
|
||
for k, v in q.items():
|
||
if not _PARAM_RE.match(str(k)):
|
||
errors.append(f"{label}.query: bad param name {k!r}")
|
||
continue
|
||
rx = _check_regex(v, f"{label}.query.{k}", errors)
|
||
if rx:
|
||
qo[str(k)] = rx
|
||
out["query"] = qo
|
||
fp = rule.get("forcedParams")
|
||
if fp is not None:
|
||
if not isinstance(fp, dict):
|
||
errors.append(f"{label}.forcedParams must be an object")
|
||
else:
|
||
fo = {}
|
||
for k, v in fp.items():
|
||
if not _PARAM_RE.match(str(k)):
|
||
errors.append(f"{label}.forcedParams: bad param name {k!r}")
|
||
continue
|
||
fo[str(k)] = str(v)[:200]
|
||
out["forcedParams"] = fo
|
||
if rule.get("noAuth"):
|
||
out["noAuth"] = True
|
||
if rule.get("creates"):
|
||
out["creates"] = True
|
||
un = rule.get("units")
|
||
if un is not None:
|
||
if not isinstance(un, dict) or not all(_UNIT_RE.match(str(k)) for k in un):
|
||
errors.append(f"{label}.units must be an object of unit name → count")
|
||
else:
|
||
try:
|
||
out["units"] = {str(k): max(0, min(1000, int(v))) for k, v in un.items()}
|
||
except (TypeError, ValueError):
|
||
errors.append(f"{label}.units counts must be integers")
|
||
ow = rule.get("owned")
|
||
if ow is not None:
|
||
ok = isinstance(ow, dict) and all(isinstance(ow.get(k), str) and ow.get(k)
|
||
for k in ("group", "file", "key"))
|
||
if ok:
|
||
try:
|
||
ok = ow["group"] in re.compile(pat).groupindex
|
||
except re.error:
|
||
ok = False
|
||
if not ok or ".." in ow.get("file", "").split("/") or ow.get("file", "").startswith("/"):
|
||
errors.append(f"{label}.owned needs group (a named group of the path), file, key")
|
||
else:
|
||
out["owned"] = {"group": ow["group"], "file": ow["file"], "key": ow["key"]}
|
||
return out
|
||
|
||
|
||
def _ui_vis(raw: Any, where: str, errors: list[str]) -> dict[str, Any] | None:
|
||
"""A slot's / tool card's ``vis`` toggle: ``{key, label, hint, defaultOff?}``
|
||
(stored host-side as ``plugin:<pluginId>:<key>``)."""
|
||
if raw is None:
|
||
return None
|
||
if not isinstance(raw, dict):
|
||
errors.append(f"{where}.vis must be an object")
|
||
return None
|
||
key = str(raw.get("key") or "").strip()
|
||
if not _KEY_RE.match(key):
|
||
errors.append(f"{where}.vis.key invalid")
|
||
return None
|
||
if raw.get("defaultOff") is not None and not isinstance(raw.get("defaultOff"), bool):
|
||
errors.append(f"{where}.vis.defaultOff must be true or false")
|
||
out: dict[str, Any] = {
|
||
"key": key,
|
||
"label": str(raw.get("label") or key)[:48],
|
||
"hint": str(raw.get("hint") or "")[:160],
|
||
}
|
||
if raw.get("defaultOff") is True:
|
||
out["defaultOff"] = True
|
||
return out
|
||
|
||
|
||
_SLOT_QUERY_MAX = 2048
|
||
|
||
|
||
def _slot_query(raw: Any, actions: dict[str, Any], where: str,
|
||
errors: list[str]) -> dict[str, Any] | None:
|
||
"""``{"action", "payload"}`` of a slot's ``query``: a declared readOnly
|
||
action and a small JSON object (string values may hold the
|
||
``$conversationId`` / ``$sessionId`` placeholders the app fills in)."""
|
||
if not isinstance(raw, dict):
|
||
errors.append(f"{where} must be an object {{action, payload?}}")
|
||
return None
|
||
action = raw.get("action")
|
||
if not isinstance(action, str) or not action:
|
||
errors.append(f"{where}.action must be a string")
|
||
return None
|
||
if not (actions.get(action) or {}).get("readOnly"):
|
||
errors.append(f"{where}.action must name a declared readOnly action")
|
||
return None
|
||
payload = raw.get("payload", {})
|
||
if payload is None:
|
||
payload = {}
|
||
if not isinstance(payload, dict):
|
||
errors.append(f"{where}.payload must be a JSON object")
|
||
return None
|
||
try:
|
||
body = json.dumps(payload, separators=(",", ":"), allow_nan=False)
|
||
except (TypeError, ValueError):
|
||
errors.append(f"{where}.payload must be plain JSON")
|
||
return None
|
||
if len(body.encode("utf-8")) > _SLOT_QUERY_MAX:
|
||
errors.append(f"{where}.payload must be at most {_SLOT_QUERY_MAX} bytes of JSON")
|
||
return None
|
||
return {"action": action, "payload": json.loads(body)}
|
||
|
||
|
||
def _menu_items(root: pathlib.Path, raw: Any, errors: list[str]) -> list[dict[str, Any]]:
|
||
"""``ui.menuItems[]``: rows a plugin adds to a menu of the app —
|
||
``{id, where, label, icon?, html, height?, title?}``. A click opens the
|
||
item's ``html`` in a sandboxed dialog (docs/plugins.md → "Menu items and
|
||
dialogs")."""
|
||
if raw is None:
|
||
return []
|
||
if not isinstance(raw, list):
|
||
errors.append("ui.menuItems must be a list")
|
||
return []
|
||
if len(raw) > _MENU_ITEMS_MAX:
|
||
errors.append(f"ui.menuItems: at most {_MENU_ITEMS_MAX}")
|
||
return []
|
||
out: list[dict[str, Any]] = []
|
||
seen: set[str] = set()
|
||
for i, it in enumerate(raw):
|
||
where = f"ui.menuItems[{i}]"
|
||
if not isinstance(it, dict):
|
||
errors.append(f"{where} must be an object")
|
||
continue
|
||
mid = str(it.get("id") or "").strip()
|
||
if not _KEY_RE.match(mid) or mid in seen:
|
||
errors.append(f"{where}.id invalid or repeated")
|
||
continue
|
||
seen.add(mid)
|
||
place = str(it.get("where") or "")
|
||
if place not in _MENU_PLACES:
|
||
errors.append(f"{where}.where must be one of {sorted(_MENU_PLACES)}")
|
||
continue
|
||
label = str(it.get("label") or "").strip()
|
||
if not label or len(label) > 40:
|
||
errors.append(f"{where}.label must be 1..40 characters")
|
||
continue
|
||
if not it.get("html"):
|
||
errors.append(f"{where}.html required")
|
||
continue
|
||
_safe_rel(root, it.get("html"), f"{where}.html", errors)
|
||
item: dict[str, Any] = {"id": mid, "where": place, "label": label,
|
||
"html": str(it["html"])}
|
||
if it.get("icon") is not None:
|
||
ic = str(it.get("icon") or "").strip()
|
||
if not re.match(r"^[a-z0-9][a-z0-9-]{0,39}$", ic):
|
||
errors.append(f"{where}.icon must be a lucide icon name")
|
||
else:
|
||
item["icon"] = ic
|
||
if it.get("title") is not None:
|
||
ti = str(it.get("title") or "").strip()
|
||
if not ti or len(ti) > 60:
|
||
errors.append(f"{where}.title must be 1..60 characters")
|
||
else:
|
||
item["title"] = ti
|
||
if it.get("height") is not None:
|
||
try:
|
||
h = int(it["height"])
|
||
except (TypeError, ValueError):
|
||
h = 0
|
||
if not 80 <= h <= 900:
|
||
errors.append(f"{where}.height must be 80..900")
|
||
else:
|
||
item["height"] = h
|
||
out.append(item)
|
||
return out
|
||
|
||
|
||
def _ui_events(raw: Any, where: str, errors: list[str]) -> list[str] | None:
|
||
"""A frame's forwarded SSE event types, a subset of ``_UI_EVENTS``."""
|
||
if raw is None:
|
||
return None
|
||
if not isinstance(raw, list) or not all(isinstance(e, str) for e in raw):
|
||
errors.append(f"{where}.events must be a list of strings")
|
||
return None
|
||
bad = [e for e in raw if e not in _UI_EVENTS]
|
||
if bad:
|
||
errors.append(f"{where}.events: unknown {bad} (one of {sorted(_UI_EVENTS)})")
|
||
return None
|
||
out: list[str] = []
|
||
for e in raw:
|
||
if e not in out:
|
||
out.append(e)
|
||
return out or None
|
||
|
||
|
||
def _file_types(raw: Any, where: str, errors: list[str]) -> list[str] | None:
|
||
"""``fileTypes``: 1..32 lowercase extensions without the dot
|
||
(``^[a-z0-9]{1,10}$``), de-duplicated in order. None (with an error) when
|
||
refused."""
|
||
if (not isinstance(raw, list) or not raw or len(raw) > _FILE_TYPES_MAX
|
||
or not all(isinstance(t, str) and _FILE_TYPE_RE.match(t) for t in raw)):
|
||
errors.append(f"{where}.fileTypes must be a list of 1..{_FILE_TYPES_MAX} lowercase "
|
||
"extensions without the dot (pdf, glb, mp4…)")
|
||
return None
|
||
return list(dict.fromkeys(raw))
|
||
|
||
|
||
def _file_previews(root: pathlib.Path, raw: Any, errors: list[str]) -> list[dict[str, Any]]:
|
||
"""``ui.filePreviews[]``: an inline card under an agent's message that
|
||
names a host file of one of its ``fileTypes`` (docs/plugins.md → "File
|
||
viewers"). ``{id, label?, html, fileTypes, height?, vis?}``, at most 4."""
|
||
if raw is None:
|
||
return []
|
||
if not isinstance(raw, list):
|
||
errors.append("ui.filePreviews must be a list")
|
||
return []
|
||
out: list[dict[str, Any]] = []
|
||
ids: set[str] = set()
|
||
for i, fp in enumerate(raw[:_FILE_PREVIEWS_MAX]):
|
||
where = f"ui.filePreviews[{i}]"
|
||
if not isinstance(fp, dict):
|
||
errors.append(f"{where} must be an object")
|
||
continue
|
||
fid = str(fp.get("id") or "").strip()
|
||
if not _KEY_RE.match(fid):
|
||
errors.append(f"{where}.id invalid")
|
||
continue
|
||
if fid in ids:
|
||
errors.append(f"{where}.id '{fid}' declared twice")
|
||
continue
|
||
ids.add(fid)
|
||
types = _file_types(fp.get("fileTypes"), where, errors)
|
||
_safe_rel(root, fp.get("html"), f"{where}.html", errors)
|
||
height = fp.get("height", 240)
|
||
if not isinstance(height, int) or isinstance(height, bool) or not 40 <= height <= 1200:
|
||
errors.append(f"{where}.height must be an integer 40..1200")
|
||
height = 240
|
||
fp_out: dict[str, Any] = {
|
||
"id": fid,
|
||
"label": str(fp.get("label") or fid)[:60],
|
||
"html": str(fp.get("html") or ""),
|
||
"fileTypes": types or [],
|
||
"height": height,
|
||
}
|
||
fp_vis = _ui_vis(fp.get("vis"), where, errors)
|
||
if fp_vis:
|
||
fp_out["vis"] = fp_vis
|
||
out.append(fp_out)
|
||
if len(raw) > _FILE_PREVIEWS_MAX:
|
||
errors.append(f"ui.filePreviews: at most {_FILE_PREVIEWS_MAX}")
|
||
return out
|
||
|
||
|
||
def _fences(root: pathlib.Path, raw: Any, errors: list[str]) -> list[dict[str, Any]]:
|
||
"""``ui.fences[]``: a fenced block of an agent's message the plugin draws —
|
||
```` ```chart ```` → its sandboxed frame, ``init {fence, code, …}``
|
||
(docs/plugins.md → "Fenced blocks in messages"). ``{id, lang, html,
|
||
height?, label?, vis?}``; one language per fence, unique in the plugin."""
|
||
if raw is None:
|
||
return []
|
||
if not isinstance(raw, list):
|
||
errors.append("ui.fences must be a list")
|
||
return []
|
||
out: list[dict[str, Any]] = []
|
||
langs: set[str] = set()
|
||
for i, fe in enumerate(raw[:8]):
|
||
if not isinstance(fe, dict):
|
||
errors.append(f"ui.fences[{i}] must be an object")
|
||
continue
|
||
fid = str(fe.get("id") or "").strip()
|
||
if not _KEY_RE.match(fid):
|
||
errors.append(f"ui.fences[{i}].id invalid")
|
||
continue
|
||
lang = str(fe.get("lang") or "").strip()
|
||
if not _FENCE_LANG_RE.match(lang):
|
||
errors.append(f"ui.fences[{i}].lang must be 2-32 lowercase letters, digits, _ + -")
|
||
continue
|
||
if lang in _FENCE_RESERVED:
|
||
errors.append(f"ui.fences[{i}].lang '{lang}' is a code language (or the closing notify block)")
|
||
continue
|
||
if lang in langs:
|
||
errors.append(f"ui.fences[{i}].lang '{lang}' declared twice")
|
||
continue
|
||
langs.add(lang)
|
||
_safe_rel(root, fe.get("html"), f"ui.fences[{i}].html", errors)
|
||
height = fe.get("height", 240)
|
||
if not isinstance(height, int) or isinstance(height, bool) or not 40 <= height <= 1200:
|
||
errors.append(f"ui.fences[{i}].height must be an integer 40..1200")
|
||
height = 240
|
||
fe_out: dict[str, Any] = {
|
||
"id": fid,
|
||
"lang": lang,
|
||
"label": str(fe.get("label") or fid)[:60],
|
||
"html": str(fe.get("html") or ""),
|
||
"height": height,
|
||
}
|
||
fe_vis = _ui_vis(fe.get("vis"), f"ui.fences[{i}]", errors)
|
||
if fe_vis:
|
||
fe_out["vis"] = fe_vis
|
||
out.append(fe_out)
|
||
if isinstance(raw, list) and len(raw) > 8:
|
||
errors.append("ui.fences: at most 8")
|
||
return out
|
||
|
||
|
||
def validate_manifest(plugin_dir: pathlib.Path) -> dict[str, Any]:
|
||
"""Read and validate ``plugin_dir/plugin.json``. Returns the normalized
|
||
manifest dict or raises :class:`ManifestError`."""
|
||
root = pathlib.Path(plugin_dir)
|
||
mf = root / "plugin.json"
|
||
if not mf.is_file():
|
||
raise ManifestError(["plugin.json not found in plugin directory"])
|
||
try:
|
||
raw = json.loads(mf.read_text(encoding="utf-8"))
|
||
except (OSError, ValueError) as e:
|
||
raise ManifestError([f"plugin.json is not valid JSON: {e}"]) from None
|
||
if not isinstance(raw, dict):
|
||
raise ManifestError(["plugin.json must be a JSON object"])
|
||
|
||
errors: list[str] = []
|
||
unknown = sorted(set(raw) - _TOP_KEYS)
|
||
if unknown:
|
||
errors.append(f"unknown manifest keys: {', '.join(unknown)}")
|
||
|
||
if raw.get("schema") != SCHEMA_VERSION:
|
||
errors.append(f"schema must be {SCHEMA_VERSION}")
|
||
|
||
pid = str(raw.get("id") or "").strip()
|
||
if not _ID_RE.match(pid):
|
||
errors.append("id must be lowercase alphanumeric/dashes (1-48 chars)")
|
||
|
||
name = str(raw.get("name") or "").strip()
|
||
if not name or len(name) > 80:
|
||
errors.append("name is required (<= 80 chars)")
|
||
|
||
version = str(raw.get("version") or "1.0.0").strip()[:32]
|
||
description = str(raw.get("description") or "").strip()[:300]
|
||
art = _parse_art(root, raw, errors)
|
||
icon = art["icon"]
|
||
author = str(raw.get("author") or "").strip()[:64]
|
||
|
||
out: dict[str, Any] = {
|
||
"schema": SCHEMA_VERSION,
|
||
"id": pid,
|
||
"name": name,
|
||
"version": version,
|
||
"description": description,
|
||
"icon": icon,
|
||
"author": author,
|
||
"iconSvg": art["iconSvg"],
|
||
"illustration": art["illustration"],
|
||
"color": art["color"],
|
||
"readme": art["readme"],
|
||
"artVersion": art["artVersion"],
|
||
}
|
||
# ``category``: checked against ``kind`` (plugins/categories.py)
|
||
from plugins.categories import parse_category
|
||
out["category"] = parse_category(raw, errors)
|
||
|
||
# ── skill ────────────────────────────────────────────────────────────────
|
||
if raw.get("skill") is not None:
|
||
sk = raw["skill"]
|
||
if not isinstance(sk, dict):
|
||
errors.append("skill must be an object")
|
||
else:
|
||
sdir = str(sk.get("dir") or "skill")
|
||
sname = str(sk.get("name") or pid).strip()
|
||
if not _SKILL_RE.match(sname):
|
||
errors.append("skill.name must be lowercase alphanumeric/._- (1-48 chars)")
|
||
target = _safe_rel(root, sdir, "skill.dir", errors, want_dir=True)
|
||
if target and not (target / "SKILL.md").is_file():
|
||
errors.append(f"skill.dir '{sdir}' must contain SKILL.md")
|
||
out["skill"] = {"dir": sdir, "name": sname}
|
||
|
||
# ── secrets ──────────────────────────────────────────────────────────────
|
||
secret_keys: set[str] = set()
|
||
secrets_out: list[dict[str, Any]] = []
|
||
if raw.get("secrets") is not None:
|
||
if not isinstance(raw["secrets"], list):
|
||
errors.append("secrets must be an array")
|
||
else:
|
||
for i, s in enumerate(raw["secrets"]):
|
||
if not isinstance(s, dict):
|
||
errors.append(f"secrets[{i}] must be an object")
|
||
continue
|
||
key = str(s.get("key") or "").strip()
|
||
if not _KEY_RE.match(key):
|
||
errors.append(f"secrets[{i}].key invalid: {key!r}")
|
||
continue
|
||
if key in secret_keys:
|
||
errors.append(f"duplicate secret key: {key}")
|
||
continue
|
||
scope = str(s.get("scope") or "user")
|
||
if scope not in _SECRET_SCOPES:
|
||
errors.append(f"secrets[{i}].scope must be 'user' or 'hub'")
|
||
continue
|
||
secret_keys.add(key)
|
||
secrets_out.append({
|
||
"key": key,
|
||
"label": str(s.get("label") or key)[:80],
|
||
"placeholder": str(s.get("placeholder") or "")[:80],
|
||
"help": str(s.get("help") or "")[:300],
|
||
"scope": scope,
|
||
"required": bool(s.get("required", True)),
|
||
})
|
||
out["secrets"] = secrets_out
|
||
|
||
# ── actions (v3) ─────────────────────────────────────────────────────────
|
||
actions_out: dict[str, dict[str, Any]] = {}
|
||
if raw.get("actions") is not None:
|
||
if not isinstance(raw["actions"], dict):
|
||
errors.append("actions must be an object")
|
||
else:
|
||
for ak, av in raw["actions"].items():
|
||
if not _KEY_RE.match(str(ak)):
|
||
errors.append(f"actions.{ak}: invalid action name")
|
||
continue
|
||
if not isinstance(av, dict):
|
||
errors.append(f"actions.{ak}: must be an object")
|
||
continue
|
||
script = av.get("script")
|
||
_safe_rel(root, script, f"actions.{ak}.script", errors)
|
||
timeout = int(av.get("timeoutSec") or 30)
|
||
if not 1 <= timeout <= 1200:
|
||
errors.append(f"actions.{ak}.timeoutSec must be 1..1200")
|
||
act_item: dict[str, Any] = {
|
||
"script": str(script or ""),
|
||
"timeoutSec": timeout,
|
||
"description": str(av.get("description") or "")[:200],
|
||
}
|
||
if av.get("ownerOnly") is True:
|
||
act_item["ownerOnly"] = True
|
||
# Reads only: also callable by GET, so a read-only account
|
||
# (the screenshot bot) sees the data a plugin page lists.
|
||
if av.get("readOnly") is True:
|
||
act_item["readOnly"] = True
|
||
run_as = av.get("runAs")
|
||
if run_as is not None:
|
||
if str(run_as) not in ("caller", "owner"):
|
||
errors.append(f"actions.{ak}.runAs must be 'caller' or 'owner'")
|
||
elif str(run_as) == "owner":
|
||
act_item["runAs"] = "owner"
|
||
actions_out[str(ak)] = act_item
|
||
out["actions"] = actions_out
|
||
|
||
# ── settings (declarative) ───────────────────────────────────────────────
|
||
if raw.get("settings") is not None:
|
||
st = raw["settings"]
|
||
if not isinstance(st, dict):
|
||
errors.append("settings must be an object")
|
||
else:
|
||
fields_out: list[dict[str, Any]] = []
|
||
seen_fk: set[str] = set()
|
||
for i, f in enumerate(st.get("fields") or []):
|
||
if not isinstance(f, dict):
|
||
errors.append(f"settings.fields[{i}] must be an object")
|
||
continue
|
||
fk = str(f.get("key") or "").strip()
|
||
ft = str(f.get("type") or "text")
|
||
if not _KEY_RE.match(fk) or fk in seen_fk:
|
||
errors.append(f"settings.fields[{i}].key invalid or duplicate")
|
||
continue
|
||
if ft not in _FIELD_TYPES:
|
||
errors.append(f"settings.fields[{i}].type must be one of {sorted(_FIELD_TYPES)}")
|
||
continue
|
||
seen_fk.add(fk)
|
||
item = {
|
||
"key": fk,
|
||
"label": str(f.get("label") or fk)[:80],
|
||
"type": ft,
|
||
"help": str(f.get("help") or "")[:300],
|
||
"default": f.get("default"),
|
||
"required": bool(f.get("required", False)),
|
||
}
|
||
if ft == "select":
|
||
opts = f.get("options") or []
|
||
if not isinstance(opts, list) or not opts:
|
||
errors.append(f"settings.fields[{i}].options required for select")
|
||
item["options"] = opts
|
||
fields_out.append(item)
|
||
test_act = st.get("testAction")
|
||
status_act = st.get("statusAction")
|
||
if test_act and test_act not in actions_out and test_act != "inspect":
|
||
errors.append(f"settings.testAction '{test_act}' is not in actions (or 'inspect')")
|
||
if status_act and status_act not in actions_out:
|
||
errors.append(f"settings.statusAction '{status_act}' is not in actions")
|
||
links_out: list[dict[str, str]] = []
|
||
links_raw = st.get("links")
|
||
if links_raw is not None and not isinstance(links_raw, list):
|
||
errors.append("settings.links must be a list")
|
||
links_raw = []
|
||
for i, ln in enumerate(links_raw or []):
|
||
if not isinstance(ln, dict):
|
||
errors.append(f"settings.links[{i}] must be an object")
|
||
continue
|
||
label = str(ln.get("label") or "").strip()[:60]
|
||
url = str(ln.get("url") or "").strip()
|
||
if not label:
|
||
errors.append(f"settings.links[{i}].label is required")
|
||
continue
|
||
if not _LINK_URL_RE.match(url) or len(url) > 500:
|
||
errors.append(f"settings.links[{i}].url must be an https:// URL "
|
||
"(with optional {{config.<key>}} placeholders)")
|
||
continue
|
||
bad = [k for k in _LINK_VAR_RE.findall(url) if k not in seen_fk]
|
||
if bad:
|
||
errors.append(f"settings.links[{i}].url names unknown settings field(s): "
|
||
f"{', '.join(bad)}")
|
||
continue
|
||
links_out.append({"label": label, "url": url})
|
||
if len(links_out) > 12:
|
||
errors.append("settings.links: at most 12 links")
|
||
out["settings"] = {
|
||
"subtitle": str(st.get("subtitle") or "")[:140],
|
||
"instructions": str(st.get("instructions") or "")[:12000],
|
||
"fields": fields_out,
|
||
"links": links_out[:12],
|
||
"testAction": str(test_act) if test_act else None,
|
||
"statusAction": str(status_act) if status_act else None,
|
||
}
|
||
|
||
# ── proxy (v1) ───────────────────────────────────────────────────────────
|
||
if raw.get("proxy") is not None:
|
||
pr = raw["proxy"]
|
||
if not isinstance(pr, dict):
|
||
errors.append("proxy must be an object")
|
||
else:
|
||
base = str(pr.get("baseUrl") or "").strip().rstrip("/")
|
||
internal = bool(pr.get("internal", False))
|
||
parts = urlsplit(base)
|
||
if not parts.scheme or not parts.hostname:
|
||
errors.append("proxy.baseUrl must be a valid URL")
|
||
elif not internal and parts.scheme != "https":
|
||
errors.append("proxy.baseUrl must use https:// (set internal: true for local services)")
|
||
elif internal and parts.scheme not in ("http", "https"):
|
||
errors.append("proxy.baseUrl must use http:// or https://")
|
||
|
||
auth_out = None
|
||
if pr.get("auth") is not None:
|
||
a = pr["auth"]
|
||
if not isinstance(a, dict):
|
||
errors.append("proxy.auth must be an object")
|
||
else:
|
||
ain = str(a.get("in") or "header")
|
||
asec = str(a.get("secret") or "")
|
||
if ain not in _AUTH_INS:
|
||
errors.append(f"proxy.auth.in must be one of {sorted(_AUTH_INS)}")
|
||
if asec and asec not in secret_keys:
|
||
errors.append(f"proxy.auth.secret '{asec}' not declared in secrets")
|
||
auth_out = {
|
||
"in": ain,
|
||
"name": str(a.get("name") or "Authorization")[:64],
|
||
"prefix": str(a.get("prefix") or ""),
|
||
"secret": asec,
|
||
"username": str(a.get("username") or ""),
|
||
}
|
||
|
||
allow_out: list[dict[str, str]] = []
|
||
allow = pr.get("allow") or []
|
||
if not isinstance(allow, list) or not allow:
|
||
errors.append("proxy.allow must be a non-empty array of {method, path}")
|
||
else:
|
||
for i, rule in enumerate(allow):
|
||
if not isinstance(rule, dict):
|
||
errors.append(f"proxy.allow[{i}] must be an object")
|
||
continue
|
||
method = str(rule.get("method") or "GET").upper()
|
||
if method not in _METHODS:
|
||
errors.append(f"proxy.allow[{i}].method invalid: {method}")
|
||
continue
|
||
pat = _check_regex(rule.get("path"), f"proxy.allow[{i}].path", errors)
|
||
if pat:
|
||
allow_out.append(_clean_rule(rule, method, pat, f"proxy.allow[{i}]", errors))
|
||
|
||
headers_out = {}
|
||
if pr.get("headers") is not None:
|
||
if not isinstance(pr["headers"], dict):
|
||
errors.append("proxy.headers must be an object")
|
||
else:
|
||
headers_out = {str(k): str(v) for k, v in pr["headers"].items()}
|
||
|
||
inspect_out = None
|
||
if pr.get("inspect") is not None:
|
||
ins = pr["inspect"]
|
||
if not isinstance(ins, dict) or not ins.get("path"):
|
||
errors.append("proxy.inspect must be an object with 'path'")
|
||
else:
|
||
im = str(ins.get("method") or "GET").upper()
|
||
if im not in _METHODS:
|
||
errors.append(f"proxy.inspect.method invalid: {im}")
|
||
inspect_out = {
|
||
"method": im,
|
||
"path": str(ins["path"]).lstrip("/"),
|
||
"params": dict(ins.get("params") or {}),
|
||
"requireOnlyScopes": [str(s) for s in (ins.get("requireOnlyScopes") or [])],
|
||
}
|
||
|
||
stream = bool(pr.get("stream", False))
|
||
max_cap = 2 * 1024 * 1024 * 1024 if (stream and internal) else 250 * 1024 * 1024
|
||
max_bytes = int(pr.get("maxBytes") or 20 * 1024 * 1024)
|
||
if not 1024 <= max_bytes <= max_cap:
|
||
errors.append(f"proxy.maxBytes must be between 1 KB and {max_cap // (1024 * 1024)} MB")
|
||
|
||
strip_keys: list[str] = []
|
||
if pr.get("stripResponseKeys") is not None:
|
||
if not isinstance(pr["stripResponseKeys"], list):
|
||
errors.append("proxy.stripResponseKeys must be an array of field names")
|
||
else:
|
||
strip_keys = [str(k).strip() for k in pr["stripResponseKeys"] if str(k).strip()][:50]
|
||
|
||
# A Dynamic service the homelab's services-manager stops when idle:
|
||
# the proxy wakes it before calling (plugins/proxy.ensure_awake).
|
||
# Internal only — a public API has nothing to wake.
|
||
wake_out = None
|
||
if pr.get("wake") is not None:
|
||
wk = pr["wake"]
|
||
if not internal:
|
||
errors.append("proxy.wake needs internal: true")
|
||
elif not isinstance(wk, dict):
|
||
errors.append("proxy.wake must be an object {service, holdMinutes}")
|
||
else:
|
||
svc = str(wk.get("service") or "")
|
||
if not _WAKE_SERVICE_RE.fullmatch(svc):
|
||
errors.append("proxy.wake.service must match ^[a-z0-9][a-z0-9_.-]{0,62}$")
|
||
hold = wk.get("holdMinutes", 15)
|
||
if isinstance(hold, bool) or not isinstance(hold, int) or not 1 <= hold <= 240:
|
||
errors.append("proxy.wake.holdMinutes must be an integer 1..240")
|
||
hold = 15
|
||
wake_out = {"service": svc, "holdMinutes": hold}
|
||
|
||
out["proxy"] = {
|
||
"baseUrl": base,
|
||
"internal": internal,
|
||
"stream": stream,
|
||
"auth": auth_out,
|
||
"headers": headers_out,
|
||
"allow": allow_out,
|
||
"denyParams": [str(p).lower() for p in (pr.get("denyParams") or [])],
|
||
"stripResponseKeys": strip_keys,
|
||
"scrubSecrets": bool(pr.get("scrubSecrets", True)),
|
||
"maxBytes": max_bytes,
|
||
"inspect": inspect_out,
|
||
"handlerOnly": bool(pr.get("handlerOnly", False)),
|
||
"wake": wake_out,
|
||
}
|
||
|
||
# ── storage (v1) ─────────────────────────────────────────────────────────
|
||
st_cfg = raw.get("storage") or {}
|
||
if not isinstance(st_cfg, dict):
|
||
errors.append("storage must be an object")
|
||
st_cfg = {}
|
||
max_mb = int(st_cfg.get("maxMb") or 50)
|
||
if not 1 <= max_mb <= 500:
|
||
errors.append("storage.maxMb must be 1..500")
|
||
out["storage"] = {"maxMb": max_mb}
|
||
|
||
# ── schedules (v1) ───────────────────────────────────────────────────────
|
||
sched_out: list[dict[str, Any]] = []
|
||
seen_sc: set[str] = set()
|
||
for i, sc in enumerate(raw.get("schedules") or []):
|
||
if not isinstance(sc, dict):
|
||
errors.append(f"schedules[{i}] must be an object")
|
||
continue
|
||
sid = str(sc.get("id") or f"job-{i}").strip()
|
||
if not _KEY_RE.match(sid) or sid in seen_sc:
|
||
errors.append(f"schedules[{i}].id invalid or duplicate")
|
||
continue
|
||
seen_sc.add(sid)
|
||
cron_expr = _check_cron(sc.get("cron"), f"schedules[{i}].cron", errors)
|
||
script = sc.get("script")
|
||
_safe_rel(root, script, f"schedules[{i}].script", errors)
|
||
timeout = int(sc.get("timeoutSec") or 180)
|
||
if not 5 <= timeout <= 900:
|
||
errors.append(f"schedules[{i}].timeoutSec must be 5..900")
|
||
sched_out.append({
|
||
"id": sid,
|
||
"cron": cron_expr or "",
|
||
"script": str(script or ""),
|
||
"timeoutSec": timeout,
|
||
"description": str(sc.get("description") or "")[:200],
|
||
})
|
||
out["schedules"] = sched_out
|
||
|
||
# ── ui (v2 + v3 slots) ───────────────────────────────────────────────────
|
||
ui_raw = raw.get("ui")
|
||
if ui_raw is not None:
|
||
if not isinstance(ui_raw, dict):
|
||
errors.append("ui must be an object")
|
||
else:
|
||
ui_out: dict[str, Any] = {"pages": [], "toolCards": [], "slots": []}
|
||
overlays = _overlays(root, ui_raw.get("overlays"), errors)
|
||
if overlays:
|
||
ui_out["overlays"] = overlays
|
||
prefs = _prefs(ui_raw.get("prefs"), errors)
|
||
if prefs:
|
||
ui_out["prefs"] = prefs
|
||
if ui_raw.get("settingsHtml"):
|
||
_safe_rel(root, ui_raw["settingsHtml"], "ui.settingsHtml", errors)
|
||
ui_out["settingsHtml"] = str(ui_raw["settingsHtml"])
|
||
for i, pg in enumerate(ui_raw.get("pages") or []):
|
||
if not isinstance(pg, dict):
|
||
errors.append(f"ui.pages[{i}] must be an object")
|
||
continue
|
||
pgid = str(pg.get("id") or "").strip()
|
||
if not _ID_RE.match(pgid):
|
||
errors.append(f"ui.pages[{i}].id invalid")
|
||
continue
|
||
nav = str(pg.get("nav") or "dashboards")
|
||
if nav not in _NAV_GROUPS:
|
||
errors.append(f"ui.pages[{i}].nav must be one of {sorted(_NAV_GROUPS)}")
|
||
_safe_rel(root, pg.get("html"), f"ui.pages[{i}].html", errors)
|
||
page_out = {
|
||
"id": pgid,
|
||
"label": str(pg.get("label") or pgid)[:60],
|
||
"nav": nav,
|
||
"icon": str(pg.get("icon") or icon)[:40],
|
||
"html": str(pg.get("html") or ""),
|
||
}
|
||
# A full-page canvas: the frame fills the page below its header
|
||
# instead of growing with its content. Only written when set —
|
||
# ``ui`` is in the approval fingerprint.
|
||
if pg.get("fill") is True:
|
||
page_out["fill"] = True
|
||
if pg.get("subpath") is True:
|
||
page_out["subpath"] = True
|
||
if nav == "settings":
|
||
group = str(pg.get("group") or "you")
|
||
if group not in _SETTINGS_GROUPS:
|
||
errors.append(f"ui.pages[{i}].group must be one of {sorted(_SETTINGS_GROUPS)}")
|
||
page_out["group"] = group
|
||
if pg.get("after") is not None:
|
||
after = str(pg.get("after") or "")
|
||
if not _ID_RE.match(after):
|
||
errors.append(f"ui.pages[{i}].after must be a Settings entry id")
|
||
page_out["after"] = after
|
||
# a page with no use on a phone (Settings → Keyboard):
|
||
# left out of its Settings drawer; only written when set
|
||
if pg.get("desktopOnly") is not None:
|
||
if not isinstance(pg["desktopOnly"], bool):
|
||
errors.append(f"ui.pages[{i}].desktopOnly must be true or false")
|
||
elif pg["desktopOnly"]:
|
||
page_out["desktopOnly"] = True
|
||
elif pg.get("group") is not None or pg.get("after") is not None or pg.get("desktopOnly") is not None:
|
||
errors.append(f"ui.pages[{i}].group / after / desktopOnly are for nav \"settings\" pages")
|
||
# What the page adds to the app beyond its nav entry — the core
|
||
# names no plugin page, a page claims its own links. 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 (the What's new editor: users.manage)
|
||
# header a button in the head of the home page ("home")
|
||
# tag the tag kind whose pills open it at <page>/<slug>
|
||
# (skills-agents: skill, agent)
|
||
# feature the App usage id its visits count under — an id a
|
||
# page had before it was a plugin's keeps its history
|
||
if pg.get("perm") is not None:
|
||
perm = str(pg.get("perm") or "")
|
||
from authz import catalog as authz_catalog
|
||
if perm not in authz_catalog.BY_ID:
|
||
errors.append(f"ui.pages[{i}].perm must be a known permission")
|
||
page_out["perm"] = perm
|
||
# unless hidden from whoever holds this permission: a page
|
||
# that is a person's own while the operator has
|
||
# another (the cron-jobs plugin: a guest's jobs vs
|
||
# the owner's Cron jobs, automation.manage)
|
||
if pg.get("unless") is not None:
|
||
unless = str(pg.get("unless") or "")
|
||
from authz import catalog as authz_catalog
|
||
if unless not in authz_catalog.BY_ID:
|
||
errors.append(f"ui.pages[{i}].unless must be a known permission")
|
||
page_out["unless"] = unless
|
||
if pg.get("header") is not None:
|
||
if pg["header"] not in _PAGE_HEADERS:
|
||
errors.append(f"ui.pages[{i}].header must be one of {sorted(_PAGE_HEADERS)}")
|
||
page_out["header"] = str(pg["header"])
|
||
if pg.get("tag") is not None:
|
||
tag = str(pg.get("tag") or "")
|
||
if tag in _CORE_TAG_KINDS or not _ID_RE.match(tag):
|
||
errors.append(f"ui.pages[{i}].tag must be a tag kind the core does not route ({', '.join(sorted(_CORE_TAG_KINDS))} are its own)")
|
||
elif not pg.get("subpath"):
|
||
errors.append(f"ui.pages[{i}].tag needs \"subpath\": true (a pill opens <page>/<slug>)")
|
||
page_out["tag"] = tag
|
||
if pg.get("feature") is not None:
|
||
feature = str(pg.get("feature") or "")
|
||
if not _FEATURE_RE.match(feature):
|
||
errors.append(f"ui.pages[{i}].feature must look like an App usage id (page.forms)")
|
||
page_out["feature"] = feature
|
||
if pg.get("opens") is not None:
|
||
opens = pg["opens"]
|
||
if (not isinstance(opens, list) or not opens or len(opens) > _PAGE_OPENS_MAX
|
||
or not all(isinstance(k, str) and _PAGE_OPEN_RE.match(k) for k in opens)):
|
||
errors.append(f"ui.pages[{i}].opens must be a list of 1..{_PAGE_OPENS_MAX} "
|
||
"link kinds (commit, conversation-diff…)")
|
||
else:
|
||
page_out["opens"] = list(dict.fromkeys(opens))
|
||
if pg.get("fileTypes") is not None:
|
||
# a viewer by file type: only on a page that opens host files
|
||
if "host-file" not in (page_out.get("opens") or []):
|
||
errors.append(f"ui.pages[{i}].fileTypes needs \"opens\": [\"host-file\"]")
|
||
types = _file_types(pg["fileTypes"], f"ui.pages[{i}]", errors)
|
||
if types:
|
||
page_out["fileTypes"] = types
|
||
ui_out["pages"].append(page_out)
|
||
for i, tc in enumerate(ui_raw.get("toolCards") or []):
|
||
if not isinstance(tc, dict):
|
||
errors.append(f"ui.toolCards[{i}] must be an object")
|
||
continue
|
||
tcid = str(tc.get("id") or "").strip()
|
||
if not _KEY_RE.match(tcid):
|
||
errors.append(f"ui.toolCards[{i}].id invalid")
|
||
continue
|
||
match = tc.get("match") or {}
|
||
if not isinstance(match, dict) or not match.get("tool"):
|
||
errors.append(f"ui.toolCards[{i}].match.tool required")
|
||
if match.get("commandRegex"):
|
||
_check_regex(match["commandRegex"], f"ui.toolCards[{i}].match.commandRegex", errors)
|
||
if match.get("filePathRegex"):
|
||
_check_regex(match["filePathRegex"], f"ui.toolCards[{i}].match.filePathRegex", errors)
|
||
_safe_rel(root, tc.get("html"), f"ui.toolCards[{i}].html", errors)
|
||
match_out: dict[str, Any] = {
|
||
"tool": str(match.get("tool") or ""),
|
||
"commandRegex": str(match.get("commandRegex") or ""),
|
||
}
|
||
if match.get("filePathRegex"):
|
||
match_out["filePathRegex"] = str(match["filePathRegex"])
|
||
if match.get("hasField") is not None:
|
||
hf = str(match.get("hasField") or "")
|
||
if hf not in _HAS_FIELDS:
|
||
errors.append(f"ui.toolCards[{i}].match.hasField must be one of {sorted(_HAS_FIELDS)}")
|
||
else:
|
||
match_out["hasField"] = hf
|
||
if match.get("hasInput") is not None:
|
||
hi = str(match.get("hasInput") or "").strip()
|
||
if not _KEY_RE.match(hi):
|
||
errors.append(f"ui.toolCards[{i}].match.hasInput must be a valid input key")
|
||
else:
|
||
match_out["hasInput"] = hi
|
||
if match.get("hasReport") is not None:
|
||
if match.get("hasReport") is not True:
|
||
errors.append(f"ui.toolCards[{i}].match.hasReport must be true (or left out)")
|
||
elif str(match.get("tool") or "") not in _HAS_REPORT_TOOLS:
|
||
errors.append(f"ui.toolCards[{i}].match.hasReport needs tool "
|
||
f"{' or '.join(sorted(_HAS_REPORT_TOOLS))}")
|
||
else:
|
||
match_out["hasReport"] = True
|
||
tc_out: dict[str, Any] = {
|
||
"id": tcid,
|
||
"label": str(tc.get("label") or tcid)[:60],
|
||
"match": match_out,
|
||
"html": str(tc.get("html") or ""),
|
||
"height": int(tc.get("height") or 180),
|
||
}
|
||
if tc.get("replace") is True:
|
||
tc_out["replace"] = True
|
||
if tc.get("bare") is True:
|
||
tc_out["bare"] = True
|
||
if tc.get("verb"):
|
||
tc_out["verb"] = str(tc["verb"])[:40]
|
||
# Stands in the chat where its call happened instead of inside
|
||
# the call's row (which folds away with the tools); `keyRegex`
|
||
# (its first non-empty group, over the command + the output)
|
||
# keeps one card per key — a later call on it is a plain row.
|
||
if tc.get("inThread") is not None and not isinstance(tc.get("inThread"), bool):
|
||
errors.append(f"ui.toolCards[{i}].inThread must be true or false")
|
||
elif tc.get("inThread"):
|
||
tc_out["inThread"] = True
|
||
if tc.get("inThreadWhile") is not None:
|
||
iw = str(tc.get("inThreadWhile") or "")
|
||
if iw not in _IN_THREAD_WHILE:
|
||
errors.append(f"ui.toolCards[{i}].inThreadWhile must be one of {sorted(_IN_THREAD_WHILE)}")
|
||
elif not tc.get("inThread"):
|
||
errors.append(f"ui.toolCards[{i}].inThreadWhile only applies with inThread: true")
|
||
else:
|
||
tc_out["inThreadWhile"] = iw
|
||
if tc.get("keyRegex"):
|
||
kr = _check_regex(tc["keyRegex"], f"ui.toolCards[{i}].keyRegex", errors)
|
||
if kr:
|
||
try:
|
||
groups = re.compile(kr).groups
|
||
except re.error:
|
||
groups = 0
|
||
if not groups:
|
||
errors.append(f"ui.toolCards[{i}].keyRegex needs a capture group (the key)")
|
||
elif not tc.get("inThread"):
|
||
errors.append(f"ui.toolCards[{i}].keyRegex only applies with inThread: true")
|
||
else:
|
||
tc_out["keyRegex"] = kr
|
||
# ``stackable``: consecutive thread items this card claims are
|
||
# drawn as one frame (the CommitStack); ``pullOut``: in the
|
||
# Summary view the card still stands after its fold. Both
|
||
# need ``inThread``.
|
||
for flag in ("stackable", "pullOut"):
|
||
v = tc.get(flag)
|
||
if v is None:
|
||
continue
|
||
if not isinstance(v, bool):
|
||
errors.append(f"ui.toolCards[{i}].{flag} must be true or false")
|
||
elif v and not tc.get("inThread"):
|
||
errors.append(f"ui.toolCards[{i}].{flag} only applies with inThread: true")
|
||
elif v:
|
||
tc_out[flag] = True
|
||
# Optional keys are only written when set: ``ui`` is in the
|
||
# approval fingerprint.
|
||
tc_vis = _ui_vis(tc.get("vis"), f"ui.toolCards[{i}]", errors)
|
||
if tc_vis:
|
||
tc_out["vis"] = tc_vis
|
||
tc_ev = _ui_events(tc.get("events"), f"ui.toolCards[{i}]", errors)
|
||
if tc_ev:
|
||
tc_out["events"] = tc_ev
|
||
ui_out["toolCards"].append(tc_out)
|
||
for i, sl in enumerate(ui_raw.get("slots") or []):
|
||
if not isinstance(sl, dict):
|
||
errors.append(f"ui.slots[{i}] must be an object")
|
||
continue
|
||
slid = str(sl.get("id") or "").strip()
|
||
where = str(sl.get("where") or "")
|
||
if not _KEY_RE.match(slid) or where not in _SLOT_PLACES:
|
||
errors.append(f"ui.slots[{i}]: invalid id or where ({sorted(_SLOT_PLACES)})")
|
||
continue
|
||
_safe_rel(root, sl.get("html"), f"ui.slots[{i}].html", errors)
|
||
sl_out: dict[str, Any] = {
|
||
"id": slid,
|
||
"where": where,
|
||
"html": str(sl.get("html") or ""),
|
||
"height": int(sl.get("height") or 120),
|
||
}
|
||
# Optional keys only when set (approval fingerprint).
|
||
lab_max = _TAB_LABEL_MAX if where == "conversation.tab" else 48
|
||
if sl.get("label") is not None:
|
||
lab = str(sl.get("label") or "").strip()
|
||
if not lab or len(lab) > lab_max:
|
||
errors.append(f"ui.slots[{i}].label must be 1..{lab_max} characters")
|
||
else:
|
||
sl_out["label"] = lab
|
||
if where == "conversation.tab":
|
||
if sl.get("label") is None:
|
||
errors.append(f"ui.slots[{i}].label is required on a conversation.tab slot")
|
||
if sum(1 for s in ui_out["slots"] if s["where"] == where) >= _TAB_SLOTS_MAX:
|
||
errors.append(f"ui.slots[{i}]: at most {_TAB_SLOTS_MAX} conversation.tab slots")
|
||
continue
|
||
if sl.get("legacyView") is not None:
|
||
lv = str(sl.get("legacyView") or "")
|
||
if where != "conversation.tab" or lv not in _TAB_LEGACY_VIEWS:
|
||
errors.append(f"ui.slots[{i}].legacyView: one of {sorted(_TAB_LEGACY_VIEWS)}, "
|
||
"on conversation.tab only")
|
||
else:
|
||
sl_out["legacyView"] = lv
|
||
if sl.get("defaultStashed") is not None:
|
||
if not isinstance(sl.get("defaultStashed"), bool):
|
||
errors.append(f"ui.slots[{i}].defaultStashed must be true or false")
|
||
elif sl["defaultStashed"]:
|
||
sl_out["defaultStashed"] = True
|
||
# ``preload``: an ``app.modal`` document the app loads hidden
|
||
# once it's idle and keeps, so it opens at once (the command
|
||
# palette); each opening reaches it as an ``update``.
|
||
if sl.get("preload") is not None:
|
||
if not isinstance(sl.get("preload"), bool):
|
||
errors.append(f"ui.slots[{i}].preload must be true or false")
|
||
elif sl["preload"]:
|
||
if where != "app.modal":
|
||
errors.append(f"ui.slots[{i}].preload is for app.modal slots")
|
||
else:
|
||
sl_out["preload"] = True
|
||
sl_vis = _ui_vis(sl.get("vis"), f"ui.slots[{i}]", errors)
|
||
if sl_vis:
|
||
sl_out["vis"] = sl_vis
|
||
sl_ev = _ui_events(sl.get("events"), f"ui.slots[{i}]", errors)
|
||
if sl_ev:
|
||
sl_out["events"] = sl_ev
|
||
if sl.get("icon") is not None:
|
||
ic = str(sl.get("icon") or "").strip()
|
||
if where not in _ICON_SLOTS or not _LUCIDE_RE.match(ic):
|
||
errors.append(f"ui.slots[{i}].icon: a lucide name, on {sorted(_ICON_SLOTS)} only")
|
||
else:
|
||
sl_out["icon"] = ic
|
||
if sl.get("badge") is not None:
|
||
bd = str(sl.get("badge") or "")
|
||
if where != "conversations.drawer":
|
||
errors.append(f"ui.slots[{i}].badge: only on conversations.drawer")
|
||
elif not (actions_out.get(bd) or {}).get("readOnly"):
|
||
errors.append(f"ui.slots[{i}].badge must name a declared readOnly action")
|
||
else:
|
||
sl_out["badge"] = bd
|
||
if sl.get("size") is not None:
|
||
sz = str(sl.get("size") or "")
|
||
if where != "app.modal" or sz not in _MODAL_SIZES:
|
||
errors.append(f"ui.slots[{i}].size: one of {sorted(_MODAL_SIZES)}, on app.modal only")
|
||
elif sz != "md":
|
||
sl_out["size"] = sz
|
||
# ``query``: the readOnly action the app reads for this slot in
|
||
# one batch with the others (``POST /api/plugins/batch-read``)
|
||
# and hands the frame as ``init.data`` — no capability of its
|
||
# own, it names an action the manifest already declares.
|
||
if sl.get("query") is not None:
|
||
q = _slot_query(sl.get("query"), actions_out, f"ui.slots[{i}].query", errors)
|
||
if q:
|
||
sl_out["query"] = q
|
||
# ``reuseFrame``: the app keeps one frame of this slot and
|
||
# sends it each new conversation as an ``update``.
|
||
if sl.get("reuseFrame") is not None:
|
||
if not isinstance(sl.get("reuseFrame"), bool):
|
||
errors.append(f"ui.slots[{i}].reuseFrame must be true or false")
|
||
elif sl["reuseFrame"]:
|
||
sl_out["reuseFrame"] = True
|
||
ui_out["slots"].append(sl_out)
|
||
menu_items = _menu_items(root, ui_raw.get("menuItems"), errors)
|
||
if menu_items: # only when set: ``ui`` is in the approval fingerprint
|
||
ui_out["menuItems"] = menu_items
|
||
fences = _fences(root, ui_raw.get("fences"), errors)
|
||
if fences:
|
||
ui_out["fences"] = fences
|
||
file_previews = _file_previews(root, ui_raw.get("filePreviews"), errors)
|
||
if file_previews: # only when set: ``ui`` is in the approval fingerprint
|
||
ui_out["filePreviews"] = file_previews
|
||
out["ui"] = ui_out
|
||
|
||
# ── requires / exports / emits (plugin-to-plugin dependencies) ───────────
|
||
requires_out: list[str] = []
|
||
if raw.get("requires") is not None:
|
||
if not isinstance(raw["requires"], list):
|
||
errors.append("requires must be a list of plugin ids")
|
||
else:
|
||
seen_req: set[str] = set()
|
||
for i, dep in enumerate(raw["requires"]):
|
||
d = str(dep or "").strip()
|
||
if not _ID_RE.match(d):
|
||
errors.append(f"requires[{i}]: invalid plugin id {dep!r}")
|
||
continue
|
||
if d == pid:
|
||
errors.append(f"requires[{i}]: plugin cannot require itself")
|
||
continue
|
||
if d not in seen_req:
|
||
seen_req.add(d)
|
||
requires_out.append(d)
|
||
if requires_out:
|
||
out["requires"] = requires_out
|
||
|
||
# ``optionalRequires``: the optional peers — never checked at install /
|
||
# enable / disable / uninstall; while one is active for the user, this
|
||
# plugin may call its ``exports`` and hear its ``emits``, as with
|
||
# ``requires`` (the keyboard-shortcuts plugin's named prompt-shortcut
|
||
# keys). A handler sees which are on in ``AIA_ACTIVE_PLUGINS``.
|
||
optional_out: list[str] = []
|
||
if raw.get("optionalRequires") is not None:
|
||
if not isinstance(raw["optionalRequires"], list):
|
||
errors.append("optionalRequires must be a list of plugin ids")
|
||
else:
|
||
for i, dep in enumerate(raw["optionalRequires"]):
|
||
d = str(dep or "").strip()
|
||
if not _ID_RE.match(d):
|
||
errors.append(f"optionalRequires[{i}]: invalid plugin id {dep!r}")
|
||
continue
|
||
if d == pid:
|
||
errors.append(f"optionalRequires[{i}]: plugin cannot require itself")
|
||
continue
|
||
if d in requires_out:
|
||
errors.append(f"optionalRequires[{i}]: '{d}' is already in requires")
|
||
continue
|
||
if d not in optional_out:
|
||
optional_out.append(d)
|
||
if optional_out:
|
||
out["optionalRequires"] = optional_out
|
||
|
||
exports_out: list[str] = []
|
||
if raw.get("exports") is not None:
|
||
if not isinstance(raw["exports"], list):
|
||
errors.append("exports must be a list of action names")
|
||
else:
|
||
seen_exp: set[str] = set()
|
||
for i, ex in enumerate(raw["exports"]):
|
||
name_ex = str(ex or "").strip()
|
||
if name_ex not in actions_out:
|
||
errors.append(f"exports[{i}]: '{name_ex}' is not a declared action")
|
||
continue
|
||
if name_ex not in seen_exp:
|
||
seen_exp.add(name_ex)
|
||
exports_out.append(name_ex)
|
||
if exports_out:
|
||
out["exports"] = exports_out
|
||
|
||
emits_out: list[str] = []
|
||
if raw.get("emits") is not None:
|
||
if not isinstance(raw["emits"], list):
|
||
errors.append("emits must be a list of event names")
|
||
else:
|
||
seen_em: set[str] = set()
|
||
for i, em in enumerate(raw["emits"]):
|
||
evn = str(em or "").strip()
|
||
if not _EVENT_NAME_RE.match(evn):
|
||
errors.append(f"emits[{i}]: invalid event name {em!r}")
|
||
continue
|
||
if evn not in seen_em:
|
||
seen_em.add(evn)
|
||
emits_out.append(evn)
|
||
if emits_out:
|
||
out["emits"] = emits_out
|
||
|
||
# ``seed``: an app plugin the hub installs once from its seed dir at start
|
||
# (``carryover.seed_typed_plugins``) — the prompt-shortcuts plugin, which
|
||
# replaced a core feature every composer used. Only written when true.
|
||
if raw.get("seed") is not None:
|
||
if not isinstance(raw["seed"], bool):
|
||
errors.append("seed must be true or false")
|
||
elif raw["seed"]:
|
||
out["seed"] = True
|
||
|
||
# ``languages``: the languages the plugin's own UI and texts speak — shown
|
||
# on its page. Base language codes; English is always one of them.
|
||
out["languages"] = _languages(raw.get("languages"), errors)
|
||
# ``i18n``: the folder of its own strings — ``en.json`` (the English
|
||
# source list) and one ``<lang>.json`` per language (plugins/plugin_i18n.py).
|
||
# Every language a file is there for is one ``languages`` names.
|
||
from plugins import plugin_i18n
|
||
i18n_rel, file_langs = plugin_i18n.validate(root, raw.get("i18n"), errors)
|
||
if i18n_rel:
|
||
out["i18n"] = i18n_rel
|
||
for c in file_langs:
|
||
if c not in out["languages"]:
|
||
out["languages"].append(c)
|
||
|
||
# ── agents (declarative Claude --agents contributions) ───────────────────
|
||
pref_keys = {p["key"] for p in ((out.get("ui") or {}).get("prefs") or [])}
|
||
agents_out: list[dict[str, Any]] = []
|
||
if raw.get("agents") is not None:
|
||
if not isinstance(raw["agents"], list):
|
||
errors.append("agents must be a list")
|
||
else:
|
||
seen_ag: set[str] = set()
|
||
for i, ag in enumerate(raw["agents"][:5]):
|
||
if not isinstance(ag, dict):
|
||
errors.append(f"agents[{i}] must be an object")
|
||
continue
|
||
aname = str(ag.get("name") or "").strip()
|
||
if not _KEY_RE.match(aname) or aname in seen_ag:
|
||
errors.append(f"agents[{i}].name invalid or duplicate")
|
||
continue
|
||
desc = str(ag.get("description") or "").strip()[:2000]
|
||
if not desc:
|
||
errors.append(f"agents[{i}].description is required")
|
||
continue
|
||
pf = ag.get("promptFile")
|
||
target_pf = _safe_rel(root, pf, f"agents[{i}].promptFile", errors)
|
||
if target_pf and target_pf.stat().st_size > 64 * 1024:
|
||
errors.append(f"agents[{i}].promptFile exceeds 64 KB")
|
||
continue
|
||
tools = [str(t_name)[:64] for t_name in (ag.get("tools") or []) if isinstance(t_name, str) and t_name.strip()][:32]
|
||
item_ag: dict[str, Any] = {
|
||
"name": aname,
|
||
"description": desc,
|
||
"promptFile": str(pf or ""),
|
||
"tools": tools,
|
||
}
|
||
if ag.get("omitClaudeMd") is True:
|
||
item_ag["omitClaudeMd"] = True
|
||
for pk_field in ("enabledPref", "modelPref", "effortPref"):
|
||
if ag.get(pk_field):
|
||
pkv = str(ag[pk_field]).strip()
|
||
if pkv not in pref_keys:
|
||
errors.append(f"agents[{i}].{pk_field} '{pkv}' not declared in ui.prefs")
|
||
else:
|
||
item_ag[pk_field] = pkv
|
||
if ag.get("defaultModel"):
|
||
item_ag["defaultModel"] = str(ag["defaultModel"]).strip()[:40]
|
||
if ag.get("defaultEffort"):
|
||
item_ag["defaultEffort"] = str(ag["defaultEffort"]).strip()[:20]
|
||
seen_ag.add(aname)
|
||
agents_out.append(item_ag)
|
||
if agents_out:
|
||
out["agents"] = agents_out
|
||
|
||
# ── events (v2 outbound + plugin:<dep>:<event>) ──────────────────────────
|
||
events_out: list[dict[str, Any]] = []
|
||
# a plugin event of a required plugin, or of an optional peer
|
||
req_set = set(requires_out) | set(optional_out)
|
||
for i, ev in enumerate(raw.get("events") or []):
|
||
if not isinstance(ev, dict):
|
||
errors.append(f"events[{i}] must be an object")
|
||
continue
|
||
eid = str(ev.get("id") or f"ev-{i}").strip()
|
||
on = [str(x) for x in (ev.get("on") or [])]
|
||
bad_ev = []
|
||
for ev_name in on:
|
||
if ev_name in _EVENT_TYPES:
|
||
continue
|
||
m_pe = _PLUGIN_EVENT_RE.match(ev_name)
|
||
if m_pe and m_pe.group(1) in req_set:
|
||
continue
|
||
bad_ev.append(ev_name)
|
||
if not on or bad_ev:
|
||
errors.append(f"events[{i}].on has unknown events {bad_ev} (allowed: {sorted(_EVENT_TYPES)} or plugin:<required-id>:<event>)")
|
||
url = str(ev.get("url") or "").strip()
|
||
act = str(ev.get("action") or "").strip()
|
||
if not url and not act:
|
||
errors.append(f"events[{i}] needs 'url' or 'action'")
|
||
if act and act not in actions_out:
|
||
errors.append(f"events[{i}].action '{act}' not in actions")
|
||
if ev.get("secret") and ev["secret"] not in secret_keys:
|
||
errors.append(f"events[{i}].secret '{ev['secret']}' not in secrets")
|
||
events_out.append({
|
||
"id": eid, "on": on, "url": url,
|
||
"secret": str(ev.get("secret") or ""),
|
||
"action": act,
|
||
"internal": bool(ev.get("internal", False)),
|
||
})
|
||
out["events"] = events_out
|
||
|
||
# ── webhooks (v2 inbound) ────────────────────────────────────────────────
|
||
hooks_out: list[dict[str, Any]] = []
|
||
seen_wh: set[str] = set()
|
||
for i, wh in enumerate(raw.get("webhooks") or []):
|
||
if not isinstance(wh, dict):
|
||
errors.append(f"webhooks[{i}] must be an object")
|
||
continue
|
||
wid = str(wh.get("id") or "").strip()
|
||
mode = str(wh.get("mode") or "notify")
|
||
if not _ID_RE.match(wid) or wid in seen_wh:
|
||
errors.append(f"webhooks[{i}].id invalid or duplicate")
|
||
continue
|
||
if mode not in _WEBHOOK_MODES:
|
||
errors.append(f"webhooks[{i}].mode must be one of {sorted(_WEBHOOK_MODES)}")
|
||
continue
|
||
act = str(wh.get("action") or "").strip()
|
||
if mode == "action" and act not in actions_out:
|
||
errors.append(f"webhooks[{i}].action '{act}' not in actions")
|
||
# An ``action`` webhook that *is* an API of the plugin's own (a phone
|
||
# app's one door): ``respond: "result"`` answers the action's JSON as
|
||
# the body (or the file it names) instead of the ``{ok, mode, result}``
|
||
# envelope; ``methods`` lets it answer GET (a download link).
|
||
respond = str(wh.get("respond") or "envelope")
|
||
if respond not in _WEBHOOK_RESPONDS:
|
||
errors.append(f"webhooks[{i}].respond must be one of {sorted(_WEBHOOK_RESPONDS)}")
|
||
continue
|
||
methods_raw = wh.get("methods")
|
||
methods = (sorted({str(m).upper() for m in methods_raw})
|
||
if isinstance(methods_raw, list) and methods_raw else ["POST"])
|
||
if not set(methods) <= _WEBHOOK_METHODS:
|
||
errors.append(f"webhooks[{i}].methods must be among {sorted(_WEBHOOK_METHODS)}")
|
||
continue
|
||
if mode != "action" and (respond != "envelope" or methods != ["POST"]):
|
||
errors.append(f"webhooks[{i}]: respond / methods need mode \"action\"")
|
||
continue
|
||
seen_wh.add(wid)
|
||
hook = {
|
||
"id": wid,
|
||
"mode": mode,
|
||
"titleTemplate": str(wh.get("titleTemplate") or f"{name}: {{{{title}}}}")[:120],
|
||
"promptTemplate": str(wh.get("promptTemplate") or "{{body}}")[:2000],
|
||
"action": act,
|
||
"description": str(wh.get("description") or "")[:200],
|
||
"internalOnly": bool(wh.get("internalOnly", False)),
|
||
}
|
||
# Written only when set, so webhooks installed before keep their record.
|
||
if respond != "envelope":
|
||
hook["respond"] = respond
|
||
if methods != ["POST"]:
|
||
hook["methods"] = methods
|
||
hooks_out.append(hook)
|
||
out["webhooks"] = hooks_out
|
||
|
||
# ── resources (conversation resource kinds — plugins/resources.py) ───────
|
||
out["resources"] = _resources(raw.get("resources"), errors)
|
||
|
||
# ── harnessHooks (hooks in the agent harness — plugins/harness_hooks.py) ─
|
||
from plugins import harness_hooks
|
||
hh = harness_hooks.parse(root, raw.get("harnessHooks"), errors)
|
||
if hh:
|
||
out["harnessHooks"] = hh
|
||
# ── pathShims (commands wrapped on every run's PATH — plugins/path_shims.py)
|
||
from plugins import path_shims
|
||
ps = path_shims.parse(root, raw.get("pathShims"), errors)
|
||
if ps:
|
||
out["pathShims"] = ps
|
||
# ── endpoints (HTTP it answers on the hub's own address — plugins/endpoints.py)
|
||
from plugins import endpoints as plugin_endpoints
|
||
eps = plugin_endpoints.parse(raw.get("endpoints"), pid, out.get("actions") or {}, errors)
|
||
if eps:
|
||
out["endpoints"] = eps
|
||
|
||
# ── sockets (websockets its frames open through the host — plugins/sockets.py)
|
||
from plugins import sockets as plugin_sockets
|
||
socks = plugin_sockets.parse(raw.get("sockets"), errors)
|
||
if socks:
|
||
out["sockets"] = socks
|
||
|
||
# ── provides (data the host merges into its own answers) ─────────────────
|
||
prov_raw = raw.get("provides") or {}
|
||
prov_out: dict[str, str] = {}
|
||
if not isinstance(prov_raw, dict):
|
||
errors.append("provides must be an object")
|
||
else:
|
||
for name, act in prov_raw.items():
|
||
if name not in _PROVIDES:
|
||
errors.append(f"provides.{name}: unknown (one of {sorted(_PROVIDES)})")
|
||
elif not isinstance(act, str) or act not in actions_out:
|
||
errors.append(f"provides.{name}: must name a declared action")
|
||
else:
|
||
prov_out[name] = act
|
||
out["provides"] = prov_out
|
||
|
||
# ── commands (the ai-agent CLI + MCP tools, over declared actions) ───────
|
||
from plugins import commands as plugin_commands
|
||
cmds = plugin_commands.parse(raw.get("commands"), pid, actions_out, errors)
|
||
if cmds:
|
||
out["commands"] = cmds
|
||
|
||
# ── capabilities ─────────────────────────────────────────────────────────
|
||
caps = [str(c) for c in (raw.get("capabilities") or [])]
|
||
bad_caps = sorted(set(caps) - _CAPABILITIES)
|
||
if bad_caps:
|
||
errors.append(f"unknown capabilities: {', '.join(bad_caps)}")
|
||
out["capabilities"] = sorted(set(caps))
|
||
|
||
# ── managed (hub-owned, granted per guest) ───────────────────────────────
|
||
if raw.get("managed") is not None:
|
||
mg = raw["managed"]
|
||
if not isinstance(mg, dict):
|
||
errors.append("managed must be an object")
|
||
else:
|
||
grant_fields: list[dict[str, Any]] = []
|
||
seen_gf: set[str] = set()
|
||
for i, f in enumerate(mg.get("grantFields") or []):
|
||
if not isinstance(f, dict):
|
||
errors.append(f"managed.grantFields[{i}] must be an object")
|
||
continue
|
||
fk = str(f.get("key") or "").strip()
|
||
ft = str(f.get("type") or "checkbox")
|
||
if not _KEY_RE.match(fk) or fk in seen_gf:
|
||
errors.append(f"managed.grantFields[{i}].key invalid or duplicate")
|
||
continue
|
||
if ft not in _FIELD_TYPES:
|
||
errors.append(f"managed.grantFields[{i}].type invalid: {ft}")
|
||
continue
|
||
seen_gf.add(fk)
|
||
gf_item: dict[str, Any] = {
|
||
"key": fk,
|
||
"label": str(f.get("label") or fk)[:80],
|
||
"type": ft,
|
||
"help": str(f.get("help") or "")[:300],
|
||
"default": f.get("default"),
|
||
}
|
||
if ft == "select":
|
||
gf_item["options"] = list(f.get("options") or [])
|
||
grant_fields.append(gf_item)
|
||
|
||
lim_raw = mg.get("limits") or {}
|
||
if not isinstance(lim_raw, dict):
|
||
errors.append("managed.limits must be an object")
|
||
lim_raw = {}
|
||
limits_out: dict[str, Any] = {}
|
||
if lim_raw.get("inFlight") is not None:
|
||
limits_out["inFlight"] = max(1, min(64, int(lim_raw["inFlight"])))
|
||
if lim_raw.get("jobsPerDay") is not None:
|
||
limits_out["jobsPerDay"] = max(1, min(10000, int(lim_raw["jobsPerDay"])))
|
||
if lim_raw.get("defaultMonthlyBudgetUsd") is not None:
|
||
limits_out["defaultMonthlyBudgetUsd"] = max(0.0, float(lim_raw["defaultMonthlyBudgetUsd"]))
|
||
|
||
kh_raw = mg.get("keyHealth")
|
||
kh_out = None
|
||
if kh_raw is not None and not isinstance(kh_raw, dict):
|
||
errors.append("managed.keyHealth must be an object")
|
||
elif isinstance(kh_raw, dict):
|
||
kh_out = _key_health(kh_raw, raw, errors)
|
||
|
||
out["managed"] = {
|
||
"defaultForGuests": bool(mg.get("defaultForGuests", False)),
|
||
"allowUserSecretOverride": bool(mg.get("allowUserSecretOverride", False)),
|
||
"metered": bool(mg.get("metered", False)),
|
||
"grantFields": grant_fields,
|
||
"limits": limits_out,
|
||
"keyHealth": kh_out,
|
||
}
|
||
|
||
# ── kind + provider / harness (typed plugins) ────────────────────────────
|
||
from plugins.typed_manifest import parse_typed
|
||
out.update(parse_typed(root, raw, pid, secret_keys, errors))
|
||
# a translation speaks its own language, whatever ``languages`` forgot
|
||
if (tv := out.get("translation")) and tv.get("lang") and tv["lang"] not in out["languages"]:
|
||
out["languages"].append(tv["lang"])
|
||
|
||
# an endpoint's action answers HTTP and nothing else (plugins/endpoints.py)
|
||
plugin_endpoints.cross_check(out, errors)
|
||
|
||
if errors:
|
||
raise ManifestError(errors)
|
||
return out
|
||
|
||
|
||
_LINK_URL_RE = re.compile(r"^https://[^\s<>\"']+$")
|
||
_LINK_VAR_RE = re.compile(r"\{\{\s*config\.([A-Za-z0-9_]+)\s*\}\}")
|
||
_TOOL_RE = re.compile(r"^[a-z0-9][a-z0-9:_-]{0,63}$")
|
||
|
||
|
||
def _key_health(kh_raw: dict[str, Any], raw: dict[str, Any], errors: list[str]) -> dict[str, Any]:
|
||
"""``managed.keyHealth``: the hub key's monthly alert line (``alertLimit``
|
||
+ ``currency``; ``alertLimitEur`` is the older spelling), when to push,
|
||
which hub secret is the key (``secretKey``, default: the first
|
||
``scope: "hub"`` secret) and the pre-plugin ledger tool whose rows count
|
||
as this plugin's (``legacyLedgerTool``)."""
|
||
cur = str(kh_raw.get("currency") or "EUR").upper()
|
||
if cur not in ("EUR", "USD"):
|
||
errors.append("managed.keyHealth.currency must be EUR or USD")
|
||
cur = "EUR"
|
||
limit = kh_raw.get("alertLimit")
|
||
if limit is None:
|
||
limit = kh_raw.get("alertLimitEur", 20.0)
|
||
if "alertLimitEur" in kh_raw and "currency" not in kh_raw:
|
||
cur = "EUR"
|
||
try:
|
||
limit_f = max(0.0, min(100000.0, float(limit)))
|
||
except (TypeError, ValueError):
|
||
errors.append("managed.keyHealth.alertLimit must be a number")
|
||
limit_f = 20.0
|
||
hub_secrets = [str(s.get("key")) for s in (raw.get("secrets") or [])
|
||
if isinstance(s, dict) and s.get("scope") == "hub"]
|
||
secret_key = kh_raw.get("secretKey")
|
||
if secret_key is not None:
|
||
secret_key = str(secret_key)
|
||
if secret_key not in hub_secrets:
|
||
errors.append(f"managed.keyHealth.secretKey '{secret_key}' is not a hub-scoped secret")
|
||
else:
|
||
secret_key = hub_secrets[0] if hub_secrets else None
|
||
legacy = kh_raw.get("legacyLedgerTool")
|
||
if legacy is not None:
|
||
legacy = str(legacy)
|
||
if not _TOOL_RE.match(legacy) or legacy.startswith("plugin:"):
|
||
errors.append("managed.keyHealth.legacyLedgerTool must be a plain ledger tool id")
|
||
legacy = None
|
||
return {
|
||
"alertLimit": round(limit_f, 2),
|
||
"currency": cur,
|
||
"pushAtPct": max(1, min(100, int(kh_raw.get("pushAtPct", 80)))),
|
||
"pushOnBreak": bool(kh_raw.get("pushOnBreak", True)),
|
||
"secretKey": secret_key,
|
||
"legacyLedgerTool": legacy,
|
||
}
|
||
|
||
|
||
_LANG_CODE_RE = re.compile(r"^[a-z]{2,3}$")
|
||
|
||
|
||
def _languages(v: Any, errors: list[str]) -> list[str]:
|
||
"""``languages`` (``["en", "fr"]``): unique base codes, English first and
|
||
always there; absent = ``["en"]``."""
|
||
if v is None:
|
||
return ["en"]
|
||
if not isinstance(v, list) or not 1 <= len(v) <= 32:
|
||
errors.append("languages must be a list of 1-32 language codes")
|
||
return ["en"]
|
||
out = ["en"]
|
||
for i, c in enumerate(v):
|
||
if not isinstance(c, str) or not _LANG_CODE_RE.match(c):
|
||
errors.append(f"languages[{i}] must be a language code like 'fr' (got {c!r})")
|
||
elif c not in out:
|
||
out.append(c)
|
||
return out
|
||
|
||
|
||
def requires_operator(manifest: dict[str, Any]) -> bool:
|
||
"""True when the manifest asks for host/internal capabilities only the
|
||
operator may approve."""
|
||
# A model provider prices and bills every conversation; a harness ships
|
||
# code the sidecar runs on every machine — the operator's call only.
|
||
# A translation's prompt line goes into every guest run of its language.
|
||
if manifest.get("kind") in ("provider", "harness", "translation"):
|
||
return True
|
||
if manifest.get("managed"):
|
||
return True
|
||
# a script hook is plugin code every machine's harness runs
|
||
from plugins.harness_hooks import has_script
|
||
if has_script(manifest):
|
||
return True
|
||
# a path shim is plugin code every run's git (or other command) goes through
|
||
if manifest.get("pathShims"):
|
||
return True
|
||
# its own code answering HTTP on the hub's address, the internet's included
|
||
if manifest.get("endpoints"):
|
||
return True
|
||
pr = manifest.get("proxy") or {}
|
||
if pr.get("internal"):
|
||
return True
|
||
# a websocket into the host's network (the lab Chrome's VNC)
|
||
if manifest.get("sockets"):
|
||
return True
|
||
if any(s.get("scope") == "hub" for s in (manifest.get("secrets") or [])):
|
||
return True
|
||
if any(ev.get("internal") for ev in (manifest.get("events") or [])):
|
||
return True
|
||
if any(c in _OPERATOR_CAPS and c != "conversations.spawn"
|
||
for c in (manifest.get("capabilities") or [])):
|
||
return True
|
||
return False
|
||
|
||
|
||
_OVERLAY_LABELS = {
|
||
"conversation": "Draws a transparent overlay on conversation pages — it sees the conversation's colour, state and lifecycle stamps and the page's box outlines, never its text",
|
||
"home": "Draws a transparent overlay on the home page — it sees the running conversations' colours and states and the page's box outlines, never their text",
|
||
}
|
||
|
||
_CAP_LABELS = {
|
||
"footprint.read": "Reads every conversation's estimated carbon, water and energy, with its model and projects (the operator's only)",
|
||
"telemetry.read": "Reads the hub's own telemetry: which pages and features people used, by whom, on which device, and where conversations started (the operator's only)",
|
||
"analytics.read": "Reads how many conversations ran and how long they worked, by model, harness, project, machine, person and origin — never costs (the operator's only)",
|
||
"graph.read": "Reads the lab's projects, services, conversations, subagents, plans and memories as graph nodes (the operator's only)",
|
||
"services.read": "Reads the host's services folder (compose and Traefik files, read-only; the operator's runs only)",
|
||
"runs.start": "Starts conversations as you — any model, machine, lean run or EVOX2 fallback (the operator's only)",
|
||
"conversations.send": "Sends a message into your conversations (the operator's only)",
|
||
"runs.guest": "Runs a guest's scheduled job as that guest, confined like their own runs (the operator's only)",
|
||
"conversations.reply": "Posts an app-tagged turn into a conversation, preserving its owner/guest scope",
|
||
"models.read": "Reads the model catalogue and Settings → Models presets",
|
||
"complete.run": "Asks any model for one short answer (no tools, no transcript), billed to your logins (the operator's only)",
|
||
"conversations.label": "Reads your conversations' titles and first prompts, and writes their action badges and short titles (the operator's only)",
|
||
"conversations.title": "Asks your title plugin for a prompt's title (the operator's only)",
|
||
"catalog.read": "Reads the skills and agents catalogs: every SKILL.md and agent definition, their calls, runs and spend (the operator's only)",
|
||
"skills.share": "Shares one of your skills with every guest run, or stops (the operator's only)",
|
||
"agents.run": "Runs one of your agent definitions now, or schedules it as a cron job (the operator's only)",
|
||
"workers.read": "Lists your machines and what each can run",
|
||
"askform.bridge": "Creates, reads and manages forms on the hub's ask-form mirror",
|
||
"users.read": "Reads user names, languages, web addresses and project grants",
|
||
"scaffold.run": "Scaffolds new projects on the host, grants access and relocates conversations into them",
|
||
"plans.read": "Reads implementation plan files under data/plans/ (the operator's only)",
|
||
"plans.write": "Updates implementation plan files under data/plans/ (the operator's only)",
|
||
"templates.read": "Reads the project scaffolding templates folder (read-only; the operator's runs only)",
|
||
"memories.read": "Reads Claude's memories folder (read-only; the operator's runs only)",
|
||
"projects.env": "Reads and writes the projects' .env files, secrets included (the operator's runs only)",
|
||
"activity.read": "Reads agent activity: 5-minute concurrency bins, subagents, tokens and cost per day (the operator's only)",
|
||
"usage.read": "Reads each plan's usage limits: the live /usage %, its history, the plans and the calibration's exchange rate (the operator's only)",
|
||
"home.read": "Reads your home page as data: the tiles the plugins you use show there (plan usage, activity…) and how many conversations run and wait on you",
|
||
"usage.calibrate": "Refits the plan calibration (plan units and list $ per 1% of each window) now (the operator's only)",
|
||
"perf.read": "Reads the CPU, memory and disk use of every agent run and of the processes it started, on every machine (the operator's only)",
|
||
"perf.act": "Stops the processes ended conversations left running, keeps them from the auto-kill, removes scratch dirs and worktrees on a machine, measures its disk and changes those settings (the operator's handlers only)",
|
||
"ship.run": "Deploys projects to their hosts through the host's zipgo broker and reads their deploy configs (the operator's handlers only)",
|
||
"machines.mcp": "Lists your machines and reads, adds, removes and signs in the MCP servers of each one's harness logins (the operator's handlers only)",
|
||
"machines.wake": "Sends Wake-on-LAN packets onto your LAN from the host and checks whether your machines came up (the operator's handlers only)",
|
||
"relay.serve": "Serves authenticated relays from your machines to upstreams it holds the credentials of — the hub gateway (the operator's handlers only)",
|
||
"conversations.data": "Reads and writes its own notes on your conversations (links between them, shown in the thread; the operator's handlers only)",
|
||
"notify.respond": "Answers your questions, taps your pushes' buttons and marks your pushes read on your behalf, and reads one of your pushes back — yours only",
|
||
"conversations.checks": "Reads when each of your conversations was committed, pushed, merged, deployed and notified, and whether it finished — never its text",
|
||
"conversations.reports": "Reads what its own command shims reported from your conversations' runs (the commits they made) — nothing else",
|
||
"diff.read": "Reads your conversations' commits and diffs and your projects' commit diffs (a guest: their projects' only)",
|
||
"contextcost.read": "Reads what your Claude context costs to load: every context file's tokens and cost, each skill's calls and estimated spend (the operator's only)",
|
||
"i18n.read": "Reads which strings each translation and each plugin's own dictionaries are missing, per language — never anything else (the operator's only)",
|
||
"conversations.tasks": "Reads the background shells and Monitors of your conversations, tails their output and stops live ones when you ask",
|
||
"hub.api": "Calls the hub's own API as you — everything your `ai-agent` CLI can do — or, narrowed to their own conversations and projects, as a guest it is granted to (the operator's handlers only)",
|
||
"notify.ask": "Sends you tappable questions (a push with 2–3 buttons) and reads the answers to its own",
|
||
"security.record": "Writes its own lines in the Security log, and may push them when you have plugin events on",
|
||
"hostfiles.read": "Reads and browses the host files each person may open — their granted projects; for the operator also ~/homelab and ~/worktrees — never secrets, noise dirs or the lab's runtime state (the operator's only)",
|
||
"context.read": "Reads the workspace's Claude context catalog (CLAUDE.md, .claude/, read-only data/) with real token counts and costs (the operator's only)",
|
||
"plugins.manage": "Lists your installed plugins and asks to install or uninstall plugins of the public catalog — the app shows you each install's capabilities and asks you to confirm every change (the operator's only)",
|
||
"context.write": "Edits editable files in the workspace's Claude context (CLAUDE.md, .claude/ — the operator's handlers only)",
|
||
}
|
||
|
||
|
||
def capability_summary(manifest: dict[str, Any]) -> list[dict[str, Any]]:
|
||
"""Plain-language capability bullets shown in the install consent card."""
|
||
items: list[dict[str, Any]] = []
|
||
if pv := manifest.get("provider"):
|
||
n_acc = len(pv.get("accounts") or [])
|
||
items.append({"kind": "provider", "privileged": True,
|
||
"label": f"Model provider `{pv['vendorId']}`: {len(pv.get('models') or [])} model(s), "
|
||
f"pricing ({(pv.get('pricing') or {}).get('kind') or 'none'}), "
|
||
f"{n_acc} account(s)"
|
||
+ (" · a usage reader the sidecar runs" if pv.get("usageReader") else "")
|
||
+ (" · a sidecar module (routes, run hooks)" if pv.get("sidecar") else "")
|
||
+ (" (operator only)")})
|
||
if hv := manifest.get("harness"):
|
||
vendors = ", ".join(s["vendor"] for s in hv.get("supports") or [])
|
||
items.append({"kind": "harness", "privileged": True,
|
||
"label": f"Agent harness `{hv['harnessId']}` (runs {vendors}): ships a sidecar driver "
|
||
f"every {'machine' if hv.get('runsOn') == 'any' else 'lab sidecar'} runs"
|
||
+ (", guests' computers included" if hv.get("guestAllowed") else "")
|
||
+ (f" · installs `{hv['workerSetup']['tool']}` on a worker from its Setup checklist"
|
||
if hv.get("workerSetup") else "")
|
||
+ " (operator only)"})
|
||
if tv := manifest.get("translation"):
|
||
items.append({"kind": "translation", "privileged": True,
|
||
"label": f"Translation into {tv['englishName']} (`{tv['lang']}`): "
|
||
f"{tv['uiCount']} interface strings, {tv['backendCount']} mail, push and "
|
||
"error texts"
|
||
+ (", and a line telling the agent to write in that language "
|
||
"in its runs" if tv.get("promptLine") else "")
|
||
+ " (operator only)"})
|
||
if mg := manifest.get("managed"):
|
||
bits = ["operator-owned"]
|
||
if mg.get("defaultForGuests"):
|
||
bits.append("default on for guests")
|
||
if mg.get("metered"):
|
||
bits.append("metered")
|
||
if mg.get("allowUserSecretOverride"):
|
||
bits.append("optional BYOK")
|
||
items.append({"kind": "managed", "privileged": True,
|
||
"label": f"Managed hub plugin ({', '.join(bits)})"})
|
||
if manifest.get("settings") or (manifest.get("ui") or {}).get("settingsHtml") or manifest.get("secrets"):
|
||
items.append({"kind": "settings", "label": f"Adds Settings page: {manifest['name']}"})
|
||
for s in manifest.get("secrets") or []:
|
||
scope_note = " (hub-wide, operator)" if s.get("scope") == "hub" else " (write-only)"
|
||
items.append({"kind": "secret", "label": f"Stores secret `{s['key']}`{scope_note}"})
|
||
if pr := manifest.get("proxy"):
|
||
methods = sorted({r["method"] for r in pr.get("allow") or []})
|
||
n = len(pr.get("allow") or [])
|
||
host_note = " (internal host — operator only)" if pr.get("internal") else ""
|
||
stream_note = " · streaming" if pr.get("stream") else ""
|
||
if wk := pr.get("wake"):
|
||
stream_note += f" · wakes service `{wk['service']}`"
|
||
items.append({
|
||
"kind": "proxy",
|
||
"privileged": bool(pr.get("internal")),
|
||
"label": f"Calls `{pr['baseUrl']}` ({', '.join(methods)} · {n} path{'s' if n != 1 else ''}{stream_note}){host_note}",
|
||
})
|
||
if sk := manifest.get("skill"):
|
||
items.append({"kind": "skill", "label": f"Adds skill `{sk['name']}` to your conversations & paired computers"})
|
||
for sc in manifest.get("schedules") or []:
|
||
items.append({"kind": "schedule", "label": f"Runs scheduled job `{sc['id']}` (`{sc['cron']}`)"})
|
||
ui = manifest.get("ui") or {}
|
||
if ui.get("settingsHtml"):
|
||
items.append({"kind": "ui", "label": "Renders custom sandboxed Settings UI"})
|
||
for pg in ui.get("pages") or []:
|
||
items.append({"kind": "ui", "label": f"Adds sandboxed page `{pg['label']}` ({pg['nav']})"})
|
||
for tc in ui.get("toolCards") or []:
|
||
items.append({"kind": "ui", "label": f"Adds sandboxed tool card `{tc['label']}`"})
|
||
for sl in ui.get("slots") or []:
|
||
items.append({"kind": "ui", "label": f"Adds sandboxed slot at `{sl['where']}`"})
|
||
for fe in ui.get("fences") or []:
|
||
items.append({"kind": "ui", "label": f"Draws ```{fe['lang']} blocks in agents' messages (sandboxed)"})
|
||
for fp in ui.get("filePreviews") or []:
|
||
exts = ", ".join("." + t for t in fp["fileTypes"][:6]) + ("…" if len(fp["fileTypes"]) > 6 else "")
|
||
items.append({"kind": "ui", "label": f"Previews {exts} files agents' messages name (sandboxed)"})
|
||
for ov in ui.get("overlays") or []:
|
||
items.append({"kind": "ui", "label": _OVERLAY_LABELS[ov["where"]]
|
||
+ (" · takes clicks on what it draws" if ov.get("pointer") == "hits" else " · clicks go through")
|
||
+ (" · sees where your pointer is" if ov.get("cursor") else "")})
|
||
for ev in manifest.get("events") or []:
|
||
items.append({"kind": "event", "label": f"Subscribes to hub events: {', '.join(ev['on'])}"})
|
||
for wh in manifest.get("webhooks") or []:
|
||
items.append({"kind": "webhook", "label": f"Opens inbound webhook `{wh['id']}` ({wh['mode']})"})
|
||
if acts := manifest.get("actions"):
|
||
items.append({"kind": "action", "label": f"Defines {len(acts)} sandboxed action(s): {', '.join(sorted(acts))}"})
|
||
from plugins.harness_hooks import summary as _hooks_summary
|
||
items.extend(_hooks_summary(manifest))
|
||
from plugins.path_shims import summary as _shims_summary
|
||
items.extend(_shims_summary(manifest))
|
||
from plugins.endpoints import consent_items as _endpoint_items
|
||
items.extend(_endpoint_items(manifest))
|
||
for so in manifest.get("sockets") or []:
|
||
items.append({"kind": "socket", "privileged": True,
|
||
"label": f"Opens websocket `{so['id']}` to `{so['url']}` from its frames, for you only (internal host — operator only)"})
|
||
for r in manifest.get("resources") or []:
|
||
items.append({"kind": "resource", "label": f"Extracts `{r['label']}` resource pills in conversations"})
|
||
if reqs := manifest.get("requires"):
|
||
items.append({"kind": "requires", "label": f"Requires plugin(s): {', '.join(f'`{r}`' for r in reqs)}"})
|
||
if opt := manifest.get("optionalRequires"):
|
||
items.append({"kind": "requires", "label": f"Works with plugin(s), when installed: {', '.join(f'`{r}`' for r in opt)}"})
|
||
if exps := manifest.get("exports"):
|
||
items.append({"kind": "exports", "label": f"Exports action(s) to dependent plugins: {', '.join(f'`{e}`' for e in exps)}"})
|
||
if ems := manifest.get("emits"):
|
||
items.append({"kind": "emits", "label": f"Emits plugin event(s): {', '.join(f'`{e}`' for e in ems)}"})
|
||
for ag in manifest.get("agents") or []:
|
||
items.append({"kind": "agent", "label": f"Adds Claude subagent `{ag['name']}` to conversations"})
|
||
for name, act in (manifest.get("provides") or {}).items():
|
||
if name == "notify.channel":
|
||
items.append({"kind": "provides", "label": f"Receives your pushes, questions and their clears to deliver them (action `{act}`)"})
|
||
elif name == "composer.shortcuts":
|
||
items.append({"kind": "provides", "label": f"Contributes prompt shortcut chips to the composer (action `{act}`)"})
|
||
elif name == "notify.audio":
|
||
items.append({"kind": "provides", "label": f"Renders the spoken audio of your pushes (action `{act}`)"})
|
||
elif name == "app.banner":
|
||
items.append({"kind": "provides", "privileged": True,
|
||
"label": f"Shows a floating status banner to the operator (action `{act}`)"})
|
||
elif name == "machine.attention":
|
||
items.append({"kind": "provides", "privileged": True,
|
||
"label": f"Adds rows to your machines' Needs you and Setup checklists (action `{act}`)"})
|
||
elif name == "runs.schedule":
|
||
items.append({"kind": "provides", "privileged": True,
|
||
"label": f"Schedules conversations for later: the hub's Send later, its CLI and budget ask it (action `{act}`)"})
|
||
elif name == "runs.cron":
|
||
items.append({"kind": "provides", "privileged": True,
|
||
"label": f"Holds the cron jobs: the week's budget, auto-archive and the agents page ask it (action `{act}`)"})
|
||
elif name == "app.launch":
|
||
items.append({"kind": "provides",
|
||
"label": f"May open a window of its own when someone opens the app (action `{act}`)"})
|
||
elif name == "chrome.lab":
|
||
items.append({"kind": "provides", "privileged": True,
|
||
"label": f"Runs the browser your --chrome lab runs drive: brings it up before one launches, sets the Chrome chip's default and whether guests may use it (action `{act}`)"})
|
||
elif name == "app.keymap":
|
||
items.append({"kind": "provides",
|
||
"label": f"Sets which keys run the app's commands — your keyboard shortcuts (action `{act}`)"})
|
||
elif name == "runs.limits":
|
||
items.append({"kind": "provides", "privileged": True,
|
||
"label": f"Sets how many agents each of your machines runs at once: starts over it wait in the hub's queue (action `{act}`)"})
|
||
elif name == "machine.wake":
|
||
items.append({"kind": "provides", "privileged": True,
|
||
"label": f"Wakes your sleeping machines before a run pinned to one, and from their Wake button (action `{act}`)"})
|
||
else:
|
||
items.append({"kind": "provides", "label": f"Adds `{name}` data to the hub's own pages (action `{act}`)"})
|
||
from plugins import commands as plugin_commands
|
||
items += plugin_commands.summary_items(manifest)
|
||
for c in manifest.get("capabilities") or []:
|
||
label = _CAP_LABELS.get(c, f"Hub capability: `{c}`")
|
||
items.append({"kind": "capability",
|
||
"privileged": c in _OPERATOR_CAPS and c not in ("models.read", "workers.read"),
|
||
"label": label})
|
||
return items
|
||
|
||
|
||
def capability_fingerprint(manifest: dict[str, Any]) -> str:
|
||
"""Deterministic SHA-256 over every security-relevant declaration.
|
||
Reloading a plugin whose fingerprint matches keeps approval automatically."""
|
||
pr = manifest.get("proxy")
|
||
mg = manifest.get("managed")
|
||
sig = {
|
||
"secrets": [(s["key"], s.get("scope", "user")) for s in (manifest.get("secrets") or [])],
|
||
"proxy": None if not pr else {
|
||
"baseUrl": pr["baseUrl"],
|
||
"internal": bool(pr.get("internal")),
|
||
"stream": bool(pr.get("stream")),
|
||
"auth": pr.get("auth"),
|
||
"headers": pr.get("headers") or {},
|
||
"allow": pr.get("allow") or [],
|
||
"denyParams": pr.get("denyParams") or [],
|
||
"stripResponseKeys": pr.get("stripResponseKeys") or [],
|
||
"inspect": pr.get("inspect"),
|
||
"handlerOnly": bool(pr.get("handlerOnly")),
|
||
# ``wake`` only when declared (below), so every plugin without it
|
||
# keeps its exact approval fingerprint.
|
||
},
|
||
"managed": None if not mg else {
|
||
"defaultForGuests": bool(mg.get("defaultForGuests")),
|
||
"allowUserSecretOverride": bool(mg.get("allowUserSecretOverride")),
|
||
"metered": bool(mg.get("metered")),
|
||
"limits": mg.get("limits") or {},
|
||
},
|
||
"skill": (manifest.get("skill") or {}).get("name"),
|
||
"schedules": [(s["id"], s["cron"], s["script"]) for s in (manifest.get("schedules") or [])],
|
||
# Preferences are a person's own knobs (size, a colour): not a capability.
|
||
"ui": None if manifest.get("ui") is None else {
|
||
k: v for k, v in manifest["ui"].items() if k != "prefs"},
|
||
"events": manifest.get("events") or [],
|
||
# ``respond`` / ``methods`` join the tuple only when set: webhooks
|
||
# approved before them keep their fingerprint.
|
||
"webhooks": [(w["id"], w["mode"], w.get("action"), bool(w.get("internalOnly")),
|
||
*([w["respond"]] if w.get("respond") else []),
|
||
*(["+".join(w["methods"])] if w.get("methods") else []))
|
||
for w in (manifest.get("webhooks") or [])],
|
||
"actions": {k: v["script"] for k, v in (manifest.get("actions") or {}).items()},
|
||
# (id, urlRegex) only: the rest of a resource kind (templates, tool
|
||
# extractors, look) mines text, it opens nothing — and installed
|
||
# plugins keep their approval.
|
||
"resources": [(r["id"], r.get("urlRegex") or "") for r in (manifest.get("resources") or [])],
|
||
"capabilities": manifest.get("capabilities") or [],
|
||
"provides": manifest.get("provides") or {},
|
||
}
|
||
# Only include new top-level keys when declared, so existing installed
|
||
# plugins keep their exact approval fingerprint across upgrades.
|
||
if pr and pr.get("wake"):
|
||
sig["proxy"]["wake"] = dict(pr["wake"])
|
||
if manifest.get("requires"):
|
||
sig["requires"] = list(manifest["requires"])
|
||
if manifest.get("optionalRequires"):
|
||
sig["optionalRequires"] = list(manifest["optionalRequires"])
|
||
if manifest.get("exports"):
|
||
sig["exports"] = list(manifest["exports"])
|
||
if manifest.get("emits"):
|
||
sig["emits"] = list(manifest["emits"])
|
||
# A typed plugin's kind and everything its provider / harness block can
|
||
# reach (code it ships, URLs, accounts, how it launches) — app plugins
|
||
# leave all three out, so their fingerprints don't move.
|
||
if manifest.get("kind") not in (None, "app"):
|
||
sig["kind"] = manifest["kind"]
|
||
if pv := manifest.get("provider"):
|
||
sig["provider"] = {
|
||
"vendorId": pv.get("vendorId"),
|
||
"local": bool(pv.get("local")), "keyless": bool(pv.get("keyless")),
|
||
"discovery": pv.get("discovery"), "servers": pv.get("servers") or {},
|
||
"localInfra": pv.get("localInfra"),
|
||
"accounts": [(a["id"], a.get("configDir"), list(a.get("aliases") or []))
|
||
for a in pv.get("accounts") or []],
|
||
"usageReader": pv.get("usageReader"),
|
||
}
|
||
if pv.get("sidecar"): # only when declared: other fingerprints don't move
|
||
sig["provider"]["sidecar"] = pv["sidecar"]
|
||
if hv := manifest.get("harness"):
|
||
sig["harness"] = {
|
||
"harnessId": hv.get("harnessId"), "caps": hv.get("caps") or [],
|
||
"loginMode": hv.get("loginMode"), "loginFlow": hv.get("loginFlow"),
|
||
"runsOn": hv.get("runsOn"), "guestAllowed": bool(hv.get("guestAllowed")),
|
||
"entrypoint": hv.get("entrypoint"), "sidecar": hv.get("sidecar"),
|
||
"supports": [(s["vendor"], s.get("argTemplate"), bool(s.get("allowUnlisted")))
|
||
for s in hv.get("supports") or []],
|
||
}
|
||
if hv.get("workerSetup"): # what it may install on a worker (only when declared)
|
||
ws = hv["workerSetup"]
|
||
sig["harness"]["workerSetup"] = [ws.get("tool"), bool(ws.get("guestAllowed")),
|
||
bool(ws.get("update")), ws.get("installerEnv"),
|
||
ws.get("recipe")]
|
||
if tv := manifest.get("translation"):
|
||
# what reaches every run of that language: its prompt line
|
||
sig["translation"] = {"lang": tv.get("lang"), "promptLine": tv.get("promptLine")}
|
||
from plugins.harness_hooks import fingerprint_sig as _hooks_sig
|
||
if (hh := _hooks_sig(manifest)) is not None:
|
||
sig["harnessHooks"] = hh
|
||
from plugins.path_shims import fingerprint_sig as _shims_sig
|
||
if (ps := _shims_sig(manifest)) is not None:
|
||
sig["pathShims"] = ps
|
||
if manifest.get("endpoints"):
|
||
from plugins.endpoints import signature as _endpoints_sig
|
||
sig["endpoints"] = _endpoints_sig(manifest)
|
||
if manifest.get("sockets"):
|
||
sig["sockets"] = [(so["id"], so["url"], list(so.get("subprotocols") or []))
|
||
for so in manifest["sockets"]]
|
||
if manifest.get("agents"):
|
||
sig["agents"] = [(a["name"], a["promptFile"], list(a.get("tools") or [])) for a in manifest["agents"]]
|
||
blob = json.dumps(sig, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
||
return hashlib.sha256(blob).hexdigest()[:24]
|
||
|