Skip to main content

Dynamic Workflow

Create, run, and reuse dynamic workflows in Managed Agents, with in-session generation or manual JavaScript.

Dynamic Workflow uses JavaScript to orchestrate the execution order, parallel tasks, and result aggregation of multiple agents. The script describes the workflow; agents perform the analysis, generation, retrieval, and other work. Use it for parallel research from multiple perspectives followed by a unified summary, processing a batch of materials one by one, generating output before validation, and reusing saved workflows. For a single simple question, call an agent directly.

Creation methods

On the Dynamic Workflows page, click Create dynamic workflow and choose a creation method.

Create in a session

  1. Select Create in a session. In the Agent selection area, select an agent or click New agent.
  2. Click Configure session. The system enables workflow creation for the agent, saves a new agent version, and opens the session configuration page.
  3. Confirm the agent and environment on the session configuration page, enter the session, and describe the task. The agent generates a workflow during execution.
  4. Confirm and save the workflow for later reuse.

Write a script manually

  1. Select Write a script manually, enter the workflow name and description, and click Create and write script.
  2. In the editor, write the JavaScript script. To constrain input, add fields under Field structure.
  3. Click Save to publish a version.

Script quick start

The following script reads input and returns a result without calling an agent. Use it to verify input and output first.
export const meta = {
  name: 'hello-workflow',
  description: 'Reads a topic and returns a result'
}

const topic = args.topic || 'Dynamic Workflow'
return { message: 'Hello, ' + topic }
The args passed at run time:
{ "topic": "product research" }
Returned result:
{ "message": "Hello, product research" }
A script has three parts: the first statement declares meta, the body reads input through args, and the final return returns a JSON object. The body supports top-level await and return; you do not need to wrap it in a function or write export default.

Script structure

Declare meta

export const meta = {
  name: 'research-and-review',
  description: 'Research in parallel, cross-check, and summarize',
  phases: [
    { title: 'Research', detail: 'Collect information from different perspectives' },
    { title: 'Verify', detail: 'Check whether conclusions have evidence' },
    { title: 'Summarize', detail: 'Prepare final recommendations' }
  ]
}

return { ready: true }
  • name is required and must be a non-empty string.
  • description is optional and must be a string.
  • phases is optional and must be an array of objects. Each item must have a non-empty title, may have a detail, and titles must be unique.
  • meta must be a static literal. It cannot reference variables, call functions, or use object spread. The body cannot read or modify meta.
  • Comments and blank lines may appear before meta; no other statements may precede it.

Read args and return an object

args is the JSON object passed by the caller. There is no built-in input variable named input. args and its nested data are read-only. To sort or modify data, copy it first, for example const items = [...args.items]. The final return value must be a JSON object. It can be {} or contain nested objects, arrays, strings, numbers, booleans, and null. You cannot return an array, string, or null directly; wrap an array as return { items }. Data cannot contain undefined, functions, BigInt, NaN, Infinity, or circular references.

Built-in functions

FunctionUsage and return value
agent(prompt, options?)Runs a sub-agent and waits for text or a structured result.
parallel([fn1, fn2, ...])Runs an array of functions in parallel, waits for all branches, and returns results in the original order.
pipeline(items, stage1, stage2, ...)Processes different items in parallel and runs the stages for each item in order, returning an array of results.
workflow(ref, childArgs?)Calls a bound workflow, waits for completion, and returns its result object. Arguments default to {}.
phase(title)Marks the current execution phase. It does not wait for business tasks to finish.
log(value)Records a run log. The argument is a string or JSON object.
agent(), workflow(), parallel(), and pipeline() return promises and must be awaited. Do not start a task and end the script immediately. phase() and log() can be called directly or awaited. They do not accept callbacks, and log() does not accept arrays; write log({ items }) instead. Logs are for diagnostics and are not displayed as page phase events.

Call an agent

Basic usage

export const meta = { name: 'summarize-topic' }

const summary = await agent(
  'Summarize the following topic in Chinese and list the information that needs verification: ' + args.topic,
  { label: 'Topic summary' }
)
return { summary }
When schema is not set, summary is a string. A sub-agent has an independent execution context and does not automatically receive the full history of the main session. Include the task, required materials, and instructions in the prompt. Sub-agents do not receive Dynamic Workflow tools or prompts. options supports the following fields. Do not add parameters such as timeout or tools.
FieldTypeDescription
agent_idstringOptional. Agent ID for this call. When specified explicitly, the agent must be a resource that the calling identity can access. If omitted, the session default Agent is used. Inline scripts require inline_agents.type=enabled; reusing a published Workflow is not subject to this switch.
labelstringOptional. Non-empty call label used to distinguish calls. It does not affect task execution.
phasestringOptional. Non-empty phase title. A different title switches the current phase.
schemaobjectOptional. JSON Schema for the sub-agent's structured return value.
modelstringOptional. Overrides the model used by this sub-agent. Use a model name supported by the service.
To call a specific agent, set agent_id in the second argument. Get the real ID from the agent configuration or resource list; do not use a placeholder from an example. Omitting agent_id does not create a separate new agent configuration.

