Scheduled Invocation
Run agents and swarms on cron, interval, or one-shot schedules with built-in retries, jitter, and lifecycle controls.
#Scheduled invocation
Choose between durable remote triggers and an in-process local scheduler. Remote mode is the default. The same builders declare event-driven triggers, so this page also lists every trigger source on Agent and Swarm, explains how to serve an agent, and describes the objects registration returns. The scheduling reference has the full signatures and defaults.
#Durable remote schedule
from datetime import timedelta
from maivn import Agent
agent = Agent(name="reporter", agent_id="agent-123", version=2, api_key="...")
daily = (
agent.cron("0 9 * * MON-FRI", tz="America/New_York")
.key("weekday-report")
.invoke("Prepare the weekday report")
)
hourly = (
agent.interval(timedelta(hours=1))
.key("hourly-health")
.invoke("Check service health")
)Registration is idempotent. A trigger's identity is derived from the target agent ID and the .key(...), so the version is not part of it: registering again with a new version or prompt updates the same trigger. stable_trigger_ids(agent_id, key) returns the (scenario_id, trigger_id) pair a registration will use. Registering calls the server, so these examples need a deployed agent, valid credentials, and network access.
Both cron(..., name="Morning report") and interval(..., name="Hourly check") accept a display name in durable mode. You can change it later with .named(...). .key(...) stays the stable registration identity.
#Remote schedule rules
- Cron syntax: five fields (minute, hour, day of month, month, day of week). Names such as
MON-FRIandJANwork, and so do@hourly,@daily,@midnight,@weekly,@monthly,@yearlyand@annually. There is no seconds field and no@every. When both day of month and day of week are restricted, a day matching either one fires. - Time zones: schedules run in UTC unless
tzis an IANA zone name. A local time that does not exist during a daylight-saving jump is skipped. - Intervals: whole seconds, from 1 to 31,536,000.
- Jitter: each remote trigger gets one fixed offset, chosen per trigger within plus or minus
jitterseconds. The default is 60, so a0 9 * * *trigger can fire up to a minute either side of 09:00. Passjitter=0for exact times. The maximum is 3600. AJitterSpecis accepted, and its largest bound is used. - Other options:
nameandjitterare the only schedule options in remote mode.misfire,retry,max_runsand the rest raiseValueError.
#Trigger identity
All durable trigger helpers inherit their owning agent's identity, including on_webhook, on_email, on_connection, on_manual, and the other event sources. By default, the agent ID is its name and the version is 1. Set agent_id and version once on the agent for a custom identity, as above. agent.serving(), agent.serve(), and maivn serve use those defaults too. Trigger declarations capture this identity when created. Per-session serving overrides do not change existing trigger targets.
Use .target("another-agent", version=3) to override a trigger's target. A standalone TriggerInvocationBuilder still requires .target(...) because it has no owning agent. Declaring a trigger does not register it. .invoke(...) or .ainvoke(...) performs registration. Give every trigger a .key(...): Studio lists a declaration without one as unfinished, and neither serves nor registers it until you add a key.
For example, an inbound webhook uses the same owner without repeating its ID:
incoming = (
agent.on_webhook("vault://project-webhook-secret:YOUR_PROJECT_ID:reporter")
.key("incoming-report")
.invoke("Process the incoming webhook event")
)The signing secret must already exist at the given vault reference. A secret_ref that does not start with vault:// is refused. Create it as described in Webhook signing secrets.
#Webhook signing secrets
An on_webhook trigger verifies each request with a signing secret the platform holds for your project. A project owner or admin creates one in either place:
- Developer Portal: open the project, then Connections → Webhook signing secrets. Enter a name and choose Create secret.
- Terminal:
maivn connections webhook-secret --base-url https://api.maivn.io --project-id YOUR_PROJECT_ID --email YOU@example.com --name reporter --secret-file ~/.maivn-private/reporter.json. It signs you in with a private password prompt, likemaivn connections create, and writes the value to a new owner-private file.
A name is 1 to 64 lowercase letters, digits, hyphens or underscores, and a project holds up to 50. Both places show the value once, with the reference to pass to on_webhook: vault://project-webhook-secret:{project_id}:{name}. Give the value only to the service that sends the webhooks. The Portal and the API list names and references, never values.
The sender posts JSON to /v1/triggers/{trigger_id}/invoke on the platform's origin, with two headers:
X-Webhook-Timestamp: the current Unix time in seconds. Requests more than five minutes old or ahead are refused.X-Webhook-Signature:v1=followed by the hex HMAC-SHA256 of{timestamp}.{raw body}under the secret.
A body event_id names the event, and a repeat of the same event_id within the trigger's dedupe window starts no second run. trigger.trigger_id gives the ID after invoke(). maivn connections send-test --trigger-id sends a correctly signed sample.
To rotate, create the same name again (or choose Rotate in the Portal). The new value replaces the old one at once, so requests signed with the old value are refused until the sender switches. The reference does not change, so registered triggers keep working without being registered again.
agent.declared_triggers lists every builder declared on the agent, in order, whether or not a client exists. A tool can read them without registering anything. A builder's declaration() returns what has been declared so far, and declaration_payload() returns the exact body invoke() would send. Neither one contacts the server.
#The attached trigger
invoke() returns a Trigger. It has scenario_id, trigger_id and status properties, and each method below also has an a-prefixed async version (ahistory, apause, and so on). All of them call the server.
TriggerFireReceipt is a frozen dataclass with fire_id, trigger_id and session_id.
#Trigger sources
Every source method returns a TriggerInvocationBuilder. Each source is a frozen model you can also pass to agent.on(source). TriggerSource is the union of them.
on_record_change also accepts a memory record kind in place of a table. That form is kept for older code, and on_memory_change is the call to use for memory records. Discord events use on_connection with an event type such as discord.interaction.command; see Discord triggers.
Every source except schedules, manual fires and webhooks is admitted through a rollout flag that the platform operator sets per organization or project, and the reference seed data ships each one switched off. If the operator has not enabled a source for your project, the platform does not admit its fires, and SLA and reply calls fail with source_not_enabled.
#Write the prompt
A trigger is the agent called by an event instead of a person, so something has to stand in for what the person would have typed. Pass it to invoke(...), or declare it earlier with .asking(...). A plain string and a list of strings both work. Registering with neither raises ValueError.
Templates read the event with {{event}} for the whole payload, or {{event.some.path}} for one field:
alert = (
agent.on_manual()
.key("alert")
.asking("Summarize this alert: {{event.message}}")
)Rendering is a single literal pass. A path that does not exist stays in the text unchanged, strings go in as they are, and any other value becomes sorted JSON. Field content is never rendered as a template, so event text cannot add placeholders. Treat everything in the event as untrusted input.
#Choose where the result goes
display_in_app() is the default. to_connection(connection_id) sends the completed result to a saved output connection in the same project, and the declaration holds only the connection ID. The helpers to_slack, to_discord, reply_by_email, comment_on_github and to_webhook name a destination by reference instead. The last output helper you call wins.
emit(event_type) is accepted, but the platform does not currently deliver an event-emission output anywhere.
#Trigger options
with_options(...) sets the guard options for a trigger. Anything you omit keeps its default. Out-of-range values raise a Pydantic ValidationError.
The RetryPolicy and TriggerOptions models are exported from maivn if you prefer to build them yourself. where(jsonpath) adds a JSONPath admission filter. JSONPath is the only filter language.
#Events from the platform
These three sources react to things the platform records in your project.
done = agent.on_event("session.completed").key("after-run")
new_skill = agent.on_memory_change("skill", operation="inserted").key("skill-added")
upload = agent.on_storage("source", operation="inserted").key("source-uploaded")on_eventtakessession.completedortool.dispatch_completed. Addorigin_trigger_idto react only to runs started by one trigger. The payload is the original event plus a_maivn_source_eventobject withevent_id,type,session_id,trigger_id,root_event_idandtrigger_chain_depth. Chains are bounded bydepth_capandfanout_cap.on_memory_changetakes a record kind ofskill,insight,resource_pointerorthread_message, and an operation ofinsertedorupdated.thread_messagewithinsertedfires on each new thread message.on_storagewatches the privatememory-resourcesbucket. The object kind issourceorartifact, and the operation isinsertedorupdated.
#SLA timers (on_sla)
An SLA trigger watches a named condition for each business item you arm.
sla = (
agent.on_sla("invoice_paid", fire_when="condition_missing", deadline_seconds=3600)
.key("invoice-overdue")
.asking("No payment arrived in time: {{event}}")
)
trigger = sla.invoke()
trigger.arm("invoice-1042", payload={"invoice_id": "1042"})
trigger.satisfy("invoice-1042", evidence={"method": "card"})
receipt = trigger.timer("invoice-1042")
print(receipt.deadline_at, receipt.condition_met_at, receipt.process_outcome)conditionis a lowercase identifier such asinvoice_paid.deadline_secondsruns from the moment you arm the instance, up to 31,536,000, and the server clock sets the start.fire_when="condition_missing"fires when the deadline passes without an on-timesatisfy.fire_when="condition_met"fires as soon assatisfyarrives before the deadline, and a timer that is never satisfied in time expires without a fire.instance_keynames one item. It starts with a letter or digit and holds up to 200 letters, digits,.,_,:or-. Arming the same key again returns the existing timer, so a retry is safe when it repeats the same payload.- Payloads and evidence are JSON objects, and each request must stay under 262,144 bytes.
SLATimerReceiptcarriestimer_id,instance_key,condition,fire_when,started_at,deadline_at,condition_met_at,processed_at,process_outcomeandinserted. A processed timer means the platform acted on it. It does not mean the agent run succeeded.
#Conversation replies (on_reply)
support = (
agent.on_reply()
.key("support-thread")
.asking("Continue the conversation: {{event}}")
)
trigger = support.invoke()
receipt = trigger.reply(
"Thanks, that fixed it.",
conversation_key="ticket-88",
reply_id="msg-3",
)
print(receipt.sequence, receipt.inserted)conversation_key (up to 500 characters) groups replies, and reply_id (up to 200) is your retry identity. Sending the same reply_id again does not add a second message, and inserted is false. content can run to 65,536 characters. The receipt means the reply was committed. Admission and the run follow separately. ConversationReplyReceipt carries event_id, conversation_id, reply_id, sequence, received_at and inserted.
SLA and reply calls fail unless the trigger is enabled and was registered with the matching source. The error codes are source_kind_mismatch, trigger_not_enabled, source_not_enabled and source_instance_unavailable (all 409), producer_replay_mismatch (409, a retry that changed the payload), not_found (404), invalid_producer_input (422) and producer_unavailable (503).
#Fire from another run (on_tool_fire)
on_tool_fire() declares a trigger that a running agent can fire through the server-side fire_trigger system tool. The tool takes a trigger_id and a payload of up to 65,536 bytes, and it reaches only triggers in the same project. The deployment must enable the tool, and it is off by default. A run that sets an explicit system-tool policy has to allow fire_trigger. Each run can request at most fire_budget fires, and depth_cap and fanout_cap apply to the chain.
#Serve an agent
The platform watches your triggers, but the agent runs in your process. A serving process announces itself, keeps announcing, and on the default worker transport claims the fires your triggers produce and runs them against the agent.
import asyncio
from maivn import Agent, ServingEvent
agent = Agent(name="reporter", agent_id="agent-123", version=2, api_key="...")
def show(event: ServingEvent) -> None:
print(event.kind, event.agent_id, event.version, event.detail)
asyncio.run(agent.serve(project_id="YOUR_PROJECT_ID", listener=show))maivn serve app.py:agent --project-id YOUR_PROJECT_ID does the same from a terminal. See Serve your agent.
serve(...)returns after a clean stop, and Ctrl-C is one. A fire the process took but did not finish is handed back, not lost.serving(...)takes the same keyword arguments and returns aServingSessionwithout announcing.await session.run()announces, then heartbeats while it claims work.async with session:only announces on entry and stops on exit. Session methods areannounce(),heartbeat()(returns whether the beat landed),stop()andrun(), withproject_id,instance_id,process_id,servedandmanifestproperties.- Only
Agentcan serve.Swarmdeclares triggers but has noserve. project_idcomes from the argument orMAIVN_PROJECT_ID. Without either, serving raisesConfigurationError.transport="webhook"is for a process the platform reaches at a URL. It requiresendpoint_urland claims no work. Theworkertransport refuses anendpoint_url.- The platform learns your agent ID, version, name, tool names, SDK version and a fingerprint of the definition. Instructions, model settings and tool schemas stay on your machine.
- A beat goes out every 25 seconds by default (
heartbeat_interval_seconds). The platform forgets a process it has not heard from in 90 seconds. A transient failure costs one beat, and a refused key (401 or 403) ends the run. If the platform has forgotten the process, the next beat announces it again.
ServingListener is any Callable[[ServingEvent], None]. A ServingEvent has kind, agent_id, version, instance_id, process_id and detail. The kind is announced, re_announced, heartbeat, retrying, unreachable or stopped. Events never carry the API key or any part of the definition.
#Local scheduler
Pass mode="local" explicitly when the current Python process should own the schedule:
from maivn import Agent
agent = Agent(name="local-report", api_key="...")
job = agent.cron("0 9 * * *", mode="local").invoke("Prepare the report")
job.on_fire(lambda receipt: print(receipt.fired_at))
job.on_error(lambda receipt: print(receipt.error))Keep the ScheduledJob alive and shut it down using its lifecycle methods. Local schedules do not survive process restarts.
#Local lifetime and one-shot jobs
Local .invoke(...) starts the job immediately. The scheduler uses background threads, so a short script must keep its process alive until shutdown:
import time
try:
while not job.is_done:
time.sleep(1)
except KeyboardInterrupt:
pass
finally:
job.stop(drain=True, timeout=30)agent.at(when).invoke(...) is a local one-shot job. Unlike cron and interval, at has no remote-mode option. Use a timezone-aware datetime, since a naive one is read as UTC. For local retries pass Retry(...). Durable remote retries use the trigger builder's .with_options(...) instead.
#Local options
These keyword arguments go to cron, interval and at in local mode.
- Misfire:
'skip'records the fire asskipped_misfire.'fire_now'and'coalesce'both run it, and'coalesce'also stores the delay in the record's metadata. - Overlap:
'skip'recordsskipped_overlap.'queue'makes the new fire wait for a free slot.'replace'asks the active run to stop by settingcancellation_requestedin its metadata, cancels any older queued fire (replaced_bynames the newer one), and queues the new fire. Your code stops only if it checks that flag, so'replace'does not interrupt a call in progress. - Jitter: each fire draws an offset from
JitterSpec(min, max, distribution, sigma, align_to, skip_if_overruns_next, seed). Distributions are'uniform'(default),'normal'(centered, withsigmadefaulting to a sixth of the range) and'triangular'. Positive offsets delay the run. Negative offsets cannot start it early, so they run it at the scheduled time. By default a fire whose jittered time reaches the next scheduled time is recorded asskipped_jitter.JitterSpec.symmetric(amount)builds a plus-or-minus range. - Retry:
Retry(max_attempts=1, backoff='constant', base=5s, factor=2.0, max_delay=10 minutes, retry_on=(Exception,)). Backoff is'constant','linear'or'exponential'. Retries stay inside one fire.
#Inspect and control a job
list_jobs() returns the live local jobs in this process, and stop_all_jobs() stops them. A RunRecord has scheduled_at, fire_id, fired_at, finished_at, jitter_offset, attempt, status, result, error, metadata and a duration property. status is pending, running, succeeded, failed, skipped_misfire, skipped_jitter, skipped_overlap or cancelled.
For immediately started server work that survives a client disconnect, see Bounded hosted jobs. Jobs have separate explicit bounds and deployment enablement.