Перейти к содержимому
AggregaAggrega
Выберите язык: Русский
Эта страница переведена машинным способом. Читать оригинал на английском.

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 Wasm
plugins rather than in the binary, so this is where you see which ones are
reachable, add or remove a workspace binding, and check a guest before you
publish it.
Plugins reach the CLI two ways. Some are compiled into the binary and resolve
with 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 the
machine-owned records in a Plugin entity with its .wasm, and generate Plugin
catalog 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 your
configuration.
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 configuration
unless --global is passed, so outside a workspace it is refused before the
registry 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-run
does everything the plain command does except write: it hands back the
configuration the write would have produced, creating and modifying nothing. The
answer names the file that content is for — which matters here, because a
--global attachment targets the config shared across every workspace. A caller
that keeps its own document model puts the content there, where it is visible
before 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 document
carries the identity a write would have written.
Under --dry-run standard output carries that content and nothing else, so it stays
parseable; a version substitution is announced on standard error instead. The cli
type does not accept --dry-run: what it records is the content digest of the bytes
it verified, which is a record the machine maintains rather than content you
edit.

Флаги aggrega plugin add

ФлагПо умолчаниюОписание
--accept-capabilitiesfalseПринять объявленные возможности плагина cli без интерактивного запроса (только для типа cli)
--capability—Возможность, которую обслуживает привязка провайдера (обязателен для типа provider и допустим только с ним)
--dry-runfalseВыполнить всё, кроме записи: вернуть итоговую конфигурацию как содержимое с указанием файла, для которого она предназначена, ничего не создавая и не изменяя. Без этого флага подключение записывается в разрешённый файл конфигурации. Не принимается с типом cli.
--globalfalseЗаписать подключение в глобальную конфигурацию, общую для всех рабочих пространств.
--role—Роль подключения governance: annotation-transform, label-transform, ir-verdict или render-verdict (обязателен для типа governance и допустим только с ним)
--workspacefalseЗаписать подключение в конфигурацию рабочего пространства этого проекта. Подключение provider или socket по умолчанию записывается сюда; плагин cli по умолчанию записывается в глобальную конфигурацию.
--yesfalseПропустить запрос подтверждения возможностей 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 the
entity can never promise a capability the binary does not provide. The entity's
identity (metadata.name), runtime limits, and provider block come from an authored
per-plugin overlay; the entity version is the guest's describe() self-report
version. The plugin-level description, when the guest reports one, is emitted as
metadata.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.yaml
and carries a generated-output banner. The leading pluginType segment keeps two
same-named plugins in different sockets apart, since a bare plugin name is unique
only within its own socket. Regenerating over unchanged inputs yields
byte-identical files.
A generated entity is a catalog document you own and go on editing, so --dry-run
does everything gen-catalog does except write: it hands the content back, creating
and modifying nothing, and the answer names the file each document is for. A
caller that keeps its own document model — an editor, for instance — puts the
content there, where it is visible before it is saved and can be amended or
undone. Every other behaviour is the write's — the same guests are read and the
same 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 a
terminal has nowhere better to put them.

Флаги aggrega plugin gen-catalog

ФлагПо умолчаниюОписание
--dry-runfalseВыполнить всё, кроме записи: вернуть сгенерированные сущности как содержимое с указанием файла для каждой, ничего не создавая и не изменяя. Всё остальное поведение совпадает с записью, поэтому выбор, который запись отклонила бы, отклоняется и здесь. Без этого флага сущности записываются в —output-dir.
--from-embeddedfalseсгенерировать сущность для каждого гостевого модуля, встроенного в этот исполняемый файл
--output-dir—каталог, в который записываются сгенерированные сущности (обязателен)
--overlay—каталог авторского оверлея (—from-embedded) или файл (—plugin) (обязателен)
--plugin—сгенерировать одну сущность для гостевого модуля .wasm по этому пути

Описание aggrega plugin list