Structured output

export const meta = { name: 'structured-research' }

const report = await agent(
  'Analyze the topic and output a conclusion and the risks that need verification: ' + args.topic,
  {
    schema: {
      type: 'object',
      properties: {
        conclusion: { type: 'string', description: 'Conclusion in Chinese' },
        risk: { type: 'string', description: 'Uncertain information and risks' }
      },
      required: ['conclusion', 'risk']
    }
  }
)

return { conclusion: report.conclusion, risk: report.risk }
When schema is set, the return value is already parsed and validated: object schemas return objects and array schemas return arrays. Do not call JSON.parse(report), report.match(), report.replace(), or Markdown cleanup on it. To pass it to the next agent, use JSON.stringify(report) to convert it to text in the prompt. If the structured result does not match the schema, the call fails and does not fall back to a string. The workflow must still return an object, for example return { reports } for an array result.

Parallel research and summary

This pattern suits tasks that need multiple independent perspectives, such as market analysis and solution reviews. Make sure the session has a usable default agent and that the script is allowed to use it. Example args at run time:
{ "topic": "Customer service product for small and medium businesses", "material": "Research materials and known facts go here" }
export const meta = {
  name: 'parallel-research',
  description: 'Analyze requirements and risks in parallel, verify, and summarize',
  phases: [
    { title: 'Research', detail: 'Analyze requirements and risks in parallel' },
    { title: 'Verify', detail: 'Separate facts from assumptions' },
    { title: 'Summarize', detail: 'Provide actionable recommendations' }
  ]
}

await phase('Research')
const context = JSON.stringify({ topic: args.topic, material: args.material })
const reports = await parallel([
  () => agent('Analyze customer requirements and product opportunities, and cite evidence: ' + context, { label: 'Requirements analysis' }),
  () => agent('Analyze competitive risks and implementation difficulties, and note uncertainties: ' + context, { label: 'Risk analysis' })
])

if (reports.some(report => report === null)) {
  throw new Error('A research branch failed. Check the run errors and try again.')
}

await phase('Verify')
const verified = await agent(
  'Cross-check the following reports and identify contradictions, unsupported conclusions, and missing materials: ' + JSON.stringify(reports),
  { label: 'Cross-check' }
)

await phase('Summarize')
const summary = await agent(
  'Combine the reports and verification feedback to provide conclusions and action recommendations in Chinese: ' + JSON.stringify({ reports, verified }),
  { label: 'Final summary' }
)

await log({ message: 'Research and summary completed', report_count: reports.length })
return { reports, verified, summary }
parallel() takes functions: [() => agent('Task A'), () => agent('Task B')]. Do not write [agent('Task A'), agent('Task B')], which is an array of promises for already-started calls. The result array follows the order of the function array, not the order of completion. phase() only marks progress and does not create task dependencies. Real dependencies come from await and data passing. For example, verification must run after await parallel(...).

Batch processing

When each item needs to be extracted and then turned into recommendations, use pipeline to express the stages for each item. Different items run in parallel, and the stages for the same item run in order. Example args:
{ "items": ["First document body", "Second document body"] }
export const meta = { name: 'batch-review' }

const results = await pipeline(
  args.items,
  item => agent('Extract the key information from the following material: ' + item),
  (outline, originalItem) => agent(
    'Combine the original text and the extracted result, and provide three recommendations: ' + JSON.stringify({ originalItem, outline })
  )
)

const failedCount = results.filter(result => result === null).length
return { results, failed_count: failedCount }
Each stage receives (previous stage result, original item). The previous stage result for the first stage is the original item. There is no third index argument. Results keep the original item order. Do not append a concurrency configuration object to pipeline; the service controls concurrency.

Reuse a saved workflow

Before reuse, bind the workflow id and a fixed version to the agent and enable the reuse switch.
{
  "multiagent": {
    "type": "coordinator",
    "reuse_workflows": {
      "type": "enabled",
      "workflows": [
        { "id": "wf_01M7RMD9PRNVEPY2QKW1MA36TE", "version": 1 }
      ]
    }
  }
}
When updating an existing agent, include the agents and workflows that you want to keep in multiagent. The snippet above shows only the reuse fields.
Call the bound workflow with workflow() in the script:
export const meta = { name: 'reuse-research' }

