# Skills --- > Source: https://loopstack.ai/llms/skills/create-custom-document.md --- title: 'Skill: Create a Custom Document' description: Step-by-step instructions for AI agents to scaffold a new document — @Document decorator, Zod schema, YAML widget config, and how to save instances via documentStore. --- # Skill: Create a Custom Document > **For AI coding agents:** This page is a dense reference checklist optimized for tools like Claude Code scaffolding Loopstack code. For the human-readable guide, see [Creating Documents](../build/fundamentals/documents.md). ## Document Anatomy A document is a **plain TypeScript DTO** decorated with `@Document()`. It pairs a Zod schema (for content validation) with an optional YAML widget config (for Studio rendering). ```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 ``` > **Documents are NOT NestJS providers.** Unlike `@Tool` and `@Workflow`, `@Document` does not apply `@Injectable()`. Do **not** add document classes to a module's `providers` array. Do **not** inject them. Reference the class directly: `documentStore.save(NotesDocument, …)`. ## `@Document()` Options 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`. | | `title` | `string` | — | Display title shown in Studio. | | `description` | `string` | — | Description shown in Studio. | | `widget` | `WidgetRef \| WidgetRef[]` | — | YAML file path(s) — or inline widget object(s) — defining how the document renders. | | `schema` | `z.ZodType` | — | Zod schema validating document content on `documentStore.save()`. | | `tags` | `string[]` | — | Default tags assigned to every instance. | | `meta` | `StaticDocumentMeta` | — | Static metadata served via the config endpoint, not persisted per instance. | ## Saving Documents `documentStore` is auto-injected on `BaseWorkflow` and `BaseTool`. Reference document classes directly — no injection. ```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' }, { key: 'notes-1' }); // Update in place — the new revision takes the place of the previous one await this.documentStore.save(NotesDocument, { text: 'Updated' }, { key: 'notes-1', position: 'keep' }); ``` To hide a document type from the UI entirely, declare `internal: true` on its decorator (`@Document({ internal: true, ... })`) rather than passing a per-save flag. Internal documents are persisted and still readable server-side (e.g. by LLM providers), but never reach Studio. ### Save an instance instead ```typescript const draft = this.documentStore.create(NotesDocument, { text: 'Initial' }); draft.text += '\n\nMore.'; await this.documentStore.save(draft); // overload: pre-built instance await this.documentStore.save(draft, { key: 'notes-1' }); // with save options ``` `create()` returns a typed class instance with the data attached. Nothing is persisted until `save()`. ### Save Options | Option | Type | Description | | ---------- | ------------------------------ | ----------------------------------------------------------------------------------------------------- | | `key` | `string` | Stable revision key — saving again with the same `key` invalidates the previous revision. | | `position` | `'keep' \| 'end'` | Where a keyed save puts the new revision: `'end'` (default) appends it, `'keep'` updates in place. | | `validate` | `'strict' \| 'safe' \| 'skip'` | Schema validation mode. Default `'strict'`. | | `meta` | `Record` | Free-form extension data persisted on the row. For framework concerns, use decorator options instead. | ## Querying Documents All methods return only non-invalidated documents for the current run. | Method | Returns | Use for | | --------------------- | ------------------ | ----------------------------------------------- | | `findAll(MyDocument)` | `MyDocument[]` | Typed hydrated instances of one document type. | | `findByTag('tag')` | `DocumentEntity[]` | All documents tagged with `tag` (across types). | | `findAllDocuments()` | `DocumentEntity[]` | Every document in this run, raw entities. | ```typescript const notes = this.documentStore.findAll(NotesDocument); // typed const tagged = this.documentStore.findByTag('message'); const all = this.documentStore.findAllDocuments(); ``` `documentStore.create(MyDocument, data)` returns a typed instance **without** persisting — validates against the Zod schema only. ## Reusing Built-in Documents Don't redefine these — import and save: | Document | Source | Key fields | | -------------------- | ------------------------- | ------------------------------------------ | | `LlmMessageDocument` | `@loopstack/llm-provider` | `role`, `text`, `blocks` | | `LinkDocument` | `@loopstack/common` | `label`, `workflowId`, `embed`, `expanded` | | `MessageDocument` | `@loopstack/common` | `role`, `text` | | `MarkdownDocument` | `@loopstack/common` | `markdown` | | `PlainDocument` | `@loopstack/common` | `text` | | `ErrorDocument` | `@loopstack/common` | `error` | ```typescript import { MarkdownDocument } from '@loopstack/common'; import { LlmMessageDocument } from '@loopstack/llm-provider'; await this.documentStore.save(LlmMessageDocument, { role: 'assistant', text: 'Hello!' }); await this.documentStore.save(MarkdownDocument, { markdown: '# Report\n- A\n- B' }); ``` ## YAML Widget Config The `widget` option points to a YAML file describing how the document renders in Studio. The most common widget is `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' ``` ### Widget Types Used in `options.properties..widget`: | Widget | Description | | ----------- | --------------------------------- | | `text` | Single-line text (default) | | `textarea` | Multi-line text | | `select` | Dropdown | | `radio` | Radio buttons | | `checkbox` | Checkbox | | `switch` | Toggle | | `slider` | Numeric slider | | `code-view` | Syntax-highlighted read-only code | ### Property Options | Option | Type | Description | | ------------- | --------- | ---------------------------------- | | `title` | `string` | Display label | | `widget` | `string` | Widget type (see above) | | `placeholder` | `string` | Placeholder text | | `rows` | `number` | Visible rows (textarea) | | `readonly` | `boolean` | Read-only field (server-enforced) | | `hidden` | `boolean` | Hide the field | | `disabled` | `boolean` | Disable interaction | | `collapsed` | `boolean` | Collapse arrays/objects by default | | `items` | `object` | UI config for array items | #### Read-only fields `readonly: true` is enforced, not just rendered: Studio shows the field as non-editable, the CLI discards `$EDITOR` changes to it, and the **backend rejects** any transition submission that changes the field's value relative to the active document's content (`400 — Field "subject" of document "feedback_form" is read-only.`). Use it for workflow-provided values the user must see but not alter: ```yaml properties: subject: title: Subject readonly: true ``` Enforcement applies to user submissions of transitions the widget declares (`actions[].transition` / `options.transition`); the workflow itself can always update its own documents. See `inline_form_example` in the [HITL examples](/docs/examples/hitl#inline-form) for a working example. ### Actions Buttons that trigger `wait: true` transitions: ```yaml actions: - type: button transition: confirm # must match the transition method name label: Confirm ``` ## Checklist 1. Decide if a built-in document covers your need first — don't reinvent `MessageDocument`, `MarkdownDocument`, etc. 2. Create the class file with `@Document({ schema, widget })`. 3. Define the Zod schema next to or above the class. 4. Add the YAML widget config beside the `.ts` file (e.g. `notes.ui.yaml`). 5. **Do not** add the class to module `providers`. Reference it directly via `documentStore.save(MyDocument, …)`. 6. Save via `documentStore.save(MyDocument, content, options?)` from a workflow transition or tool. --- > Source: https://loopstack.ai/llms/skills/create-custom-tool.md --- title: 'Skill: Create a Custom Tool' description: Step-by-step instructions for AI agents to scaffold a new tool — BaseTool class, @Tool decorator, Zod argument schema, handle() method, and module registration. --- # Skill: Create a Custom Tool > **For AI coding agents:** This page is a dense reference checklist optimized for tools like Claude Code scaffolding Loopstack code. For the human-readable guide, see [Creating Tools](../build/fundamentals/tools.md). ## Tool Anatomy A tool is a class that extends `BaseTool`, decorated with `@Tool()`. Tools are the atomic units of logic invoked by workflows via `await this.tool.call(args)`. ```typescript import { z } from 'zod'; import { BaseTool, Tool, ToolEnvelope } from '@loopstack/common'; import type { RunContext } from '@loopstack/common'; const InputSchema = z .object({ query: z.string().describe('Search query'), limit: z.number().default(10).describe('Max results'), }) .strict(); type MyToolArgs = z.infer; @Tool({ name: 'my_tool', description: 'Short description of what this tool does.', schema: InputSchema, }) export class MyTool extends BaseTool { // BaseTool protected async handle(args: MyToolArgs, ctx: RunContext): Promise> { return { data: `Found results for: ${args.query}` }; } } ``` ### `BaseTool` Generics | Parameter | Types | Validated against | Default | | --------- | ------------------------------------ | ------------------------- | ------------------------- | | `TArgs` | input arguments to `handle()` | `@Tool({ schema })` | `object` | | `TConfig` | per-call config via `options.config` | `@Tool({ configSchema })` | `object` | | `TResult` | `data` field of `ToolEnvelope` | — | `unknown` | | `TMeta` | `metadata` field of `ToolEnvelope` | — | `Record` | Pass `object` for `TConfig` when the tool has no configuration. Most tools only thread `TArgs` and `TResult`; `TConfig` and `TMeta` are reserved for tools that opt into config validation or typed result metadata (e.g. `LlmGenerateTextTool` types token usage on `metadata`). ## Decorators ### `@Tool(options?)` Class decorator. Marks the class as a tool. ```typescript @Tool({ name: 'my_tool', // Snake_case name used as identifier (for LLM wire format) description: 'User-facing description.', // Also seen by LLMs for function calling schema: InputSchema, // Zod schema for input validation configSchema: ConfigSchema, // Optional: Zod schema for tool config }) ``` - `name` — Unique identifier for the tool - `description` — Human-readable description (shown to LLMs for tool-use) - `schema` — Zod schema that validates tool arguments before `handle()` is invoked. Validation is **strict**: if args fail validation, `tool.call()` throws a `ZodError` and `handle()` is never invoked. Tools have no `safe`/`skip` modes (unlike documents). - `configSchema` — Optional Zod schema for config (provided via `options.config`). Same strict throw-on-failure behavior. - `widget` — less common; see the [`@Tool` reference table](../build/fundamentals/tools.md#the-tool-decorator) ### Constructor Injection Inject other tools or services via the constructor: ```typescript constructor(private readonly otherTool: OtherTool) { super(); } ``` Tools are NestJS providers, so injecting another tool and calling `await this.otherTool.call(args)` is the standard pattern for composing tools. Each call goes through the full pipeline (args validation, config validation, interceptors). ## The `handle()` Method ```typescript protected async handle( args: TArgs, ctx: RunContext, options?: ToolCallOptions, ): Promise>; ``` The `handle()` method receives validated arguments, the execution context, and optional config. This is the abstract method you implement. The public `call()` method is the entry point — it routes through validation before calling `handle()`. - `args` — Validated input (against the `@Tool({ schema })` Zod schema) - `ctx` — Read-only [`RunContext`](../build/fundamentals/workflows.md#baseworkflow): `userId`, `workspaceId`, `workflowId`, `args`. `ctx.execution` is **undefined** in tools (it's only populated when `ctx` is passed to a workflow transition). - `options` — Options including validated config and optional callback ### Args vs Config Tools have two independent validation surfaces: | Concept | Decorator option | Passed in via | Typical source | | ---------- | ------------------------- | ---------------------------- | ---------------------------------------- | | **args** | `@Tool({ schema })` | first arg of `tool.call()` | LLM (when tool-calling) or workflow code | | **config** | `@Tool({ configSchema })` | `options.config` of `call()` | the workflow author at the call site | Use `args` for the **per-call input** (what the tool acts on) and `config` for **behavior knobs** (which provider, which model, retry budget, etc.). Config is optional; most tools only need `schema`. ```typescript @Tool({ name: 'summarize', description: 'Summarize text using an LLM.', schema: z.object({ text: z.string() }), // args — the input configSchema: z.object({ model: z.string() }), // config — behavior }) export class Summarize extends BaseTool<{ text: string }, { model: string }, string> { protected async handle(args, ctx, options): Promise> { const model = options?.config?.model ?? 'claude-sonnet-4-6'; // ...use `model` to drive the LLM call, `args.text` as the prompt return { data: '...' }; } } // Call site: await this.summarize.call({ text: 'long article...' }, { config: { model: 'claude-opus-4-7' } }); ``` ### Async Tools: `complete()` `BaseTool` also has an optional `complete(result)` method, called when a tool launches a sub-workflow from `handle()` and finishes asynchronously. Override it to post-process the sub-workflow result before it's returned to the LLM. The default passes the result through. See [Async Tools](../build/fundamentals/tools.md#async-tools-sub-workflow-callbacks) for the full lifecycle. ## ToolEnvelope vs ToolResult `handle()` returns a `ToolEnvelope` (the raw shape, with `error`/`pending` arms); `tool.call()` returns a narrowed `ToolResult` (data + metadata required, throws on `error`/`pending`). ```typescript type ToolEnvelope = { type?: 'text' | 'image' | 'file'; data?: TData; error?: string; metadata?: Record; pending?: { workflowId: string }; }; interface ToolResult { data: TData; metadata: Record; type?: 'text' | 'image' | 'file'; } ``` Return patterns inside `handle()`: ```typescript // Simple value return { data: 42 }; // Typed data return { data: { name: 'result', items: [...] } }; // Recoverable failure (LLM tool loop forwards as is_error) return { error: 'Something went wrong' }; // Text type return { type: 'text', data: 'Mostly sunny, 14C.' }; // With metadata (e.g. usage tracking) return { data: result, metadata: { tokensUsed: 150 }, }; // Async sub-workflow launched return { pending: { workflowId } }; ``` ## Document Store `this.documentStore` is auto-injected on `BaseTool` (and `BaseWorkflow`). Use it to save documents: ```typescript protected async handle(args: MyArgs, ctx: RunContext): Promise> { await this.documentStore.save(MessageDocument, { role: 'assistant', text: 'Processing complete.', }); return { data: 'done' }; } ``` ## Module Registration Every tool must be registered as a NestJS provider and exported from a module. ```typescript import { Module } from '@nestjs/common'; @Module({ imports: [ // Import modules whose tools you inject ], providers: [ MyTool, // the tool MyService, // services injected via constructor ], exports: [MyTool], }) export class MyToolModule {} ``` Then import `MyToolModule` in the app module or feature module that contains the workflow using the tool. > **Reminder:** The module that defines your launchable workflows must also have `@StudioApp({ title, workflows })` — see [Modules & Workspaces](../build/fundamentals/modules.md) for details. ## Example: Tool with Injected Service ```typescript // services/math.service.ts import { Injectable } from '@nestjs/common'; @Injectable() export class MathService { sum(a: number, b: number): number { return a + b; } } // tools/math-sum.tool.ts import { z } from 'zod'; import { BaseTool, Tool, ToolEnvelope } from '@loopstack/common'; import type { RunContext } from '@loopstack/common'; import { MathService } from '../services/math.service'; const MathSumSchema = z .object({ a: z.number(), b: z.number(), }) .strict(); type MathSumArgs = z.infer; @Tool({ name: 'math_sum', description: 'Math tool calculating the sum of two arguments.', schema: MathSumSchema, }) export class MathSumTool extends BaseTool { constructor(private readonly mathService: MathService) { super(); } protected async handle(args: MathSumArgs, ctx: RunContext): Promise> { const sum = this.mathService.sum(args.a, args.b); return { data: sum }; } } ``` ## Example: Tool for LLM Function Calling Tools exposed to the LLM need a `description` so the LLM knows when to use them. The `schema` field names and `.describe()` calls on schema fields provide the LLM with parameter information. ```typescript import { z } from 'zod'; import { BaseTool, Tool, ToolEnvelope } from '@loopstack/common'; import type { RunContext } from '@loopstack/common'; @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 when calling the LLM: ```typescript constructor( private readonly llmGenerateText: LlmGenerateTextTool, private readonly getWeather: GetWeather, ) { super(); } await this.llmGenerateText.call( {}, { config: { provider: 'claude', model: 'claude-sonnet-4-6', tools: ['get_weather'] } }, ); ``` ## Using a Tool in a Workflow ```typescript @Workflow({ widget: './my.ui.yaml', }) export class MyWorkflow extends BaseWorkflow { constructor(private readonly myTool: MyTool) { super(); } @Transition({ to: 'end' }) async run(state: unknown) { const result = await this.myTool.call({ query: 'hello', limit: 5 }); // result.data contains the tool's return value } } ``` ## File Structure Convention ``` src/ ├── tools/ │ ├── my-tool.tool.ts │ ├── another.tool.ts │ └── index.ts # re-exports all tools ├── services/ │ └── my.service.ts ├── my-feature.module.ts └── index.ts # re-exports module + tools ``` ## Checklist 1. Create tool class extending `BaseTool` with `@Tool({ name, description, schema })` 2. Implement `handle(args, ctx, options?)` returning `Promise>` 3. Register as provider in a NestJS `@Module()` 4. Export from the module 5. Import module in the workflow's parent module 6. Inject in workflow via constructor 7. Call via `await this.tool.call(args)` in transition methods --- > Source: https://loopstack.ai/llms/skills/create-custom-workflow.md --- title: 'Skill: Create a Custom Workflow' description: Step-by-step instructions for AI agents to scaffold a new workflow — file structure, TypeScript class with @Workflow and @Transition decorators, YAML widget config, and module registration. --- # Skill: Create a Custom Workflow > **For AI coding agents:** This page is a dense reference checklist optimized for tools like Claude Code scaffolding Loopstack code. For the human-readable guide, see [Creating Workflows](../build/fundamentals/workflows.md). For design judgment — scripted vs agentic, where logic belongs, state vs result vs documents — read [Best Practices](../build/best-practices.md) before scaffolding. ## Workflow Anatomy A workflow is a **state machine** defined by two files: 1. **TypeScript class** — extends `BaseWorkflow`, decorated with `@Workflow()`, contains transition logic, state, guards, and tool calls 2. **YAML config** — UI-only configuration (widgets, forms, enabled states) ``` src/ ├── workflows/ │ ├── my.workflow.ts # class definition │ └── my.ui.yaml # UI config only ├── my-feature.module.ts └── index.ts ``` ## TypeScript Class ```typescript import { z } from 'zod'; import { BaseWorkflow, Guard, Transition, Workflow } from '@loopstack/common'; import type { RunContext } from '@loopstack/common'; const MyArgs = z.object({ name: z.string().default('world'), count: z.number().default(1), }); type MyArgs = z.infer; interface MyState { total?: number; message?: string; } @Workflow({ schema: MyArgs, widget: './my.ui.yaml', }) export class MyWorkflow extends BaseWorkflow { // --- Tool & sub-workflow injection via constructor --- constructor( private readonly myTool: MyTool, private readonly helperWorkflow: HelperWorkflow, ) { super(); } // --- Initial transition (workflow entry point, from defaults to 'start') --- @Transition({ to: 'ready' }) setup(state: MyState, ctx: RunContext) { this.assignState({ message: `Hello, ${ctx.args.name}!` }); } // --- Regular transition --- @Transition({ from: 'ready', to: 'processed' }) async process(state: MyState) { const result = await this.myTool.call({ query: state.message! }); this.assignState({ total: result.data }); } // --- Final transition (to: 'end' completes the workflow) --- @Transition({ from: 'processed', to: 'end' }) finish(state: MyState) { this.setResult({ total: state.total }); } // --- Regular helper method --- private formatMessage(text: string): string { return text.toUpperCase(); } } ``` ## Decorators Reference ### `@Workflow(options?)` Class decorator. Configures the workflow. ```typescript @Workflow({ widget: './my.ui.yaml', // UI-only YAML config schema: z.object({ // Input validation schema prompt: z.string(), }), }) ``` - `widget` — path to YAML file containing UI widget configuration - `schema` — Zod schema that validates workflow input arguments - `name`, `title`, `description`, `configSchema`, `stateSchema` — less common; see the [`@Workflow` reference table](../build/fundamentals/workflows.md#the-workflow-decorator) ### `extends BaseWorkflow` All workflows must extend `BaseWorkflow` (or just `BaseWorkflow` for no input). State is typed per-transition on the `state` parameter. It provides: - `this.documentStore` — auto-injected, for saving and querying documents - `ctx.args` — the validated workflow input arguments (via the `ctx` parameter on transitions) ### Constructor Injection Tools and sub-workflows are injected via standard NestJS constructor injection: ```typescript constructor( private readonly llmGenerateText: LlmGenerateTextTool, private readonly subWorkflow: SubWorkflow, ) { super(); } // Usage: const result = await this.llmGenerateText.call( { prompt: 'Hello' }, { config: { provider: 'claude', model: 'claude-sonnet-4-6' } }, ); await this.subWorkflow.run(args, { callback: { transition: 'onComplete' } }); ``` ### `@Transition(options)` Defines a state transition. All transitions use this single decorator. ```typescript // Initial transition (from defaults to 'start') @Transition({ to: 'ready' }) async setup(state: MyState, ctx: RunContext) { ... } // Regular transition @Transition({ from: 'ready', to: 'processed' }) async doWork(state: MyState) { ... } // Final transition (to: 'end' completes the workflow) @Transition({ from: 'done', to: 'end' }) async finish(state: MyState) { ... } // Wait for external callback @Transition({ from: 'waiting', to: 'ready', wait: true, schema: z.object({ message: z.string() }), }) async onCallback(state: MyState, input: TransitionInput<{ message: string }>) { ... } // Multiple source places @Transition({ from: 'ready', to: 'prompt_executed' }) @Transition({ from: 'tools_done', to: 'prompt_executed' }) async llmTurn(state: MyState) { ... } ``` Options: - `from` — source place (defaults to `'start'` if omitted — making it the initial transition) - `to` — target place (use `'end'` for final transitions) - `wait` — if `true`, workflow pauses until externally triggered - `schema` — Zod schema that validates the `data` payload arriving on the resume (used with `wait: true`). The transition method receives the full `TransitionInput` envelope; `schema` describes only its `data` field. - `priority` — evaluation order when multiple transitions share the same `from` (higher = checked first) ### `@Guard('methodName')` Conditional routing. The referenced method must return a boolean. Use with `priority` to control evaluation order. ```typescript @Transition({ from: 'prompt_executed', to: 'awaiting_tools', priority: 10 }) @Guard('hasToolCalls') async executeToolCalls(state: MyState) { ... } // Fallback — no guard, lower/no priority @Transition({ from: 'prompt_executed', to: 'end' }) async respond(state: MyState) { ... } hasToolCalls(state: MyState): boolean { return state.llmResult?.message.stopReason === 'tool_use'; } ``` ## State Management Transitions return nothing — mutate state via `this.assignState(...)`. Use `async` when the body awaits. Read state via the `state` parameter; write it through setters on `BaseWorkflow`: | Setter | Effect | | ---------------------------- | ----------------------------------------------------------------------------------------------------------------- | | `this.assignState(partial)` | Shallow-merge `partial` into the current state. Most common. | | `this.setState(full)` | Replace state outright. | | `this.assignResult(partial)` | Shallow-merge `partial` into the workflow's published `result` (returned to parent callbacks / `WorkflowRunner`). | | `this.setResult(full)` | Replace the published `result` outright. | Returning a value from a transition is a runtime error. ```typescript interface MyState { llmResult?: LlmGenerateTextResult; confirmedConcept?: string | null; counter: number; } export class MyWorkflow extends BaseWorkflow { @Transition({ from: 'ready', to: 'processed' }) async process(state: MyState) { const result = await this.myTool.call({ ... }); this.assignState({ llmResult: result.data, counter: state.counter + 1 }); } } ``` ## Documents Documents are referenced by class — no injection needed. Use `this.documentStore.save()` to create/update documents. `documentStore` is auto-injected on `BaseWorkflow`. ```typescript import { LlmMessageDocument } from '@loopstack/llm-provider'; // Save a new document await this.documentStore.save(LlmMessageDocument, { role: 'user', text: 'Hello!', }); // Save with a stable key and `position: 'keep'` — saving again updates the document in place // (without `position`, the new revision is placed at the end and the previous one invalidated) await this.documentStore.save( LlmMessageDocument, { role: 'assistant', text: 'Hi!' }, { key: 'greeting', position: 'keep' }, ); // To hide a message from the UI (still picked up by the LLM as conversation history), // use LlmContextDocument — its @Document decorator declares { internal: true, tags: ['message'] } await this.documentStore.save(LlmContextDocument, { role: 'user', text: 'System prompt text' }); ``` ## Handlebars Templates `render` is available directly on `BaseWorkflow` (like `documentStore`), so workflows just use `this.render(...)` without any injection: ```typescript const rendered = this.render(join(__dirname, 'templates', 'prompt.md'), { subject: args.subject, items: state.items, }); ``` Template file (`templates/prompt.md`): ```markdown Write a haiku about {{subject}}. {{#each items}} - {{this.name}} {{/each}} ``` ## YAML Config — UI Only YAML files contain only UI configuration. No `transitions:` section. ```yaml title: 'My Workflow' description: 'What this workflow does' ui: widgets: - widget: form enabledWhen: [waiting] options: properties: name: title: 'Name' count: title: 'Count' widget: slider actions: - type: button transition: userResponse # Must match the method name label: Submit - widget: prompt-input enabledWhen: [waiting_for_user] options: transition: userMessage # Must match the method name label: Send Message ``` > **Important:** The `transition` value in widget options must match the **method name** of the `wait: true` transition, not an arbitrary ID. ## Places (States) Places are implicit — defined by `from`/`to` values in transition decorators. Two special places: - **`start`** — implicit initial place (transitions with no `from` default to `'start'`) - **`end`** — when reached (via `to: 'end'`), workflow completes All other place names are arbitrary strings. ## Conditional Routing / Guards When multiple transitions share the same `from` place: 1. Transitions with `@Guard` and higher `priority` are checked first 2. First transition whose guard returns `true` fires 3. A transition without `@Guard` acts as the fallback ```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; } ``` ## Async Callbacks (Wait Transitions) Use `wait: true` to pause the workflow until an external trigger (user input, sub-workflow callback, API call). ```typescript import type { TransitionInput } from '@loopstack/common'; @Transition({ from: 'responded', to: 'waiting_for_user' }) waitForUser(state: MyState) { // Moves to waiting_for_user, where the wait transition pauses } @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, }); } ``` Best practice: add a `schema` (describing only `data`) and type the parameter with `TransitionInput` so `input.data` is fully typed alongside `input.hasError` / `input.errorMessage` / `input.status` for failure branches. ## Sub-Workflows Inject sub-workflows via the constructor and use `.run()` to execute them asynchronously. The orchestrator automatically renders the child in the parent's run view based on the `show` option (default `'inline'`). ```typescript constructor(private readonly subWorkflow: SubWorkflow) { super(); } @Transition({ to: 'sub_started' }) async start(state: MyState) { await this.subWorkflow.run( { prompt: 'Hello' }, // args { callback: { transition: 'onSubComplete' }, show: 'inline', label: 'Running sub-workflow...' }, ); } @Transition({ from: 'sub_started', to: 'sub_done', wait: true, schema: z.object({ message: z.string() }), }) onSubComplete(state: MyState, input: TransitionInput<{ message: string }>) { // input.data contains the sub-workflow's published result // input.hasError / input.errorMessage are populated if the child failed } ``` `show` accepts `'inline'` (default — embed as iframe), `'link'` (status link card opening in a separate window), or `'hidden'` (no card). See [Sub-Workflows](../build/patterns/sub-workflows.md) for the full reference. ## Workflow Output Publish the workflow's output via `this.assignResult(...)` or `this.setResult(...)` — that value is what `WorkflowRunner` callers receive and what flows into a parent workflow's callback when this workflow runs as a sub-workflow. ```typescript @Transition({ from: 'done', to: 'end' }) finish(state: MyState) { this.setResult({ concept: state.confirmedConcept! }); } ``` ## Module Registration Every module whose workflows should appear in **Loopstack Studio** must be decorated with `@StudioApp`. Without it, workflows are NestJS providers but are not visible or launchable from the UI. ```typescript import { StudioApp } from '@loopstack/common'; @StudioApp({ title: 'My Feature', workflows: [MyWorkflow], }) @Module({ imports: [ClaudeModule], providers: [ MyWorkflow, MyTool, // Documents are NOT listed as providers — they are plain DTOs ], }) export class MyFeatureModule {} ``` > **Note:** `@StudioApp` is required alongside `@Module` — it does not replace it. If you are building a reusable library module (not a standalone app), omit `@StudioApp` and let the consuming app module declare the workflows. ## Complete Examples ### Example 1: Simple prompt workflow ```typescript import { z } from 'zod'; import { BaseWorkflow, Transition, Workflow } from '@loopstack/common'; import type { RunContext } from '@loopstack/common'; import { LlmGenerateTextTool } from '@loopstack/llm-provider'; const PromptSchema = z.object({ subject: z.string().default('coffee'), }); type PromptArgs = z.infer; @Workflow({ widget: './prompt.ui.yaml', schema: PromptSchema, }) export class PromptWorkflow extends BaseWorkflow { constructor(private readonly llmGenerateText: LlmGenerateTextTool) { super(); } @Transition({ to: 'end' }) async prompt(state: Record, ctx: RunContext) { await this.llmGenerateText.call( { prompt: this.render(join(__dirname, 'templates', 'prompt.md'), { subject: ctx.args.subject }), }, { config: { provider: 'claude', model: 'claude-sonnet-4-6' } }, ); } } ``` ### Example 2: Stateful workflow with dynamic routing ```typescript interface RoutingState { value: number; } const RoutingSchema = z.object({ value: z.number().default(150) }).strict(); type RoutingArgs = z.infer; @Workflow({ widget: './routing.ui.yaml', schema: RoutingSchema, }) export class RoutingWorkflow extends BaseWorkflow { @Transition({ to: 'prepared' }) setup(state: RoutingState, ctx: RunContext) { this.assignState({ value: ctx.args.value }); } @Transition({ from: 'prepared', to: 'high', priority: 10 }) @Guard('isAbove200') routeHigh(state: RoutingState) {} @Transition({ from: 'prepared', to: 'medium', priority: 5 }) @Guard('isAbove100') routeMedium(state: RoutingState) {} @Transition({ from: 'prepared', to: 'low' }) routeLow(state: RoutingState) {} isAbove200(state: RoutingState): boolean { return state.value > 200; } isAbove100(state: RoutingState): boolean { return state.value > 100; } @Transition({ from: 'high', to: 'end' }) showHigh(state: RoutingState) {} @Transition({ from: 'medium', to: 'end' }) showMedium(state: RoutingState) {} @Transition({ from: 'low', to: 'end' }) showLow(state: RoutingState) {} } ``` ### Example 3: Chat loop with tool calling ```typescript interface ChatState { llmResult?: LlmGenerateTextResult; delegateResult?: LlmDelegateResult; } const ChatSchema = z.object({ prompt: z.string() }); type ChatArgs = z.infer; @Workflow({ widget: './chat.ui.yaml', schema: ChatSchema, }) export class ChatWorkflow extends BaseWorkflow { constructor( private readonly llmGenerateText: LlmGenerateTextTool, private readonly llmDelegateToolCalls: LlmDelegateToolCallsTool, private readonly llmUpdateToolResult: LlmUpdateToolResultTool, private readonly getWeather: GetWeather, ) { super(); } @Transition({ to: 'ready' }) async setup(state: ChatState, ctx: RunContext) { await this.documentStore.save(LlmMessageDocument, { role: 'user', text: ctx.args.prompt, }); } @Transition({ from: 'ready', to: 'prompt_executed' }) @Transition({ from: 'tools_done', to: 'prompt_executed' }) async llmTurn(state: ChatState) { const result = await this.llmGenerateText.call( {}, { config: { provider: 'claude', model: 'claude-sonnet-4-6', tools: ['get_weather'] } }, ); this.assignState({ llmResult: result.data }); } @Transition({ from: 'prompt_executed', to: 'awaiting_tools', priority: 10 }) @Guard('hasToolCalls') async executeToolCalls(state: ChatState) { const result = await this.llmDelegateToolCalls.call({ message: state.llmResult!.message, tools: ['get_weather'], callback: { transition: 'toolResultReceived' }, }); this.assignState({ delegateResult: result.data }); } hasToolCalls(state: ChatState): boolean { return state.llmResult?.message.stopReason === 'tool_use'; } @Transition({ from: 'awaiting_tools', to: 'awaiting_tools', wait: true }) async toolResultReceived(state: ChatState, payload: unknown) { const result = await this.llmUpdateToolResult.call({ delegateResult: state.delegateResult!, completedTool: payload, }); this.assignState({ delegateResult: result.data }); } @Transition({ from: 'awaiting_tools', to: 'tools_done' }) @Guard('allToolsComplete') toolsComplete(state: ChatState) {} allToolsComplete(state: ChatState): boolean { return state.delegateResult?.allCompleted ?? false; } @Transition({ from: 'prompt_executed', to: 'end' }) respond(_state: ChatState) {} } ``` ## Workflow Lifecycle 1. Workflow starts — initial transition (from `'start'`) fires, args available via `ctx.args` 2. Transitions fire automatically in sequence — each writes state via `this.assignState(...)` / `this.setState(...)` (use `async` when the body awaits) 3. Tool calls execute via `await this.tool.call(args)` in transition methods 4. The published `result` (built via `this.assignResult(...)` / `this.setResult(...)`) is the workflow's output 5. If a transition targets `'end'`, workflow completes and exposes its published `result` 6. If a `wait: true` transition is reached, workflow pauses until externally triggered 7. `@Guard` methods control routing when multiple transitions share a `from` place 8. On error, the workflow fails (or use try/catch in method bodies) ## Checklist 1. Extend `BaseWorkflow` (or just `BaseWorkflow` for no input) and add `@Workflow({ widget, schema? })` 2. Inject tools and sub-workflows via constructor — call via `await this.tool.call(args)` 3. Define `@Transition({ to })` method for workflow entry (from defaults to `'start'`) — access args via `ctx.args` 4. Define `@Transition({ from, to })` methods for intermediate steps 5. Define `@Transition({ from, to: 'end' })` method for completion — publish output via `this.setResult(...)` 6. Use `wait: true` + `schema` for callback/user-input transitions 7. Use `@Guard('methodName')` + `priority` for conditional routing 8. Transitions return nothing — mutate state via `this.assignState(...)` / `this.setState(...)`. Use `async` when the body awaits. 9. Write YAML config with UI widgets only (no transitions) 10. Register workflow as provider in a NestJS `@Module()` 11. Add `@StudioApp({ title, workflows: [MyWorkflow] })` to the module so workflows appear in Studio --- > Source: https://loopstack.ai/llms/skills/use-core-tools.md --- title: 'Skill: Use Core Tools' description: Reference for AI agents on using built-in tools and documents from @loopstack/core and @loopstack/common — sub-workflow execution, document store, render, HTTP client, and core document types. --- # Skill: Use Core Tools ## Overview Core tools and documents ship with the Loopstack framework itself (via `@loopstack/core` and `@loopstack/common`). They are available globally through `LoopstackModule.forRoot()` without installing any registry packages — no extra imports needed in feature modules. Document classes are imported from `@loopstack/common`. ## Sub-Workflow Execution Inject sub-workflows via the constructor and use `.run()` to execute them asynchronously. The parent workflow pauses at a `wait: true` transition until the sub-workflow completes and triggers the callback. ### Inject in workflow ```typescript import { QueueResult } from '@loopstack/common'; constructor(private readonly subWorkflow: SubWorkflow) { super(); } ``` ### Run the sub-workflow ```typescript const result: QueueResult = await this.subWorkflow.run( { prompt: 'Hello' }, // args passed to the sub-workflow { callback: { transition: 'onSubComplete' }, // method name of the wait transition show: 'inline', // 'inline' (default) | 'link' | 'hidden' — how the child appears in the parent's view label: 'Running sub-workflow', // optional override (defaults to the child workflow's name) }, ); // result.workflowId — the ID of the spawned sub-workflow ``` ### Receive the callback ```typescript import type { TransitionInput } from '@loopstack/common'; const SubWorkflowMessageSchema = z.object({ message: z.string() }); @Transition({ from: 'sub_started', to: 'sub_done', wait: true, schema: SubWorkflowMessageSchema, }) onSubComplete(state: MyState, input: TransitionInput<{ message: string }>) { // input.workflowId — the sub-workflow's ID // input.status — 'completed' | 'failed' | 'canceled' // input.hasError / input.errorMessage — populated if the child failed // input.data — the sub-workflow's published result (validated against schema) const message = input.data.message; } ``` ### Sub-workflow output The sub-workflow's published `result` (written via `this.assignResult(...)` / `this.setResult(...)`) is passed as `input.data` in the parent's callback: ```typescript // In the sub-workflow: @Transition({ from: 'done', to: 'end' }) finish(state: SubState) { this.setResult({ message: 'Hi mom!' }); } ``` In the parent, validate the data shape via the `schema:` option on the wait transition — it describes `input.data` only; the framework constructs the surrounding envelope. ### Rendering in the Parent's View The `show` option on `.run()` controls how the child appears inside the parent's run view: - `'inline'` _(default)_ — child is embedded as an inline iframe. Best for HITL / OAuth / interactive children. - `'link'` — status link card, opens the child in a separate window. Best for autonomous children the parent just tracks. - `'hidden'` — no card at all. Best for background fan-out. The orchestrator auto-creates the corresponding `LinkDocument` for `'inline'` and `'link'`; the card's status is derived live from the child workflow's actual state — no manual updates needed. ## Built-in Document Types These document types are available from `@loopstack/common` without additional imports: | Document | Description | Key Fields | | ------------------ | ------------------------------------------------------------------ | ------------------------------------------ | | `MessageDocument` | UI-only chat message | `role`, `text` | | `MarkdownDocument` | Rendered markdown | `markdown` | | `PlainDocument` | Plain text | `text` | | `ErrorDocument` | Error message (red styling) | `error` | | `LinkDocument` | Status card / iframe link to sub-workflows (auto-saved by `run()`) | `label`, `workflowId`, `embed`, `expanded` | ### Usage ```typescript import { MessageDocument } from '@loopstack/common'; await this.documentStore.save(MessageDocument, { role: 'assistant', text: 'Hello! How can I help?', }); ``` ## Requirements - The parent workflow must be **stateful** (the default). Sub-workflow execution requires state persistence. - The target workflow must be registered as a provider in an imported module. - The callback `transition` value must match the **method name** of a `wait: true` transition. --- > Source: https://loopstack.ai/llms/skills/use-registry.md --- title: 'Skill: Use the Loopstack Registry' description: Instructions for AI agents to discover, install, and integrate @loopstack/* registry packages via npm, and to read and copy example workflows from the examples app. --- # Skill: Use the Loopstack Registry ## Overview The Loopstack Registry is a collection of `@loopstack/*` packages providing pre-built tools, workflows and modules. Always check the registry before building a custom tool or workflow — the functionality you need may already exist. Every registry package is a NestJS module you import as a dependency (LLM providers, OAuth, Docker sandboxes, HITL, git, MCP, etc.): `npm install @loopstack/`. The package lives at `registry/` in the Loopstack repository and is documented at `https://loopstack.ai/docs/registry/`. Example workflows are not registry packages. They live in one app in the Loopstack repository and are meant to be read and copied — see [Using an Example](#using-an-example). ## Discovering Packages Browse the registry at `https://loopstack.ai/docs/registry`. ## Installing a Package ```bash npm install @loopstack/ ``` Then import its module in your app: ```typescript import { Module } from '@nestjs/common'; import { MyModule } from '@loopstack/'; @Module({ imports: [MyModule], }) export class AppModule {} ``` The module's exports — tools, services, documents — become available for constructor injection in your workflows. ## Using an Example Every example lives in one app, `examples/`, in the Loopstack repository — one module per theme under `examples/src/`. Clone it once to read and run all of them: ```bash npx giget@latest gh:loopstack-ai/loopstack/examples loopstack-examples cd loopstack-examples && npm install && npm run build && npm start ``` Examples are meant to be read, copied and adapted. To take one into your own project, copy its module directory and install what it imports — each module's README names the exact packages: ```bash cp -r loopstack-examples/src/hitl src/hitl npm install @loopstack/agent @loopstack/claude @loopstack/common @loopstack/hitl @loopstack/llm-provider ``` Then register the module like any local NestJS module: ```typescript import { Module } from '@nestjs/common'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { HitlExamplesModule } from './hitl/hitl-examples.module'; @Module({ imports: [LoopstackModule.forRoot(), HitlExamplesModule], }) export class AppModule {} ``` ## Inspecting a Package Before Committing To explore a registry package without adding it to the project, install it in a temporary directory: ```bash mkdir -p /tmp/loopstack-inspect && cd /tmp/loopstack-inspect npm init -y && npm install @loopstack/ ``` Review `node_modules/@loopstack//README.md` and `src/` to verify the package does what you need. The source of a package or a single example module can also be fetched straight into `/tmp`: ```bash npx giget@latest gh:loopstack-ai/loopstack/registry/ /tmp/ npx giget@latest gh:loopstack-ai/loopstack/examples/src/ /tmp/ ``` ## Reading Source Code When in doubt about a tool's behavior — its input schema, return type, or side effects — read the source directly. For packages installed via npm: ``` node_modules/@loopstack//src/tools/.tool.ts ``` For an example module you copied, the source lives wherever you put it (e.g. `src//`). Look for: - `@Tool({ name, description, schema })` — the name, description (seen by LLMs), and Zod schema for accepted arguments - `handle()` method — the actual implementation - `ToolEnvelope` return — what data comes back (workflow callers see the narrowed `ToolResult` after `tool.call()` throws on `error` / `pending`) ---