aggrega plugin
Инспекция плагинов Wasm, которые может разрешить CLI
Синтаксис
aggrega pluginОписание
Work with the WebAssembly plugins this CLI can resolve.
All of Aggrega's provider-specific and policy-specific behaviour lives in Wasmplugins rather than in the binary, so this is where you see which ones arereachable, add or remove a workspace binding, and check a guest before youpublish it.
Plugins reach the CLI two ways. Some are compiled into the binary and resolvewith no filesystem, cache or network access. The rest are workspace bindings in.aggrega-config.yaml, resolved through the plugin cascade. "aggrega plugin list"shows both groups together.
The subcommands below cover the whole life of a binding: list what is reachable,add and remove bindings, run a local guest export directly, sync themachine-owned records in a Plugin entity with its .wasm, and generate Plugincatalog entities from a guest's own metadata.Подкоманды
| Команда | Описание |
|---|---|
aggrega plugin add | Поиск плагина указанного типа в реестре и его добавление |
aggrega plugin gen-catalog | Генерация сущностей каталога Plugin из describe() гостевого модуля и авторского оверлея |
aggrega plugin list | Список плагинов, которые может разрешить CLI, с их метаданными describe() |
aggrega plugin remove | Удаление настроенного плагина указанного типа |
aggrega plugin run-local | Загрузка локального гостевого модуля .wasm и вызов одного из его экспортов |
aggrega plugin sync | Синхронизация машинно-управляемых записей плагина (функций хоста, команд CLI) в его файле сущности с его .wasm |
Описание aggrega plugin add
Find a plugin of the named type in the configured registry and add it to yourconfiguration.
Examples: aggrega plugin add cli moo # add the moo command aggrega plugin add cli moo:0.2.4 # a specific version aggrega plugin add governance rego --role render-verdict
Arguments: <type> The plugin socket to add for. One of: provider, governance, linter, importer, or cli. The governance type requires --role. <query> The plugin's name, optionally followed by :<version> to add that version rather than the latest published one. The name is looked up directly first. Where no plugin of the chosen type has that name, it is matched as a case-insensitive substring against the plugin names of that type, which reads the registry's whole catalog and must resolve to exactly one plugin — otherwise the command lists the candidates so you can narrow it. A query naming a version is never matched that way. The provider type takes no version.
What add writes depends on the type:
- A socket type (governance, linter, importer) pins the version the query names, or else the latest published version, and adds the bare plugin identity (<type>/<name>:<version>) to the plugins.<type> list. The latest is never taken from pre-release versions, so a plugin that publishes only those is added by naming one. A governance entry also records its --role, one of annotation-transform, label-transform, ir-verdict, or render-verdict. An importer the plugins.importer list already names keeps its one entry, moved to the pinned version with its place and what it carries under with. - The provider type adds a plugins.providers entry naming the plugin by its bare identity (provider/<name>) with no version; --capability names the capability the binding serves, preserving existing settings. The version is the one the Recipe pins, or else the highest available, and the lockfile records the one a pull chose. - The cli type fetches the plugin from the registry, verifies it, and caches its bytes, then pins it into the plugins.cli list as a top-level aggrega command — no separate pull step. Its resolved reference and the content digest of the verified bytes are recorded so the command runs those exact bytes, resolving from the local cache on later runs with no further network access. A cli plugin defaults to the global config, so its command is available in every workspace; --workspace pins it to this project instead. It needs no workspace: run outside one, its bytes are cached in the machine-wide cache rather than in the folder you ran it in. Its declared capabilities are confirmed before installing, and --accept-capabilities or --yes skips that prompt for non-interactive use.
A provider or socket attachment is written to a workspace's own configurationunless --global is passed, so outside a workspace it is refused before theregistry is reached; so is anything else that can be refused without it.
A provider or socket attachment is configuration you go on editing, so --dry-rundoes everything the plain command does except write: it hands back theconfiguration the write would have produced, creating and modifying nothing. Theanswer names the file that content is for — which matters here, because a--global attachment targets the config shared across every workspace. A callerthat keeps its own document model puts the content there, where it is visiblebefore it is saved and can be amended or undone. The registry is still searched,and for a socket type the version still resolved, since the returned documentcarries the identity a write would have written.
Under --dry-run standard output carries that content and nothing else, so it staysparseable; a version substitution is announced on standard error instead. The clitype does not accept --dry-run: what it records is the content digest of the bytesit verified, which is a record the machine maintains rather than content youedit.Флаги aggrega plugin add
| Флаг | По умолчанию | Описание |
|---|---|---|
--accept-capabilities | false | Принять объявленные возможности плагина cli без интерактивного запроса (только для типа cli) |
--capability | — | Возможность, которую обслуживает привязка провайдера (обязателен для типа provider и допустим только с ним) |
--dry-run | false | Выполнить всё, кроме записи: вернуть итоговую конфигурацию как содержимое с указанием файла, для которого она предназначена, ничего не создавая и не изменяя. Без этого флага подключение записывается в разрешённый файл конфигурации. Не принимается с типом cli. |
--global | false | Записать подключение в глобальную конфигурацию, общую для всех рабочих пространств. |
--role | — | Роль подключения governance: annotation-transform, label-transform, ir-verdict или render-verdict (обязателен для типа governance и допустим только с ним) |
--workspace | false | Записать подключение в конфигурацию рабочего пространства этого проекта. Подключение provider или socket по умолчанию записывается сюда; плагин cli по умолчанию записывается в глобальную конфигурацию. |
--yes | false | Пропустить запрос подтверждения возможностей cli для неинтерактивного использования (только для типа cli) |
Описание aggrega plugin gen-catalog
Generate one Plugin entity per selected Wasm guest.
Each entity's contract fields — pluginType, abiVersion, capabilities, exports,and contract — are derived from the guest's describe() self-report, so theentity can never promise a capability the binary does not provide. The entity'sidentity (metadata.name), runtime limits, and provider block come from an authoredper-plugin overlay; the entity version is the guest's describe() self-reportversion. The plugin-level description, when the guest reports one, is emitted asmetadata.description and omitted cleanly when it does not.
Two selection modes:
--from-embedded generate an entity for every guest embedded in this binary. The overlay path is a directory; each overlay is matched to a guest by its metadata.name identity, and, where overlays in several socket directories (<socket>/<name>.yaml) declare one name, by the directory naming the guest's socket. --plugin <f.wasm> generate a single entity for one non-embedded guest. The overlay path is a single overlay file.
The output is written under <output-dir>/<pluginType>/<name>/<version>/plugin.yamland carries a generated-output banner. The leading pluginType segment keeps twosame-named plugins in different sockets apart, since a bare plugin name is uniqueonly within its own socket. Regenerating over unchanged inputs yieldsbyte-identical files.
A generated entity is a catalog document you own and go on editing, so --dry-rundoes everything gen-catalog does except write: it hands the content back, creatingand modifying nothing, and the answer names the file each document is for. Acaller that keeps its own document model — an editor, for instance — puts thecontent there, where it is visible before it is saved and can be amended orundone. Every other behaviour is the write's — the same guests are read and thesame overlays matched — so a selection gen-catalog would refuse is refused under--dry-run too. Without the flag the entities are written, because a caller at aterminal has nowhere better to put them.Флаги aggrega plugin gen-catalog
| Флаг | По умолчанию | Описание |
|---|---|---|
--dry-run | false | Выполнить всё, кроме записи: вернуть сгенерированные сущности как содержимое с указанием файла для каждой, ничего не создавая и не изменяя. Всё остальное поведение совпадает с записью, поэтому выбор, который запись отклонила бы, отклоняется и здесь. Без этого флага сущности записываются в —output-dir. |
--from-embedded | false | сгенерировать сущность для каждого гостевого модуля, встроенного в этот исполняемый файл |
--output-dir | — | каталог, в который записываются сгенерированные сущности (обязателен) |
--overlay | — | каталог авторского оверлея (—from-embedded) или файл (—plugin) (обязателен) |
--plugin | — | сгенерировать одну сущность для гостевого модуля .wasm по этому пути |
Описание aggrega plugin list
List every Wasm plugin the CLI can see and, for each, its self-reporteddescribe() metadata.
Two groups are printed. Embedded built-ins are the provider and linter guestscompiled into the binary; they resolve with no filesystem, cache, or networkaccess. Configured plugins are the workspace bindings — the provider and linterbindings and the CLI-extension commands — resolved through the plugin cascade.Each plugin's type appears in the TYPE column, so a CLI-extension command(type cli) is legible alongside the socket plugins; a CLI plugin also carries astatus of its own — ready, unresolved, describe-failed, or digest-drift whenits bytes changed since it was pinned at install.
The default output is a scannable table with one row per plugin, showing itstype, name, served capabilities, and version. The output is read-only anddeterministic. A plugin that fails to resolve or describe is listed with itsfailure status rather than halting the whole listing.
With -o json, the output is a structured object carrying the full per-plugindetail — type, name, version, commit, capabilities, input kinds, boundaryassembly, exports, origin, readiness, and any resolve or describe error —grouped as embedded and configured. It is suitable for programmaticconsumption and documentation generation.Флаги aggrega plugin list
| Флаг | По умолчанию | Описание |
|---|---|---|
--output, -o | table | Формат вывода: table|json. |
Описание aggrega plugin remove
Remove a configured plugin of the named type from a config file so it no longerparticipates.
The type is one of provider, governance, linter, importer, or cli — the sameset 'plugin add' accepts. The query identifies the entry to remove: the plugin'sshort name (matched against 'add's short name so remove is symmetric with add),its full pinned reference, or, for the provider type, the capability the bindingserves. A query that matches nothing halts and leaves the config untouched, so atypo never silently removes the wrong plugin.
A provider or socket attachment defaults to this project's workspace config; a clicommand defaults to the global config shared across every workspace. --global and--workspace force the file the removal targets, overriding the default.Флаги aggrega plugin remove
| Флаг | По умолчанию | Описание |
|---|---|---|
--global | false | Удалить из глобальной конфигурации, общей для всех рабочих пространств. |
--workspace | false | Удалить из конфигурации рабочего пространства этого проекта. Подключение provider или socket по умолчанию находится здесь; команда cli по умолчанию — в глобальной конфигурации. |
Описание aggrega plugin run-local
Load a .wasm guest from a filesystem path, call one of its declaredexports with an optional payload, and write the guest's answer to stdout.
The guest is addressed directly by --plugin path; it is not resolved throughthe workspace plugin cascade. The export named by --export must be one theguest advertises in its describe() self-report, or the call is rejected beforethe guest runs.
The command has two forms. The artifact form takes no positional argument andloads the guest bare. The entity form takes a Plugin entity file as its onepositional argument: the entity is schema-validated, and its declaredmetadata.pluginType and export contract are cross-checked against the guest'sdescribe() before the guest runs. In both forms the guest bytes come from--plugin; the entity carries no artifact path.
The payload is supplied with --with, and it is always written as JSON. A valuebeginning with @ reads the payload bytes from a file (--with @input.json); anyother value is taken as a literal inline JSON payload (--with '{"k":1}'). When--with is omitted, the export receives the minimal empty JSON object {}. Theresolved payload is validated as JSON before the guest runs, so malformed inputis reported up front.
An export a socket calls with a payload reads it in a binary encoding ratherthan as JSON; a CLI plugin's cli_run export is the exception, and reads JSON.Which encoding an export reads is fixed by the socket that export serves, so noflag selects it: the resolved payload is converted into the encoding the namedexport reads before the guest is called. The conversion reads the payload'sshape from the export's name, so it covers each export a socket calls bydefault; an entry function an attachment or a pipeline step names under a nameof its own receives the payload as written. The authored payload stays JSONeither way.
The answer is converted the same way in reverse. An export a socket callsanswers in that binary encoding, so its answer is read as the export's outputshape and written to stdout as indented JSON; an answer that is not that shapeis reported as an error naming the export rather than printed. A cli_runexport's answer, and an entry function under a name of its own, are written tostdout exactly as the guest wrote them. When the guest exits non-zero, what itwrote is passed through unchanged.
In the artifact form, --type optionally names a plugin type the guest'sdescribe() self-report must agree with, or the load is rejected before theguest runs; when omitted, no type expectation is imposed. In the entity form--type is rejected, because the entity's metadata.pluginType supplies the type.
The guest's clean exit code becomes this command's exit status, so a failureinside the plugin is distinguishable from a failure of aggrega itself.Флаги aggrega plugin run-local
| Флаг | По умолчанию | Описание |
|---|---|---|
--export | — | объявленный экспорт для вызова |
--plugin | — | путь в файловой системе к артефакту .wasm |
--type | — | тип плагина, которому должен соответствовать самоотчёт describe() гостевого модуля |
--with | — | полезная нагрузка для экспорта: встроенный JSON или @ |
Описание aggrega plugin sync
Sync a plugin's machine-owned records in a Plugin entity file with its .wasm.
Two records are not authored by hand: the set of host functions a plugin maycall, derived from the plugin's .wasm import section, and the top-level commands aCLI plugin contributes, read from the plugin's describe() self-report. Both areground truth in the binary. This command reads the .wasm, derives thehost-function set in canonical form and the command mirror in describe()-declaredorder, and aligns the entity's spec.runtime.hostFunctions and spec.commands withthem — creating the runtime block when the file has none. Only those blockschange; every comment, blank line, and other field is preserved byte-for-byte. Aplugin that imports no host functions or contributes no commands records anexplicit empty list, so each field is always present and reviewable.
The write is idempotent: re-running when the records already match the .wasmleaves the file untouched. Commit the result; publish (aggrega push) then onlyverifies the committed records against the .wasm and refuses to publish a filewhose records are out of sync with its binary.Флаги aggrega plugin sync
| Флаг | По умолчанию | Описание |
|---|---|---|
--plugin | — | Путь к артефакту .wasm плагина, импорты и describe() которого определяют записываемые функции хоста и команды |
Что делает запись импортёра
aggrega plugin add importer записывает идентификатор плагина и последнюю опубликованную для него версию или версию, указанную вами как <name>:<version>, — importer/<name>:<version> — в список plugins.importer. Эта запись подключает импортёр, который она называет: импорт, запрашивающий формат, заявленный этим импортёром, запускает именно этот импортёр в этой версии, даже если другие импортёры в вашем каталоге тоже заявляют этот формат, и только этому импортёру передаётся то, что запись содержит в with. Полное описание записи приведено в разделе Какой импортёр превращает источник в черновики.
Импортёр подключается одной записью, поэтому добавление импортёра, который уже назван в списке plugins.importer записываемого файла — в любой версии или через диапазон, — не создаёт второй записи. Вместо этого команда переводит эту запись на разрешённую ею версию: запись сохраняет своё место в списке и всё, что она содержит в with. Добавление импортёра в той версии, которую уже называет его запись, оставляет запись без изменений.
Команды CLI-плагина и их флаги
При каждом запуске aggrega добавляет по одной команде для каждой команды, которую предоставляет настроенный плагин cli, считывая команды и их флаги из самоотчёта плагина describe() — из кэша describe, если в нём хранится закреплённый дайджест плагина, а иначе путём вызова describe для плагина. Каждый объявленный флаг объявляется для своей команды, поэтому aggrega help <command> выводит его так же, как флаги встроенной команды; при этом плагин по-прежнему получает свои аргументы неразобранными и сам считывает свои флаги.
Закреплённый дайджест располагается рядом со ссылкой на плагин в списке plugins.cli конфигурации и записывается как sha256:, за которым следуют 64 шестнадцатеричные цифры в нижнем регистре, — именно в таком написании его записывает aggrega plugin add cli. Дайджест в любом другом написании, например в виде шестнадцатеричной строки без префикса sha256:, отклоняется при загрузке файла конфигурации с указанием файла и записи; пока он не исправлен, не добавляется ни одна команда ни одного настроенного плагина, а сообщение об отказе выводится как предупреждение в стандартный поток ошибок.
Прежде чем добавить какую-либо команду плагина, aggrega проверяет каждый флаг, объявленный каждой из них. Плагин, объявления которого не проходят проверку, пропускается: ни одна из его команд не добавляется, одно предупреждение в стандартном потоке ошибок называет плагин, команду, флаг и то, что с ним не так, а все остальные команды — встроенные или из других плагинов — работают как обычно:
warning: CLI plugin "oci://hub.aggrega.ai/plugin/cli/greet:1.2.0" was not added as a command: its command "greet" declares the flag "--verbose" with the shorthand "vv"; a shorthand is a single ASCII letter or digitОбъявление флага проходит проверку, если:
- у флага есть имя и ни у какого другого флага той же команды нет такого же имени;
- его краткая форма, если она есть, — это одна буква или цифра ASCII, которую не использует ни один другой флаг той же команды;
- ни его имя, ни его краткая форма не повторяют флаг, который уже есть у каждой команды
aggrega, —--help,-hи глобальные флаги; - его тип, если он объявлен, —
string,boolилиint; флаг без типа является строковым; - его значение по умолчанию, если оно объявлено, является значением его типа.
Пропуск вместе с предупреждением повторяется при каждом вызове, пока конфигурация не закрепит версию плагина, объявления которой проходят проверку. Поля, которые несёт объявление флага, описаны в разделе spec.commands на странице Plugin: страница сущности.
Генерация сущностей и синхронизация записей: два разных вида действий
Две из этих подкоманд создают файл, и то, что они создают, — вещи разного рода.
plugin gen-catalog — сгенерированные сущности принадлежат вам, и их можно редактировать
aggrega plugin gen-catalog создаёт сущности каталога Plugin. Сущность — это документ каталога: вы сохраняете её, проверяете и продолжаете редактировать вместе с остальным каталогом. Поскольку это содержимое принадлежит вам, команда может передать его вам, а не записывать на диск.
--dry-run делает всё то же, что и gen-catalog, кроме записи. Сгенерированные сущности возвращаются как содержимое — ни один файл не создаётся, ни один каталог не создаётся, — и каждый документ в ответе указывает файл, для которого он предназначен, чтобы вызывающая сторона знала, куда относится каждый из них. Вызывающая сторона со своей моделью документов, например редактор, помещает содержимое туда, где вы видите его до сохранения и можете изменить или отменить. Без этого флага сущности записываются в --output-dir, потому что у вызывающей стороны в терминале нет лучшего места для них.
Возвращаемое содержимое и записываемые байты — одно и то же содержимое: --dry-run возвращает то, что создала бы запись, а не отдельно собранный предварительный просмотр. Всё остальное поведение тоже совпадает с записью — читаются те же гостевые модули, сопоставляются те же оверлеи, и --output-dir обязателен в обоих случаях, потому что каждый возвращаемый документ по-прежнему указывает файл, для которого он предназначен, а этот путь составляется из него.
Каждая сущность составляется и проверяется до того, как будет выдана любая из них, поэтому запуск либо создаёт весь набор, либо не создаёт ничего. Оверлей, останавливающий генерацию, — отсутствующий или с идентичностью, не совпадающей с гостевым модулем, с которым он объединяется, — не оставляет после себя частично записанного вывода, который пришлось бы убирать.
plugin sync — машинные записи принадлежат компилятору
aggrega plugin sync приводит машинные записи плагина в соответствие с его модулем: набор host-функций, выводимый из секции импорта модуля, и зеркало команд, считываемое из собственного самоотчёта плагина. И то и другое — фактические данные в бинарном файле, а не значения, которые кто-либо выбирает.
Эта команда всегда выполняет запись и не предлагает --dry-run. Так происходит, даже несмотря на то что она пишет в файл сущности, созданный вами, — граница проводится по содержимому, а не по файлу. Записи, которые компилятор ведёт о себе сам, не предназначены для редактирования вами, поэтому проверять перед их записью нечего; окружающий документ остаётся побайтно нетронутым, и меняются только эти блоки.