# Build / Patterns --- > Source: https://loopstack.ai/llms/build/patterns/dynamic-routing.md --- title: Dynamic Routing description: Conditional workflow routing using @Guard decorators and priority-based transition selection when multiple transitions share the same source state. --- # Dynamic Routing Route workflows conditionally using `@Guard` decorators and `priority` to control which transition fires when multiple transitions share the same source state. ## Basic Guard ```typescript @Transition({ from: 'check', to: 'high', priority: 10 }) @Guard('isHigh') routeHigh(state: MyState) {} @Transition({ from: 'check', to: 'low' }) routeLow(state: MyState) {} // Fallback — no guard isHigh(state: MyState): boolean { return state.value > 100; } ``` **How it works:** 1. Transitions with higher `priority` are checked first 2. The `@Guard` references a method that returns a boolean 3. First transition whose guard returns `true` fires 4. A transition without `@Guard` acts as the fallback ## Multi-Level Routing Chain routing decisions with cascading forks: ```typescript import { z } from 'zod'; import { BaseWorkflow, Guard, Transition, Workflow } from '@loopstack/common'; import type { RunContext } from '@loopstack/common'; import { MessageDocument } from '@loopstack/common'; interface RoutingState { value?: number; } const RoutingSchema = z.object({ value: z.number().default(150) }).strict(); type RoutingArgs = z.infer; @Workflow({ schema: RoutingSchema, }) export class DynamicRoutingExampleWorkflow extends BaseWorkflow { @Transition({ to: 'prepared' }) async createMockData(state: RoutingState, ctx: RunContext) { await this.documentStore.save(MessageDocument, { role: 'assistant', text: `Analyzing value = ${ctx.args.value}`, }); this.assignState({ value: ctx.args.value }); } // First fork: value > 100? @Transition({ from: 'prepared', to: 'placeA', priority: 10 }) @Guard('isAbove100') routeToPlaceA(state: RoutingState) {} @Transition({ from: 'prepared', to: 'placeB' }) routeToPlaceB(state: RoutingState) {} // Fallback: value <= 100 isAbove100(state: RoutingState): boolean { return (state.value ?? 0) > 100; } // Second fork: value > 200? @Transition({ from: 'placeA', to: 'placeC', priority: 10 }) @Guard('isAbove200') routeToPlaceC(state: RoutingState) {} @Transition({ from: 'placeA', to: 'placeD' }) routeToPlaceD(state: RoutingState) {} // Fallback: 100 < value <= 200 isAbove200(state: RoutingState): boolean { return (state.value ?? 0) > 200; } // Terminal transitions @Transition({ from: 'placeB', to: 'end' }) async showMessagePlaceB(state: RoutingState) { await this.documentStore.save(MessageDocument, { role: 'assistant', text: 'Value is less or equal 100' }); } @Transition({ from: 'placeC', to: 'end' }) async showMessagePlaceC(state: RoutingState) { await this.documentStore.save(MessageDocument, { role: 'assistant', text: 'Value is greater than 200' }); } @Transition({ from: 'placeD', to: 'end' }) async showMessagePlaceD(state: RoutingState) { await this.documentStore.save(MessageDocument, { role: 'assistant', text: 'Value is less or equal 200, but greater than 100', }); } } ``` ## Routing Flow ``` prepared → [value > 100?] ├─ yes → placeA → [value > 200?] │ ├─ yes → placeC (done) │ └─ no → placeD (done) └─ no → placeB (done) ``` ## Common Patterns ### Tool Call Routing Route based on LLM response (see [AI Tool Calling](../ai/tool-calling.md)): ```typescript @Transition({ from: 'prompt_executed', to: 'ready', priority: 10 }) @Guard('hasToolCalls') async executeToolCalls(state: MyState) { ... } // Run tools, loop back @Transition({ from: 'prompt_executed', to: 'end' }) async respond(state: MyState) { ... } // Fallback: no tool calls hasToolCalls(state: MyState): boolean { return state.llmResult?.message.stopReason === 'tool_use'; } ``` For async tools that complete via callback (sub-workflows, HITL), insert an `awaiting_tools` intermediate state with a `wait: true` re-entry transition — see [Agent Workflows](../ai/agent-workflows.md). ### Error-Based Routing Route based on a tool's error response: ```typescript @Transition({ from: 'fetched', to: 'auth_needed', priority: 10 }) @Guard('needsAuth') async startAuth(state: MyState) { ... } @Transition({ from: 'fetched', to: 'end' }) async displayResults(state: MyState) { ... } needsAuth(state: MyState): boolean { return state.fetchResult?.error === 'unauthorized'; } ``` ## Guard Method Rules - Guard methods must return a **boolean** (or truthy/falsy value) - They receive `state` as their first parameter - They should be **synchronous** — no async guards - Use descriptive names: `hasToolCalls`, `isAbove100`, `needsAuth` ## Registry References - [Dynamic Routing example](/docs/examples/advanced-workflows#dynamic-routing) — Multi-level guard-based routing with cascading forks - [Custom Agent example](/docs/examples/agent#custom-agent) — Guard-based routing for LLM tool call detection --- > Source: https://loopstack.ai/llms/build/patterns/error-handling.md --- title: Error Handling, Retry & Timeout description: Recovering from transition errors with auto-retry and exponential backoff, retryTarget for retry-via-another-place, errorPlace routing for sync throws and sub-workflow failure callbacks, manual retry via Studio UI, and transition timeouts. --- # Error Handling, Retry & Timeout When a transition fails — by throwing, timing out, or receiving a `failed` / `canceled` callback from a sub-workflow — the framework rolls back local changes and then runs a single decision tree: 1. **Auto-retry** if `retryAttempts` has budget left. 2. **Route to `errorPlace`** if declared (retries exhausted, or no retries configured). 3. **Manual retry (default)** — stay at the current place and surface a Retry button in the UI. The same rule applies to sync throws, timeouts, and sub-workflow failure callbacks — there's one mental model. ## Retry Modes ### Auto-Retry Automatically re-run a failed transition with exponential backoff: ```typescript @Transition({ from: 'fetching', to: 'done', retryAttempts: 3 }) async fetchData() { await this.httpClient.call({ url: 'https://api.example.com/data' }); } ``` If `fetchData` throws, the framework retries up to 3 times with exponential delays (1s, 2s, 4s). The workflow stays at the `fetching` place during retries. ### Retry via a Different Place (`retryTarget`) Some retries need preparation work between attempts — refresh a token, invalidate a cache, log out and back in. `retryTarget` moves the workflow to a different place on each auto-retry, instead of re-running the failing transition directly: ```typescript @Transition({ from: 'fetching', to: 'done', retryAttempts: 3, retryTarget: 'refresh_credentials', }) async callApi() { await this.api.call({ ... }); } @Transition({ from: 'refresh_credentials', to: 'fetching' }) async refreshCredentials() { await this.auth.refreshToken(); } ``` On failure, `callApi`'s retry budget is decremented, the workflow jumps to `refresh_credentials`, the refresh transition runs, and the workflow loops back to `fetching` to re-attempt `callApi`. Transitions inside the retry target have their own independent retry budget — a failure in `refreshCredentials` doesn't consume `callApi`'s attempts. ### Custom Error Place (`errorPlace`) Route to a dedicated error state when a transition fails: ```typescript @Transition({ from: 'processing', to: 'done', errorPlace: 'error_processing' }) async processData() { await this.processor.call({ data: this.rawData }); } @Transition({ from: 'error_processing', to: 'done', wait: true }) async handleProcessingError() { // Recovery logic — user clicks a "Recover" button to trigger this await this.documentStore.save(MessageDocument, { role: 'assistant', text: 'Processing failed. Retrying with fallback strategy.', }); } ``` The workflow transitions to `error_processing` where you define recovery logic via `wait: true` transitions (buttons in the UI). When `errorPlace` is set without `retryAttempts`, attempts default to `0` — failures route straight to the error place on the first try. ### Manual Retry (Default) When no failure handling is specified, the workflow stays at the current place and shows a "Retry" button: ```typescript @Transition({ from: 'sending', to: 'sent' }) async sendEmail() { await this.email.call({ to: 'user@example.com', body: this.content }); } ``` If it fails, the user sees the error message and can retry manually. No auto-retry, no error place — just pause and let the user decide. ### Hybrid: Auto-Retry + Error Place Combine auto-retry with a fallback error state: ```typescript @Transition({ from: 'deploying', to: 'deployed', retryAttempts: 2, errorPlace: 'deploy_failed', }) async deploy() { await this.deployer.call({ target: 'production' }); } @Transition({ from: 'deploy_failed', to: 'deployed', wait: true }) async retryDeploy() { // Manual recovery after auto-retries exhausted } ``` Retries twice automatically. If both fail, transitions to `deploy_failed` for manual intervention. ## Sub-Workflow Failure Callbacks A wait transition that resumes from a sub-workflow callback can fail just like a synchronous transition — when the child finishes with `status: failed` or `canceled`. The same `retryAttempts` / `retryTarget` / `errorPlace` rules apply: ```typescript @Transition({ from: 'awaiting_child', to: 'done', wait: true, errorPlace: 'sub_failed' }) async childCompleted(_state, _input) { // Happy path only — the child succeeded. } @Transition({ from: 'sub_failed', to: 'done', wait: true }) async handleSubFailed() { // Recovery when the child failed — surfaces a Recover button. } ``` Without `errorPlace` (or `retryAttempts`), a sub-workflow failure callback still fires the body — for accumulator patterns where the body itself handles error results (e.g. LLM tool delegation). With either declared, the framework treats the failure as the wait transition failing and skips the body entirely. That protects schema-validated bodies from receiving `null` / malformed data when the child never reached `setResult(...)`. ## Failure-Handling Configuration ```typescript retryAttempts?: number // -1 = unlimited manual retry (default). // 0 = no auto-retry (default when errorPlace is set). // N>0 = up to N auto-retries. retryDelay?: number // Base delay in ms (default: 1000). retryBackoff?: 'fixed' | 'exponential' // (default: 'exponential') retryMaxDelay?: number // Backoff cap in ms (default: 30000). retryTarget?: string // Re-enter this place on each auto-retry, instead of re-running this transition. errorPlace?: string // Where to route when retries are exhausted (or no retry is configured). ``` **Backoff calculation (exponential):** `retryDelay * 2^(attempt - 1)`, capped at `retryMaxDelay`. | Attempt | Delay (default config) | | ------- | ---------------------- | | 1 | 1,000ms | | 2 | 2,000ms | | 3 | 4,000ms | | 4 | 8,000ms | | 5 | 16,000ms | | 6+ | 30,000ms (capped) | ### Reading the retry count Transitions can access the current retry count through `ctx.execution.retryCount`. It is 0-indexed: `0` on the first attempt, `1` after the first retry, and so on. Add `1` for a human-friendly attempt number when logging or branching on retries. ```typescript @Transition({ from: 'fetching', to: 'done', retryAttempts: 3 }) async fetchData(state: MyState, ctx: RunContext) { const attempt = (ctx.execution?.retryCount ?? 0) + 1; this.logger.log(`Fetch attempt ${attempt}`); // ... } ``` `ctx.execution` is optional in the type — guard with `?.` or `!` depending on your call site. `ctx.execution.place` is also available for the current place name. ## Timeout Every transition has a default timeout of **5 minutes** (300,000ms). If a transition takes longer, it's interrupted with `Error: Transition '...' timed out after ...ms` and flows through the normal retry logic. You can override the default globally with the `DEFAULT_TRANSITION_TIMEOUT` environment variable (in ms), or per-transition: ```typescript @Transition({ from: 'analyzing', to: 'analyzed', timeout: 5000 }) async analyzeData() { await this.analyzer.call({ dataset: this.data }); } ``` To disable the timeout for a specific transition, set `timeout: 0`: ```typescript @Transition({ from: 'processing', to: 'done', timeout: 0 }) async longRunningTask() { // No timeout — runs until completion } ``` You can combine timeout with retry: ```typescript @Transition({ from: 'analyzing', to: 'analyzed', timeout: 5000, retryAttempts: 2, }) async analyzeData() { await this.analyzer.call({ dataset: this.data }); } ``` Times out after 5s, retries up to 2 times, then falls to manual retry. ## What Gets Rolled Back When a transition fails, the framework rolls back: - **Documents** created during the transition (restored from snapshot) - **Database changes** within the transition's transaction - **Workflow state** stays at the pre-transition place What is **not** rolled back: - An `ErrorDocument` is saved after rollback as an audit trail - The error message is stored in workflow metadata - Workflow instance variables (`this.someField`) persist across retries — useful for attempt counters ## ErrorDocument Every failed transition creates an `ErrorDocument` with the error message: ```typescript // Automatically created by the framework: { className: 'ErrorDocument', content: { error: 'Connection refused: api.example.com' } } ``` Multiple `ErrorDocument`s accumulate if retries fail repeatedly — giving a full audit trail of each attempt. ## Registry References - [Auto Retry example](/docs/examples/error-handling#auto-retry) — `retryAttempts` re-runs a failing service call with exponential backoff until the third attempt succeeds. - [Retry Target example](/docs/examples/error-handling#retry-target) — `retryTarget` routes each retry through a credential-refresh place before the call runs again. - [Error Place example](/docs/examples/error-handling#error-place) — `errorPlace` moves a failed workflow to a recovery place with a Recover button. - [Manual Retry example](/docs/examples/error-handling#manual-retry) — The default: the failed workflow stays at its place and offers a Retry button. - [Transition Timeout example](/docs/examples/error-handling#transition-timeout) — `timeout` fails a transition that runs too long; the tool stops its work via `ctx.signal`. - [Sub-Workflow Error Place example](/docs/examples/error-handling#sub-workflow-error-place) — A failed child workflow callback is routed to a recovery place via `errorPlace`. --- > Source: https://loopstack.ai/llms/build/patterns/human-in-the-loop.md --- title: Human-in-the-Loop description: Pausing workflows for user input, review, or confirmation. Covers wait:true transitions on custom documents, AskUserWorkflow / ConfirmUserWorkflow sub-workflow shortcuts, and LLM-agent HITL via the ask_clarification and ask_for_approval tools. --- # Human-in-the-Loop Pause workflows for user input, review, or confirmation. Loopstack offers three distinct patterns — pick the one that matches who decides what to ask. ## Choosing a HITL Pattern | You are building... | Use | Where it lives | | --------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | | A predefined workflow with known user-input steps — form fields, structured records | **Custom document with a widget** — your workflow owns the document + `wait: true` | This page → [Wait Transition Pattern](#wait-transition-pattern) | | A predefined workflow that just needs a quick generic ask (free text, yes/no, pick one) | **`AskUserWorkflow` / `ConfirmUserWorkflow`** as a sub-workflow shortcut | This page → [Using HITL as a Sub-Workflow](#using-hitl-as-a-sub-workflow) | | An LLM agent loop where the agent dynamically decides when to ask | **Agent tools** `ask_clarification` / `ask_for_approval` | This page → [Agent-Driven HITL](#agent-driven-hitl) | The custom-document pattern is the **default for predefined workflows**: the form _is_ the structured data, the wait-transition payload schema _is_ the document schema, and types line up end-to-end. Sub-workflow shortcuts are for when designing a form would be overkill. Agent tools are for LLM-driven flows where the next question isn't known in advance. ## Wait Transition Pattern A transition with `wait: true` pauses the workflow until externally triggered by user interaction: ```typescript import type { TransitionInput } from '@loopstack/common'; @Transition({ from: 'waiting_for_user', to: 'ready', wait: true, schema: z.object({ message: z.string() }), }) async userMessage(state: Record, input: TransitionInput<{ message: string }>) { await this.documentStore.save(LlmMessageDocument, { role: 'user', text: input.data.message, }); } ``` ## Document Action Buttons Documents can include buttons that trigger `wait: true` transitions: ```yaml # Document YAML type: document ui: widgets: - widget: form options: properties: text: title: Text widget: textarea actions: - type: button transition: userResponse # Must match the method name label: 'Submit' ``` When the user clicks **Submit**, the workflow's `userResponse` method fires with the document's current content as the payload. ## Chat Input Widget For conversational UIs, use the `prompt-input` widget: ```yaml ui: widgets: - widget: prompt-input enabledWhen: - waiting_for_user options: transition: userMessage ``` ```typescript @Transition({ from: 'waiting_for_user', to: 'ready', wait: true, schema: z.string(), }) async userMessage(state: Record, input: TransitionInput) { await this.documentStore.save(LlmMessageDocument, { role: 'user', text: input.data, }); } ``` ## Confirmation Pattern Show AI-generated content for user review before proceeding: ```typescript import { z } from 'zod'; import { toJSONSchema } from 'zod'; import { BaseWorkflow, Transition, Workflow } from '@loopstack/common'; import type { RunContext } from '@loopstack/common'; import { LlmGenerateObjectTool } from '@loopstack/llm-provider'; interface MeetingNotesState { meetingNotes?: z.infer; } const MeetingNotesArgsSchema = z.object({ inputText: z.string().default('...') }); type MeetingNotesArgs = z.infer; @Workflow({ widget: './meeting-notes.ui.yaml', schema: MeetingNotesArgsSchema, }) export class MeetingNotesWorkflow extends BaseWorkflow { constructor(private readonly llmGenerateObject: LlmGenerateObjectTool) { super(); } @Transition({ to: 'waiting_for_response' }) async createForm(state: MeetingNotesState, ctx: RunContext) { await this.documentStore.save(MeetingNotesDocument, { text: ctx.args.inputText }, { key: 'input' }); } // Wait for user to edit and submit @Transition({ from: 'waiting_for_response', to: 'response_received', wait: true, schema: MeetingNotesDocumentSchema }) async userResponse(state: MeetingNotesState, input: TransitionInput>) { const result = await this.documentStore.save(MeetingNotesDocument, input.data, { key: 'input' }); this.assignState({ meetingNotes: result.content as z.infer }); } // AI generates structured output @Transition({ from: 'response_received', to: 'notes_optimized' }) async optimizeNotes(state: MeetingNotesState) { const result = await this.llmGenerateObject.call( { outputSchema: toJSONSchema(OptimizedMeetingNotesDocumentSchema) as Record, prompt: `Structure these notes: ${state.meetingNotes?.text}`, }, { config: { provider: 'claude', model: 'claude-sonnet-4-6' } }, ); const objectResult = result.data as LlmGenerateObjectResult; await this.documentStore.save( OptimizedNotesDocument, objectResult.data as z.infer, { key: 'final', validate: 'skip' }, ); } // Wait for user to confirm @Transition({ from: 'notes_optimized', to: 'end', wait: true, schema: OptimizedMeetingNotesDocumentSchema }) async confirm(state: MeetingNotesState, input: TransitionInput>) { await this.documentStore.save(OptimizedNotesDocument, input.data, { key: 'final' }); } } ``` ## `enabledWhen` and `showWhen` — Conditional Widgets Two widget keys gate a widget on the current workflow place. `enabledWhen` keeps the widget on screen but disables it outside the listed places: ```yaml ui: widgets: - widget: form enabledWhen: - review - editing options: properties: summary: title: Summary widget: textarea actions: - type: button transition: confirm label: 'Confirm' ``` The form is visible at every place, but it can only be edited and submitted while the workflow is at the `review` or `editing` place. `showWhen` hides the widget entirely outside the listed places — use it for a widget that should only exist at one step: ```yaml ui: widgets: - widget: prompt-input enabledWhen: - waiting_for_user options: transition: userMessage - widget: button showWhen: - awaiting_tools options: transition: cancelPendingTools label: Cancel pending tools ``` The prompt input is always on screen and disabled while the agent works; the cancel button is only rendered while the workflow is at `awaiting_tools`. When a widget sets both keys, `showWhen` decides whether it is rendered and `enabledWhen` whether it is enabled. See [Workflow YAML Schema — `showWhen`](../../reference/workflow-yaml.md#showwhen). When a park has more than one enabled widget — a confirmation document from a sub-workflow and the parent's chat input, say — Studio, the CLI and `parkView()` all pick the same one as the prompt: in run-tree order, and within each workflow its document prompts before its workflow-level widgets. [Prompt Selection Rules](../../reference/prompt-selection.md) describes the full order. ## Using HITL as a Sub-Workflow The `wait: true` pattern above is for workflows that own their own UI. For generic prompts you don't want to design a form for, run `AskUserWorkflow` or `ConfirmUserWorkflow` from `@loopstack/hitl` as a sub-workflow and receive the answer through a callback. The callback delivers the standard `TransitionInput` envelope — the `schema` on the transition describes only `data`, and `input.data` is fully typed. See [Sub-Workflows → Typing the Callback Envelope](./sub-workflows.md#typing-the-callback-envelope) for the full reference. ### `AskUserWorkflow` — free text ```typescript import { z } from 'zod'; import { BaseWorkflow, MessageDocument, Transition, type TransitionInput, Workflow } from '@loopstack/common'; import { AskUserWorkflow } from '@loopstack/hitl'; const AnswerSchema = z.object({ answer: z.string() }); @Workflow({ title: 'Ask Then Continue' }) export class AskThenContinueWorkflow extends BaseWorkflow { constructor(private readonly askUser: AskUserWorkflow) { super(); } @Transition({ to: 'waiting' }) async ask(state: Record) { await this.askUser.run({ question: 'What is your name?' }, { callback: { transition: 'onAnswer' } }); } @Transition({ from: 'waiting', to: 'end', wait: true, schema: AnswerSchema }) onAnswer(state: Record, input: TransitionInput<{ answer: string }>) { this.setResult({ name: input.data.answer }); } } ``` ### `AskUserWorkflow` — pick from options Pass `mode: 'options'` with a list of choices. `allowCustomAnswer: true` adds a free-text field alongside the choices for "other". ```typescript await this.askUser.run( { question: 'Which environment should we deploy to?', mode: 'options', options: ['staging', 'production'], allowCustomAnswer: true, }, { callback: { transition: 'choiceReceived' } }, ); ``` The envelope shape is the same as the free-text case (`input.data: { answer: string }`). ### `AskUserWorkflow` — yes / no Pass `mode: 'confirm'`. The answer comes back as the literal string `'yes'` or `'no'` in `input.data.answer` — compare directly. ```typescript await this.askUser.run( { question: 'Send the email now?', mode: 'confirm' }, { callback: { transition: 'decisionReceived' } }, ); ``` ### `ConfirmUserWorkflow` — markdown review For showing a pre-rendered markdown blob (a release plan, a summary, a code diff) and receiving an explicit approve/deny, use `ConfirmUserWorkflow`. The callback `input.data` carries both the user's decision and the original markdown: ```typescript import { ConfirmUserWorkflow } from '@loopstack/hitl'; const ConfirmSchema = z.object({ confirmed: z.boolean(), markdown: z.string() }); @Transition({ to: 'awaiting' }) async showSummary(state: Record) { await this.confirmUser.run( { markdown: '## Ready to deploy v1.2.3?\n\n- 3 commits since last release\n- Smoke tests passing' }, { callback: { transition: 'decisionReceived' } }, ); } @Transition({ from: 'awaiting', to: 'end', wait: true, schema: ConfirmSchema }) decisionReceived( state: Record, input: TransitionInput>, ) { this.setResult({ confirmed: input.data.confirmed }); } ``` ## Agent-Driven HITL When the asking party is an LLM agent rather than your workflow, use the `ask_clarification` and `ask_for_approval` tools from `@loopstack/hitl`. The agent decides at runtime to call the tool; the agent loop pauses, the user answers, and the answer flows back as the tool result — no extra wait-transition wiring at your level. ### `ask_clarification` — agent asks the user a question Register the tool in your module and add it to the agent's tool list. A system prompt that tells the agent to use the tool when info is missing is enough: ```typescript import { z } from 'zod'; import { AgentWorkflow } from '@loopstack/agent'; import { BaseWorkflow, MessageDocument, Transition, type TransitionInput, Workflow } from '@loopstack/common'; const AgentResponseSchema = z.object({ response: z.string() }); const SYSTEM_PROMPT = `You are a trip-planning assistant. - Before recommending a destination, you MUST know BOTH the user's budget AND climate preference. - If either is missing, your response MUST be exactly ONE tool call to "ask_clarification".`; @Workflow({ title: 'Trip Planner' }) export class TripPlannerWorkflow extends BaseWorkflow { constructor(private readonly agent: AgentWorkflow) { super(); } @Transition({ to: 'running' }) async start(state: Record) { await this.agent.run( { system: SYSTEM_PROMPT, tools: ['ask_clarification'], userMessage: 'Where should I go on holiday next month?', }, { callback: { transition: 'onComplete' } }, ); } @Transition({ from: 'running', to: 'end', wait: true, schema: AgentResponseSchema }) async onComplete(state: Record, input: TransitionInput<{ response: string }>) { await this.documentStore.save(MessageDocument, { role: 'assistant', text: input.data.response }); this.setResult({ response: input.data.response }); } } ``` `ask_clarification` supports the same `mode` arg as `AskUserWorkflow` (`'text'` / `'options'` / `'confirm'`) — the LLM can pick the right mode per call. ### `ask_for_approval` — agent asks the user to approve content Same shape, with `tools: ['ask_for_approval']`. The agent drafts content and passes it as the `concept` argument; the user sees the markdown and confirms or denies. The agent loop only resumes after the decision. ```typescript const SYSTEM_PROMPT = `You are a release-notes drafting assistant. - Your response MUST be exactly ONE tool call to "ask_for_approval". - The "concept" argument IS the markdown draft.`; await this.agent.run( { system: SYSTEM_PROMPT, tools: ['ask_for_approval'], userMessage: 'Draft release notes for v1.2.3.', }, { callback: { transition: 'onComplete' } }, ); ``` See [`@loopstack/hitl`](/docs/registry/hitl) for the full tool args reference. ## Registry References - [HITL examples](/docs/examples/hitl) — Side-by-side examples of every HITL pattern: custom document with widget, all `AskUserWorkflow` modes, `ConfirmUserWorkflow`, and both agent tools - [@loopstack/hitl](/docs/registry/hitl) — The underlying HITL module: `AskUserWorkflow`, `ConfirmUserWorkflow`, `ask_clarification`, `ask_for_approval` - [Meeting Notes example](/docs/examples/hitl#meeting-notes) — Full human-in-the-loop workflow with editable form, AI optimization, and user confirmation - [Prompt Input Chat example](/docs/examples/hitl#prompt-input-chat) — Chat input pattern with prompt-input widget --- > Source: https://loopstack.ai/llms/build/patterns/state-management.md --- title: State Management description: Defining, reading, and updating typed workflow state. Covers state interfaces, per-transition state typing, state persistence across transitions, and state access patterns. --- # State Management Workflow state is managed through a typed state interface passed as the first parameter to transition methods. Transitions return nothing — they write through setter methods on `BaseWorkflow`, and the engine persists the updated state automatically across transitions. Use `async` when the body awaits. ## Defining State Define a state interface and reference it on each transition's `state` parameter: ```typescript interface MyState { counter?: number; llmResult?: LlmGenerateTextResult; items?: string[]; } export class MyWorkflow extends BaseWorkflow { // State is typed per-transition via the `state` parameter — see below. } ``` State begins as an empty object `{}` — the initial transition is responsible for populating it. For this reason, **all properties on a state schema should be optional**. If a property is required, the empty starting state will fail validation immediately. Treat missing fields as the absence of data and read them defensively (`state.counter ?? 0`). ## Writing State `BaseWorkflow` exposes four setters. Pick the one that matches the write you want: | Setter | Effect | | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | | `this.assignState(partial)` | Shallow-merge `partial` into the current state. The most common form — leaves any field you don't mention untouched. | | `this.setState(full)` | Replace the state object outright. Use when you want to reset state or know you're writing every field. | | `this.assignResult(partial)` | Shallow-merge `partial` into the workflow's published `result` (the value parent callbacks and `WorkflowRunner` callers see). | | `this.setResult(full)` | Replace the published `result` outright. | Transitions return nothing — mutate state via setters. Returning a value is a runtime error. ```typescript @Transition({ from: 'ready', to: 'processed' }) async process(state: MyState) { const result = await this.llmGenerateText.call( {}, { config: { provider: 'claude', model: 'claude-sonnet-4-6' } }, ); this.assignState({ llmResult: result.data, counter: (state.counter ?? 0) + 1, items: [...(state.items ?? []), 'new item'], }); } ``` A transition that doesn't write state simply omits the setter call: ```typescript @Transition({ from: 'ready', to: 'logged' }) log(state: MyState) { this.logger.log(`counter = ${state.counter}`); } ``` If `stateSchema` is defined on the workflow, the merged state is validated after every write. ## Reading State Access state in any transition or guard method: ```typescript @Transition({ from: 'processed', to: 'end' }) async display(state: MyState) { await this.documentStore.save(MessageDocument, { role: 'assistant', text: `Processed ${state.counter} items. Result: ${state.llmResult?.text}`, }); } hasToolCalls(state: MyState): boolean { return state.llmResult?.message.stopReason === 'tool_use'; } ``` ## Publishing a Result The workflow's `result` field is what `WorkflowRunner.runSync()` returns and what parent callbacks receive as `input.data`. Write to it on the final transition (or any earlier transition that wants to surface partial output): ```typescript @Transition({ from: 'done', to: 'end' }) finish(state: MyState) { this.setResult({ concept: state.confirmedConcept! }); } ``` Use `this.assignResult(partial)` to build the result up across multiple transitions, and `this.setResult(full)` to replace it. Publish what callers need and keep working data in state. The [workflow result example](/docs/examples/advanced-workflows#workflow-result) builds its result across two transitions while its working data stays private. ## Persistence Across Pauses State survives when a workflow pauses at a `wait: true` transition and resumes later: ```typescript @Transition({ to: 'waiting' }) setup(state: MyState) { this.assignState({ counter: 42 }); // Set before pause } @Transition({ from: 'waiting', to: 'end', wait: true }) onResume(state: MyState) { // state.counter is still 42 } ``` ## Accessing Workflow Args Input arguments are available via `ctx.args`: ```typescript const MyArgsSchema = z.object({ value: z.number().default(150) }); type MyArgs = z.infer; @Workflow({ schema: MyArgsSchema, }) export class MyWorkflow extends BaseWorkflow { @Transition({ to: 'ready' }) setup(state: MyState, ctx: RunContext) { console.log(ctx.args.value); // 150 } } ``` ## Helper Methods Use regular private methods for reusable logic — no special decorator needed: ```typescript export class MyWorkflow extends BaseWorkflow { @Transition({ from: 'data_created', to: 'end' }) async showResults(state: MyState) { await this.documentStore.save(MessageDocument, { role: 'assistant', text: this.formatMessage(state.message!), }); } private formatMessage(text: string): string { return text.toUpperCase(); } } ``` ## Registry References - [WorkflowStateWorkflow](/docs/examples/advanced-workflows#workflow-state) — Stores state in a typed state interface, reads it in the next transition, uses a helper method - [WorkflowResultWorkflow](/docs/examples/advanced-workflows#workflow-result) — Builds the published result across two transitions with `assignResult()`, keeping working data in private state --- > Source: https://loopstack.ai/llms/build/patterns/sub-workflows.md --- title: Sub-Workflows description: Running workflows inside other workflows via .run(), the show option ('inline' | 'link' | 'hidden') for parent-view rendering, callback transitions, typing the callback envelope via TransitionInput, handling sub-workflow failures via input.hasError / input.errorMessage without try/catch, passing arguments to child workflows, receiving sub-workflow results, and coordinating multiple sub-workflows via FanOutWorkflow (parallel) and SequenceWorkflow (sequential) with 'all' / 'allSettled' failure modes. --- # Sub-Workflows Sub-workflows let you compose complex automations from smaller, reusable workflow building blocks. A parent workflow can launch one or more child workflows via `.run()`, pause until they complete, and receive results through a callback transition. ## Injecting a Sub-Workflow ```typescript import { QueueResult } from '@loopstack/common'; constructor(private readonly subWorkflow: SubWorkflow) { super(); } ``` ## Running a Sub-Workflow ```typescript @Transition({ to: 'sub_started' }) async start(state: MyState) { await this.subWorkflow.run( { prompt: 'Hello' }, // Args passed to the sub-workflow { callback: { transition: 'onSubComplete' } }, // Method to call when done ); } ``` The parent's run view automatically renders the child sub-workflow inline by default — there is no extra `documentStore.save(LinkDocument, …)` step. ## Controlling How the Child Appears: `show` The `show` option on `RunOptions` controls how the child sub-workflow is rendered inside the parent's run view: | `show` | What the parent sees | Use for | | ---------------------- | -------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | | `'inline'` _(default)_ | The child is embedded as an inline iframe; the user can interact with it in place. | HITL prompts, OAuth flows, agents whose progress you want visible. | | `'link'` | A status link card with the child's label and live status — opens the child in a separate window when clicked. | Long-running autonomous children the parent just tracks. | | `'hidden'` | Nothing is shown. | Background fan-out where surfacing each child would be noise. | ```typescript await this.askUser.run(args, { callback: { transition: 'answered' }, show: 'inline', // (default) embed the child UI in the parent's view label: 'Waiting for user answer', // optional — defaults to the child workflow's name }); await this.longJob.run(args, { callback: { transition: 'done' }, show: 'link', // status card, opens child in a separate window }); await this.background.run(args, { show: 'hidden', // no card at all }); ``` The link card's status is read live from the child workflow's actual state — it transitions from pending to success or failure automatically as the child runs. ## Receiving the Callback The sub-workflow's published `result` (built via `assignResult` / `setResult`) is passed as `input.data`: ```typescript import type { TransitionInput } from '@loopstack/common'; @Transition({ from: 'sub_started', to: 'sub_done', wait: true, schema: z.object({ message: z.string() }), }) async onSubComplete( state: MyState, input: TransitionInput<{ message: string }>, ) { await this.documentStore.save(MessageDocument, { role: 'assistant', text: `Sub-workflow said: ${input.data.message}`, }); } ``` ## Typing the Callback Envelope Every `wait: true` transition receives a `TransitionInput` envelope — the same shape whether the resume came from a sub-workflow completion or a frontend / API trigger: ```typescript interface TransitionInput { workflowId: string; status: 'completed' | 'failed' | 'canceled'; hasError: boolean; errorMessage: string | null; data: TData; meta?: TMeta; } ``` | Field | Type | What it is | | -------------- | ---------------- | ---------------------------------------------------------------------------------------------------------- | | `workflowId` | `string` | ID of the run that produced this resume (the child for sub-workflow callbacks, the parent for user input). | | `status` | enum | `'completed'` / `'failed'` / `'canceled'`. | | `hasError` | `boolean` | `true` if the trigger source ended in failure — branch on this, not on `status`. | | `errorMessage` | `string \| null` | Error message if `hasError`, otherwise `null`. | | `data` | `TData` | The validated payload (the child's published `result`, or the user's form data). | | `meta` | `TMeta?` | Optional correlation metadata passed via `callback.metadata`. Undefined for user-driven resumes. | The `schema` on `@Transition({ wait: true })` describes **only `data`** — the framework constructs the surrounding envelope. Type the parameter via `TransitionInput`: ```typescript import type { TransitionInput } from '@loopstack/common'; import { z } from 'zod'; const AnswerSchema = z.object({ answer: z.string() }); @Transition({ from: 'awaiting', to: 'end', wait: true, schema: AnswerSchema, }) onAnswer(state: MyState, input: TransitionInput<{ answer: string }>) { // input.workflowId, input.status, input.hasError available at the top level // input.data.answer is fully typed against AnswerSchema this.setResult({ answer: input.data.answer }); } ``` ## Error Handling When a sub-workflow throws, the failure does **not** bubble up through `run()` — `run()` only schedules the child. Instead, the parent's callback transition still fires, with `hasError: true` and `errorMessage` populated. The parent branches on `input.hasError`: ```typescript import { BaseWorkflow, MessageDocument, Transition, type TransitionInput, Workflow } from '@loopstack/common'; @Workflow({ title: 'Recovers from a Failing Child' }) export class RecoveringParentWorkflow extends BaseWorkflow { constructor(private readonly failingSub: FailingSubWorkflow) { super(); } @Transition({ to: 'awaiting' }) async launch(state: Record) { await this.failingSub.run({}, { callback: { transition: 'onFinished' }, show: 'link', label: 'Failing child' }); } @Transition({ from: 'awaiting', to: 'end', wait: true }) async onFinished(state: Record, input: TransitionInput) { if (input.hasError) { await this.documentStore.save(MessageDocument, { role: 'assistant', text: `Child failed: ${input.errorMessage ?? 'unknown error'} — continuing with a fallback.`, }); this.setResult({ recovered: true }); return; } this.setResult({ recovered: false }); } } ``` Two things to note: - **No try/catch at the parent.** The child's exception is captured by the framework, persisted on the child run, and surfaced through the envelope. The parent only sees `hasError`. - **The link card / inline iframe turns red automatically.** No extra UI wiring is needed to reflect the failure in the parent's run view. For `FanOutWorkflow` and `SequenceWorkflow` the same idea applies one level deeper: each item's per-result entry carries its own `hasError`, and the aggregate `input.data` exposes `hasErrors` and `errorCount`. ## Sub-Workflow Output The sub-workflow defines its output by writing to the run's `result` field via `this.assignResult(...)` or `this.setResult(...)`: ```typescript @Workflow({ widget: './sub.ui.yaml' }) export class SubWorkflow extends BaseWorkflow { @Transition({ to: 'end' }) start() { this.setResult({ message: 'Hi mom!' }); } } ``` ## Complete Example ```typescript @Workflow({ widget: './parent.ui.yaml' }) export class ParentWorkflow extends BaseWorkflow { constructor(private readonly subWorkflow: SubWorkflow) { super(); } @Transition({ to: 'sub_started' }) async runWorkflow(state: Record) { await this.subWorkflow.run( {}, { callback: { transition: 'subWorkflowCallback' }, show: 'link', label: 'Sub-Workflow' }, ); } @Transition({ from: 'sub_started', to: 'end', wait: true, schema: z.object({ message: z.string() }), }) async subWorkflowCallback(state: Record, input: TransitionInput<{ message: string }>) { await this.documentStore.save(MessageDocument, { role: 'assistant', text: `Message from sub-workflow: ${input.data.message}`, }); } } ``` ## Running Sub-Workflows in Parallel To launch multiple sub-workflows at the same time and receive a single aggregated callback when they all complete, use the built-in `FanOutWorkflow` from `@loopstack/core`. Inject it like any other sub-workflow. ```typescript import { z } from 'zod'; import { type TransitionInput } from '@loopstack/common'; import { FanOutResultSchema, FanOutWorkflow } from '@loopstack/core'; type FanOutResultData = z.infer; @Workflow({ title: 'Parallel Fan-Out' }) export class ParallelWorkflow extends BaseWorkflow { constructor(private readonly fanOut: FanOutWorkflow) { super(); } @Transition({ to: 'awaiting' }) async launch(state: Record) { await this.fanOut.run( { items: { user: { workflow: 'fetch_user', args: { id: 1 } }, orders: { workflow: 'fetch_orders', args: { id: 1 } }, }, }, { callback: { transition: 'onAllDone' } }, ); } @Transition({ from: 'awaiting', to: 'end', wait: true, schema: FanOutResultSchema }) onAllDone(state: Record, input: TransitionInput) { const user = (input.data.results as Record).user.data; const orders = (input.data.results as Record).orders.data; this.setResult({ user, orders }); } } ``` `items` accepts either a **keyed record** (results addressable by name) or an **array** of `{ workflow, args, label?, show? }` (results returned in input order with each entry's `key`). The `workflow` field is the canonical name string — either the explicit `@Workflow({ name })` value or the auto-derived snake_case form (e.g. `FetchUserWorkflow` → `'fetch_user'`). ### Failure modes | `mode` | Behavior | | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `'all'` _(default)_ | First failure triggers `cancelChildren` on the parent; the callback fires once every in-flight child has settled (canceled siblings also send callbacks). `input.data.hasErrors` is `true`. | | `'allSettled'` | Every child runs to completion regardless of siblings; the callback aggregates `completed` / `failed` results for every item. | ## Running Sub-Workflows in Sequence To run sub-workflows one after another with a single aggregated callback at the end, use `SequenceWorkflow`. Same call shape as `FanOutWorkflow`, same `'all'` / `'allSettled'` modes. ```typescript import { type TransitionInput } from '@loopstack/common'; import { SequenceResultSchema, SequenceWorkflow } from '@loopstack/core'; import { z } from 'zod'; type SequenceResultData = z.infer; @Workflow({ title: 'Sequential' }) export class SequentialWorkflow extends BaseWorkflow { constructor(private readonly sequence: SequenceWorkflow) { super(); } @Transition({ to: 'awaiting' }) async launch(state: Record) { await this.sequence.run( { items: [ { workflow: 'step_a', args: { ... }, label: 'step-1' }, { workflow: 'step_b', args: { ... }, label: 'step-2' }, { workflow: 'step_c', args: { ... }, label: 'step-3' }, ], }, { callback: { transition: 'onComplete' } }, ); } @Transition({ from: 'awaiting', to: 'end', wait: true, schema: SequenceResultSchema }) onComplete(state: Record, input: TransitionInput) { this.setResult({ results: input.data.results }); } } ``` In `mode: 'all'`, a failure aborts the sequence and remaining items are marked `'skipped'` in the result. In `mode: 'allSettled'`, the sequence continues past failures. `FanOutWorkflow` and `SequenceWorkflow` are auto-registered by `LoopstackModule.forRoot()` — there is no manual `providers: [...]` entry needed for them. You still register your own sub-workflows normally. ## Registering Sub-Workflows Both workflows must be registered in the module: ```typescript @Module({ providers: [ParentWorkflow, SubWorkflow], exports: [ParentWorkflow, SubWorkflow], }) export class MyModule {} ``` ## Wrapping as a Task Tool A task tool is a `BaseTool` that launches a sub-workflow and returns `pending`. The framework calls `complete()` when the sub-workflow finishes. This lets agents decide when to run sub-workflows. ```typescript @Tool({ name: 'run_tests', description: 'Run tests in the specified directory.', schema: z.object({ testDirectory: z.string().describe('Directory containing the test files to run.'), }), }) export class RunTestsTask extends BaseTool { constructor(private readonly testRunner: TestRunnerWorkflow) { super(); } protected async handle( args: { testDirectory: string }, ctx: RunContext, options?: ToolCallOptions, ): Promise { const result = await this.testRunner.run( { testDirectory: args.testDirectory }, { callback: options?.callback, show: 'inline', label: 'Running tests...' }, ); return { data: { workflowId: result.workflowId }, pending: { workflowId: result.workflowId }, }; } async complete(result: Record): Promise { const data = result as { data?: { passed: boolean; output: string } }; return { data: data.data ?? result }; } } ``` Key parts: - **`pending: { workflowId }`** tells the framework this tool is async — the parent workflow waits for a callback - **`callback: options?.callback`** passes the parent's callback config to the sub-workflow - **`show`** decides how the child appears in the parent's run view (`'inline'` by default) - **`complete()`** is called when the sub-workflow finishes — transform results and return the tool's final value here ## Nested Agents The sub-workflow can be an `AgentWorkflow` itself, enabling multi-agent architectures. See [Agent Workflows](../ai/agent-workflows.md) for the full pattern. ## Registry References - [Sub-Workflow example](/docs/examples/advanced-workflows#sub-workflow) — Parent calling sub-workflows with callbacks and typed output, all three `show` modes chained, `FanOutWorkflow` / `SequenceWorkflow` coordination, and a failing-child workflow paired with a parent that branches on `input.hasError` - [@loopstack/code-agent](/docs/registry/code-agent) — ExploreTask wrapping AgentWorkflow as a task tool --- > Source: https://loopstack.ai/llms/build/patterns/templates.md --- title: Template Expressions description: Rendering dynamic text content with Handlebars templates via this.render(). Covers template syntax, variable interpolation, helpers, and use in prompts. --- # Template Expressions Use Handlebars templates to render dynamic text content in workflows. Call `this.render()` from any `BaseWorkflow` to interpolate state values, format prompts, and generate dynamic output. ## Setup ```typescript import { BaseWorkflow, Transition, Workflow } from '@loopstack/common'; @Workflow({}) export class MyWorkflow extends BaseWorkflow { // this.render() is available from BaseWorkflow — no injection needed } ``` ## Usage ```typescript import { join } from 'node:path'; const rendered = this.render(join(__dirname, 'templates', 'prompt.md'), { subject: args.subject, items: state.items, }); ``` `this.render()` expects an absolute path. Build it with `path.join(__dirname, ...)` so templates resolve relative to the workflow's compiled `.js` file at runtime (where the `templates/` folder is copied during build). Template file (`templates/prompt.md`): ```markdown Write a haiku about {{subject}}. {{#each items}} - {{this.name}} {{/each}} ``` ## Passing Data Pass any data as the second argument to `this.render()`: ```typescript // Workflow args (from ctx parameter — typed via RunContext<{ subject: string }>) this.render(templatePath, { subject: ctx.args.subject }); // Workflow state (from state parameter) this.render(templatePath, { items: state.items, count: state.counter }); // Mixed data this.render(templatePath, { prompt: ctx.args.prompt, history: state.conversationHistory, timestamp: new Date().toISOString(), }); ``` ## Handlebars Syntax ### Variables ```markdown Hello {{name}} Nested: {{user.profile.email}} Array element: {{items.[0]}} ``` ### Conditionals ```markdown {{#if isActive}}Welcome back!{{else}}Please log in{{/if}} {{#unless isBlocked}}Access granted{{/unless}} ``` ### Iteration ```markdown {{#each items}} - {{this.name}}: {{this.value}} {{else}} No items found. {{/each}} ``` ### Context Scoping ```markdown {{#with user}}{{name}} ({{email}}){{/with}} ``` ## Multi-line Template Example ```markdown # Events This Week {{#each events}} - **{{this.summary}}**: {{this.start}} – {{this.end}} {{/each}} {{#unless events}} No events found. {{/unless}} ``` ## When to Use Templates | Scenario | Approach | | ----------------------------------- | --------------------------------- | | LLM prompts with variables | `this.render(templatePath, data)` | | Simple string interpolation | Template literals in TypeScript | | Complex multi-line content | Handlebars template file | | Prompts with iteration/conditionals | Handlebars with `#each`, `#if` | ## YAML UI Config YAML widget configuration uses `transition` values that reference method names and `enabledWhen` / `showWhen` to enable or show widgets only at certain places. These are not template expressions — they are static configuration: ```yaml ui: widgets: - widget: prompt-input enabledWhen: [waiting_for_user] options: transition: userMessage ``` ## Registry References - [Prompt example](/docs/examples/llm#prompt) — Uses `this.render()` for Handlebars prompt templates - [Meeting Notes example](/docs/examples/hitl#meeting-notes) — Renders the LLM prompt that extracts structured notes from a template ---