Manage Agent Automations

Create an automation task with a fixed instruction and Cron schedule for an agent, update the schedule and activate triggers, inspect historical or manual runs, and disable or archive the task when finished.

Task flow

Create a disabled automation task and read back
                      │
                      ▼
Update the Cron schedule and set status to active
                      │
                      ▼
List run history or trigger a manual run
                      │
                      ▼
Disable triggers or archive the task

Prerequisites

  1. Complete the endpoint, personal access token, and workspace setup in Use the SDK.

  2. Obtain the target agent ID (AGENT_ID) and source workspace ID (AGENT_WORKSPACE_ID) via Discover and Select Agents.

  3. Choose an execution model identifier (AGENT_MODEL), which you can query via Inspect Model Backends and Endpoints or service.resource_get("llm", "/models", sdk.with_query_param("type", "chat")).

  4. Prepare a unique task ID (AUTOMATION_TASK_ID), task name (AUTOMATION_NAME), fixed instruction (AUTOMATION_INSTRUCTION), and Cron expression (CRON_EXPRESSION). Create the task with status disabled first and enable it after reviewing the configuration; active schedules invoke models and authorized tools automatically.

Create and read a task

Submit the task definition with a client-assigned id to agent-automation-tasks. The server validates the Cron expression on creation even when the initial status is disabled.

import os

import moi_product_sdk as sdk

client = sdk.new_with_personal_access_token(
    os.environ["PRODUCT_API_BASE_URL"],
    os.environ["PRODUCT_API_KEY"],
)
workspace_id = os.environ["WORKSPACE_ID"]
service = client.workspace(workspace_id).agents()
task_id = os.environ["AUTOMATION_TASK_ID"]

body = {
    "id": task_id,
    "name": os.environ["AUTOMATION_NAME"],
    "agent_id": os.environ["AGENT_ID"],
    "agent_workspace_id": os.environ.get("AGENT_WORKSPACE_ID", workspace_id),
    "model": os.environ["AGENT_MODEL"],
    "instruction_text": os.environ["AUTOMATION_INSTRUCTION"],
    "trigger": {
        "mode": "cron",
        "cron_expression": os.environ["CRON_EXPRESSION"],
    },
    "status": "disabled",
}
created = service.resource_post("agent-automation-tasks", "", body)
if created.get("id") != task_id:
    raise RuntimeError("Created task identity does not match")

saved = service.resource_get("agent-automation-tasks", "/" + task_id)
print("Task:", saved["id"], "Status:", saved["status"], "Version:", saved["version"])
print("Trigger:", saved["trigger"], "Next trigger:", saved.get("next_trigger_at"))
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	sdk "github.com/matrixorigin/matrixflow/sdk/go-sdk"
)

func mustObject(data *sdk.ProductData, err error) map[string]any {
	if err != nil {
		log.Fatal(err)
	}
	value, ok := data.Value.(map[string]any)
	if !ok {
		log.Fatal("expected an object response")
	}
	return value
}