const research = await workflow('wf_01M7RMD9PRNVEPY2QKW1MA36TE', { topic: args.topic })
const summary = await agent('Summarize the key conclusions of this research: ' + JSON.stringify(research))
return { research, summary }
The first argument of workflow() is the bound workflow ID. The second argument must be a JSON object whose fields follow the target workflow's input contract. The return value is the object returned by the target workflow's final return. Binding uses only id and version, and calls run the bound version. The example ID is not runnable as is; replace it with the real ID of a bound resource. When a published workflow is reused, its internal agent calls skip the caller's agent usage restrictions (the default agent, inline_agents, and predefined_agents), but workspace and resource availability checks still apply.

Configure inline scripts and reuse

The agent's multiagent also contains inline script configuration:
FieldDescription
workflows.typeenabled allows the main agent to generate and submit inline scripts. disabled or omitted turns it off.
workflows.inline_agents.typeenabled allows inline scripts to use the session default agent. The default is disabled.
workflows.predefined_agentsFixed agent versions that inline scripts can call, up to 20 items. id values in the list must be unique. Required when inline scripts are enabled and the default agent is disabled.
The two switches can be enabled independently:
Inline scriptsWorkflow reuseCapability
OffOffThe main agent does not receive Dynamic Workflow tools or prompts.
OnOffThe model can generate and submit inline scripts.
OffOnThe agent can call bound fixed published workflow versions.
OnOnSupports both inline scripts and fixed-version reuse.
Enabling reuse alone does not require predefined_agents or inline_agents. Turning a switch off keeps existing bindings. After you modify an agent, new sessions use the new agent version; existing sessions do not switch automatically. For all agent configuration fields, see Create Agent.

Role of input_schema

You can omit input_schema when creating a workflow; the script still reads parameters through args. To constrain caller input explicitly, configure a standard JSON Schema separately:
{
  "type": "object",
  "properties": {
    "topic": { "type": "string", "description": "Topic to research" }
  },
  "required": ["topic"]
}
input_schema constrains the args passed to the workflow. agent(..., { schema }) constrains the return value of one agent call. They serve different purposes, and neither is a prompt. The caller must still pass actual data such as {"topic": "customer service product"}; do not pass the schema as data. The service submits args in its original structure, does not convert parameter types, and does not fill in default values automatically.

Runtime limits

The body can use variables, objects, arrays, template strings, functions, conditionals, loops, try/catch, JSON.parse/stringify, and common array methods. Loops must have a clear upper bound, and every agent or workflow call must be awaited.
Unsupported syntax or capabilityHow to handle it
TypeScript types, Markdown code fences as script contentSubmit plain JavaScript source. Do not include fences when copying examples.
import, require, and other export statementsKeep only the leading export const meta and use built-in functions.
console.logUse log('message') or log({ key: 'value' }).
fetch, browser page APIs, Node.js modules, files, processes, environment variables, ShellGive the actual business operation to an agent configured with the required capability. The script handles orchestration.
eval, Function, and other dynamic code executionWrite deterministic workflow logic directly.
Timers, background tasksExpress dependencies by awaiting sub-calls. Do not create background work that outlives the script.
Date.now(), new Date() without arguments, Math.random(), cryptoHave the caller pass the current time or a random identifier through args.
You can parse an explicit date value, such as new Date(args.timestamp), when the caller provides a valid time value. Do not rely on the script to read the current time. The service controls concurrency, agent startup count, nesting depth, and execution duration. Calls queue when the concurrency limit is reached and may fail when other runtime limits are exceeded. Do not bypass quotas through scripts, and do not treat a caught exception as success by default.

Failure handling and submission checklist

A direct await agent(...) or await workflow(...) call throws when it fails. parallel and pipeline return null in the corresponding position for ordinary non-fatal subtask failures. Check the results before using the remaining ones. Fatal errors such as cancellation and timeout still fail the entire run and cannot be turned into success with try/catch. Before submitting, check:
  1. The first statement is a static export const meta, name is non-empty, and phases use { title, detail? } objects.
  2. Input is read from args, and the required materials are explicitly written into each agent() prompt.
  3. Every sub-call is awaited, and parallel tasks use arrays of functions.
  4. When schema is used, object fields are read directly and no string method is called on the object.
  5. null values in parallel or batch results are checked, and the final return is a JSON object.
  6. Referenced agents are real and available, and referenced workflows are bound. Test with a small input before scaling up.
Syntax validation before saving can detect syntax errors and unsupported capabilities, but it does not prove that the business result is correct. Judge success by the run's final successful status and result, not by submission success alone.