Skip to content

Plugin development

Add jobs, file processors, workflow steps and connection types to Tessra with a compiled-in plugin.

A plugin adds background work to Tessra: 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/Tessra.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. Tessra does not download or load plugins at runtime. External workers in other languages are planned separately (PROJECT.md §11).

Project layout

  1. Create a class library under backend/plugins/, for example backend/plugins/Tessra.Plugins.Example/, targeting the same .NET version as the server.
  2. Reference only the contracts: <ProjectReference Include="../../Tessra.Plugins/Tessra.Plugins.csproj" />. Pin every package to an exact version.
  3. Add a reference to your project in backend/Tessra.Api/Tessra.Api.csproj, add it to Tessra.slnx, and add its .csproj to the restore step in the Dockerfile.

Tessra finds every ITessraPlugin in the libraries that depend on Tessra.Plugins, so no registration code in the server is needed.

The plugin class

public sealed class ExamplePlugin : ITessraPlugin
{
    public string Id => "example.hello";

    public void Configure(ITessraPluginBuilder plugin)
    {
        plugin.AddJob<GreetJob>("example.hello.greet", maxAttempts: 3);
        plugin.OnEvent(TessraEvents.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 Tessra:Plugins:{Id} (in Docker, Tessra__Plugins__example.hello__Setting). plugin.Configuration is that section.
  • Tessra:Plugins:{Id}:Enabled=false turns a plugin off without rebuilding.
  • plugin.Services is 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 PermanentJobException when 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. OnEvent queues the job with the event's JSON payload, which includes fileId or folderId and ownerId. See TessraEvents for 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). Tessra 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);
    }
}
  • MimeType is detected by Tessra from the bytes, never taken from the client.
  • Derivatives are limited to image/webp, image/png and image/jpeg, 10 MiB each, one per kind. The thumbnail kind 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 Version whenever 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 IContentInspector as a singleton on plugin.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/Tessra.Plugins.Core; read them for complete examples. The full contract is in workflows.md.

public void Configure(ITessraPluginBuilder 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. Tessra derives the settings schema from it: Required, MaxLength, Range and RegularExpression from System.ComponentModel.DataAnnotations, and Setting (label, help), Bindable, Advanced, Multiline and TextFormat from the contracts. TextFormat(TextFormatAttribute.Markdown) marks text the step sends as Markdown so the editor offers formatting; set Connection and Feature to use Markdown only when the chosen connection provides that capability feature (Send notification uses Notify.Markdown). TextFormatAttribute.Json gives a monospaced editor. Nullable types may be null; constructor defaults are the defaults. Use FileRef, FolderRef and TagRef for library resources, ContentRef for a working file, and JsonElement for a value of any type (it tells a missing value, Undefined, from null).
  • 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 in Groups (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 its EmptySummary (None, Not shared) while closed. Advanced: true moves the section to the larger editor's Advanced tab. Columns: 2 lays 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: true hides 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. WorkflowKind offers 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. Tessra has tags, ai-model, ai-decision-model (a connection's default decision model), ai-image, ai-categories (a table of id, label, description items: ids are made from names and kept on rename; With can name a boolean shown as a checkbox below it, such as Allow no match), ai-values (a list of key, label, type, description, required items: keys are made from names and kept on rename, with a custom field picker and an example output) and structured-output; an editor Tessra 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's label, name or 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. MayBeEmpty marks outputs that can be null when the step succeeds; Example is an illustrative value.
    • Surface picks where the step is configured: Inline (the default) in the inspector only, or Expanded, 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. Use Expanded for steps with list editors or many sections. Both keeps the full form in the inspector and adds Configure step; prefer Expanded.
    • Description is 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. SaveFileNode and NotifyNode in backend/plugins/Tessra.Plugins.Core use most of them; AiNodeDescriptor in backend/plugins/Tessra.Plugins.Ai shows Surface, the column and optional-input groups, and [Summary].
  • Start new steps with other settings. InitialSettings are 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. Description is shown in the step browser under the name. Override Aliases with other names people may search for and Keywords with extra search terms; neither is shown. Tessra's own nodes keep these in frontend/i18n/locales/en.json (automationNodes.<id>.aliases and .keywords), which take precedence. Steps from plugins whose id doesn't start with tessra. 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 a string? shows the AI model picker, which reads the connection from the step's ai.chat@1 connection setting; null or empty means the connection's default model. The schema carries it as x-editor.
  • Raise Version when 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 declares RetrySafety.Unsafe.
  • Content nodes (NodeKind.Content) take a ContentRef setting (bindable) and return a new one. Read with step.Content.OpenReadAsync and write with step.Content.CreateAsync(name, write); never change the input, and return the input's reference when there is nothing to do. Tessra detects the new file's type and enforces the run's working limits. backend/plugins/Tessra.Plugins.Images/ImageNodes.cs has examples.
  • Return NodeResult.Next(outputs), NodeResult.ToPort(port, outputs) for nodes with several ports (override PortsFor), NodeResult.Wait(until) or NodeResult.Stop(reason). Outputs must be declared and are at most 64 KiB. When a test run gives an ExternalProcessing or ExternalMutation node placeholder outputs instead of running it, it continues on PlaceholderPort(settings), the first port by default; AI detect overrides it to take unsure. The editor labels the ports true, false, default, error, yes, no and unsure; 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(ITessraPluginBuilder 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 id that starts with the plugin id, such as example.hello.upper-names.
  • Tessra 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.
  • Tessra's own templates translate their name and description in frontend/i18n/locales/en.json (workflowTemplates.<id>.name and .description); others show the document's English text.
  • backend/plugins/Tessra.Plugins.Ai/Templates holds the built-in AI templates, and AiWorkflowTemplateTests runs 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/Tessra.Plugins.Discord and Tessra.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 Tessra.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_invalid before sending, saying what to change.
  • A capability can implement SendTestAsync for the user's Send test message. Testing a connection never calls it.

Connection types

public void Configure(ITessraPluginBuilder 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. EndpointOf is shown to the user as where data goes; never put a secret in it.
  • Settings have their own version. Raise SettingsVersion when stored settings need changing to bind, and turn older ones into current ones in MigrateSettings (secrets included, as plain values). Tessra migrates a connection the first time it's used and stores the result; when MigrateSettings returns 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 Listed to list both). Set Category to one of ConnectionCategories (ai-local, ai-hosted, ai-gateway, ai-custom, notifications, webhooks, other) or an id of your own, Logo to an icon name such as i-simple-icons-discord (only properly licensed logos; otherwise a Lucide icon), SetupUrl to where users get credentials, and Keywords for search. Presets take the same properties, plus Advanced (settings shown under Advanced for this preset, such as a hosted provider's fixed address), Primary (advanced settings shown with the main ones) and Required (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/test and, for AI types, /draft/models run 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's Timeout.
  • Origins. A connection sends only to OriginsOf(settings), by default its endpoint's origin, on every request, redirect and ReachAsync. Override it when a service spans several origins. An empty list sends nowhere; it never means "anywhere". A type that really may send anywhere sets AnyOrigin => 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 to MaxRequestBytes (default 256 KiB, at most 32 MiB); responses up to MaxResponseBytes (default 1 MiB, at most 16 MiB); the type's Timeout (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 declared Content-Length only lets Tessra refuse earlier.
  • Testing never changes anything outside. TestAsync must not send anything a receiver could act on; use connection.ReachAsync(address) to only open a connection. It follows the same origins, address and DNS rules, private-network setting and timeout as connection.Http. Report each part with the ConnectionChecks ids (reachable, auth, model, and ConnectionChecks.Feature(capability, feature), which gives feature:http@1/deduplicates). Mark capability probes Optional. Only required checks decide the result: an empty test, or a skipped required check, is unverified, never a pass. Return DetectedFeatures, 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 with connection_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 is Uncertain, 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 offers ai.decide@1 only 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 raise SettingsVersion when a change affects which capabilities existing connections offer.
  • Presets fill in settings for a known service. Override Presets with ConnectionPreset(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 Tessra relies on it.

AI chat

ai.chat@1 (AiChat in Tessra.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 CompleteAsync is one request. The request has the model, instructions, input parts (AiPart.Text, AiPart.Image), AiGeneration (max output tokens, optional temperature) and an optional AiOutputFormat with a JSON Schema and a mode: Native (the provider enforces the schema), JsonMode (the provider guarantees JSON) or Prompted (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), AiUsage with the provider's token counts (null when not reported), the model that answered and, behind a gateway, ServedBy when 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 with ai_model_unavailable, Rejected.
  • Model lists return AiModel(id) { Name, ContextTokens, MaxOutputTokens, Features }. Put a feature in Features only when the provider's list says so (AiFeatureSource.Provider); Infer returns guesses (Inferred). Tessra 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 ask IAiModels.FindAsync for the merged view.
  • A type without a model list (model-list not provided) still works: users type model names.

backend/plugins/Tessra.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 255 AiOptions) and AiQuestion.Score (2 to 10 ordered levels, lowest first), each with a unique name and instructions. Answers are AiAnswer.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) or AiAnswer.Refusal. Confidence and probabilities are null when the model doesn't report them.
  • One DecideAsync is one request. Never retry, fall back to another model, or turn on a gateway's own fallbacks. Reserve tokens with AiTokens.Estimate(body, input, 64) and settle with the provider's counts.
  • Wire formats. Two are in use, both in AiDecisionWire: OpenAI's (input parts and a questions array: OpenAI and Vercel AI Gateway at /decisions) and TypeSafe's System One (state and a questions object with noul, choice and score: TypeSafe and llama.cpp at /systemone, OpenRouter at /api/alpha/decisions, and Cloudflare at /ai/run/{model}, inside a result envelope). System One has no common way to send images: the OpenAI-compatible type offers images with it only for Cloudflare, which takes data URLs in images, and OpenRouter, which takes image_url parts in a state array.
  • Model lists. AiModel.Kind says what a listed model does (Language, Decision, Extraction or Other) when the provider says: Vercel's type, OpenRouter's endpoints (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 with ai_model_wrong_kind before sending when the list says the chosen model is of another kind.
  • AiRunner.StartDecisionAsync resolves the client, model, features and input limits for a node; AiDecisionSession.DecideAsync checks 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 kinds Text, Number, Integer, Boolean, Date and TextList. AiExtractionRequest.ReferenceDate anchors dates written without a year. Values are AiExtractedValue(name, value, confidence): the value in its kind's JSON form, or null when the content doesn't state it. Truncated says the provider stopped before reading every value.
  • One ExtractAsync is one request, with tokens reserved like decisions (256 for the answer).
  • Wire format. Cloudflare's Clairic format (state, a fields object, images as data URLs, reference_date), in AiExtractionWire: Cloudflare at /ai/run/{model} and OpenRouter at /api/alpha/extractions, which takes no boolean fields and images as an assets map (format, data_base64) whose names the state mentions. Values of the wrong type fail with provider_invalid_response.
  • AiRunner.StartExtractionAsync and AiExtractionSession.ExtractAsync work like their decision counterparts. AI extract asks for booleans through ConnectionFeaturesFor only when its method is extraction, 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), optional OcrPreprocessing (segmentation, scale, invert, threshold), the step's idempotency key, and an optional Timeout the 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 by Outbound. Reading is safe to repeat, so retryable failures are marked retryable.
  • The first-party tessra.ocr.worker type speaks the worker protocol described in The worker's API.

Lifetimes and ownership

  • The IConnectionType implementation is resolved from the step's (or the test's) scope.
  • CreateClient returns a new client for one step or one test. Tessra disposes it (IDisposable or IAsyncDisposable) and its HttpClient when the step ends. Never cache clients, HttpClients or settings between calls.
  • connection.Http shares Tessra's pooled connections; don't dispose it or change its defaults.
  • A client creates and disposes its own HttpRequestMessage and HttpResponseMessage. Request values from a node are read-only. For OutboundFile (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 JsonNode in 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 with Outbound.ReadJsonAsync or ReadTextAsync: they fail with response_too_large or provider_invalid_response rather 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:

OutcomeWhenCodes
NotSentTessra 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. Tessra 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
RejectedThe service established that it didn't act. Tessra 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
UncertainEverything 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, Tessra 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 Tessra's clock) is honored without using an attempt, Rejected fails, and the rest retry when they could help. Every wait is at least Tessra:Workflows:MinRetryDelay and a service's wait at most Tessra: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, Tessra 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: Tessra 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.AddTessraPlugins(configuration, typeof(MyPlugin)) in TessraFactory.ExtraServices, and drive jobs with JobRunner.ClaimAsync and RunAsync. See backend/Tessra.Tests/ProcessingTests.cs, and WorkflowTests.cs for nodes. Connection adapters are tested against provider documentation shapes kept as JSON fixtures: see backend/Tessra.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 TESSRA_LIVE_AI_TYPE (openai-compatible, anthropic or gemini), TESSRA_LIVE_AI_MODEL, and as needed TESSRA_LIVE_AI_URL, TESSRA_LIVE_AI_KEY and TESSRA_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 Tessra itself.