Task plugins
A task plugin is an entry in the device context menu. The user selects devices, chooses the entry, maybe fills a dialog, and OADM runs one task per device on the server. Each task has its own state, steps and log in the tasks pane, so one failing device never marks the others as failed.
The task plugin tutorial builds a complete one; this page explains each part.
How a run works
Section titled “How a run works”sequenceDiagram
actor User
participant Dialog as Dialog (client)
participant Server
participant Task as ExecuteAsync (one per device)
User->>Dialog: picks devices and the menu entry
Dialog->>Server: Run(plugin, devices, payload JSON)
Note over Server: checks RequiredPermissions,<br/>names the run with GetTaskName,<br/>writes one queued task per device
loop every device, at most 16 at once per plugin
Server->>Task: ExecuteAsync(ctx, device, payload, ct)
Task-->>Server: steps, progress, log
Server-->>User: tasks pane, live
end
Note over Server: Done, Done with warnings,<br/>Failed or Cancelled per device
- The payload is the dialog’s JSON (or null without a dialog). It lives in memory only, so it may carry a password. It is never stored or logged.
ExecuteAsyncreturns for Done, callsctx.ReportWarningfor Done with warnings, throws for Failed. The exception message is what the user reads.ctis cancelled when the user cancels the task. Pass it to every call.- Once a task ends, the server refreshes the device.
The members
Section titled “The members”| Member | Purpose |
|---|---|
Id |
Stable id, e.g. acme.upnp-name |
DisplayName |
The menu and toolbar name, at most 32 characters (TaskPluginNames.MaxDisplayNameLength), never ending in “…”, also for a task that opens a dialog. The server shortens a longer name with “…” and logs a warning |
IconKey |
An icon of the icon list, e.g. restart |
Group |
The context menu submenu: a TaskGroups constant (Applications, Maintenance, Network, Overlays, Security, Users, Video, General) or your own. Groups are always submenus, sorted by name, even with one task |
RequiresDialog |
The client opens your ITaskPluginDialog first |
ShowInToolbar |
Also a button in the Devices toolbar |
CanRun(device) |
Whether the entry is enabled for this device. Cached data only, no requests |
NotSupportedReason(device) |
Why CanRun is false; shown as the tooltip of the greyed entry |
GetTaskName(payload) |
The task’s name in the tasks pane |
ExecuteAsync(ctx, device, payload, ct) |
The work, once per device |
MaxParallelDevices |
Lowers how many devices run at once (Upgrade AXIS OS uses 4); null = the server setting (16, Settings page). It can only lower that setting: the server uses the smaller value |
ShowInMenus |
False: not in menus; a core plugin starts it from its page, see Tasks from a page |
IsDestructive |
SDK 0.15.0: true for a task that removes something as a whole (Remove all overlays): its entry sits last in its group, after a separator. Ask in its dialog before it runs |
Permissions, RequiredPermissions(payload) |
Finer rights for choices of different risk, see Permissions |
SiteSupport |
Whether this task works for devices at a site; null = the package’s siteSupport, see Sites |
Greyed entries say why
Section titled “Greyed entries say why”The context menu always lists the task. When it cannot run on the selection it is greyed out with the reason as tooltip. Say what is missing or what to do, without a final period. Put details about this one device last, in parentheses starting with “this device”: the host drops them when it sums up several devices (“Needs AXIS OS 11.11 or later: 3 of 5 selected devices”).
public bool CanRun(IDeviceInfo device) => device.Status is DeviceStatus.Ok or DeviceStatus.Unknown && device.Apis.Supports("user-management", "1.0");
public string? NotSupportedReason(IDeviceInfo device) => TaskSupportReasons.ForStatus(device) // "The device does not answer", "Site offline: ...", ... ?? TaskSupportReasons.NeedsApi("the user management API", device);NeedsApi tells the user to refresh a device whose API list was not read yet. For a real version check,
TaskSupportReasons.NeedsFirmware("11.11", device) says “Needs AXIS OS 11.11 or later (this device has 10.12.338)”.
TaskSupportReasons.ForSiteSupport(support, device) says “Not available for devices at a site” for a package with
siteSupport none; the host already greys such tasks.
NotSupportedReasonis called only whenCanRunis false, and reads cached data only.- Name an AXIS OS version only when your check really is a version check, or you verified the version the API first came in. Otherwise name the missing function (“Needs the Time API”).
- Null, an empty text or an exception shows “Not supported on this device”; the host logs the exception once.
- The toolbar button of the task is greyed with the same text.
Task names
Section titled “Task names”The tasks pane shows what each task does, not the menu name: “Add user joe”, “Set static IP 10.0.0.60”, “Upgrade
AXIS OS to 12.11.77”. At most 120 characters (TaskPluginNames.MaxTaskNameLength; the server shortens a longer name
with “…” and logs a warning), no secrets (names are stored and shown to every user). GetTaskName is called once per
run, so all devices of a run share the name: put everything the name needs (the application’s name, upgrade or
downgrade) into the payload. An empty name or an exception falls back to DisplayName.
Every device request and every wait is its own named step. The user sees exactly what the task is doing and where it failed.
ctx.PlanSteps("Check compatibility", "Upload AXIS OS to the device", "Wait for the device to come back");
await ctx.StepAsync("Check compatibility", async _ => (await ctx.Vapix.GetApiListAsync(ct)).Require("fwmgr", "1.0"));
using (var step = ctx.BeginStep("Upload AXIS OS to the device")){ // ... step.ReportProgress(45, ByteSize.Progress(sent, size)); // "37.0 of 82.4 MB"} // returns: Done; throws: Failed with the message
ctx.SkipStep("Factory default", "Keep settings"); // a step that does not applyPlanStepsshows the steps as Pending from the start.BeginStepmay add steps that were not planned.- A step ends with
Complete(detail),Warn(message)(the task ends Done with warnings),Skip(reason)orFail(message). Disposing it without an end means Done; an exception escaping it means Failed. - Beginning the next step ends the running one. Planned steps never reached end Skipped.
- When the task succeeds (Done or Done with warnings), OADM adds the final step Completed itself. A failed or cancelled task gets none: the failed step stays the current one. Never add it yourself.
- Names are short imperatives with the article: “Read users”, “Set the name”, “Wait for the device to come back”. No secrets in names or details.
- A size in a detail comes from
ByteSize(Oadm.Sdk.Formatting):ByteSize.Progress(sent, size)writes “37.0 of 82.4 MB”,ByteSize.Text(size)“82.4 MB”.
Progress comes from the steps by themselves. ctx.ReportProgress(percent, message) overrides it, and ctx.Log(level, message) writes to the task log in the task details. Never log a secret.
The dialog
Section titled “The dialog”The client part implements ITaskPluginDialog with the same PluginId:
public sealed class MyDialog : ITaskPluginDialog{ public string PluginId => "acme.my-task";
public async Task<string?> ShowAsync(ITaskDialogContext ctx, IReadOnlyList<IDeviceInfo> devices, Window owner) { // show a window, return the payload JSON, or null when the user cancelled }}A dialog that leaves out some of the selected devices (already up to date, no file for them) implements
ShowForDevicesAsync instead and returns a TaskDialogResult with the payload and the ids of the devices the task runs
on. The host calls ShowForDevicesAsync and ignores ids that were not selected; its default runs ShowAsync on every
selected device. The Upgrade AXIS OS dialog works this way. It needs SDK 0.5.0.
A task that only needs a yes has a dialog that shows MessageWindow.ConfirmAsync and returns "{}" (or null for
Cancel). The PKI tasks work this way.
ITaskDialogContext gives the dialog:
| Member | Use |
|---|---|
QueryAsync(deviceId, method, payload, ct) |
Read the device’s current state through your ITaskPluginQuery on the server |
UploadAsync(path, progress, ct) |
Upload a local file (an AXIS OS file, a package); progress gets the part sent, from 0.0 to 1.0; put the returned id into the payload |
Has(permission), HasAllDevices |
Hide choices the user’s role does not allow, or that only users with all devices may make |
AllDevices |
Every device, e.g. to copy settings from a device that is not selected |
CanRunTasks, RunTaskAsync(deviceIds, payload, progress, ct) |
Keep the dialog open: start the task from it and show each device’s step and result there (progress gets every task’s TaskRunState, the call returns once all ended); then return null from ShowAsync, so nothing runs twice. Without CanRunTasks (an older host) return the payload. A task deleted while it ran is reported as Cancelled with an empty message |
MyAxis |
SDK 0.9.0: the user’s MyAxis sign-in (IsSignedIn, Changed, SignInAsync(owner)), e.g. to ask for it before a task downloads from axis.com; null on an older host |
StartView |
SDK 0.7.0: the part of the dialog a core plugin page asked for (ICorePluginClientContext.RunTaskAsync(..., startView, ct)), a name your dialog defines; null or a name you do not know: open as usual |
Failed calls throw RpcException; show Status.Detail, or use ServerErrors.Message(ex).
Read-only queries
Section titled “Read-only queries”public sealed class MyTask : ITaskPlugin, ITaskPluginQuery{ public async Task<string?> QueryAsync(ITaskQueryContext ctx, ICallContext caller, IDeviceInfo device, string method, string? payloadJson, CancellationToken ct) => method switch { "users" => await ReadUsersAsync(ctx.Vapix, ct), _ => throw new ArgumentException("Unknown query " + method), };
// The host calls the overload above; the interface still needs this one. public Task<string?> QueryAsync(ITaskQueryContext ctx, IDeviceInfo device, string method, string? payloadJson, CancellationToken ct) => throw new NotSupportedException();}A query must never change the device. It runs on the server with the stored login and a 30 s limit. It reads devices
other than the queried one only through caller (the devices of the user who asks, see
Device groups); ctx.Devices lists the same devices and may be null on another host. An
address-in-use check asks ctx.ManagedAddressesAsync(addresses, ct).
Uploaded files
Section titled “Uploaded files”The dialog uploads with ctx.UploadAsync, the task opens the file by its id:
var file = await ctx.Files.FindAsync(payload.FileId, ct) ?? throw new InvalidOperationException("The uploaded file is gone. Choose it again. Nothing was changed.");await using var stream = await ctx.Files.OpenReadAsync(file.Id, ct);The server deletes uploads after a day; plugins never delete them.
Permissions
Section titled “Permissions”By default a task has one permission, task:<id>, which administrators give per role. A task whose choices differ in
risk declares finer ones and names what a run needs:
public IReadOnlyList<PermissionDefinition> Permissions { get; } =[ new("add", "Add users", "Create accounts on the devices."), new("remove", "Remove users", "Delete accounts on the devices.") { OperatorDefault = false, FullDeviceControl = true },];
public IReadOnlyList<string>? RequiredPermissions(string? payloadJson) => Read(payloadJson)?.Mode == "remove" ? ["remove"] : ["add"];The server refuses the run before any task starts when the role lacks a key; without an answer from
RequiredPermissions a run needs every declared key. The dialog hides what the role lacks with
ctx.Has(PermissionKeys.Task(PluginId, "remove")). Keys are stored in roles: never rename one. The rules for keys and
defaults are the same as for core plugins.
Files from axis.com
Section titled “Files from axis.com”ctx.AxisDownloads (SDK 0.9.0, IAxisDownloads) downloads a file from axis.com with the MyAxis sign-in of the user who
started the task. It is null for a task the system started and on an older host.
await using var file = await ctx.AxisDownloads!.DownloadAsync(uri, sha256, size, progress, ct);await using var stream = file.OpenRead();The host downloads, checks the size and the SHA-256 and keeps the file for the other devices of the run. Your plugin
never gets the session. A failure is an AxisDownloadException with a text for the user. Upgrade AXIS OS uses it. In
tests: FakeAxisDownloads.
Tasks for AI agents
Section titled “Tasks for AI agents”An AI agent runs a task like a user, in two calls: a preview that checks the settings and shows what would happen, then a run of that preview (SDK 0.13.0). A task is offered to agents only when it describes its settings:
public Type? PayloadType => typeof(SetNamePayload); // the record the dialog sendspublic JsonSerializerOptions? PayloadJsonOptions => SetNamePayload.Json; // the options you read it with
public IReadOnlyList<PayloadError> ValidatePayload(string? payloadJson, ICallContext caller) => SetNamePayload.Problems(payloadJson); // the dialog's rules: ("name", "Enter a name.")
public Task<TaskPlan> PlanAsync(string? payloadJson, IReadOnlyList<IDeviceInfo> devices, CancellationToken ct) => Task.FromResult(new TaskPlan([.. devices.Select(d => CanRun(d) ? new TaskPlanDevice(d.Id) : new TaskPlanDevice(d.Id, "Needs AXIS OS 11.11 or later."))]));- The host writes the JSON Schema of
PayloadTypefor the agent:[Description]explains a property,[MaxLength],[Length]and[Range]bound it, enums go by name (give them a string converter). Use[property: ...]on a positional record. A task without settings returns an empty record. ValidatePayloadholds the dialog’s rules, field by field (the payload’s JSON names, dots for nested fields). The server calls it before every run, also for the client: an invalid payload starts no task. Use it in your dialog too.PlanAsyncsays per device whether the run changes it or why not, from the cached data only (no device request). The default usesCanRunandNotSupportedReason. The overload withIUploadedFilesmay read the uploads: name them inTaskPlan.Files, answer a problem only they show inTaskPlan.Errors(per field, likeValidatePayload) and say what the run does inTaskPlan.Details(plain lines, such as the package each group of devices gets).- Mark a password or key with
[Secret]([Secret(Label = "passphrase")]names what the person is asked for). The host leaves it out of the agent’s schema: a secret never goes through an AI model. The person types it into their own shell or the assistant’s card, the host checks it at once with yourValidatePayload(the error at that field) and puts it into the run’s payload at its field. YourValidatePayloadholds the rule for the value too; while the person has not entered it, the preview ignores its errors there. SecretsOf(payloadJson)answers the secrets one run needs: by default the top-level[Secret]properties. Override it when it depends on the payload (a removal needs no password) or when a secret sits in a list, with the field asValidatePayloadnames it:
public IReadOnlyList<TaskSecret> SecretsOf(string? payloadJson) => [.. Settings(payloadJson).Select((s, i) => (s, i)).Where(p => p.s.IsPassword) .Select(p => new TaskSecret($"setting_{p.i}", "password for " + p.s.Name, $"settings[{p.i}].value"))];- A task only your page starts (
ShowInMenusfalse, noPermissions) is offered to agents whenPagePermissionsnames the keys of your core plugin’s permissions one run needs (["format"]). Return null for the page’s own payload to keep it on the page.
A file as the result
Section titled “A file as the result”A task that makes a file (an exported configuration, a report) keeps it for the user who started it (SDK 0.13.0):
using var content = new MemoryStream(Encoding.UTF8.GetBytes(export));await ctx.SaveResultFileAsync("config-" + device.Serial + ".txt", "text/plain", content, ct);One file per task (a second call replaces it), at most 64 MB, kept a day. The user fetches it with the task: an agent
gets a one-time download link, the assistant shows a card with Save. Never a private key or a secret the user did not ask
for. Older hosts and tasks the system started throw NotSupportedException.
Device safety
Section titled “Device safety”These rules hold for every plugin that changes a device:
- Compatibility first.
CanRunchecks the cacheddevice.Apis.ExecuteAsyncchecks a freshGetApiListAsync()withRequire(...)before the first write. A device that lacks the API fails with “Nothing was changed”. - Validate before writing. Check every input (addresses, masks, passwords, files) before the first request.
Use the device’s own dry run or validation methods when the API has one. Check a new address on the device’s route
with
ctx.Network(IDeviceNetwork:Reaches, thenPingAsyncandProbeTcpAsyncto see whether it is in use), never with your ownPingor socket; see Sites. - No lock-out. Never remove or demote
device.CredentialUserName. Write the setting that could cut the connection (address, HTTPS, the account’s password) last, and warn in the dialog when a change may make the device unreachable. - Secrets. Payloads stay in memory. Never log, store or name a password.
- Queries are read-only.
- Hardware tests that write are opt-in only and run only when the developer asks for them, against a test device. See Testing.
Say “Nothing was changed” in an error when nothing was. The user then knows the device is as it was.
Reference
Section titled “Reference”Every member with its signature in the SDK reference: ITaskPlugin, ITaskExecutionContext, ITaskStep, TaskStepExtensions, TaskSupportReasons, ITaskPluginQuery, IUploadedFiles, ITaskPluginDialog, ITaskDialogContext, PermissionDefinition, PayloadError, TaskPlan, SecretAttribute.