Plugin development
Add jobs, file processors, workflow steps and connection types to Avenvail with a compiled-in plugin.
A plugin adds background work to Avenvail: jobs that react to events, jobs on a schedule, and file processors that make previews or read details from uploaded files. Image thumbnails are themselves a plugin (backend/plugins/Avenvail.Plugins.Images), and they use the same contracts described here.
Plugins are compiled into the server. They run with the server's full trust, so only add a plugin whose source you have reviewed. Avenvail does not download or load plugins at runtime. External workers in other languages are planned separately (PROJECT.md §11).
Project layout
- Create a class library under
backend/plugins/, for examplebackend/plugins/Avenvail.Plugins.Example/, targeting the same .NET version as the server. - Reference only the contracts:
<ProjectReference Include="../../Avenvail.Plugins/Avenvail.Plugins.csproj" />. Pin every package to an exact version. - Add a reference to your project in
backend/Avenvail.Api/Avenvail.Api.csproj, add it toAvenvail.slnx, and add its.csprojto the restore step in theDockerfile.
Avenvail finds every IAvenvailPlugin in the libraries that depend on Avenvail.Plugins, so no registration code in the server is needed.
The plugin class
public sealed class ExamplePlugin : IAvenvailPlugin
{
public string Id => "example.hello";
public void Configure(IAvenvailPluginBuilder plugin)
{
plugin.AddJob<GreetJob>("example.hello.greet", maxAttempts: 3);
plugin.OnEvent(AvenvailEvents.FileUploaded, "example.hello.greet");
plugin.AddFileProcessor<ExampleProcessor>();
}
}
- Id is lowercase, dot-separated and globally unique. Every job and processor id must start with it.
- Configuration for the plugin lives under
Avenvail:Plugins:{Id}(in Docker,Avenvail__Plugins__example.hello__Setting).plugin.Configurationis that section. Avenvail:Plugins:{Id}:Enabled=falseturns a plugin off without rebuilding.plugin.Servicesis the server's service collection, for anything your handlers need.
Jobs
A job handler implements IJobHandler. Handlers are resolved per run from a fresh dependency injection scope.
public sealed class GreetJob(ILogger<GreetJob> logger) : IJobHandler
{
public Task RunAsync(JobContext job, CancellationToken ct)
{
logger.LogInformation("Uploaded: {Payload}", job.Payload);
return Task.CompletedTask;
}
}
- At least once. A job can run again after a crash, a timeout or a lost lease. Write handlers so a second run does no harm.
- Failures. Any exception is retried with a growing delay until the job runs out of attempts, then it shows under Settings > Operations. Throw
PermanentJobExceptionwhen retrying can't help, such as invalid input. - Cancellation. Honor the
CancellationToken. It fires on timeout (default 10 minutes) and on shutdown. A job stopped by shutdown is requeued without using an attempt. - Events.
OnEventqueues the job with the event's JSON payload, which includesfileIdorfolderIdandownerId. SeeAvenvailEventsfor the event names. - Schedules.
AddRecurringJob(name, interval)runs a job every interval, at most once a minute.
File processors
A file processor turns one file into derivatives (such as a thumbnail) and facts (size, date taken). Avenvail does the rest: it queues the processor after each upload, retries it, reads the original into a seekable stream, checks and stores the output, applies the file's access rules and lifecycle to derivatives, replaces older output, and processes existing files when the processor is new or its Version changes.
public sealed class ExampleProcessor : IFileProcessor
{
public string Id => "example.hello.preview";
public int Version => 1;
public bool Accepts(ProcessorFile file) => file.MimeType == "image/png";
public Task<ProcessorResult> ProcessAsync(ProcessorFile file, Stream content, CancellationToken ct)
{
var result = new ProcessorResult { Facts = new FileFacts(Width: 640, Height: 480) };
result.Derivatives.Add(new DerivativeOutput(DerivativeKinds.Thumbnail, "image/webp", bytes, 320, 240));
return Task.FromResult(result);
}
}
MimeTypeis detected by Avenvail from the bytes, never taken from the client.- Derivatives are limited to
image/webp,image/pngandimage/jpeg, 10 MiB each, one per kind. Thethumbnailkind is what the library, the inspector, ShareX and share-link previews show. A thumbnail must not carry metadata from the original. - A processor must never change the original, and must protect itself against hostile input: check pixel counts before decoding, and set limits on anything that can grow.
- Raise
Versionwhenever the output changes; files made by an older version are processed again in the background. - A failed processor never affects the file. The inspector shows that the preview couldn't be made and offers a retry.
- To read facts from content that isn't saved yet (an upload going through an intake workflow, a working file), also register an
IContentInspectoras a singleton onplugin.Services. It gets a seekable stream and must not dispose it.
Workflow nodes
A workflow node is two classes: a descriptor (data the editor and validation read) and an executor (the code that runs a step). The built-in nodes are a plugin like any other, in backend/plugins/Avenvail.Plugins.Core; read them for complete examples. The full contract is in workflows.md.
public void Configure(IAvenvailPluginBuilder plugin) => plugin.AddNode<UpperNode, UpperExecutor>();
public sealed class UpperNode : NodeDescriptor<UpperNode.Settings>
{
public sealed record Settings(
[property: Setting("Text"), Bindable, Required, MaxLength(1000)] string Text);
public override string Id => "example.hello.upper";
public override int Version => 1;
public override NodeKind Kind => NodeKind.Transform;
public override NodeCategory Category => NodeCategory.AiAndText;
public override string Name => "Uppercase";
public override IReadOnlyList<NodeOutput> Outputs => [new("text", WorkflowType.String)];
}
public sealed class UpperExecutor : INodeExecutor<UpperNode.Settings>
{
public Task<NodeResult> ExecuteAsync(NodeContext<UpperNode.Settings> step, CancellationToken ct) =>
Task.FromResult(NodeResult.Next(new { text = step.Settings.Text.ToUpperInvariant() }));
}
- The settings record is the form. Avenvail derives the settings schema from it:
Required,MaxLength,RangeandRegularExpressionfromSystem.ComponentModel.DataAnnotations, andSetting(label, help),Bindable,Advanced,MultilineandTextFormatfrom the contracts.TextFormat(TextFormatAttribute.Markdown)marks text the step sends as Markdown so the editor offers formatting; setConnectionandFeatureto use Markdown only when the chosen connection provides that capability feature (Send notification usesNotify.Markdown).TextFormatAttribute.Jsongives a monospaced editor. Nullable types may benull; constructor defaults are the defaults. UseFileRef,FolderRefandTagReffor library resources,ContentReffor a working file, andJsonElementfor a value of any type (it tells a missing value,Undefined, fromnull). - Shape the inspector only when the defaults don't fit. Without hints, the inspector shows content and file inputs first, then the other settings (required ones first), an Outputs section built from
Outputs, and Advanced. These optional attributes and overrides change only how settings are shown, never what they accept:[Group("id")]puts a setting in one of the sections the descriptor lists inGroups(new SettingGroup(id, label, Collapsible, Help, EmptySummary, Advanced, Columns, AddOptional)), shown in that order after the ungrouped settings. A collapsible section stays closed until one of its settings has a value, and shows a summary such as 3 tags or itsEmptySummary(None, Not shared) while closed.Advanced: truemoves the section to the larger editor's Advanced tab.Columns: 2lays its settings out in pairs in the larger editor, such as a connection and its model; long text, lists and editors still take a whole row.AddOptional: truehides optional settings without a value behind Add … buttons, as AI steps do for their text and image inputs. Phrase a section's label as the question it answers when that helps, such as What should be classified?.[VisibleWhen("other", value)]shows the setting only while another setting has that value. A hidden setting keeps its value.Setting(..., Placeholder = "...")fills the empty input, such as Keep the content's name; prefer it to help text that explains an empty value.[PlaceholderWhen("other", value, "...")]swaps it while another setting has a value.[Choice(value, "Label", Help = "...")], once per value, shows a boolean or enum as labeled options.WorkflowKindoffers an option only in that kind of workflow; a setting left with one option is hidden.[Editor(EditorAttribute.Tags, With = ["tagNames"])]picks a specialized editor and lets it edit other settings too. Avenvail hastags,ai-model,ai-decision-model(a connection's default decision model),ai-image,ai-categories(a table ofid,label,descriptionitems: ids are made from names and kept on rename;Withcan name a boolean shown as a checkbox below it, such as Allow no match),ai-values(a list ofkey,label,type,description,requireditems: keys are made from names and kept on rename, with a custom field picker and an example output) andstructured-output; an editor Avenvail doesn't know falls back to the default for the setting's type.[Summary]marks the settings that say what a step does. The canvas shows their values under the step's name, such as a classify step's category names; a list of objects shows each item'slabel,nameor key. Without it, the canvas shows the first required setting's value.NodeOutput(name, type, Label: "...", Description: "...", MayBeEmpty: true, Example: "0.85")describes an output on the larger editor's Outputs tab and in the inspector.MayBeEmptymarks outputs that can be null when the step succeeds;Exampleis an illustrative value.Surfacepicks where the step is configured:Inline(the default) in the inspector only, orExpanded, where the inspector shows a summary of each section with Configure step and Edit buttons, and editing happens in the larger editor's Configuration, Advanced, Outputs and Test tabs. Both edit the same draft. UseExpandedfor steps with list editors or many sections.Bothkeeps the full form in the inspector and adds Configure step; preferExpanded.Descriptionis one sentence. The summary sidebar and the larger editor show it under the step's name.
Registration fails when a hint names a group the node doesn't declare or a setting it doesn't have, or a group asks for more than two columns.SaveFileNodeandNotifyNodeinbackend/plugins/Avenvail.Plugins.Coreuse most of them;AiNodeDescriptorinbackend/plugins/Avenvail.Plugins.AishowsSurface, the column and optional-input groups, and[Summary]. - Start new steps with other settings.
InitialSettingsare the settings a step added in the editor starts with. Use them to change what new steps choose without changing saved steps, which keep the record's defaults for settings they don't store. AI classify starts new steps on decision models this way, while saved steps keep language models. - Help people find the node.
Descriptionis shown in the step browser under the name. OverrideAliaseswith other names people may search for andKeywordswith extra search terms; neither is shown. Avenvail's own nodes keep these infrontend/i18n/locales/en.json(automationNodes.<id>.aliasesand.keywords), which take precedence. Steps from plugins whose id doesn't start withavenvail.show the plugin id in the picker. [Editor]picks a special control for a setting the editor would otherwise show as plain text.[Editor(EditorAttribute.AiModel)]on astring?shows the AI model picker, which reads the connection from the step'sai.chat@1connection setting; null or empty means the connection's default model. The schema carries it asx-editor.- Raise
Versionwhen settings, outputs or ports change in a way saved workflows can't use. Old revisions keep the version they pinned. - Change files only through
step.Files. Each call is fenced by the step's lease and the run's cancellation, locks the file, and is recorded so a retry gets the first result instead of acting twice. Reaching the database directly is a review failure.step.Files.ListTagsAsync(only, limit, ct)reads the run owner's tags, most used first, optionally only the given ones that still exist; AI suggest tags uses it to offer tags to the model. - Fail with
NodeException(code, message, retryable). Other exceptions are retried unless the node declaresRetrySafety.Unsafe. - Content nodes (
NodeKind.Content) take aContentRefsetting (bindable) and return a new one. Read withstep.Content.OpenReadAsyncand write withstep.Content.CreateAsync(name, write); never change the input, and return the input's reference when there is nothing to do. Avenvail detects the new file's type and enforces the run's working limits.backend/plugins/Avenvail.Plugins.Images/ImageNodes.cshas examples. - Return
NodeResult.Next(outputs),NodeResult.ToPort(port, outputs)for nodes with several ports (overridePortsFor),NodeResult.Wait(until)orNodeResult.Stop(reason). Outputs must be declared and are at most 64 KiB. When a test run gives anExternalProcessingorExternalMutationnode placeholder outputs instead of running it, it continues onPlaceholderPort(settings), the first port by default; AI detect overrides it to takeunsure. The editor labels the portstrue,false,default,error,yes,noandunsure; others show their name.
Workflow templates
A plugin can offer workflow templates under New workflow › From a template. Register each template document, usually an embedded JSON file:
public void Configure(IAvenvailPluginBuilder plugin)
{
using var reader = new StreamReader(typeof(HelloPlugin).Assembly.GetManifestResourceStream("templates/upper.json")!);
plugin.AddWorkflowTemplate(reader.ReadToEnd());
}
- The document is the template format with an
idthat starts with the plugin id, such asexample.hello.upper-names. - Avenvail checks it at startup: a malformed template, one whose placeholders name undeclared resources or the wrong type, or one that holds an id fails startup. A template whose steps come from a plugin that isn't installed or is turned off is listed as unavailable instead.
- Avenvail's own templates translate their name and description in
frontend/i18n/locales/en.json(workflowTemplates.<id>.nameand.description); others show the document's English text. backend/plugins/Avenvail.Plugins.Ai/Templatesholds the built-in AI templates, andAiWorkflowTemplateTestsruns each one end to end against fake AI servers.
Connections
A connection is an outside service a user sets up once (a webhook, a Discord channel, an AI provider). Nodes never take a URL or a key; they take a connection and ask it for a capability, an interface such as INotifyClient. Connection types implement capabilities, so a new notification service is one connection type and every notify node can use it. The design is in workflows.md; backend/plugins/Avenvail.Plugins.Discord and Avenvail.Plugins.Http are complete examples, and they use only these public contracts. The contract is experimental (version 1) until 1.0. Compiled-in plugins are trusted code: these rules keep them correct, they don't sandbox them.
Capabilities
A capability is an id, a major version and a client interface, with optional features a connection may or may not have. Its identity is the versioned key id@version, such as notify@1, and everything is keyed by it: provided capabilities, a connection's features, feature checks and [Connection] settings. Core defines notify@1 (feature attachments), http@1 (feature deduplicates), ai.chat@1 (see AI chat), ai.decide@1 (see AI decisions), ai.extract@1 (see AI extraction) and ocr@1 (see OCR) in Avenvail.Plugins.Capabilities. A plugin can add its own with plugin.AddCapability<MyCapability>(); its id must start with the plugin id.
- A breaking change to the client interface is a new version, registered next to the old one. Nodes and connection types move over independently.
- Startup fails when two capabilities share a key or a client interface, a client type isn't an interface, a feature id repeats or isn't lowercase, a connection type provides a capability twice or provides one (or a feature) that isn't registered, or a node's
[Connection]setting asks for a capability or feature nobody registered. - Generic request and response types belong to the capability, never to a vendor SDK. Limits that belong to one service (Discord's 2,000 characters) stay in its connection type.
- One client call is one delivery. A client never shortens, splits or drops part of what it was given; when the service can't take it whole, it fails with
input_invalidbefore sending, saying what to change. - A capability can implement
SendTestAsyncfor the user's Send test message. Testing a connection never calls it.
Connection types
public void Configure(IAvenvailPluginBuilder plugin) => plugin.AddConnectionType<PagerConnection, PagerConnectionType>();
public sealed class PagerConnection : ConnectionTypeDescriptor<PagerConnection.Settings>
{
public sealed record Settings(
[property: Setting("Token"), Required, Secret, MaxLength(200)] string Token);
public override string Id => "example.pager.webhook";
public override string Name => "Pager";
public override IReadOnlyList<ProvidedCapability> Provides => [new(Notify.CapabilityId, Notify.CapabilityVersion)];
protected override Uri? EndpointOf(Settings settings) => new("https://pager.example.com");
}
public sealed class PagerConnectionType : IConnectionType<PagerConnection.Settings>
{
public object CreateClient(ConnectionContext<PagerConnection.Settings> connection, Capability capability) => new Client(connection);
public async Task<ConnectionTestResult> TestAsync(ConnectionContext<PagerConnection.Settings> connection, CancellationToken ct)
{
using var response = await connection.Http.GetAsync("https://pager.example.com/me", ct);
return new ConnectionTestResult([new(ConnectionChecks.Auth, "Token", response.IsSuccessStatusCode ? CheckStatus.Passed : CheckStatus.Failed)]);
}
private sealed class Client(ConnectionContext<PagerConnection.Settings> connection) : INotifyClient
{
public async Task<NotifyResult> SendAsync(Notification notification, CancellationToken ct)
{
using var request = new HttpRequestMessage(HttpMethod.Post, "https://pager.example.com/send") { Content = JsonContent.Create(new { text = notification.Text }) };
request.Headers.Authorization = new("Bearer", connection.Settings.Token);
using var response = await Outbound.SendAsync(connection.Http, request, ct);
return new NotifyResult((await Outbound.ReadJsonAsync(response, 16 * 1024, ct))?["id"]?.ToString());
}
}
}
- Settings work like node settings, plus
[Secret]: secret values are encrypted at rest, never sent back to the browser, and redacted from test results, step errors and outputs.EndpointOfis shown to the user as where data goes; never put a secret in it. - Settings have their own version. Raise
SettingsVersionwhen stored settings need changing to bind, and turn older ones into current ones inMigrateSettings(secrets included, as plain values). Avenvail migrates a connection the first time it's used and stores the result; whenMigrateSettingsreturns null, or the stored version is newer, the user is asked to enter the settings again. This is independent of capability versions. - How the service is listed. The add-connection dialog builds its catalog from descriptors and presets, so a plugin's types appear with no frontend change. A type with presets is listed once per preset; a type without presets is listed itself (override
Listedto list both). SetCategoryto one ofConnectionCategories(ai-local,ai-hosted,ai-gateway,ai-custom,notifications,webhooks,other) or an id of your own,Logoto an icon name such asi-simple-icons-discord(only properly licensed logos; otherwise a Lucide icon),SetupUrlto where users get credentials, andKeywordsfor search. Presets take the same properties, plusAdvanced(settings shown under Advanced for this preset, such as a hosted provider's fixed address),Primary(advanced settings shown with the main ones) andRequired(optional settings this preset can't work without, checked when adding).[Setting(Placeholder = ...)]names what an empty setting means, such as Model default. Users never see the type's id. - Unsaved settings.
POST /api/v1/connections/draft/testand, for AI types,/draft/modelsrun the type's test or model listing on settings that aren't saved, through the same guarded client. They store nothing; a new connection's requests aren't counted, and a saved connection's (connectionId) count towards it as usual. Users can also shorten a connection's timeout below the type'sTimeout. - Origins. A connection sends only to
OriginsOf(settings), by default its endpoint's origin, on every request, redirect andReachAsync. Override it when a service spans several origins. An empty list sends nowhere; it never means "anywhere". A type that really may send anywhere setsAnyOrigin => true, and only a type without[Secret]settings may: startup fails otherwise. - Use only
connection.Http. It is the guarded outbound client: public addresses only (unless an admin allowed private networks for the connection), checked again on every connect; the connection's origins; no proxies; HTTP/1.1; at most 3 redirects; requests up toMaxRequestBytes(default 256 KiB, at most 32 MiB); responses up toMaxResponseBytes(default 1 MiB, at most 16 MiB); the type'sTimeout(default 10 s, at most 5 minutes), one deadline that also covers reading the response body; and the connection's usage limits, counting every request, retries and probes included. Sizes count the bytes actually sent and received; a declaredContent-Lengthonly lets Avenvail refuse earlier. - Testing never changes anything outside.
TestAsyncmust not send anything a receiver could act on; useconnection.ReachAsync(address)to only open a connection. It follows the same origins, address and DNS rules, private-network setting and timeout asconnection.Http. Report each part with theConnectionChecksids (reachable,auth,model, andConnectionChecks.Feature(capability, feature), which givesfeature:http@1/deduplicates). Mark capability probesOptional. Only required checks decide the result: an empty test, or a skipped required check, is unverified, never a pass. ReturnDetectedFeatures, keyed by capability key, for features the test found. - Token budgets are reservations. Before a request that uses tokens,
await connection.Usage.ReserveTokensAsync(estimate)charges the estimate against the day's budget in one conditional database statement, so concurrent steps can't overshoot it, and fails withconnection_limit_reached(the step waits) when it doesn't fit. Then call one of:SettleAsync(input, output)with the provider's counts. A count it didn't report keeps the estimate charged and is shown as unknown.ReleaseAsync()only when the request wasn't sent (ExternalOutcome.NotSent). It gives the estimate back.
Only the first call counts, and it applies to the day the reservation was made, even after midnight. A reservation left open, or for a request whose outcome isUncertain, stays charged at the estimate. Every call reserves, retries and repairs included.var reservation = await connection.Usage.ReserveTokensAsync(estimate, ct); try { using var response = await Outbound.SendAsync(connection.Http, request, ct); var usage = Usage(await Outbound.ReadJsonAsync(response, MaxBytes, ct)); await reservation.SettleAsync(usage.Input, usage.Output, ct); } catch (NodeException e) when (e.Outcome == ExternalOutcome.NotSent) { await reservation.ReleaseAsync(ct); throw; } - Capabilities that depend on settings. A connection offers a capability its type provides only while
FeaturesOf(settings)includes its key. Leave the key out when the settings say the service lacks it, as the OpenAI-compatible type offersai.decide@1only when Decision models names an API. Steps, the editor and the add-connection dialog all follow what each connection, or preset, offers. Stored connections get new keys when their settings are saved or migrated, so raiseSettingsVersionwhen a change affects which capabilities existing connections offer. - Presets fill in settings for a known service. Override
PresetswithConnectionPreset(id, name, description, icon, settings, hosting) { DocsPath = "/..." }; the dialog offers them when the type is chosen, and the connection stores the preset id. Settings may only name the type's own settings and never a secret; ids are lowercase and unique within the type.ConnectionHosting(Local,SelfHosted,Hosted,Gateway) is informational only: the dialog shows it next to the connection's real address, and nothing in Avenvail relies on it.
AI chat
ai.chat@1 (AiChat in Avenvail.Plugins.Capabilities) is the capability AI steps use. Its features are images, structured-output, json-mode, temperature and model-list; a connection type provides the ones its API can do, and each model may still lack them.
public interface IAiChatClient
{
AiDefaults Defaults { get; } // the connection's default model, temperature and limits, with its revision
Task<IReadOnlyList<AiModel>> ListModelsAsync(CancellationToken ct);
IReadOnlyList<AiModelFeature> Infer(string model); // what the model's name suggests, for models the list doesn't describe
Task<AiChatResponse> CompleteAsync(AiChatRequest request, CancellationToken ct);
}
- One
CompleteAsyncis one request. The request has the model, instructions, input parts (AiPart.Text,AiPart.Image),AiGeneration(max output tokens, optional temperature) and an optionalAiOutputFormatwith a JSON Schema and a mode:Native(the provider enforces the schema),JsonMode(the provider guarantees JSON) orPrompted(neither). The client sends what it's given and never adds the schema to the instructions; callers do that for the weaker modes and always validate the answer. - Responses give the text,
AiFinish(Complete,Length,Refused,Filtered,Other),AiUsagewith the provider's token counts (null when not reported), the model that answered and, behind a gateway,ServedBywhen the gateway says which provider served it. Map reasoning or thinking parts out of the text and count their tokens as output. - Reserve tokens for every request with
AiTokens.Estimate(body, input, maxOutput)before sending and settle with the provider's counts, as in Token budgets. A model the provider doesn't know (404) fails withai_model_unavailable,Rejected. - Model lists return
AiModel(id) { Name, ContextTokens, MaxOutputTokens, Features }. Put a feature inFeaturesonly when the provider's list says so (AiFeatureSource.Provider);Inferreturns guesses (Inferred). Avenvail stores the list per connection, keeps the last good one when a refresh fails, and merges inferred, provider, tested and user values in that order. Steps askIAiModels.FindAsyncfor the merged view. - A type without a model list (
model-listnot provided) still works: users type model names.
backend/plugins/Avenvail.Plugins.Ai has three complete adapters (OpenAI-compatible, Anthropic, Gemini) and the AI nodes. In nodes, AiRunner.StartAsync resolves the client, model and features; AiSession.CompleteJsonAsync asks for a JSON answer and checks it against a schema, and AiSession.CompleteTextAsync asks for free text, as the describe, summarize and generate text nodes do (their runs record outputMode as text).
AI decisions
ai.decide@1 (AiDecide) asks a decision model typed questions and returns probabilities instead of text. Its one feature is images.
public interface IAiDecisionClient
{
AiDefaults Defaults { get; } // the connection's default decision model, with its revision
IReadOnlyList<AiModelFeature> Infer(string model);
Task<AiDecisionResponse> DecideAsync(AiDecisionRequest request, CancellationToken ct);
}
- Questions are
AiQuestion.Predicate(yes or no),AiQuestion.Choice(1 to 255AiOptions) andAiQuestion.Score(2 to 10 ordered levels, lowest first), each with a unique name and instructions. Answers areAiAnswer.Predicate(the probability of yes),AiAnswer.Choice(the most likely value, the model's confidence and each option's probability),AiAnswer.Score(the probability-weighted level from 0, and each level's probability by label) orAiAnswer.Refusal. Confidence and probabilities are null when the model doesn't report them. - One
DecideAsyncis one request. Never retry, fall back to another model, or turn on a gateway's own fallbacks. Reserve tokens withAiTokens.Estimate(body, input, 64)and settle with the provider's counts. - Wire formats. Two are in use, both in
AiDecisionWire: OpenAI's (inputparts and aquestionsarray: OpenAI and Vercel AI Gateway at/decisions) and TypeSafe's System One (stateand aquestionsobject withnoul,choiceandscore: TypeSafe and llama.cpp at/systemone, OpenRouter at/api/alpha/decisions, and Cloudflare at/ai/run/{model}, inside aresultenvelope). System One has no common way to send images: the OpenAI-compatible type offersimageswith it only for Cloudflare, which takes data URLs inimages, and OpenRouter, which takesimage_urlparts in astatearray. - Model lists.
AiModel.Kindsays what a listed model does (Language,Decision,ExtractionorOther) when the provider says: Vercel'stype, OpenRouter'sendpoints(a model on both decision and extraction endpoints is of unknown kind), then its output modalities. OpenRouter lists decision and extraction models only when asked (?output_modalities=decisions,?endpoints=/api/alpha/extractions), so the OpenAI-compatible type asks when the connection offers them. Cloudflare has no OpenAI-style list, so its models come from/ai/models/search, with text generation models of unknown kind. The picker lists models of the step's kind and those of unknown kind. Steps fail withai_model_wrong_kindbefore sending when the list says the chosen model is of another kind. AiRunner.StartDecisionAsyncresolves the client, model, features and input limits for a node;AiDecisionSession.DecideAsyncchecks every answer against its question.
AI extraction
ai.extract@1 (AiExtract) reads typed values from text and images with an extraction model. Its features are images and booleans (fields of type Boolean can be asked for).
public interface IAiExtractionClient
{
AiDefaults Defaults { get; } // the connection's default extraction model, with its revision
IReadOnlyList<AiModelFeature> Infer(string model);
Task<AiExtractionResponse> ExtractAsync(AiExtractionRequest request, CancellationToken ct);
}
- Fields are
AiField(name, kind, instructions), with kindsText,Number,Integer,Boolean,DateandTextList.AiExtractionRequest.ReferenceDateanchors dates written without a year. Values areAiExtractedValue(name, value, confidence): the value in its kind's JSON form, or null when the content doesn't state it.Truncatedsays the provider stopped before reading every value. - One
ExtractAsyncis one request, with tokens reserved like decisions (256 for the answer). - Wire format. Cloudflare's Clairic format (
state, afieldsobject,imagesas data URLs,reference_date), inAiExtractionWire: Cloudflare at/ai/run/{model}and OpenRouter at/api/alpha/extractions, which takes nobooleanfields and images as anassetsmap (format,data_base64) whose names thestatementions. Values of the wrong type fail withprovider_invalid_response. AiRunner.StartExtractionAsyncandAiExtractionSession.ExtractAsyncwork like their decision counterparts. AI extract asks forbooleansthroughConnectionFeaturesForonly when its method isextraction, so validation flags a connection that can't read them.
OCR
ocr@1 (TextRecognition) reads the text in an image. It knows nothing about Tesseract: the Extract text step depends only on it, and any engine can provide it. Its one feature is preprocessing: the engine takes OcrRequest.Advanced overrides.
public interface IOcrClient
{
IReadOnlyList<string> DefaultLanguages { get; } // used when a request names none
Task<IReadOnlyList<OcrLanguage>> ListLanguagesAsync(CancellationToken ct);
Task<OcrResult> RecognizeAsync(OcrRequest request, CancellationToken ct);
}
- Requests carry the image stream with its media type and length, language codes, an
OcrPreset(Auto,Screenshot,Document,Sparse), optionalOcrPreprocessing(segmentation, scale, invert, threshold), the step's idempotency key, and an optionalTimeoutthe engine should keep to. - Results are the text with lines separated by newlines and blocks by a blank line, a confidence from 0 to 1 (null without text), and words with boxes in the original image's pixels. An image without text succeeds with empty text; only a failure to read throws.
- Failures are step errors whose codes start with
ocr_, or classified byOutbound. Reading is safe to repeat, so retryable failures are marked retryable. - The first-party
avenvail.ocr.workertype speaks the worker protocol described in The worker's API.
Lifetimes and ownership
- The
IConnectionTypeimplementation is resolved from the step's (or the test's) scope. CreateClientreturns a new client for one step or one test. Avenvail disposes it (IDisposableorIAsyncDisposable) and itsHttpClientwhen the step ends. Never cache clients,HttpClients or settings between calls.connection.Httpshares Avenvail's pooled connections; don't dispose it or change its defaults.- A client creates and disposes its own
HttpRequestMessageandHttpResponseMessage. Request values from a node are read-only. ForOutboundFile(an attachment or a file body), the client opens the stream, may open it more than once, and disposes each stream it opens before returning. - What a client returns is fully read and holds no stream or connection. A
JsonNodein it is mutable and belongs to the caller from then on: the client must not keep, share or change it after returning it. Read bodies withOutbound.ReadJsonAsyncorReadTextAsync: they fail withresponse_too_largeorprovider_invalid_responserather than cut or guess.
Failures
Outbound classifies a failed request; it doesn't decide retries. Each error carries an ExternalOutcome, and anything not established is Uncertain:
| Outcome | When | Codes |
|---|---|---|
NotSent | Avenvail knows none of the request was written: the outbound rules refused it before the first request, it was too large, or the connection failed before any of it was written. Avenvail tracks the bytes written for each request, so a connection that drops after sending isn't mistaken for this. | outbound_blocked, request_too_large, connection_unreachable, connection_timeout |
Rejected | The service established that it didn't act. Avenvail never infers this from a status code: a connection type claims it for statuses its service documents, with Outbound.SendAsync(http, request, ct, rejected: [400, 404, 429]), as the Discord type does. | as below |
Uncertain | Everything else, including every error status unless the connection type claims it, a timeout or dropped connection after sending, a redirect refused after the first request, and an unreadable or oversized answer. | provider_rejected (4xx), connection_auth_failed (401, 403), provider_throttled (429), provider_error (5xx, 408, 425), connection_timeout, connection_lost, outbound_blocked, response_too_large, provider_invalid_response |
Each error also says whether trying again could help: 5xx, 408, 425, timeouts and dropped connections could; other 4xx and blocked addresses can't.
Messages never include a transport exception's own text. Outbound.EnsureSuccessAsync reads at most 4 KiB of a provider's error and keeps one message field from a JSON object (any other shape gives nothing), with addresses' queries and anything that looks like a key removed, in NodeException.Detail. Before an error is stored or shown, Avenvail removes the connection's actual secret values from the message and detail, in any letter case and in URL- or JSON-escaped form, and drops the detail entirely when it still contains a stretch of a key-like part of a secret. Set Outcome yourself on a NodeException (with Outbound.Classified) for other protocols.
The engine then decides: an Uncertain outcome after an outside change began, on a step that isn't keyed or safe, always stops for confirmation, whatever else applies. Otherwise a service's wait (Retry-After, as a delay or a date measured by Avenvail's clock) is honored without using an attempt, Rejected fails, and the rest retry when they could help. Every wait is at least Avenvail:Workflows:MinRetryDelay and a service's wait at most Avenvail:Workflows:MaxRetryAfter.
Nodes that use connections
[property: Setting("Connection"), Required, Connection(Notify.CapabilityId, Notify.CapabilityVersion)] ConnectionRef Connection
[Connection(capability, version) { Features = [...] }] filters the editor's picker and makes validation report connection_unavailable, connection_wrong_capability and connection_missing_feature. When another setting decides which capability the step uses, add [ConnectionWhen("other", value, capability, version)] once per alternative: the first whose setting has that value applies, otherwise [Connection] does, as AI classify asks for ai.decide@1 unless its method is language. The editor, validation and the step all use the capability the settings pick, so the executor asks only for that client. Override ConnectionFeaturesFor(setting, settings) when the settings decide a feature, as Send notification asks for attachments only when a file is attached. In the executor, await step.Connections.GetAsync<INotifyClient>(s.Connection, ct) returns the client after checking the owner, the capability the setting declares, and the features again; asking for another capability's client is an error.
Nodes that change something outside declare ExternalMutation = true, and nodes that send content out for processing declare a DataTransmitted other than None. Tests skip such nodes and return typed placeholders unless the user turns on the matching switch.
Outside changes are marked before the first request. For an ExternalMutation node, Avenvail records that the change began right before the first request a connection client or step.Http sends, whatever the method, so it can't be forgotten. Call step.BeginExternalAsync(ct, keyed: true) before that when the receiver is known to drop repeats of step.IdempotencyKey, so the step retries instead of asking. That guarantee is the receiver's: Avenvail sends the same key on every attempt but can't check what the receiver does with it, so claim it only from the connection's settings or the service's documentation. A node that changes something without an HTTP request must call BeginExternalAsync too. The built-in steps are covered by tests for both.
Testing
Tests can load a plugin directly with services.AddAvenvailPlugins(configuration, typeof(MyPlugin)) in AvenvailFactory.ExtraServices, and drive jobs with JobRunner.ClaimAsync and RunAsync. See backend/Avenvail.Tests/ProcessingTests.cs, and WorkflowTests.cs for nodes. Connection adapters are tested against provider documentation shapes kept as JSON fixtures: see backend/Avenvail.Tests/Fixtures/Ai/README.md and AiAdapterTests.cs.
AiLiveTests sends one real request and lists models when you point it at a provider; it's skipped otherwise. Set AVENVAIL_LIVE_AI_TYPE (openai-compatible, anthropic or gemini), AVENVAIL_LIVE_AI_MODEL, and as needed AVENVAIL_LIVE_AI_URL, AVENVAIL_LIVE_AI_KEY and AVENVAIL_LIVE_AI_MODE (native, jsonmode or prompted), then run dotnet test --filter AiLiveTests. It uses your key and costs a few hundred tokens. For a local check, ollama pull llama3.2 and set only the type and model.
ExamplePluginTests.cs is a whole third-party plugin in one file: its own capability, a connection type with a secret that provides it, and a node that uses it, registered and run through a published workflow without any change to Avenvail itself.