List every Wasm plugin the CLI can see and, for each, its self-reported
describe() metadata.
Two groups are printed. Embedded built-ins are the provider and linter guests
compiled into the binary; they resolve with no filesystem, cache, or network
access. Configured plugins are the workspace bindings — the provider and linter
bindings 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 a
status of its own — ready, unresolved, describe-failed, or digest-drift when
its bytes changed since it was pinned at install.
The default output is a scannable table with one row per plugin, showing its
type, name, served capabilities, and version. The output is read-only and
deterministic. A plugin that fails to resolve or describe is listed with its
failure status rather than halting the whole listing.
With -o json, the output is a structured object carrying the full per-plugin
detail — type, name, version, commit, capabilities, input kinds, boundary
assembly, exports, origin, readiness, and any resolve or describe error —
grouped as embedded and configured. It is suitable for programmatic
consumption and documentation generation.

Флаги aggrega plugin list

ФлагПо умолчаниюОписание
--output, -otableФормат вывода: table|json.

Описание aggrega plugin remove

Remove a configured plugin of the named type from a config file so it no longer
participates.
The type is one of provider, governance, linter, importer, or cli — the same
set 'plugin add' accepts. The query identifies the entry to remove: the plugin's
short 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 binding
serves. A query that matches nothing halts and leaves the config untouched, so a
typo never silently removes the wrong plugin.
A provider or socket attachment defaults to this project's workspace config; a cli
command defaults to the global config shared across every workspace. --global and
--workspace force the file the removal targets, overriding the default.

Флаги aggrega plugin remove

ФлагПо умолчаниюОписание
--globalfalseУдалить из глобальной конфигурации, общей для всех рабочих пространств.
--workspacefalseУдалить из конфигурации рабочего пространства этого проекта. Подключение provider или socket по умолчанию находится здесь; команда cli по умолчанию — в глобальной конфигурации.

Описание aggrega plugin run-local

Load a .wasm guest from a filesystem path, call one of its declared
exports with an optional payload, and write the guest's answer to stdout.
The guest is addressed directly by --plugin path; it is not resolved through
the workspace plugin cascade. The export named by --export must be one the
guest advertises in its describe() self-report, or the call is rejected before
the guest runs.
The command has two forms. The artifact form takes no positional argument and
loads the guest bare. The entity form takes a Plugin entity file as its one
positional argument: the entity is schema-validated, and its declared
metadata.pluginType and export contract are cross-checked against the guest's
describe() 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 value
beginning with @ reads the payload bytes from a file (--with @input.json); any
other value is taken as a literal inline JSON payload (--with '{"k":1}'). When
--with is omitted, the export receives the minimal empty JSON object {}. The
resolved payload is validated as JSON before the guest runs, so malformed input
is reported up front.
An export a socket calls with a payload reads it in a binary encoding rather
than 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 no
flag selects it: the resolved payload is converted into the encoding the named
export reads before the guest is called. The conversion reads the payload's
shape from the export's name, so it covers each export a socket calls by
default; an entry function an attachment or a pipeline step names under a name
of its own receives the payload as written. The authored payload stays JSON
either way.
The answer is converted the same way in reverse. An export a socket calls
answers in that binary encoding, so its answer is read as the export's output
shape and written to stdout as indented JSON; an answer that is not that shape
is reported as an error naming the export rather than printed. A cli_run
export's answer, and an entry function under a name of its own, are written to
stdout exactly as the guest wrote them. When the guest exits non-zero, what it
wrote is passed through unchanged.
In the artifact form, --type optionally names a plugin type the guest's
describe() self-report must agree with, or the load is rejected before the
guest 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 failure
inside 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 may
call, derived from the plugin's .wasm import section, and the top-level commands a
CLI plugin contributes, read from the plugin's describe() self-report. Both are
ground truth in the binary. This command reads the .wasm, derives the
host-function set in canonical form and the command mirror in describe()-declared
order, and aligns the entity's spec.runtime.hostFunctions and spec.commands with
them — creating the runtime block when the file has none. Only those blocks
change; every comment, blank line, and other field is preserved byte-for-byte. A
plugin that imports no host functions or contributes no commands records an
explicit empty list, so each field is always present and reviewable.
The write is idempotent: re-running when the records already match the .wasm
leaves the file untouched. Commit the result; publish (aggrega push) then only
verifies the committed records against the .wasm and refuses to publish a file
whose 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. Так происходит, даже несмотря на то что она пишет в файл сущности, созданный вами, — граница проводится по содержимому, а не по файлу. Записи, которые компилятор ведёт о себе сам, не предназначены для редактирования вами, поэтому проверять перед их записью нечего; окружающий документ остаётся побайтно нетронутым, и меняются только эти блоки.