Agent Workflows
A composite tool calls other tools and subagents in code. Use it when an operation needs a fixed sequence, parallel checks, or a structured result. Durable execution adds recorded steps and pause and resume. Use a single tool for a self-contained calculation or API action.
Composite Tools
Use handler.ts with tool.json, and declare composition in tool.json:
amodal/tools/review_request/
├── tool.json
└── handler.ts{
"name": "review_request",
"description": "Load a request, review completeness and policy, and save the findings.",
"parameters": {
"type": "object",
"properties": { "request_id": { "type": "string" } },
"required": ["request_id"]
},
"uses": {
"tools": ["load_request", "persist_review_findings"],
"subagents": ["prescreen-reviewer", "policy-reviewer"]
}
}export default async function (params, ctx) {
const request = await ctx.callTool('load_request', {
request_id: params.request_id,
});
const [completeness, policy] = await Promise.all([
ctx.callSubagent('prescreen-reviewer', 'Check field completeness.', request),
ctx.callSubagent('policy-reviewer', 'Review policy requirements.', request),
]);
const findings = { completeness, policy };
await ctx.callTool('persist_review_findings', {
request_id: params.request_id,
findings,
});
return { request_id: params.request_id, findings };
}The example requires the two named child tools and two authored subagents. Subagent results are text. Parse and validate them in a child tool if your product needs structured fields.
Do not add tool.ts to this directory. A tool.ts takes precedence over tool.json, and that layout does not bind ctx.callTool or ctx.callSubagent.
Composition Semantics
- Declare every child tool in
uses.toolsand every specialist inuses.subagents. A declared name that does not resolve in the session's tool registry fails the session build, including a child tool that a named root agent does not declare. A call to an undeclared name fails at run time. ctx.callTool(name, params)executes the child tool and returns its result.ctx.callSubagent(name, task, input?, opts?)runs the specialist's agent loop and returns its final text.inputis appended to the task as a JSON block. A web citation in that text stays a[[web:<id>]]marker, and the text ends with one[[web:<id>]]: <url> "<title>"line per cited source. A handler that returns the text lets the agent's reply resolve those citations; a handler that sends the text elsewhere renders them itself.- A failed inline child call throws a
CompositeCallErrorwith acode:depth-exceeded,undeclared,unknown-tool,confirmation-unsupported,invalid-params,execution-failed,subagent-undeclared,subagent-unknown, orsubagent-failed. - Inline
ctx.callToolnesting stops at depth 4. Subagent nesting stops at five levels. - Nested tool calls render as nested cards in the chat UI.
Nested tool calls do not run the outer loop's permission or hook checks. Inline composites refuse tools marked requiresConfirmation and connection-category tools, including request, with confirmation-unsupported. They do not open an approval dialog.
Durable child execution does not apply that confirmation check to custom or connection-category tools. Use an explicit durable approval before a write that needs an operator decision. Durable child execution refuses a governed MCP tool unless the tool is read-only and needs no confirmation. A composite cannot call a governed MCP tool that needs the employee's confirmation, so the agent calls that tool directly in chat. A uses declaration limits reachability. Child code and downstream APIs must enforce authorization.
Fanning Out Attachments
Top-level handlers receive the current turn's uploads in ctx.attachments. In an agent with a sandbox, every file of the conversation is also in the sandbox under in/, and in/index.json lists them. Pass selected files in the fourth argument to a specialist:
export default async function (params, ctx) {
const results = await Promise.all(
(ctx.attachments ?? []).map((file) =>
ctx.callSubagent(
'document-extractor',
"Extract the document's facts and cite the supporting text.",
{ filename: file.filename },
{ attachments: [file] },
),
),
);
return { results };
}Declare document-extractor in uses.subagents. Attachments become file parts on the specialist's user turn. For providers without media support, they are dropped and the runtime logs subagent_attachments_stripped.
Durable Tools
Use durable execution when a tool must pause for input, approval, or a future time. The handler runs again from the top on resume. Journaled calls return their recorded results instead of executing again.
Set "execution": "durable" in tool.json:
{
"name": "release_to_environment",
"description": "Ask for a target environment and release to it.",
"execution": "durable",
"parameters": { "type": "object", "properties": {} },
"uses": { "tools": ["run_release"] }
}export default async function (params, ctx) {
const target = await ctx.requestInput({
question: 'Where should this release run?',
inputType: 'choice',
options: [
{ value: 'staging', label: 'Staging', recommended: true },
{ value: 'production', label: 'Production', sub: 'Makes the release live' },
],
});
const result = await ctx.callTool('run_release', { target: target.value });
return { target: target.value, result };
}The example requires a run_release child tool that validates the target and performs the release.
| Method | Contract |
|---|---|
ctx.requestInput(opts) | Pause for an answer. Supports question, context, inputType, options, payload, allowEdits, eligibleAnswerers, and excludeAnswerers. Returns {value, respondedBy, edits?}. |
ctx.waitForApproval(prompt) | Yes/no form of requestInput. Returns {approved, respondedBy?}. |
ctx.step(name, fn) | Run an async checkpoint and record its JSON result. On replay, return that result without calling fn. Repeated names are distinguished by call order. |
ctx.sleepUntil(when) | Pause until a Date, then resume through the scheduler. |
ctx.now() | Recorded clock value in milliseconds. |
ctx.random() | Recorded random value. |
ctx.artifactJobs.run(...) | Run a multi-stage durable artifact job with checkpointed job.stage(opts, fn) steps, stage deadlines, progress reporting, and output verification. |
inputType accepts text (the default), choice, or yesno. Choice options have a value and label. recommended and sub affect presentation. The returned value is whatever the answerer posted, so validate it before a sensitive action. eligibleAnswerers and excludeAnswerers are lists of user IDs.
Use ctx.step for handler-local work whose result must survive replay:
const record = await ctx.step('parse-input', async () => JSON.parse(params.document_json));Return plain data from checkpoints. A Date returns as an ISO string, and a class instance returns as a plain object. Mutations to variables outside fn are not restored on replay.
Route external I/O through declared child tools. In a durable handler, ctx.request, ctx.store, ctx.storeGet, ctx.storeQuery, ctx.listConfirmations, and ctx.exec reject, and ctx.env returns undefined. The handler runs again from the top on each resume, so any work outside journaled calls runs again.
When a durable tool pauses during chat, the model receives {durable: true, status: "running", session_id, message} and the turn continues. When the tool is waiting on requestInput, the result is {durable: true, status: "awaiting_operator", session_id, question, context, message}. The run's status is awaiting-input. Persistence across restarts requires a persistent session store. Local amodal dev keeps sessions in memory.
Answering A Pause
Answer the durable session named by session_id in the pause result. Its ID differs from the chat session's ID.
curl "$RUNTIME/sessions/pending-approvals" \
-H "Authorization: Bearer $RUNTIME_TOKEN"
curl -X POST "$RUNTIME/api/sessions/$DURABLE_SESSION_ID/answer" \
-H "Authorization: Bearer $RUNTIME_TOKEN" \
-H "Content-Type: application/json" \
-d '{"value": "staging"}'The body requires value. With allowEdits, include edits with the edited payload. A completed run returns 200 with outcome and result. A run that pauses again returns the next pause in outcome.
| Status | error | Cause |
|---|---|---|
400 | missing_value | The body has no value. |
403 | not_eligible_answerer | The caller is not in eligibleAnswerers. |
403 | excluded_answerer | The caller is in excludeAnswerers. |
404 | session_not_found | No such session, or it belongs to another scope. |
409 | session_not_awaiting_input | The pause was already answered. The body includes answeredBy if known. |
POST /api/sessions/:id/cancel stops a parked run. Answer and cancel publish session_updated events with status and answeredBy on GET /api/events. Every other status change of a background run, such as a new pause, publishes session_updated without status.
In the React SDK, useSessionActions(id).answer(value, edits?) answers from an inbox or custom screen. The chat widget renders inline choice, yes/no, and text cards and answers them through the same endpoint.
Single-Flight Tools
A single-flight tool runs one at a time, such as a sync that copies a mailbox into your database. Set "single_flight": true on a durable tool:
{
"name": "sync_mail",
"description": "Copy new mail into the firm database.",
"execution": "durable",
"single_flight": true,
"llm_callable": false,
"triggers": [{ "kind": "invoke" }],
"uses": { "tools": ["fetch_mail_batch"] }
}export default async function (_params, ctx) {
const { behind } = await ctx.callTool('fetch_mail_batch', {});
return { more: behind };
}- Each scope of a tool has at most one live run. While a run is running, parked, waiting for input or pending review, another start is refused:
POST /api/tools/:name/runanswers409 run_in_flight, and an automation fire is skipped without an alert. A recurring automation waits for its next fire, and a{ at }one-shot retries the fire a minute later until the tool is free. - When an automation's run completes with an output whose
moreistrue, the automation starts the next run at once. A run that completes after a pause continues at the automation's next scheduled fire. A{ at }one-shot runs until a run returns nomore. - A run that ends, whether it completes, fails or is cancelled, frees the tool. Keep your progress in your own store with the data it describes, and write with idempotent upserts, because a failed run is retried by the next fire.
single_flightrequires"execution": "durable". Two automations that start the same tool share its single run.- Each run still has the automation's 600-second limit. Do a bounded amount of work per run and return
morewhen work is left.
Triggers
| Entry point | Use |
|---|---|
| LLM tool selection | The model chooses the tool in response to a user message. |
| Predicate trigger | A regex or predicate entry in the tool's triggers starts the tool from a matching message without model selection. |
| Direct invocation | Your app calls POST /api/tools/:name/run for an inline or durable tool whose triggers include { "kind": "invoke" }. |
| App call | An app page calls POST /api/tools/:name/call for an inline tool whose triggers include { "kind": "app" }, and reads its result. |
| Automation | A platform automation runs the tool on a schedule or event. |
A { "kind": "schedule" } entry in tool.json triggers never runs. The loader ignores it and the build log shows a warning. Schedule the tool through an automation.
A trigger does not remove the tool from the model's tool list. Set "llm_callable": false in tool.json or tool.ts to hide the tool from the model while composites and triggers can still call it.
POST /api/tools/:name/run takes {"input": {...}} and optional session_id, scope_id, and context. It returns 403 tool_not_invocable without an invoke trigger. An inline tool runs as a single journaled step with its own timeout and the inline ctx, so it can use stores, connections and ctx.env. If the runtime restarts during that step, the run ends for review instead of running the tool again. It does not validate input against a tool.json parameter schema, so the handler must validate it.
POST /api/tools/:name/call takes {"input": {...}} and optional scope_id and context, which resolve as they do for /run. It runs the tool with no model and no session, stores nothing, and answers {"result": ...} with the value the handler returned, whether an object, an array, or a primitive. result is null when the handler returns nothing. Only tool.json tools can declare triggers, and a tool with an app trigger must be inline with no uses.subagents, or the bundle fails to load. input is checked against the schema's required and additionalProperties: false. The handler sees the signed-in person as ctx.userId, never a value from the body, and a fresh per-call id as ctx.sessionId. ctx.artifacts, attachment staging and ctx.callSubagent are absent, and ctx.emit events are dropped. The call is aborted at the tool's timeout or when the page disconnects. A handler that ignores ctx.signal keeps running, but the response does not wait for it. Each call writes an app_tool_call runtime log entry with the tool, caller, scope, status and duration.
| Status | error | Meaning |
|---|---|---|
200 | The body is {"result": ...}. | |
400 | invalid_body | The body is not an object of the shape above. |
400 | invalid_input | input is missing a required parameter or has an undeclared one. |
400 | scope_required | The agent sets scope.requireScope and the call resolves no scope. |
403 | tool_not_callable | No tool by that name has an app trigger. |
403 | SCOPE_FORBIDDEN | An end user named a scope that is not theirs. |
404 | agent_bundle_not_found | The runtime has no bundle for the deploy. |
422 | refused | The handler threw an error with refusal: true. message is the handler's own message. Throw one for a refusal the person should read: input they can fix, a stale edit, a missing permission. |
500 | tool_failed | The handler threw. message carries the error. |
504 | tool_timeout | The tool's timeout passed first. |
App Operations
An app usually serves all of its pages through one tool. defineAppOps from @amodalai/react/app builds that tool's handler from named operations:
import { defineAppOps, Refusal } from '@amodalai/react/app';
import type { RunCtx } from '../../lib/ctx';
export default defineAppOps({
// Runs before every operation not marked `open`. Its result reaches each operation as `caller`.
authorize: async (ctx: RunCtx) => callerOf(ctx),
ops: {
me: { open: true, run: (_args, ctx) => ({ userId: ctx.userId }) },
search: {
args: {
type: 'object',
properties: { q: { type: 'string' }, limit: { type: 'number' } },
required: ['q'],
additionalProperties: false,
},
run: ({ q, limit }: { q: string; limit?: number }, ctx, caller) => search(caller, q, limit),
},
},
});A page sends { "op": "search", "args": { "q": "Corwin" } } as the tool's input. A call runs in this order:
- The handler looks up
op. An unknown operation is refused. authorizeruns, unless the operation is markedopen. ARefusalit throws reaches the page as422 refused.- When the operation declares
args, the handler checks the arguments against that schema. A failure is refused with a message that names the field, such as"filter.team" must be a string.. Whenargsis missing frominput, the operation receives{}. runreturns the result.
An args schema supports type, properties, required, additionalProperties as a boolean, items, enum, description and title, at any depth. defineAppOps throws when a schema uses any other keyword, so a schema never declares a constraint the handler ignores. run's argument annotation gives the operation's argument type, and an unannotated argument means the operation takes none.
The matching tool.json leaves each operation's arguments to the handler:
{
"parameters": {
"type": "object",
"properties": { "op": { "type": "string" }, "args": { "type": "object" } },
"required": ["op"],
"additionalProperties": false
},
"triggers": [{ "kind": "app" }],
"llm_callable": false
}A page calls the operations through createAppClient, typed by the handler it imports with import type:
import { createAppClient } from '@amodalai/react/app';
import type ops from '../../amodal/tools/app/handler';
export const app = createAppClient<typeof ops>({ tool: 'app', runtimeUrl: window.location.origin });
await app.call('search', { q: 'Corwin' });
useQuery(app.query('search', { q: 'Corwin' }));
queryClient.invalidateQueries({ queryKey: app.key });call rejects with a Refusal when the handler refuses and with an HttpError for any other failure. query returns the queryKey and queryFn that React Query's useQuery accepts, and the page sets staleTime and retry itself. app.key is the prefix of every query key for the tool. A page inside an AmodalProvider can pass its sdk in place of runtimeUrl.