func main() {
	ctx := context.Background()
	client, err := sdk.NewWithPersonalAccessToken(
		os.Getenv("PRODUCT_API_BASE_URL"),
		os.Getenv("PRODUCT_API_KEY"),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	workspaceID := os.Getenv("WORKSPACE_ID")
	workspace, err := client.Workspace(workspaceID)
	if err != nil {
		log.Fatal(err)
	}
	service := workspace.Agents()
	taskID := os.Getenv("AUTOMATION_TASK_ID")
	agentWorkspaceID := os.Getenv("AGENT_WORKSPACE_ID")
	if agentWorkspaceID == "" {
		agentWorkspaceID = workspaceID
	}

	body := map[string]any{
		"id":                 taskID,
		"name":               os.Getenv("AUTOMATION_NAME"),
		"agent_id":           os.Getenv("AGENT_ID"),
		"agent_workspace_id": agentWorkspaceID,
		"model":              os.Getenv("AGENT_MODEL"),
		"instruction_text":   os.Getenv("AUTOMATION_INSTRUCTION"),
		"trigger": map[string]any{
			"mode":            "cron",
			"cron_expression": os.Getenv("CRON_EXPRESSION"),
		},
		"status": "disabled",
	}
	created := mustObject(service.ResourcePost(ctx, "agent-automation-tasks", "", body))
	if created["id"] != taskID {
		log.Fatal("created task identity does not match")
	}

	saved := mustObject(service.ResourceGet(ctx, "agent-automation-tasks", "/"+taskID))
	fmt.Println("Task:", saved["id"], "Status:", saved["status"], "Version:", saved["version"])
	fmt.Println("Trigger:", saved["trigger"], "Next trigger:", saved["next_trigger_at"])
}

Record the returned id as the identifier for subsequent updates and run queries. If a creation call encounters an uncertain network error, read back the task by task_id first before retrying.

Update the schedule and enable

Set the updated Cron expression (NEW_CRON_EXPRESSION, such as TZ=UTC 0 9 * * * with an explicit time zone). Continue from the previous example by retaining the editable trigger fields (mode, cron_expression, result_mode, input_schema, config), patching status to active, and reading back next_trigger_at:

editable_keys = ("mode", "cron_expression", "result_mode", "input_schema", "config")
trigger = {key: value for key, value in saved["trigger"].items() if key in editable_keys}
trigger["cron_expression"] = os.environ["NEW_CRON_EXPRESSION"]

service.resource_patch(
    "agent-automation-tasks",
    "/" + task_id,
    {"trigger": trigger, "status": "active"},
)
saved = service.resource_get("agent-automation-tasks", "/" + task_id)
print(saved["status"], saved["version"], saved["trigger"], saved.get("next_trigger_at"))
trigger := map[string]any{}
previous, _ := saved["trigger"].(map[string]any)
for _, key := range []string{"mode", "cron_expression", "result_mode", "input_schema", "config"} {
	if value, exists := previous[key]; exists {
		trigger[key] = value
	}
}
trigger["cron_expression"] = os.Getenv("NEW_CRON_EXPRESSION")

mustObject(service.ResourcePatch(
	ctx,
	"agent-automation-tasks",
	"/"+taskID,
	map[string]any{"trigger": trigger, "status": "active"},
))
saved = mustObject(service.ResourceGet(ctx, "agent-automation-tasks", "/"+taskID))
fmt.Println(saved["status"], saved["version"], saved["trigger"], saved["next_trigger_at"])

Query run history

Use agent-automation-runs to list runs across the workspace, or agent-automation-tasks/<task_id>/runs to list runs for a specific task. Both endpoints accept status, created_from, and created_to (RFC 3339 timestamps, inclusive start and exclusive end), along with limit (default 50, max 200) and offset.

workspace_page = service.resource_get(
    "agent-automation-runs",
    "",
    sdk.with_query_param("status", "succeeded"),
    sdk.with_query_param("limit", "50"),
    sdk.with_query_param("offset", "0"),
)
print("Workspace succeeded runs:", workspace_page["total"])

offset = 0
while True:
    page = service.resource_get(
        "agent-automation-tasks",
        "/" + task_id + "/runs",
        sdk.with_query_param("limit", "50"),
        sdk.with_query_param("offset", str(offset)),
    )
    for item in page["items"]:
        print(item["id"], item["status"], item["automation_task_version"])
    next_offset = page["offset"] + page["limit"]
    if not page["items"] or next_offset >= page["total"]:
        break
    offset = next_offset
workspacePage := mustObject(service.ResourceGet(
	ctx,
	"agent-automation-runs",
	"",
	sdk.WithQueryParam("status", "succeeded"),
	sdk.WithQueryParam("limit", "50"),
	sdk.WithQueryParam("offset", "0"),
))
fmt.Println("Workspace succeeded runs:", workspacePage["total"])

for offset := 0; ; {
	page := mustObject(service.ResourceGet(
		ctx,
		"agent-automation-tasks",
		"/"+taskID+"/runs",
		sdk.WithQueryParam("limit", "50"),
		sdk.WithQueryParam("offset", fmt.Sprint(offset)),
	))
	items, _ := page["items"].([]any)
	for _, raw := range items {
		item, _ := raw.(map[string]any)
		fmt.Println(item["id"], item["status"], item["automation_task_version"])
	}
	nextOffset := int(page["offset"].(float64)) + int(page["limit"].(float64))
	if len(items) == 0 || nextOffset >= int(page["total"].(float64)) {
		break
	}
	offset = nextOffset
}

Trigger a manual run and inspect results

Send a POST request to /<task_id>/runs on an active task to start an immediate run. Save the returned run_id and query agent-automation-runs/<run_id>, /events, and /result to inspect status, paged events, and terminal output:

run = service.resource_post("agent-automation-tasks", "/" + task_id + "/runs", {"payload": {}})
run_id = run["id"]
print("Run:", run_id, "Initial state:", run["status"])

current = service.resource_get("agent-automation-runs", "/" + run_id)
events = service.resource_get(
    "agent-automation-runs",
    "/" + run_id + "/events",
    sdk.with_query_param("limit", "20"),
    sdk.with_query_param("offset", "0"),
)
print("State:", current["status"], "Events total:", events.get("total"))

if current["status"] in ("succeeded", "failed", "canceled", "expired"):
    result = service.resource_get("agent-automation-runs", "/" + run_id + "/result")
    print("Result:", result)
run := mustObject(service.ResourcePost(
	ctx,
	"agent-automation-tasks",
	"/"+taskID+"/runs",
	map[string]any{"payload": map[string]any{}},
))
runID, _ := run["id"].(string)
fmt.Println("Run:", runID, "Initial state:", run["status"])

current := mustObject(service.ResourceGet(ctx, "agent-automation-runs", "/"+runID))
events := mustObject(service.ResourceGet(
	ctx,
	"agent-automation-runs",
	"/"+runID+"/events",
	sdk.WithQueryParam("limit", "20"),
	sdk.WithQueryParam("offset", "0"),
))
fmt.Println("State:", current["status"], "Events total:", events["total"])

switch current["status"] {
case "succeeded", "failed", "canceled", "expired":
	result := mustObject(service.ResourceGet(ctx, "agent-automation-runs", "/"+runID+"/result"))
	fmt.Println("Result:", result)
}

While a run has not yet reached a terminal state (succeeded, failed, canceled, expired), continue polling the same run_id and paging through /events. Once terminal, check /result for structured output validation details, errors, and generated artifacts.

Disable and archive a task

To pause future scheduled triggers, patch status to disabled and read back the task:

service.resource_patch("agent-automation-tasks", "/" + task_id, {"status": "disabled"})
saved = service.resource_get("agent-automation-tasks", "/" + task_id)
print(saved["status"], saved.get("next_trigger_at"))
mustObject(service.ResourcePatch(ctx, "agent-automation-tasks", "/"+taskID, map[string]any{"status": "disabled"}))
saved = mustObject(service.ResourceGet(ctx, "agent-automation-tasks", "/"+taskID))
fmt.Println(saved["status"], saved["next_trigger_at"])

When the task is permanently retired, call resource_delete (ResourceDelete in Go) to archive it. Archiving preserves the task definition and historical run records while marking the task archived:

service.resource_delete("agent-automation-tasks", "/" + task_id)
saved = service.resource_get("agent-automation-tasks", "/" + task_id)
print("Archived task:", saved["id"], saved["status"])
mustObject(service.ResourceDelete(ctx, "agent-automation-tasks", "/"+taskID))
saved = mustObject(service.ResourceGet(ctx, "agent-automation-tasks", "/"+taskID))
fmt.Println("Archived task:", saved["id"], saved["status"])

Limitations and notes

  • The workspace run endpoint agent-automation-runs filters at the workspace level; to list runs for one task, query agent-automation-tasks/<task_id>/runs. When new runs start concurrently during offset pagination, deduplicate entries by run id.

  • Disabling or archiving a task stops future scheduled triggers, while runs already in flight continue under their own run_id until reaching a terminal state. Creating a new task with the same display name later requires a new task ID.

Next steps

Last updated on