# Build / Fundamentals --- > Source: https://loopstack.ai/llms/build/fundamentals/documents.md --- title: Creating Documents description: How to define typed document classes with @Document() decorator, Zod validation schemas, and YAML widget configs for rendering in Loopstack Studio. --- # Creating Documents Documents are typed data objects displayed in the Loopstack Studio UI. They have a Zod schema for validation and a YAML config for rendering. ## Basic Document ```typescript import { z } from 'zod'; import { Document } from '@loopstack/common'; export const NotesSchema = z.object({ text: z.string(), }); @Document({ schema: NotesSchema, widget: './notes.ui.yaml', }) export class NotesDocument { text: string; } ``` ```yaml # notes.ui.yaml type: document ui: widgets: - widget: form options: properties: text: title: Notes widget: textarea rows: 8 ``` ## The `@Document` Decorator ```typescript @Document({ schema: NotesSchema, widget: './notes.ui.yaml', }) ``` All options are optional. | Option | Type | Default | Description | | ------------- | -------------------------- | ------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | `string` | class name with `Document` suffix stripped, snake_cased | Explicit snake_case identifier. E.g. `AskUserDocument` → `ask_user`, `LlmMessageDocument` → `llm_message`. | | `title` | `string` | — | Human-readable display title shown in Studio UI. | | `description` | `string` | — | Human-readable description shown in Studio UI. | | `widget` | `WidgetRef \| WidgetRef[]` | — | Path(s) to YAML file(s) — or inline widget object(s) — defining how the document renders in Studio. | | `schema` | `z.ZodType` | — | Zod schema validating document content on `documentStore.save()`. | | `tags` | `string[]` | — | Default tags assigned to every instance of this document. Useful for filtering and querying. | | `meta` | `StaticDocumentMeta` | — | Static document metadata — served via the config endpoint, not persisted per instance. | | `internal` | `boolean` | `false` | When `true`, instances are persisted server-side (still readable by LLM providers) but excluded from API responses and live updates — Studio never sees them. Use for framework plumbing like LLM context. | > **Documents are plain DTOs, not NestJS providers.** Unlike `@Tool` and `@Workflow`, `@Document` does **not** apply `@Injectable()`. Don't add document classes to a module's `providers` array and don't try to inject them — reference the class directly when calling `documentStore.save(MyDocument, ...)`. ## Saving Documents Use `this.documentStore.save()` inside workflow transition methods. Reference document classes directly — no injection needed. `documentStore` is auto-injected on `BaseWorkflow` and `BaseTool`. ```typescript // Create a new document await this.documentStore.save(NotesDocument, { text: 'Hello!' }); // A new revision under a key — invalidates the previous version, placed at the end await this.documentStore.save(NotesDocument, { text: 'Revised content' }, { key: 'notes-1' }); // Update in place — the new revision takes the place of the previous one await this.documentStore.save(NotesDocument, { text: 'Updated content' }, { key: 'notes-1', position: 'keep' }); // With meta options (free-form extension data on the document row) await this.documentStore.save(NotesDocument, { text: 'Tagged note' }, { meta: { source: 'import' } }); ``` ### Saving an Instance `save()` is overloaded — instead of passing class + data, you can `create()` an instance, mutate it, then save it. Useful when you need to build up a document across several steps before persisting. ```typescript const draft = this.documentStore.create(NotesDocument, { text: 'Initial draft' }); draft.text += '\n\nAddendum.'; await this.documentStore.save(draft); // With save options await this.documentStore.save(draft, { key: 'notes-1' }); ``` `create()` returns a class instance (typed as `NotesDocument`) populated with the data; it does not persist anything. Persistence only happens on `save()`. ### Save Options | Option | Type | Description | | ----------------- | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `key` | `string` | Stable revision key — saving again with the same `key` writes a new revision and invalidates the previous ones. | | `position` | `'keep' \| 'end'` | Where a keyed save puts the new revision. Default `'end'` — appended, below everything saved since. `'keep'` — in the place of the revision it supersedes; use for documents that update over time (status tickers, form state, transcripts). | | `validate` | `'strict' \| 'safe' \| 'skip'` | Validation mode. Default `'strict'` — throws on invalid content. `'safe'` stores partial data + error. `'skip'` bypasses validation. See [Validation](../../learn/document-store.md#validation). | | `meta` | `Record` | Free-form extension data persisted on the document row. Use for ad-hoc payload that downstream readers need. For framework concerns (hide from UI, etc.), use decorator options instead. | | `meta.invalidate` | `boolean` | When `false`, prevents the previous version with the same `key` from being invalidated. Default behavior replaces the old version. | ## Querying Documents `documentStore` exposes three read methods. All of them return only **non-invalidated** documents for the current workflow run — invalidated revisions are filtered out automatically. | Method | Returns | When to use | | --------------------- | ------------------ | -------------------------------------------------------------------- | | `findAll(MyDocument)` | `MyDocument[]` | All documents of one type, **hydrated as typed instances**. | | `findByTag('tag')` | `DocumentEntity[]` | Documents tagged with that tag (across types). Returns raw entities. | | `findAllDocuments()` | `DocumentEntity[]` | Everything in the run — useful for LLM tools, history scans. | ```typescript // Typed, type-safe — preferred const notes = this.documentStore.findAll(NotesDocument); notes.forEach((n) => console.log(n.text)); // By tag — across document types const messages = this.documentStore.findByTag('message'); // All documents in this run (raw entities) const all = this.documentStore.findAllDocuments(); ``` `findAll` re-validates and hydrates entities back into class instances (via `plainToInstance`). `findByTag` and `findAllDocuments` return raw `DocumentEntity` objects — use `entity.content` for the persisted data and `entity.documentName` to discriminate types. > Need a typed instance without persisting? Use [`documentStore.create(MyDocument, data)`](#saving-an-instance) — it validates against the Zod schema and returns a class instance with no DB write. ## Built-in Document Types These are available without creating custom documents: | Document | Source | Key Fields | | -------------------- | ------------------------- | ------------------------------------------ | | `LlmMessageDocument` | `@loopstack/llm-provider` | `role`, `text`, `blocks` | | `LlmContextDocument` | `@loopstack/llm-provider` | `role`, `text` | | `LinkDocument` | `@loopstack/common` | `label`, `workflowId`, `embed`, `expanded` | | `MessageDocument` | `@loopstack/common` | `role`, `text` | | `MarkdownDocument` | `@loopstack/common` | `markdown` | | `PlainDocument` | `@loopstack/common` | `text` | | `ErrorDocument` | `@loopstack/common` | `error` | ### Choosing the right built-in type - **`LlmMessageDocument`** — visible assistant/user conversation turns. Extends `MessageDocument` with structured `blocks` (tool calls, thinking, tool results) and an LLM `stopReason`. Tagged `'message'`, so it's automatically collected into LLM conversation history. The LLM provider tools save these for you in normal use. - **`LlmContextDocument`** — hidden conversation context. Declared `@Document({ internal: true, tags: ['message'] })`. The LLM provider picks these up as conversation history just like `LlmMessageDocument`, but Studio doesn't show them. Use to seed system prompts, prior steps, or background info without polluting the user-facing chat. - **`MessageDocument`** — plain `{ role, text }` UI bubbles for non-LLM flows (status updates, narrative output, logging a `system` note). Tagged `'ui-message'` — **not** collected into LLM history. Use this when you want a chat-style message in Studio without polluting the LLM's context. - **`MarkdownDocument`** — formatted prose, headings, lists, links. Use when you want Studio to render rich text. - **`PlainDocument`** — unformatted text output: raw command output, log dumps, plain blob. Use when Markdown rendering would interpret characters you want shown literally. - **`LinkDocument`** — links to other workflow runs (sub-workflows, related runs). Studio renders these as cards with a live status indicator derived from the linked workflow's state. The orchestrator saves one automatically when you call `subWorkflow.run()` (see [Sub-Workflows](../patterns/sub-workflows.md)); save manually only if you need a link card outside the standard sub-workflow flow. - **`ErrorDocument`** — engine-managed; do not construct manually. Written automatically when a transition fails (see [Workflow Engine — ErrorDocument](../../learn/workflow-engine.md#errordocument)). ```typescript import { LinkDocument, MarkdownDocument, PlainDocument } from '@loopstack/common'; import { LlmMessageDocument } from '@loopstack/llm-provider'; await this.documentStore.save(LlmMessageDocument, { role: 'assistant', text: 'Hello! How can I help?', }); await this.documentStore.save(MarkdownDocument, { markdown: '# Report\n- Item 1\n- Item 2', }); // Raw command output — keep characters literal await this.documentStore.save(PlainDocument, { text: shellOutput }); ``` ## YAML UI Configuration ### Form Widget The `form` widget renders document fields as an editable form: ```yaml type: document ui: widgets: - widget: form options: order: [name, description, items] properties: name: title: Name description: title: Description widget: textarea items: title: Items collapsed: true items: title: Item actions: - type: button transition: submit label: 'Submit' ``` ### Available Widget Types Use these in `options.properties..widget`: | Widget | Description | | ----------- | ------------------------------------ | | `text` | Single-line text input (default) | | `textarea` | Multi-line text area | | `select` | Dropdown select | | `radio` | Radio button group | | `checkbox` | Checkbox | | `switch` | Toggle switch | | `slider` | Numeric slider | | `code-view` | Code editor with syntax highlighting | ### Property Options | Option | Type | Description | | ------------- | --------- | ---------------------------------- | | `title` | `string` | Display label | | `widget` | `string` | Widget type | | `placeholder` | `string` | Placeholder text | | `rows` | `number` | Visible rows (textarea) | | `readonly` | `boolean` | Read-only field | | `hidden` | `boolean` | Hide the field | | `disabled` | `boolean` | Disable interaction | | `collapsed` | `boolean` | Collapse arrays/objects by default | | `items` | `object` | UI config for array items | ### Document Actions Buttons that trigger `wait: true` transitions in the workflow: ```yaml actions: - type: button transition: confirm # Must match the method name label: 'Confirm' ``` ### Tags Tags categorize documents for filtering and searching. There are two ways to set them: **Decorator default tags** — written to every instance, persisted on each row, queryable via `findByTag()`: ```typescript @Document({ schema: NotesSchema, widget: './notes.ui.yaml', tags: ['message', 'important'], }) export class NotesDocument { /* ... */ } ``` **YAML config tags** — static metadata served via the config endpoint, used by Studio and LLM tools for grouping/filtering, not persisted on individual rows: ```yaml type: document tags: - message - important ``` Decorator tags are the right choice for runtime querying — every saved instance carries them, and `this.documentStore.findByTag('message')` returns them. YAML tags are for static document-type metadata. Tags from both sources are also used by LLM tools with `messagesSearchTag` config to collect documents as conversation history. ## Structured Output Example Documents work with `LlmGenerateObjectTool` for AI-generated structured data: ```typescript export const FileDocumentSchema = z .object({ filename: z.string(), description: z.string(), code: z.string(), }) .strict(); @Document({ schema: FileDocumentSchema, widget: './file-document.yaml', }) export class FileDocument { filename: string; description: string; code: string; } ``` ```yaml # file-document.yaml type: document ui: widgets: - widget: form options: order: [filename, description, code] properties: filename: title: File Name readonly: true description: title: Description readonly: true code: title: Code widget: code-view ``` Used in a workflow: ```typescript const result = await this.llmGenerateObject.call( { outputSchema: toJSONSchema(FileDocumentSchema) as Record, prompt: 'Generate a Hello World script in Python', }, { config: { provider: 'claude', model: 'claude-sonnet-4-6' } }, ); ``` ## Registry References - [Structured Output example](/docs/examples/llm#structured-output) — FileDocument with code-view widget for AI-generated code - [Meeting Notes example](/docs/examples/hitl#meeting-notes) — MeetingNotesDocument and OptimizedNotesDocument with form widgets and action buttons - [UI Documents example](/docs/examples/advanced-workflows#ui-documents) — Demonstrates all core UI document types: MessageDocument, ErrorDocument, MarkdownDocument, PlainDocument --- > **Using an AI coding agent?** See [Skill: Create a Custom Document](../../skills/create-custom-document.md) for a dense checklist and syntax reference optimized for code generation. --- > Source: https://loopstack.ai/llms/build/fundamentals/modules.md --- title: Modules & Workspaces description: How to organize workflows, tools, and services into NestJS modules. Covers @StudioApp decorator for app identity, module structure, app modules vs feature modules, workspace configuration, forRoot/forFeature patterns, and provider registration. --- # Modules & Workspaces Loopstack uses NestJS modules to organize your application. Workflows and tools are registered as standard NestJS providers. ## App Modules (`@StudioApp`) Every module whose workflows should be **visible and launchable in Loopstack Studio** must be decorated with `@StudioApp`. Without it, workflows are registered as NestJS providers but do not appear in the Studio UI. ```typescript import { Module } from '@nestjs/common'; import { ClaudeModule } from '@loopstack/claude'; import { StudioApp } from '@loopstack/common'; import { MyTool } from './tools/my.tool'; import { MyWorkflow } from './workflows/my.workflow'; @StudioApp({ title: 'My App', workflows: [MyWorkflow], }) @Module({ imports: [ClaudeModule], providers: [MyWorkflow, MyTool], }) export class MyAppModule {} ``` `@StudioApp` options: - **`title`** (required) — display name shown in Studio - **`workflows`** — array of workflow classes launchable from Studio - **`app`** — explicit snake_case identifier (defaults to module class name with `Module` → `App`, e.g. `HelloModule` → `hello_app`, `CodeAgentModule` → `code_agent_app`) - **`description`** — human-readable description - **`ui`** — Studio UI options for this app. See [Studio Configuration](./studio-config.md). > **Important:** `@StudioApp` is a metadata decorator — it does not replace `@Module`. Both decorators are required on the same class. ### Recommended File Layout A typical app module groups workflows, tools, services, documents, and tests like this: ``` my-app/ └── src/ ├── my-app.module.ts # @StudioApp + @Module ├── index.ts # public exports ├── workflows/ │ ├── index.ts │ ├── my.workflow.ts │ ├── my.ui.yaml # widget config for Studio │ └── __tests__/ │ └── my.workflow.spec.ts ├── tools/ │ ├── index.ts │ ├── my.tool.ts │ └── __tests__/ │ └── my.tool.spec.ts ├── documents/ │ ├── my-document.ts # @Document class │ └── my-document.yaml # UI/widget metadata ├── services/ │ └── my.service.ts └── templates/ └── prompt.md # Handlebars templates ``` Conventions: - **`__tests__/`** folder next to source for `*.spec.ts` files - **`workflows/`, `tools/`, `documents/`, `services/`, `templates/`** as sibling folders under `src/` - **`index.ts`** re-exports public symbols (used when this module is consumed as a package) - Document classes (`*.ts`) and their widget config (`*.yaml`) sit side by side Smaller modules can collapse this — a one-workflow module often keeps everything flat under `src/`. Use this layout as the upper bound, not a requirement. See the [Custom Tool example](/docs/examples/advanced-workflows#custom-tool) and the [Meeting Notes example](/docs/examples/hitl#meeting-notes) for concrete references. ### App Modules vs Feature Modules There are two kinds of modules in a Loopstack project: - **App modules** — decorated with `@StudioApp`, define a launchable application in Studio. They list workflows in the `workflows` array. - **Feature modules** — plain `@Module` classes that provide reusable tools, services, or workflows. They are imported by app modules but don't appear in Studio on their own. Registry packages (like `ClaudeModule`, `SandboxToolModule`, or example workflows) are feature modules. When you import them, you still need a `@StudioApp` module to surface their workflows in Studio. > Feature modules are auto-discovered when reachable from a `@StudioApp` module's import graph. Some modules also opt into a Studio UI surface (panel, widget) via `forFeature()` — see [Studio Features](../../extend/features.md) for details. > **`@StudioApp` modules must not be nested.** An app module cannot import another app module — Loopstack throws at bootstrap if it detects this. Always import each app module independently from your root `AppModule`. Shared logic belongs in plain feature modules. ## Feature Modules A feature module groups related workflows, tools, and services together for reuse across app modules. ```typescript import { Module } from '@nestjs/common'; import { ClaudeModule } from '@loopstack/claude'; import { MyTool } from './tools/my.tool'; import { MyWorkflow } from './workflows/my.workflow'; @Module({ imports: [ClaudeModule], providers: [MyWorkflow, MyTool], exports: [MyWorkflow, MyTool], }) export class MyFeatureModule {} ``` ### Key Rules - **`LoopCoreModule` is global** — registered once by `LoopstackModule.forRoot()`, do not import it in feature modules - **Import feature modules** like `ClaudeModule` for AI, `SandboxToolModule` for Docker sandboxes, etc. - **Documents are NOT providers** — they are plain DTOs and don't need registration - **Export workflows and tools** that other modules might need ### Registering in AppModule Add your module to the main `AppModule`: ```typescript import { Module } from '@nestjs/common'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { MyFeatureModule } from './my-feature/my-feature.module'; @Module({ imports: [LoopstackModule.forRoot(), MyFeatureModule], }) export class AppModule {} ``` ### Multi-Module Example For larger applications, split functionality across app modules and shared feature modules: ```typescript // analytics.module.ts — app module (visible in Studio) @StudioApp({ title: 'Analytics', workflows: [AnalyticsWorkflow], }) @Module({ imports: [ClaudeModule], providers: [AnalyticsWorkflow, DataFetchTool], }) export class AnalyticsModule {} // shared-tools.module.ts — feature module (not visible in Studio) @Module({ providers: [EmailTool, SlackTool], exports: [EmailTool, SlackTool], }) export class SharedToolsModule {} // notifications.module.ts — app module (visible in Studio) @StudioApp({ title: 'Notifications', workflows: [NotificationWorkflow], }) @Module({ imports: [SharedToolsModule], providers: [NotificationWorkflow], }) export class NotificationsModule {} // app.module.ts @Module({ imports: [LoopstackModule.forRoot(), AnalyticsModule, NotificationsModule], }) export class AppModule {} ``` ## Module Configuration (`forRoot` / `forFeature`) Many Loopstack modules support `forRoot()` and `forFeature()` for configuring defaults. This follows the standard NestJS dynamic module pattern. - **`forRoot(config)`** — sets **global defaults** for the module. Call once in your root `AppModule`. - **`forFeature(config)`** — **overrides defaults** for a specific feature module. Tools in that module use the override instead of the global. ```typescript // app.module.ts — global default: all LLM calls use claude-sonnet-4-6 @Module({ imports: [ LoopstackModule.forRoot(), LlmProviderModule.forRoot({ model: 'claude-sonnet-4-6' }), ClaudeModule, MyFeatureModule, ], }) export class AppModule {} // my-feature.module.ts — this module's LLM calls use claude-opus-4-6 instead @Module({ imports: [LlmProviderModule.forFeature({ model: 'claude-opus-4-6' })], providers: [MyWorkflow], }) export class MyFeatureModule {} ``` Each `forFeature()` import creates an isolated scope — tools in `MyFeatureModule` see the override, while tools in any other module continue to see the global `forRoot()` default. Multiple `forFeature()` calls in different modules coexist without interfering, each with its own resolved config. Modules that support this pattern include `LlmProviderModule`, `RemoteClientModule`, `SecretsModule`, and others. Per-call config (via `options.config`) always takes priority over module defaults. ### Creating Your Own Configurable Module Authoring a module that supports `forRoot()` / `forFeature()` requires three pieces: 1. A **config injection token** (a `Symbol`) and a `Config` interface — so providers can `@Inject()` the resolved config. 2. A **separate `@Global()` root module** that provides the default config and exports the tools. Keeping it as its own class prevents NestJS from deduplicating it with `forFeature()` imports. 3. A **wrapper module** exposing the static `forRoot()` and `forFeature()` factories that return `DynamicModule`s with the overridden config. ```typescript // my-feature.constants.ts export const MY_FEATURE_CONFIG = Symbol('MY_FEATURE_CONFIG'); export interface MyFeatureConfig { apiKey?: string; region?: string; } ``` ```typescript // my-feature.module.ts import { DynamicModule, Global, Module } from '@nestjs/common'; import { MY_FEATURE_CONFIG, MyFeatureConfig } from './my-feature.constants.js'; import { MyTool } from './my.tool.js'; const DEFAULT_CONFIG: MyFeatureConfig = {}; const TOOLS = [MyTool]; @Global() @Module({ providers: [{ provide: MY_FEATURE_CONFIG, useValue: DEFAULT_CONFIG }, ...TOOLS], exports: [MY_FEATURE_CONFIG, ...TOOLS], }) class MyFeatureRootModule {} @Module({}) export class MyFeatureModule { static forRoot(config: MyFeatureConfig): DynamicModule { return { module: MyFeatureRootModule, global: true, providers: [{ provide: MY_FEATURE_CONFIG, useValue: config }, ...TOOLS], exports: [MY_FEATURE_CONFIG, ...TOOLS], }; } static forFeature(config: MyFeatureConfig): DynamicModule { return { module: MyFeatureModule, imports: [MyFeatureRootModule], providers: [{ provide: MY_FEATURE_CONFIG, useValue: config }, ...TOOLS], exports: [...TOOLS], }; } } ``` Providers then inject the resolved config via the token: ```typescript @Tool({ name: 'my_tool' }) export class MyTool extends BaseTool { constructor(@Inject(MY_FEATURE_CONFIG) private readonly config: MyFeatureConfig) { super(); } } ``` The `forFeature()` import of `MyFeatureRootModule` ensures the global default is always available — bare `import MyFeatureModule` works even if `forRoot()` was never called. **Why `@Global()`?** The `@Global()` decorator is a [standard NestJS feature](https://docs.nestjs.com/modules#global-modules) that makes a module's exports available to every other module in the application without an explicit `imports: [...]` entry. The root module uses it so that `MY_FEATURE_CONFIG` and the tools are injectable anywhere — including in modules that never call `forRoot()` or `forFeature()`. This is also why `LoopCoreModule` is marked global by `LoopstackModule.forRoot()`. Use `@Global()` sparingly for app-wide singletons; prefer per-module imports for scoped behavior. See [Module Config example](/docs/examples/advanced-workflows#module-config) for a complete runnable example, including a nested wrapper module that passes config through to the underlying configurable module. ## Dependency Injection Workflows and tools use standard NestJS constructor injection: ```typescript @Workflow({ widget: './chat.ui.yaml', }) export class ChatWorkflow extends BaseWorkflow { constructor( private readonly llmGenerateText: LlmGenerateTextTool, private readonly myTool: MyCustomTool, ) { super(); } } ``` Sub-workflows are also injected via constructor: ```typescript export class ParentWorkflow extends BaseWorkflow { constructor(private readonly subWorkflow: SubWorkflow) { super(); } } ``` ## Using in Loopstack Studio Once registered: 1. Open Loopstack Studio at `http://localhost:5173` 2. Your workspace appears in the sidebar 3. Click a workflow to create a new run 4. Fill in the input form and start the workflow ## Registry References - [Prompt Input Chat example](/docs/examples/hitl#prompt-input-chat) — Part of `HitlExamplesModule`, which imports `ClaudeModule` beside `HitlModule` and `AgentModule` - [Custom Tool example](/docs/examples/advanced-workflows#custom-tool) — Module with custom tools, services, and workflow providers - [Sub-Workflow example](/docs/examples/advanced-workflows#sub-workflow) — Module registering both parent and sub-workflow providers --- > Source: https://loopstack.ai/llms/build/fundamentals/studio-config.md --- title: Studio Configuration description: Reference for the `ui` option on @StudioApp. Documents StudioUiConfig, the StudioWidgetConfig widget array, and the app-level start-form widget (options workflow, title, subtitle, label) that adds launch cards with a workflow's args form to the workspace home page. --- # Studio Configuration The `ui` option on `@StudioApp` controls how an app is rendered in Loopstack Studio. This page is the single reference for those options. More options will be added over time. ## `ui.widgets` `widgets` is an array of widget descriptors. Each entry names a widget and may pass widget-specific options. ```typescript @StudioApp({ title: 'My App', workflows: [ReportWorkflow], ui: { widgets: [{ widget: 'start-form', options: { workflow: 'report', title: 'Create a report' } }], }, }) @Module({ /* ... */ }) export class MyAppModule {} ``` Each entry has: - **`widget`** — the widget identifier - **`options`** — optional, widget-specific configuration At app level, Studio renders one widget: [`start-form`](#start-form). Document and workflow YAML configs use the same `{ widget, options }` format under `ui.widgets[]`, with their own widgets (for example `prompt-input`, `button` and `form`). ### `start-form` A `start-form` entry adds a launch card to the workspace home page — the page Studio opens when you open a workspace of the app, for example after creating it from the app launcher. Each card starts one workflow. Several entries stack as several cards, in array order. An app without `start-form` entries has no home page content. | Option | Required | Default | Description | | ---------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------- | | `workflow` | yes | — | Name of the workflow to start — `@Workflow({ name })`, or the class name without `Workflow`, snake_cased (`ReportWorkflow` → `report`) | | `title` | no | — | Heading of the card | | `subtitle` | no | — | Short text under the heading | | `label` | no | `Run` | Text of the submit button | Studio looks the workflow up among the app's `workflows`. When the workflow declares an args `schema`, the card renders it as a form and the submitted values become the run's args. Without a `schema` the card shows only the button, and the run starts without args. On submit, Studio creates a run of the workflow in the current workspace, starts it, and opens it. ```typescript @StudioApp({ title: 'Maintenance', workflows: [StateReportWorkflow, CleanupWorkflow], ui: { widgets: [ { widget: 'start-form', options: { workflow: 'state_report', title: 'What is on disk?', subtitle: 'Read-only.', label: 'Report' }, }, { widget: 'start-form', options: { workflow: 'cleanup', title: 'Reclaim orphaned state', label: 'Clean Up' }, }, ], }, }) ``` ## Available Features Some registry modules light up additional Studio surfaces when imported by your app — sidebars, panels, or richer document widgets. Importing a module through its `forFeature()` (or `forRoot()`) registers its feature at bootstrap, and the feature then appears under `StudioAppConfig.features`, which Studio reads to decide what UI to expose. A bare import of the module class does not register the feature. | Feature | Registered by | What it adds to Studio | | -------------------- | --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | | `git` | `@loopstack/git` (`GitModule.forFeature(config)`) | Git status panel and version-control affordances | | `localFileExplorer` | `@loopstack/local-file-explorer` (`LocalFileExplorerModule.forFeature(config)`) | "Files" sidebar panel for browsing the local workspace filesystem | | `remoteFileExplorer` | `@loopstack/remote-file-explorer` (`RemoteFileExplorerModule.forFeature(config)`) | "Remote Files" sidebar panel for browsing a remote workspace (requires `RemoteClientModule`) | | `secrets` | `@loopstack/secrets` (`SecretsModule.forFeature(config)`) | Workspace secrets management UI | | `handoff` | `@loopstack/handoff` (`HandoffModule.forFeature(config)`) | Handoff panel and the `handoff` / `changed-files` document widgets | To enable a feature, import the corresponding module's `forFeature()` (or `forRoot()`) in your app's module graph. Features that aren't imported simply don't appear — Studio degrades gracefully and never assumes a feature is present. > Feature registration is an internal mechanism — module authors call `registerFeature()` to declare a feature exists. Most users only need to know which features are available and how to enable them, both shown above. --- > Source: https://loopstack.ai/llms/build/fundamentals/tools.md --- title: Creating Tools description: How to define custom tools with BaseTool, Zod argument schemas, @Tool() decorator, handle() method signature, resultSchema result contracts, tool configuration, and dependency injection into workflows. --- # Creating Tools Tools are reusable TypeScript classes that encapsulate a single action — calling an API, querying a database, transforming data, or any other side effect. Define a tool once with a Zod schema for its arguments, then inject it into any workflow or expose it to LLMs for autonomous tool calling. ## Basic Tool ```typescript import { z } from 'zod'; import { BaseTool, Tool, ToolEnvelope } from '@loopstack/common'; import type { RunContext } from '@loopstack/common'; @Tool({ name: 'search', description: 'Short description of what this tool does.', schema: z .object({ query: z.string().describe('Search query'), limit: z.number().default(10).describe('Max results'), }) .strict(), }) export class SearchTool extends BaseTool<{ query: string; limit: number }, object, string> { protected async handle(args: { query: string; limit: number }, ctx: RunContext): Promise> { return { data: `Found results for: ${args.query}` }; } } ``` ## The `@Tool` Decorator ```typescript @Tool({ name: 'my_tool', description: 'User-facing description.', schema: InputSchema, }) ``` All options are optional. | Option | Type | Default | Description | | -------------- | -------------------------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | `string` | class name (as-is) | Unique identifier used in the LLM tool-calling wire format. Always set this to a snake_case identifier (e.g. `git_status`, `math_sum`) — the class name is a fallback. | | `description` | `string` | — | Human-readable description shown to LLMs for tool-use. Critical for autonomous tool calling. | | `widget` | `WidgetRef \| WidgetRef[]` | — | Custom Studio widget(s) for rendering tool calls/results — YAML file path(s) or inline widget object(s). | | `schema` | `z.ZodType` | — | Zod schema validating tool arguments before `handle()` is invoked. | | `configSchema` | `z.ZodType` | — | Zod schema validating tool config (provided via `options.config` on `call()`). | | `resultSchema` | `z.ZodType` | — | Zod schema validating the tool's result (`envelope.data` on success). Optional — without it, results are not validated. | | `effects` | `'none' \| 'external'` | — | Effect classification: `'none'` = reads/computes only, safe to repeat; `'external'` = writes outside the run (sends mail, pushes commits). Unset = treated as external by cautious consumers. | ## The `handle()` Method The abstract method you implement. It receives validated arguments, the execution context, and optional config: ```typescript protected async handle( args: TArgs, ctx: RunContext, options?: ToolCallOptions, ): Promise> { // Your logic here return { data: result }; } ``` The public `call()` method is the entry point — it routes through validation before calling `handle()`, then narrows the envelope: throws on `error`, throws on `pending`, returns a `ToolResult` with `data` and `metadata` non-optional. ## ToolEnvelope vs ToolResult Two related types — pick the right one for the right side of the boundary: ```typescript // What handle() returns — internal/dispatcher shape. type ToolEnvelope = { type?: 'text' | 'image' | 'file'; data?: TData; error?: string; metadata?: Record; pending?: { workflowId: string }; documents?: ToolDocumentDeclaration[]; }; // What tool.call() returns — the narrowed success path workflow authors see. interface ToolResult { data: TData; metadata: Record; type?: 'text' | 'image' | 'file'; } ``` Return patterns inside `handle()`: ```typescript return { data: 42 }; // Simple value return { data: { name: 'result', items: [...] } }; // Typed data return { error: 'Something went wrong' }; // Recoverable failure (LLM tool loop reads this) return { type: 'text', data: 'Mostly sunny, 14C.' }; // Typed output return { data: result, metadata: { tokensUsed: 150 } }; // With metadata return { pending: { workflowId } }; // Async sub-workflow launched ``` ## Result Contract Declare what your tool returns with `resultSchema`. On every successful call, the framework parses `envelope.data` against it — a result that doesn't match fails loudly with an error naming the tool. Error and pending envelopes are exempt; they carry no data contract. ```typescript const SearchResultSchema = z.strictObject({ results: z.array(z.strictObject({ title: z.string(), url: z.string() })), totalCount: z.number(), }); @Tool({ name: 'search', description: 'Searches the index.', schema: z.object({ query: z.string() }).strict(), resultSchema: SearchResultSchema, }) export class SearchTool extends BaseTool<{ query: string }, object, z.infer> { // ... } ``` Conventions: - Use `z.strictObject({...})` — unknown keys in a result are a contract violation and should fail, in both live runs and test fixtures. - Raw third-party payloads passed through verbatim (a provider response, an API blob) are declared as `z.unknown()` **fields**, never as the whole schema. Note that a `z.unknown()` field must still be present — mark it `.optional()` if your code sometimes omits it. - Derive the `TResult` generic from the schema (`z.infer`) so the compile-time type and the runtime contract cannot drift. - Parsing applies schema defaults, so a declared `.default(...)` reaches consumers even when `handle()` omits the field. Because validation happens in the tool pipeline, replayed test fixtures are checked against the same contract as live results — a fixture that drifts from what the tool really returns fails the test instead of silently passing. ## Producing Documents A tool that produces documents **declares** them on its result envelope instead of writing them inside `handle()`. The tool pipeline applies each declaration through the document store after the call completes — the tool decides _whether_ and _what_, the framework does the writing: ```typescript return { data: result, documents: [ { documentName: 'llm_message', // registered @Document name (or the kebab-derived class name) content: result.message, options: { meta: { provider: 'claude' } }, // key / meta / validate — same options as documentStore.save() }, ], }; ``` Declarations are applied on success envelopes only (error and pending envelopes carry none), validated against the document's schema, and a failing save fails the tool call. Because application happens in the pipeline — after any interceptor or replay substitution — a replayed test fixture materializes the same documents a live call would. _Reading_ documents is different: use `this.documentStore` (`findAll`, `findAllDocuments`, `findByTag`) inside `handle()` as usual — the declaration pattern covers writes. ## Dependency Injection Use standard NestJS `@Inject()` or constructor injection: ```typescript import { Inject } from '@nestjs/common'; @Tool({ name: 'math_sum', description: 'Calculates the sum of two numbers.', schema: z.object({ a: z.number(), b: z.number() }).strict(), }) export class MathSumTool extends BaseTool<{ a: number; b: number }, object, number> { constructor(private readonly mathService: MathService) { super(); } protected async handle(args: { a: number; b: number }, ctx: RunContext): Promise> { return { data: this.mathService.sum(args.a, args.b) }; } } ``` ## Tools for LLM Function Calling When a tool is exposed to the LLM, the `description` and `schema` tell the LLM what the tool does and what arguments it accepts: ```typescript @Tool({ name: 'get_weather', description: 'Retrieve weather information for a location.', schema: z.object({ location: z.string().describe('City or location name'), }), }) export class GetWeather extends BaseTool<{ location: string }, object, string> { protected async handle(args: { location: string }, ctx: RunContext): Promise> { return Promise.resolve({ type: 'text', data: 'Mostly sunny, 14C.' }); } } ``` In the workflow, list the tool name in the `tools` config: ```typescript constructor( private readonly llmGenerateText: LlmGenerateTextTool, private readonly getWeather: GetWeather, ) { super(); } const result = await this.llmGenerateText.call( {}, { config: { provider: 'claude', model: 'claude-sonnet-4-6', tools: ['get_weather'] } }, ); ``` ## Async Tools (sub-workflow callbacks) A tool can launch a sub-workflow from `handle()` and finish asynchronously when that sub-workflow completes. The lifecycle has two halves: 1. **`handle()`** returns `{ data, pending: { workflowId } }`. The `pending` field tells the framework "I started run `workflowId`, don't return to the LLM yet — wait for that run to finish, then call me back." 2. **`complete(result)`** runs when the sub-workflow finishes **successfully**. The argument is the sub-workflow's output. The return value is the `ToolEnvelope` that's actually delivered to the LLM (or the caller). Failed or canceled sub-workflows never reach `complete()` — the framework delivers an error envelope directly. Every async tool must implement `complete()` — it defines what the sub-workflow's completion means as the tool's result. The `BaseTool` implementation throws, so a tool that returns `pending` without implementing `complete()` fails loudly on its first completion. The result it returns is validated against the tool's `resultSchema` like any other success envelope. The HITL pattern shows the shape — `AskForApprovalTool.handle()` launches the sub-workflow with `show: 'inline'` so its UI appears in the parent's run view, and returns `pending`; `complete()` returns the user's decision as the typed answer. ```typescript @Tool({ name: 'ask_for_approval', description: 'Ask the user to approve.', /* … */ }) export class AskForApprovalTool extends BaseTool { protected async handle(/* … */) { const { workflowId } = await this.confirmWorkflow.run( args, { callback: { transition: 'onConfirm' }, show: 'inline', label: 'Waiting for approval...' }, ); return { data: { workflowId }, pending: { workflowId } }; } async complete(result: Record): Promise> { const { workflowId, data } = result as { workflowId: string; data: { confirmed: boolean } }; return { data: { approved: data.confirmed, workflowId } }; } } ``` Use this when a tool genuinely depends on an async outcome (HITL, long-running provisioning, external job completion). Tools that finish synchronously inside `handle()` never go pending, so `complete()` is not involved. ## Server Tools Some LLM providers ship built-in tools that **run on the provider's side**, not in your app — examples are Anthropic's `web_search` and `code_execution`. Loopstack exposes these via the `ServerTool` base class instead of `BaseTool`. Key differences from `BaseTool`: | Aspect | `BaseTool` | `ServerTool` | | --------------- | -------------------------------------------- | ----------------------------------------- | | Execution | runs locally in your app | runs on the LLM provider's infrastructure | | Abstract method | `handle(args, ctx, options)` | `toServerToolConfig(config?)` | | Has `call()` | yes — entry point for workflow code | no — the provider invokes it | | Use it for | your own logic, API calls, internal services | provider-native built-in tools | A server tool's job is to translate the workflow author's config into the provider-native shape. The framework detects `instanceof ServerTool` when assembling the LLM request and sends the result of `toServerToolConfig()` to the provider instead of registering a callable local tool. ```typescript import { z } from 'zod'; import { ServerTool, Tool } from '@loopstack/common'; const ConfigSchema = z.object({ maxUses: z.number().int().positive().default(8), allowedDomains: z.array(z.string()).optional(), }); type Config = z.infer; @Tool({ name: 'claude_native_web_search', description: "Claude's provider-native web search. Attach it to an LLM call by listing it in `tools`.", configSchema: ConfigSchema, }) export class ClaudeNativeWebSearchTool extends ServerTool { toServerToolConfig(config?: Config): unknown { return { type: 'web_search_20260209', name: 'web_search', max_uses: config?.maxUses ?? 8, ...(config?.allowedDomains?.length ? { allowed_domains: config.allowedDomains } : {}), }; } } ``` List the server tool in the LLM `tools` config the same way as a regular tool — the framework picks the right code path based on the class. A server tool runs only on the provider whose native spec it returns; a provider that cannot run it rejects the call. ```typescript await this.llmGenerateText.call( {}, { config: { provider: 'claude', model: 'claude-sonnet-4-6', tools: ['claude_native_web_search'], }, }, ); ``` A server tool and a regular tool can wrap the same provider feature, and they are used differently. `@loopstack/claude` ships `claude_native_web_search`, the server tool above: list it in an agent's or LLM call's `tools`, and Claude searches inside that call. `@loopstack/claude-tools` ships `claude_web_search_step`, a `BaseTool` you call from workflow code: it makes its own Claude request with `claude_native_web_search` and returns the hits. To give an agent web search, list `claude_native_web_search` — listing `claude_web_search_step` works too, but every search then costs a second LLM call. ## Using Tools in Workflows ```typescript constructor(private readonly myTool: SearchTool) { super(); } @Transition({ from: 'ready', to: 'done' }) async process(state: MyState) { const result = await this.myTool.call({ query: 'hello', limit: 5 }); this.assignState({ searchResults: result.data }); } ``` ## Module Registration ```typescript @Module({ providers: [SearchTool, MathService], exports: [SearchTool], }) export class MyToolModule {} ``` Then import the module in the workflow's parent module. ## File Structure ``` src/ ├── tools/ │ ├── search.tool.ts │ ├── math-sum.tool.ts │ └── index.ts # Re-exports all tools ├── services/ │ └── math.service.ts ├── my-feature.module.ts └── index.ts ``` ## Registry References - [Custom Tool example](/docs/examples/advanced-workflows#custom-tool) — MathSumTool with injected service, stateful CounterTool, and workflow demonstrating tool usage - [Server Tool example](/docs/examples/advanced-workflows#server-tool) — a code-execution `ServerTool` listed in an `llm_generate_text` call, with the code and its output read from the reply blocks - [Custom Agent example](/docs/examples/agent#custom-agent) — `weather_lookup` and `calculator` tools exposed to the LLM for function calling --- > **Using an AI coding agent?** See [Skill: Create a Custom Tool](../../skills/create-custom-tool.md) for a dense checklist and syntax reference optimized for code generation. --- > Source: https://loopstack.ai/llms/build/fundamentals/workflows.md --- title: Creating Workflows description: How to define workflow state machines using BaseWorkflow, @Workflow() decorator, @Transition() decorator, state typing, wait transitions, and guards. Covers the run trace — the per-run event journal (transitions, tool calls, documents, run.settled) with opt-in persistence via --trace. Includes full chat workflow example. --- # Creating Workflows A workflow is a state machine defined as a TypeScript class. Define transitions between named states, add guards for conditional routing, and use wait transitions to pause for user input or external events. > **Before you build much:** read [Best Practices](../best-practices.md) — when to choose scripted vs agentic flows, where logic belongs, the difference between state, result, and documents, and the conventions that keep workflows clean. ## Chat Example A simple chat workflow: wait for a user message, call LLM, display the response, and loop back. ```typescript import { z } from 'zod'; import { BaseWorkflow, Transition, type TransitionInput, Workflow } from '@loopstack/common'; import { LlmGenerateTextTool, LlmMessageDocument } from '@loopstack/llm-provider'; @Workflow({ widget: './chat.ui.yaml', // UI config }) export class ChatWorkflow extends BaseWorkflow { constructor(private readonly llmGenerateText: LlmGenerateTextTool) { super(); } // 1. Entry point @Transition({ to: 'waiting_for_user' }) setup(state: Record) {} // 2. Wait for user message @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 }); } // 3. Call LLM and loop back @Transition({ from: 'ready', to: 'waiting_for_user', }) async llmTurn(state: Record) { await this.llmGenerateText.call({}, { config: { provider: 'claude', model: 'claude-sonnet-4-6' } }); } } ``` That's a complete workflow. The state flow is: ``` start → waiting_for_user → [user sends message] → ready → llmTurn → waiting_for_user (loop) ``` ## The `@Workflow` Decorator ```typescript @Workflow({ widget: './chat.ui.yaml', }) ``` All options are optional. | Option | Type | Default | Description | | -------------- | -------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | `name` | `string` | class name with `Workflow` suffix stripped, snake_cased | Explicit snake_case identifier. E.g. `ChatWorkflow` → `chat`, `AgentExampleWorkflow` → `agent_example`. | | `title` | `string` | — | Human-readable display title shown in Studio UI. | | `description` | `string` | — | Human-readable description shown in Studio UI. | | `widget` | `WidgetRef \| WidgetRef[]` | — | Path(s) to YAML file(s) — or inline widget object(s) — defining the Studio UI surface for this workflow. | | `schema` | `z.ZodType` | — | Zod schema validating workflow input arguments. Surfaces as `ctx.args` in transitions. | | `configSchema` | `z.ZodType` | — | Zod schema validating workflow config (provided via `options.config` at start time / sub-workflow `run()`). | | `stateSchema` | `z.ZodType` | — | Zod schema validating the resulting state after every transition (see [Validating State](#validating-state-with-stateschema)). | ```typescript @Workflow({ widget: './prompt.ui.yaml', schema: z.object({ subject: z.string().default('coffee'), }), }) ``` ## `BaseWorkflow` All workflows extend `BaseWorkflow`, which provides: | Property / Method | Description | | -------------------- | ----------------------------------------------------------------------------------- | | `this.documentStore` | Save and query documents via `this.documentStore.save(DocClass, content, options?)` | | `this.render` | Render Handlebars templates via `this.render(templatePath, data?)` | Context is passed as a parameter to transition methods via `ctx: RunContext`. The generic parameter types `ctx.args` — prefer it over casting: | Context Property | Description | | --------------------------- | ------------------------------------------------------------------------------------------ | | `ctx.userId` | User ID | | `ctx.workspaceId` | Workspace ID | | `ctx.workflowId` | Current workflow run ID | | `ctx.args` | Validated input arguments (typed via `RunContext`) | | `ctx.execution?.place` | Current state name. Present in workflow transitions, absent when `ctx` is passed to tools. | | `ctx.execution?.retryCount` | Retry attempt counter for the current transition (0 on first run). | ```typescript @Transition({ to: 'ready', schema: z.object({ subject: z.string() }) }) setup(state: MyState, ctx: RunContext<{ subject: string }>) { this.assignState({ subject: ctx.args.subject }); } ``` ## Transition Types ### Initial Transition — Entry Point Runs once when the workflow starts. Uses `@Transition` with no `from` (defaults to `'start'`): ```typescript @Transition({ to: 'ready' }) setup(state: MyState, ctx: RunContext<{ subject: string }>) { this.assignState({ subject: ctx.args.subject }); } ``` The `state` parameter starts as an empty object `{}` — the initial transition is the place to populate it. ### Standard Transition — State Change Moves between states. Fires automatically unless `wait: true` is set. ```typescript @Transition({ from: 'ready', to: 'processed' }) async doWork(state: MyState) { const result = await this.myTool.call({ query: 'hello' }); this.assignState({ data: result.data }); } ``` A method can listen on **multiple source states**: ```typescript @Transition({ from: 'ready', to: 'prompt_executed' }) @Transition({ from: 'tools_done', to: 'prompt_executed' }) async llmTurn(state: MyState) { ... } ``` ### Wait Transition — Pause for Input Add `wait: true` to pause the workflow until externally triggered — by user input, a button click, or a sub-workflow callback. Use `schema` to validate and type the incoming `data`; the transition method receives a `TransitionInput` envelope with `data` plus failure info (`hasError`, `errorMessage`, `status`). ```typescript @Transition({ from: 'waiting_for_user', to: 'ready', wait: true, schema: z.object({ message: z.string() }), }) async userMessage(state: MyState, input: TransitionInput<{ message: string }>) { await this.documentStore.save(LlmMessageDocument, { role: 'user', text: input.data.message, }); } ``` For approval gates, confirmation dialogs, and other interactive pauses built on top of `wait: true`, see [Human-in-the-Loop](../patterns/human-in-the-loop.md). ### Final Transition — Completion Uses `@Transition` with `to: 'end'`. The workflow's output is published via `this.assignResult(...)` or `this.setResult(...)` — that value is what parent workflow callbacks and `WorkflowRunner` callers receive. ```typescript @Transition({ from: 'done', to: 'end' }) finish(state: MyState) { this.setResult({ concept: state.confirmedConcept! }); } ``` ## Guarding Transitions When multiple transitions share the same `from` state, attach `@Guard('methodName')` to pick which one fires: - Higher `priority` is checked first. Transitions without `priority` are evaluated last, in declaration order. - A guard is a boolean method on the workflow that receives the current `state` and returns `true` to allow the transition. - A transition without a guard always passes — use it as the fallback. ```typescript @Transition({ from: 'prompt_executed', to: 'awaiting_tools', priority: 10 }) @Guard('hasToolCalls') async executeToolCalls(state: MyState) { const result = await this.llmDelegateToolCalls.call({ message: state.llmResult!.message, tools: TOOLS, // the tool names given to llmGenerateText callback: { transition: 'toolResultReceived' }, }); this.assignState({ delegateResult: result.data }); } @Transition({ from: 'prompt_executed', to: 'end' }) respond(_state: MyState) {} hasToolCalls(state: MyState): boolean { return state.llmResult?.message.stopReason === 'tool_use'; } ``` From `prompt_executed`, `executeToolCalls` fires whenever the LLM requested tools; otherwise `respond` (unguarded) ends the workflow. ## State Transitions return nothing — mutate state via `this.assignState(...)`. Use `async` when the body awaits. State is read from the `state` parameter and written through setters on `BaseWorkflow`: | Setter | Effect | | ---------------------------- | --------------------------------------------------------------------------------------------------------- | | `this.assignState(partial)` | Shallow-merge `partial` into the current state. The most common form. | | `this.setState(full)` | Replace the state object outright. | | `this.assignResult(partial)` | Shallow-merge `partial` into the workflow's published `result` (visible to callers and parent callbacks). | | `this.setResult(full)` | Replace the workflow's published `result` outright. | ```typescript interface MyState { counter: number; llmResult?: LlmGenerateTextResult; } export class MyWorkflow extends BaseWorkflow { @Transition({ from: 'ready', to: 'processed' }) process(state: MyState) { this.assignState({ counter: (state.counter ?? 0) + 1 }); } } ``` Values persist even when the workflow pauses and resumes. Returning a value from a transition is a runtime error — every write must go through the setters. ### Validating State with `stateSchema` Add a Zod schema via `@Workflow({ stateSchema })` to enforce the state shape at runtime. The processor validates the resulting state after every transition (before persistence). If validation fails the transition errors out — bugs that corrupt state are caught at the point they occur instead of leaking into later transitions or checkpoints. ```typescript const MyStateSchema = z.object({ counter: z.number().int().nonnegative(), llmResult: z.unknown().optional(), }); @Workflow({ stateSchema: MyStateSchema, }) export class MyWorkflow extends BaseWorkflow { @Transition({ from: 'ready', to: 'processed' }) process(state: z.infer) { this.assignState({ counter: (state.counter ?? 0) + 1 }); } } ``` Use this when the state shape is critical and you want fail-fast diagnostics. Skip it for prototyping or when the state is loose by design. ## Injecting Tools Tools are injected via standard NestJS constructor injection: ```typescript constructor( private readonly llmGenerateText: LlmGenerateTextTool, ) { super(); } @Transition({ from: 'ready', to: 'done' }) async process(state: MyState) { const result = await this.llmGenerateText.call( { prompt: 'Write a haiku' }, { config: { provider: 'claude', model: 'claude-sonnet-4-6' } }, ); this.assignState({ llmResult: result.data }); } ``` Any provider can be injected the same way. For time-dependent logic, inject the framework clock (`@Inject(CLOCK) private readonly clock: Clock`) instead of calling `Date.now()` or `setTimeout` directly — under a test clock the workflow stays deterministic. ## Documents Use `this.documentStore.save()` to create or update documents. Reference document classes directly — no injection needed. ```typescript // Create a document await this.documentStore.save(LlmMessageDocument, { role: 'user', text: 'Hello!', }); // Update an existing document by key, in place await this.documentStore.save( LlmMessageDocument, { role: 'assistant', text: 'Updated response' }, { key: 'response-1', position: 'keep' }, ); // Hidden context (not shown in UI — LLM still sees it as conversation history) await this.documentStore.save(LlmContextDocument, { role: 'user', text: 'System prompt' }); ``` ## Templates `render` is available directly on `BaseWorkflow` (like `documentStore`). Use `this.render()` to render Handlebars template files: ```typescript const rendered = this.render(join(__dirname, 'templates', 'prompt.md'), { subject: args.subject, }); ``` ## Places (States) Places are implicit — defined by `from`/`to` values in your decorators. Two special places: - **`start`** — Implicit initial place (the initial transition moves from here when `from` is omitted) - **`end`** — When reached, the workflow completes All other place names are arbitrary strings you choose. ## The Run Trace Every run produces a **trace**: an ordered, append-only journal of everything the run did. The engine never reads it — it exists for you: debugging a failed run, asserting on behavior in tests, deriving replay fixtures, and auditing what an automation actually executed. | Event | Emitted when | Carries | | ------------------------------------------------ | ------------------------------------------ | ------------------------------------------------------------------------------ | | `transition.started` | A transition begins | transition id, `from`/`to`, the wait payload | | `transition.completed` | It succeeds | duration, a per-key **state diff**, whether the result was touched | | `transition.failed` | It throws or a sub-workflow callback fails | error, retry count, whether a retry is scheduled | | `tool.called` / `tool.completed` / `tool.failed` | Each tool call | tool name, per-transition order, validated args, the result envelope, duration | | `document.emitted` | A document is saved | document name/key, the invalidated predecessor key | | `child.queued` / `child.settled` | A sub-workflow launches / finishes | child workflow id, name, status | | `run.settled` | Every park and terminal settle | status, place — parks include the transitions the run is waiting on | Events are ordered by a per-run monotonic `seq` (continuous across pause/resume) and carry a wall-clock `ts`. Failing tool calls and failing transitions are first-class events — a trace always shows _where_ a run died, with the exact call and error. **In memory, the trace is always on.** A run's processing result carries it (`meta.trace`), stateless runs carry it across park/resume, and workflow tests assert on it via [`run.trace` and `run.toolCalls`](/docs/build/testing). **Persistence is opt-in per run.** Start a run with `loopstack run --trace` (or `trace: true` on the start payload) and its whole run tree — sub-workflows inherit the flag — persists its events as queryable rows. Read them back with `loopstack runs --record ` (derives a [replay fixture](/docs/build/testing)), `GET /workflows/:id/tool-calls`, or `client.workflows.toolCalls(id)`. To record every run, e.g. on a dev backend, enable it globally with the [`trace` option / `LOOPSTACK_TRACE=true`](/docs/reference/configuration#trace). ## YAML Configuration YAML files define **UI layout only** — no transitions, conditions, or tool calls. They configure what widgets appear in the Studio interface. ```yaml title: 'My Workflow' description: 'What this workflow does' ui: widgets: - widget: form enabledWhen: [waiting] options: properties: name: title: Name actions: - type: button transition: userResponse label: Submit - widget: prompt-input enabledWhen: [waiting_for_user] options: transition: userMessage ``` The `transition` values must match **method names** of `wait: true` transitions. ### `enabledWhen` Controls when a widget is interactive based on the current workflow place. Outside the listed places the widget stays on screen but is disabled: ```yaml - widget: prompt-input enabledWhen: - waiting_for_user # Only enabled at this place options: transition: userMessage ``` ### `showWhen` Controls when a widget is visible. Outside the listed places the widget is not rendered at all — use it for widgets that only make sense at one step, such as a cancel or recover button: ```yaml - widget: button showWhen: - awaiting_tools # Only rendered at this place options: transition: cancelPendingTools label: Cancel pending tools ``` When a widget sets both, `showWhen` decides whether it is rendered and `enabledWhen` whether it is enabled. See [Workflow YAML Schema — `showWhen`](/docs/reference/workflow-yaml#showwhen). ### Form Actions Buttons that trigger `wait: true` transitions when clicked: ```yaml actions: - type: button transition: confirm # Must match the method name label: 'Confirm' ``` ## Module Registration ```typescript @Module({ imports: [ClaudeModule], providers: [ChatWorkflow], exports: [ChatWorkflow], }) export class ChatModule {} ``` ## File Structure ``` src/ ├── workflows/ │ ├── chat.workflow.ts │ ├── chat.ui.yaml │ └── templates/ │ └── systemMessage.md ├── chat.module.ts └── index.ts ``` ## Registry References - [Prompt Input Chat example](/docs/examples/hitl#prompt-input-chat) — Multi-turn chat loop with the prompt-input widget, without an LLM - [Prompt example](/docs/examples/llm#prompt) — Simple single-turn prompt workflow - [Custom Agent example](/docs/examples/agent#custom-agent) — Tool calling loop with guards and conditional routing - [Dynamic Routing example](/docs/examples/advanced-workflows#dynamic-routing) — Multi-level guard-based routing - [Workflow State example](/docs/examples/advanced-workflows#workflow-state) — State management with typed state interface - [Sub-Workflow example](/docs/examples/advanced-workflows#sub-workflow) — Sub-workflow execution with callbacks --- > **Using an AI coding agent?** See [Skill: Create a Custom Workflow](../../skills/create-custom-workflow.md) for a dense checklist and syntax reference optimized for code generation. ---