Agent assets: Create and use agents

An Agent asset is a durable, event-driven automation in Play. It consists of:

  • Definition: the human-readable description of what the agent should do and when it should run.

  • TypeScript implementation: executable code generated from the definition, or entered/edited directly.

  • Trigger registrations: the schedules, events, intents, or API endpoints that start the agent.

  • Run history: the output, console/log messages, and errors produced by each invocation.

Use an Agent asset when the automation must remain available and react to future activity. Use a one-shot Chat or product-control request for a single immediate action.

The basic workflow

  1. Create an Agent asset in the target team/folder.

  2. Write a precise definition describing the trigger and the action.

  3. Compile the definition to TypeScript.

  4. Review the generated TypeScript and trigger registrations.

  5. Save/publish the agent and test the trigger.

  6. Inspect the run log, output, and errors.

The definition and implementation can be converted in both directions:

Definition --compile--> TypeScript implementation
Definition <--decompile-- TypeScript implementation

Compilation is asynchronous. The asset records the latest compile/decompile state, including queued, running, success, fail, or stale.

Definition writing guide

A useful definition answers four questions:

  1. When does the agent run?

  2. What data should it inspect?

  3. What conditions must be true before it acts?

  4. What action and result should it produce?

Example:

When a test case run fails, check whether the failure is in the Payments folder.
If it is, create a report entry with the test name, failure message, and run link,
then send a concise notification to the team chat. Ignore failures from other folders.

Avoid definitions that depend on internal numeric IDs, omit the trigger, or leave the action ambiguous. Agent compilation cannot ask interactive clarification questions; an ambiguous definition fails compilation.

Trigger types

An implementation registers one or more triggers. The runtime supports four durable trigger categories.

Intent trigger

Runs when a matching user intent is invoked:

agent.registerIntentTrigger("summarize failed runs", async (context) => {
  const result = await context.runs.get({ status: "failed" });
  return { failedRuns: result };
});

The handler receives context.chatMessage in addition to the common context.

Schedule trigger

Runs at a configured one-time or recurring schedule:

agent.registerScheduleTrigger(
  "Daily failure summary",
  {
    timezone: "UTC",
    scheduleKind: "recurring",
    oneTime: null,
    recurring: {
      dayScope: "every-day",
      includedDays: [],
      windowStartTime: "09:00",
      windowEndTime: "09:00",
      intervalValue: 24,
      intervalUnit: "hours"
    }
  },
  async (context) => {
    return await buildDailySummary(context);
  }
);

Use the schedule shape offered by the editor/compiler for the exact schedule fields. The handler receives the common context and context.trigger metadata.

Event subscriber

Runs when a team-scoped product event is published. Event names can be exact or use a trailing wildcard where supported:

agent.onEvent("system.test-case.run.failed", async (context) => {
  const testCase = context.testCase;
  const failure = context.failure;

  if (!testCase || !failure) return { ignored: true };

  await context.notify.chat(`${testCase.label} failed: ${failure.message ?? "unknown failure"}`);

  return { notified: true, testCase: testCase.label };
});

The normalized onEvent context may include systemEvent, payload, fields, asset, parentAsset, testCase, run, runlist, step, counts, failure, healing, source, browserHost, and knowledgeBase, depending on the event. The raw event is also available through eventName, eventPayload, and event.

Convenience handlers are available for common events, including onTestCaseRunStarted, onTestCaseRunCompleted, onTestCaseRunFailed, runlist lifecycle events, step events, trigger misses, browser-host failures, and knowledge-base ingestion events.

API endpoint trigger

Runs when an authenticated request reaches the registered endpoint:

agent.registerApiTrigger(
  "Create incident",
  { method: "POST", endpointSuffix: "incidents" },
  async (context) => {
    const body = context.request.body;
    return await context.assets.create({
      name: String(body?.title ?? "Untitled incident"),
      type: "folder",
      parentAssetId: "team-root"
    });
  }
);

The request context includes the normalized HTTP method/path/body through context.request. Treat request data as untrusted input and validate it before performing mutations.

The execution context

Every handler receives a context object. It is the canonical product capability surface, not a plain database object. Use the documented context.* methods for reads and mutations.

Common areas include:

  • context.assets for asset discovery and asset operations

  • context.runs, context.runlists, and reporting capabilities

  • context.events for event history, publishing, and subscriptions

  • context.state for small JSON-serializable checkpoints and deduplication markers

  • context.notify for user-facing notifications

  • context.browser for remote browser/session/page operations

  • context.knowledgeBase for knowledge-base workflows

  • context.terminal for terminal sessions

  • context.usage for limits and cost information

The context also provides teamId, ownerAssetId, trigger, and secret-safe log.info, log.warn, and log.error on trigger handlers. Do not assume arbitrary properties exist; query through the capability methods and use the stable scope values supplied to the script when needed.

Outputs and logging

Return a JSON-serializable value from the handler when you want a structured run result:

return {
  status: "completed",
  processed: processedCount,
  skipped: skippedCount
};

The returned value is stored as the invocation output. console.log/console.warn/console.error and the trigger context logger are captured separately in the run’s console/output or error views. Returning undefined is valid, but it gives the run no structured output. Throw an Error when the run should be marked failed.

For event handlers, return an explicit ignored result when filtering is expected:

if (!matchesCondition) return { ignored: true, reason: "outside scope" };

Compilation and execution sequence

At compile time:

  1. Play loads the agent definition and owning team/asset scope.

  2. The definition is analyzed to extract trigger registrations and an immediate action request.

  3. The shared product-control planner/compiler generates the context.* action body.

  4. The body is wrapped in the appropriate agent.register... or agent.onEvent(...) registration.

  5. TypeScript is validated and saved to typescript_code.

  6. Trigger registrations are synchronized with the server.

At run time:

  1. The AgentRunner loads the saved TypeScript.

  2. TypeScript is transpiled and evaluated in the agent runtime.

  3. The code registers its triggers.

  4. The matching trigger handler is selected.

  5. The handler runs with a scoped context.

  6. The result and console/error output are persisted to the run log.

Reliability patterns

Use these patterns for production agents:

  • Filter events early and return an ignored result for non-matching events.

  • Use context.state for deduplication/checkpoints so retries do not duplicate work.

  • Prefer names, display IDs, active scope, and runtime queries over hard-coded internal IDs.

  • Validate API request bodies and event payloads before mutations.

  • Keep handlers small; move repeated logic into local helper functions.

  • Make notifications and mutations idempotent where possible.

  • Use await for every asynchronous capability call.

  • Log identifiers that help diagnose a run, but never log secrets.

  • Review the generated implementation after every compile and check the latest compile status before publishing.

Troubleshooting

Symptom

Likely cause

What to check

Compilation fails

Trigger or action is ambiguous

Make the definition explicit about event, scope, condition, and action.

Agent does not react

Registration was not synchronized or event name is wrong

Check the Registrations tab and exact published event name.

Run is successful but has no useful result

Handler returned undefined

Return a small structured object.

Run fails on a capability call

Invalid input or insufficient permission

Inspect the error output and verify the capability schema and team permissions.

Duplicate actions occur

Event delivery or retry replayed the handler

Add a key/checkpoint in context.state and make the action idempotent.

Definition and code disagree

One side was edited without conversion

Compile definition to code, or decompile code back to a definition, then review and save.