# Examples Example workflows demonstrating Loopstack patterns: chat, tool calling, agents, HITL, structured output, sub-workflows, and integrations. One runnable app, one module per theme. --- > Source: https://loopstack.ai/llms/examples/advanced-workflows.md --- title: Advanced Workflows Examples description: In-depth examples of advanced Loopstack workflow patterns — state, dynamic routing, sub-workflows (parent, fan-out, sequence, show modes, error handling), batch processing, custom tools, configurable modules, and built-in UI documents. --- # Advanced Workflows Examples > Advanced workflow pattern examples for the [Loopstack](https://loopstack.ai) automation framework. Deep-dive examples for framework patterns authors reach for less often but want available when they need them. Pick the example that matches your problem. ## Use in Your App Copy this directory into your app, then install what it imports: ```bash npm install @loopstack/claude @loopstack/common @loopstack/core @loopstack/llm-provider ``` Register the module: ```typescript import { Module } from '@nestjs/common'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { AdvancedWorkflowsExamplesModule } from './advanced-workflows/advanced-workflows-examples.module'; @Module({ imports: [LoopstackModule.forRoot(), AdvancedWorkflowsExamplesModule], }) export class AppModule {} ``` ## Required app-module configuration Examples that exercise LLM tools (`LlmGenerateTextTool`, `LlmGenerateObjectTool` — used by Sub-Workflow, Fan-Out, Sequence, Batch Processing, Custom Tool, Server Tool, Module Config) call into `@loopstack/llm-provider`. That module is `@Global` and must be configured once in your root module to set the default model: ```typescript import { Module } from '@nestjs/common'; import { LlmProviderModule } from '@loopstack/llm-provider'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { AdvancedWorkflowsExamplesModule } from './advanced-workflows/advanced-workflows-examples.module'; @Module({ imports: [ LoopstackModule.forRoot(), LlmProviderModule.forRoot({ model: 'claude-sonnet-4-6' }), AdvancedWorkflowsExamplesModule, ], }) export class AppModule {} ``` `AdvancedWorkflowsExamplesModule` already re-imports `ClaudeModule` to register the Claude provider; `LlmProviderModule.forRoot(...)` sets the default model the tools dispatch to. Pure pattern demos that don't call an LLM (Workflow State, Dynamic Routing, UI Documents) work without it. Set `ANTHROPIC_API_KEY` in the environment for the LLM examples. ## Examples | Example | Studio title | Description | | ------------------------------------- | -------------------------------------------------- | --------------------------------------------------------------------------------------- | | [Workflow State](#workflow-state) | `Advanced - Workflow State Example` | Persist typed state across transitions via `assignState()` | | [Workflow Result](#workflow-result) | `Advanced - Workflow Result Example` | Publish a result for callers via `assignResult()`, kept apart from private state | | [Dynamic Routing](#dynamic-routing) | `Advanced - Dynamic Routing Example` | Conditional routing with `@Guard` decorators and transition priorities | | [Sub-Workflow](#sub-workflow) | `Advanced - Sub-Workflow Example` | Launch a child workflow via `.run()` and resume on callback | | [Fan-Out](#fan-out) | `Advanced - Fan-Out Example` | Parallel sub-workflows with single aggregated callback (`FanOutWorkflow`) | | [Sequence](#sequence) | `Advanced - Sequence Example` | Sequential sub-workflows with single aggregated callback (`SequenceWorkflow`) | | [Batch Processing](#batch-processing) | `Advanced - Batch Processing Example` | Chunked processing of a list in fixed-size batches | | [Custom Tool](#custom-tool) | `Advanced - Custom Tool Example` | Authoring custom tools — stateless + stateful, `@Tool()`, Zod schemas, NestJS injection | | [Server Tool](#server-tool) | `Advanced - Server Tool Example` | Authoring a server tool — a tool the LLM provider runs, via `ServerTool` | | [Tool Documents](#tool-documents) | `Advanced - Tool Documents Example` | A tool that declares a document on its result envelope instead of saving it | | [Module Config](#module-config) | `Advanced - Module Config (Default/French/Nested)` | `forRoot` / `forFeature` patterns for configurable modules | | [UI Documents](#ui-documents) | `Advanced - UI Documents Example` | Smoke test for built-in document types (Message, Error, Markdown, Plain) | --- ## Workflow State `WorkflowStateWorkflow` — the minimal state pattern: `assignState()` in one transition, read the typed `state` parameter in the next, and format it with a private helper method. State is private to the workflow, so the run publishes no result. ### Files - `workflow-state-example.workflow.ts` ## Workflow Result `WorkflowResultWorkflow` — the workflow's published result. The first transition keeps a name in state and publishes a greeting with `assignResult()`. The second reads the name from state and adds a second field with another `assignResult()`, which merges into the first. The run's result is `{ greeting, shout }` — what `WorkflowRunner` callers, parent callbacks (`input.data`) and the API receive — while the name stays in private state. ### Files - `workflow-result-example.workflow.ts` ## Dynamic Routing Demonstrates `@Guard`-based conditional routing — multiple transitions out of one state, evaluated in priority order, the first one whose guard returns true wins. ### Files - `dynamic-routing-example.workflow.ts` ## Sub-Workflow Five workflow files demonstrating sub-workflow composition: - `sub-workflow-parent.workflow.ts` — basic parent that launches a child via `.run()` - `sub-workflow-sub.workflow.ts` — the child workflow - `sub-workflow-failing-sub.workflow.ts` — a child that fails unless started with `fail: false` (used by error-handling) - `sub-workflow-error-handling.workflow.ts` — parent reads the child's outcome via `input.hasError` / `input.status` / `input.errorMessage`; pass `fail: false` to see the success branch - `sub-workflow-show-modes.workflow.ts` — every `show` mode (`inline`, `link`, `hidden`) in one flow For parallel and sequential composition see [Fan-Out](#fan-out) and [Sequence](#sequence). ## Fan-Out Launches multiple sub-workflows in parallel via `FanOutWorkflow` from `@loopstack/core`. The parent receives a single callback once all children complete. ### Files - `fan-out-example.workflow.ts` ## Sequence Runs multiple sub-workflows one at a time via `SequenceWorkflow` from `@loopstack/core`. The parent receives a single aggregated callback after the last child completes. ### Files - `sequence-example.workflow.ts` ## Batch Processing Processes a list of items in fixed-size batches. Items within a batch run concurrently (`Promise.all`), batches run sequentially via a state-machine loop. Distinct from `FanOutWorkflow` which runs all sub-workflows simultaneously. Useful for rate-limited APIs, memory-bounded processing, or quota-constrained operations. ### Files - `batch-processing-example.workflow.ts` ## Custom Tool Demonstrates authoring custom tools by extending `BaseTool`: - `MathSumTool` — stateless, computes `a + b` - `CounterTool` — stateful, persists across checkpoints - `MathService` — supporting NestJS service injected into a tool ### Files - `custom-tool-example.workflow.ts` - `custom-tool-example.ui.yaml` - `tools/math-sum.tool.ts` (stateless) - `tools/counter.tool.ts` (stateful) - `services/math.service.ts` ## Server Tool Demonstrates authoring a server tool by extending `ServerTool` — a tool the LLM provider runs itself, not your app: - `CodeExecutionTool` (`example_code_execution`) — has no `handle()` and no `call()`. It only implements `toServerToolConfig()`, which returns the provider-native tool spec (here Anthropic's `code_execution`). - The workflow lists the tool by name in the `tools` config of an `llm_generate_text` call. It never calls the tool itself: Claude runs the code in Anthropic's sandbox, inside that same call. - The reply carries Claude's use of the tool as a `server_tool_use` block and its output as a `server_tool_result` block. The workflow reads the code and its stdout from these blocks, and Studio shows them as one tool call with its result. A server tool runs only on the provider whose native spec it returns — this one on Claude. Other providers reject a call that lists it. The spec fakes only the Anthropic client, so `toServerToolConfig()` and the Claude provider run in the test. ### Files - `server-tool-example.workflow.ts` - `tools/code-execution.tool.ts` ## Tool Documents Demonstrates a tool that produces a document without writing it: - `ReceiptTool` (`create_receipt`) — totals a list of items and returns the total as `data`. It returns the receipt in `documents` on its result envelope: the document name, the content, and the same options as `documentStore.save()`. It gets the name with `resolveDocumentName(ReceiptDocument)`, so the name always matches the registered class. - `ReceiptDocument` (`receipt`) — a registered `@Document` that Studio renders as Markdown. A declared document must be a registered `@Document`. Otherwise the tool call fails with `Unknown document`. - The workflow only calls the tool and publishes the total. It saves no document itself: the tool pipeline saves the declared receipt after the call. The pipeline saves declared documents after any interceptor or replay. So a replayed call saves the documents of its recorded envelope, as a live call would. The spec shows both: a live run saves the receipt the tool built, and a replayed run saves the receipt from the recording. ### Files - `tool-documents-example.workflow.ts` - `tools/receipt.tool.ts` - `documents/receipt-document.ts` ## Module Config Three scenarios for configurable modules, each a workflow that calls `GreeterTool` and saves the greeting it gets back: 1. **Default Greeting** (`default_greeting`) — no `forFeature` override; uses the app's `forRoot({ language: 'en' })` → `Hello, World! [language=en]` 2. **French Greeting** (`french_greeting`) — a `forFeature({ language: 'fr' })` override in its own module → `Bonjour, Monde! [language=fr]` 3. **Nested Greeting** (`nested_greeting`) — config passed through a wrapper module (`GreeterAgentModule.forFeature`) → `Hola, Mundo! [language=es]` All three run side by side in one app, each with its own resolved config. Each consumer module provides its own workflow, so the workflows get the `GreeterTool` of that module's scope. The `@StudioApp` `workflows` list names them, so they can be started from Studio, the API and the CLI. They are not listed again in the module's `providers`, because a second instance there would resolve the global config. ### Files - `greeter/` — configurable module (`forRoot`, `forFeature`, constants, tool) and the `GreeterAgentModule` wrapper - `consumers/` — three module + workflow pairs, one per scenario ## UI Documents A small workflow that saves one of each built-in document type so you can verify Studio renders them correctly. ### Files - `ui-documents-example.workflow.ts` ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/examples/agent.md --- title: Agent Examples description: Workflow examples for LLM agents in Loopstack — basic AgentWorkflow with custom tools, tool errors fed back to the LLM, code-exploration agent, and a from-scratch custom agent loop with a turn budget. --- # Agent Examples > LLM agent workflow examples for the [Loopstack](https://loopstack.ai) automation framework. Three ways to build agents in Loopstack — from the recommended `AgentWorkflow` shortcut to a from-scratch custom loop. Pick the right shape for your control vs. simplicity tradeoff. One more example shows how an agent recovers when its tools fail. ## Use in Your App Copy this directory into your app, then install what it imports: ```bash npm install @loopstack/agent @loopstack/claude @loopstack/code-agent @loopstack/common @loopstack/llm-provider @loopstack/remote-client ``` Register the module: ```typescript import { Module } from '@nestjs/common'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { AgentExamplesModule } from './agent/agent-examples.module'; @Module({ imports: [LoopstackModule.forRoot(), AgentExamplesModule], }) export class AppModule {} ``` ## Required app-module configuration All examples use LLM tools (`LlmGenerateTextTool`, `LlmDelegateToolCallsTool`, etc.) from `@loopstack/llm-provider`. That module is `@Global` and must be configured once in your root module to set the default model: ```typescript import { Module } from '@nestjs/common'; import { LlmProviderModule } from '@loopstack/llm-provider'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { AgentExamplesModule } from './agent/agent-examples.module'; @Module({ imports: [LoopstackModule.forRoot(), LlmProviderModule.forRoot({ model: 'claude-sonnet-4-6' }), AgentExamplesModule], }) export class AppModule {} ``` `AgentExamplesModule` re-imports `ClaudeModule` (provider), `AgentModule` (the `AgentWorkflow` / `ChatAgentWorkflow` classes), `CodeAgentModule`, and `RemoteClientModule.forFeature({ type: 'sandbox' })`. `LlmProviderModule.forRoot(...)` sets the default model the tools dispatch to. The Code Agent example additionally requires `RemoteClientModule.forRoot({ environments })` — see [Code Agent → Setup](#code-agent) below. ## Environment ```bash ANTHROPIC_API_KEY=sk-ant-... ``` ## Examples | Example | Studio title | Description | | ----------------------------- | ------------------------------ | ----------------------------------------------------------------------------------- | | [Agent](#agent) | `Agent - Basic Agent Example` | Launch `AgentWorkflow` with custom tools — recommended starting point | | [Tool Errors](#tool-errors) | `Agent - Tool Errors Example` | Failing tools reach the LLM as `is_error` tool results, and the LLM corrects course | | [Code Agent](#code-agent) | `Agent - Code Agent Example` | Specialized codebase-exploration agent with `glob` / `grep` / `read` | | [Custom Agent](#custom-agent) | `Agent - Custom Agent Example` | Build an agent loop from scratch — delegate primitives, guards, a turn budget | --- ## Agent Launches a generic `AgentWorkflow` as a sub-workflow with two custom tools (`weather_lookup`, `calculator`) and renders the agent's run inline in the parent view. The recommended starting point for agent workflows. ### Files - `agent-example.workflow.ts` — workflow class - `tools/weather-lookup.tool.ts`, `tools/calculator.tool.ts` — custom tools - `templates/system.md` — agent system prompt ## Tool Errors Launches `AgentWorkflow` with three tools that fail in different ways: - `strict_schema` — rejects a call whose args do not match its schema - `runtime_error` — throws when called with `shouldFail: true` - `failing_sub_workflow` — starts a sub-workflow that always fails The system prompt tells the LLM to trigger each failure, then make the corrected call. `AgentWorkflow` returns every failure to the LLM as a tool result with `isError: true` instead of failing the run, so the LLM reads the error and corrects course. The example has no error handling of its own: the agent loop does it for every tool. ### Files - `tool-errors-example.workflow.ts` — workflow class - `tools/strict-schema.tool.ts`, `tools/runtime-error.tool.ts`, `tools/failing-sub-workflow.tool.ts` — the failing tools - `tool-errors-failing-sub.workflow.ts` — the sub-workflow that always fails (started by `failing_sub_workflow`) - `templates/system.md` — agent system prompt with the steps to follow ## Code Agent Launches `AgentWorkflow` as a code-exploration agent with `glob`, `grep`, and `read` tools. Demonstrates configuring a domain-specific agent without building a custom loop. ### Setup The `glob`, `grep`, and `read` tools execute on a **remote agent**, so the workspace must have a `sandbox` environment connected. **1. Run a remote agent.** The simplest option is `@loopstack/remote-server` on `localhost:3001` (see `registry/remote-client/server/`). **2. Register an available environment in your app module:** ```typescript import { RemoteClientModule } from '@loopstack/remote-client'; @Module({ imports: [ LoopstackModule.forRoot(), RemoteClientModule.forRoot({ environments: { available: [ { type: 'sandbox', name: 'Local Remote Server', connectionUrl: 'http://localhost:3080', agentUrl: 'http://localhost:3001', local: true, }, ], }, }), AgentExamplesModule, ], }) export class AppModule {} ``` `AgentExamplesModule` itself declares the `sandbox` slot via `RemoteClientModule.forFeature(...)` — make sure you use the same type = sandbox. **3. Create a workspace from the Studio.** The environment is auto-selected from the matching `type` and persisted on creation. ### Files - `code-agent-example.workflow.ts` — workflow class ## Custom Agent A from-scratch agent loop using the delegate primitives (`LlmGenerateTextTool`, `LlmDelegateToolCallsTool`, `LlmUpdateToolResultTool`). Demonstrates the pattern `AgentWorkflow` encapsulates: LLM call → guard on `tool_use` vs `end_turn` → delegate tools → feed results back → loop. After two tool-using turns the workflow stops the loop itself and runs one final LLM call with a different system prompt and no tools — a control-flow shape a single `AgentWorkflow.run(...)` cannot express. ### When to use - You need finer control than `AgentWorkflow` provides (custom guards, cancellation logic, telemetry hooks) - You want to understand what `AgentWorkflow` does under the hood - You need a custom shape — multiple parallel LLMs, conditional tool sets per turn, etc. For the simple case, prefer `AgentWorkflow` (see [Basic Agent Example](#agent)). ### Files - `custom-agent-example.workflow.ts` — workflow class - `templates/system.md` — system prompt for the tool-using turns - `templates/wrap-up.md` — system prompt for the final turn without tools ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/examples/error-handling.md --- title: Error Handling Examples description: Error handling workflow examples for Loopstack — auto-retry with exponential backoff, retryTarget, errorPlace recovery, manual retry, transition timeouts, and sub-workflow failures routed via errorPlace. --- # Error Handling Examples > Error handling workflow examples for the [Loopstack](https://loopstack.ai) automation framework. One workflow per way a Loopstack workflow can react to a failing transition. Each example simulates the failure deterministically, so you can watch the mode work and copy the one you need. For the full decision tree (auto-retry → `errorPlace` → manual retry), see the [Error Handling, Retry & Timeout](https://loopstack.ai/docs/build/patterns/error-handling) guide. ## Use in Your App Copy this directory into your app, then install what it imports: ```bash npm install @loopstack/common ``` Register the module: ```typescript import { Module } from '@nestjs/common'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { ErrorHandlingExamplesModule } from './error-handling/error-handling-examples.module'; @Module({ imports: [LoopstackModule.forRoot(), ErrorHandlingExamplesModule], }) export class AppModule {} ``` ## Environment None — the examples call no LLM and need no secrets. The failures are simulated by two local tools: `FlakyServiceTool` (`flaky_service`) throws when told to, and `SlowOperationTool` (`slow_operation`) sleeps for a given time. ## Examples | Example | Studio title | Description | | ----------------------------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------------ | | [Auto Retry](#auto-retry) | `Error Handling - Auto Retry Example` | `retryAttempts` re-runs a failed transition with exponential backoff | | [Retry Target](#retry-target) | `Error Handling - Retry Target Example` | `retryTarget` routes each retry through a preparation place | | [Error Place](#error-place) | `Error Handling - Error Place Example` | `errorPlace` moves a failed workflow to a recovery place | | [Manual Retry](#manual-retry) | `Error Handling - Manual Retry Example` | The default: the workflow stays put and offers a Retry button | | [Transition Timeout](#transition-timeout) | `Error Handling - Transition Timeout Example` | `timeout` fails a transition that runs too long | | [Sub-Workflow Error Place](#sub-workflow-error-place) | `Error Handling - Sub-Workflow Error Place Example` | A failed child's callback is routed to a recovery place via `errorPlace` | --- ## Auto Retry `@Transition({ to: 'end', retryAttempts: 2 })` — the service call fails on the first two attempts. The framework re-runs the transition after 1s and 2s, and the third attempt succeeds. The attempt number comes from `ctx.execution.retryCount`. ```bash loopstack run auto_retry_example ``` Completes after about 3 seconds with `result: { attempts: 3 }`. ### Files - `workflows/auto-retry/auto-retry-example.workflow.ts` ## Retry Target `retryAttempts: 2, retryTarget: 'refresh_credentials'` — each auto-retry re-enters the workflow at `refresh_credentials` instead of re-running the failed transition. That place does the preparation work (a simulated credential refresh) and loops back to `ready`, where the service call runs again. ```bash loopstack run retry_target_example ``` Completes with `result: { attempts: 3, refreshes: 2 }`. ### Files - `workflows/retry-target/retry-target-example.workflow.ts` ## Error Place `errorPlace: 'service_failed'` — the service call always fails, and the workflow moves to `service_failed` instead of staying at its place. The run shows as failed there, with a **Recover** button that triggers the `recover` wait transition and completes the run. ```bash loopstack run error_place_example ``` The run ends failed at `service_failed` with `Simulated external service error`. Click **Recover** in Studio (**Error Handling Examples → Error Handling - Error Place Example**), or trigger it from the CLI — the run completes with `result: { recovered: true }`: ```bash loopstack answer --transition recover ``` ### Files - `workflows/error-place/error-place-example.workflow.ts` - `workflows/error-place/error-place-example.ui.yaml` — the Recover button ## Manual Retry No `retryAttempts`, no `errorPlace` — the default. The service call fails on the first attempt, and the workflow stays at its place with a **Retry** button next to the error. The second attempt succeeds. ```bash loopstack run manual_retry_example ``` The run ends failed with `Simulated external service error`. Click **Retry** in Studio (in an interactive terminal, `loopstack run` offers the retry itself); the run completes with `result: { attempts: 2 }`. ### Files - `workflows/manual-retry/manual-retry-example.workflow.ts` ## Transition Timeout `timeout: 2000` — the first attempt runs a 5-second operation and is failed after 2 seconds. With no retry options, the timeout is handled like any other failure (manual retry). The second attempt finishes instantly. `SlowOperationTool` passes `ctx.signal` to its sleep. The framework aborts that signal when the transition times out, so the abandoned operation stops instead of running on in the background — do the same in your own long-running tools. ```bash loopstack run transition_timeout_example ``` The run ends failed with `Transition 'runSlowOperation' timed out after 2000ms`. Click **Retry** in Studio (or accept the retry `loopstack run` offers in an interactive terminal); the run completes with `result: { attempts: 2 }`. ### Files - `workflows/transition-timeout/transition-timeout-example.workflow.ts` ## Sub-Workflow Error Place The parent starts a child workflow that always throws. Its callback transition declares `errorPlace: 'child_failed'`, so the failed callback moves the parent to `child_failed` — the happy-path body of `childCompleted` never runs. A **Recover** button triggers the `recover` wait transition and completes the run. ```bash loopstack run sub_workflow_error_place_example ``` The run ends failed at `child_failed` with `Child workflow failed`. Click **Recover** in Studio, or run `loopstack answer --transition recover` — the run completes with `result: { recovered: true }`. ### Files - `workflows/sub-workflow-error-place/sub-workflow-error-place-example.workflow.ts` - `workflows/sub-workflow-error-place/sub-workflow-error-place-child.workflow.ts` — the always-failing child - `workflows/sub-workflow-error-place/sub-workflow-error-place-example.ui.yaml` — the Recover button ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/examples/git.md --- title: Git Examples description: Git and GitHub workflow examples — scripted multi-tool git operations and end-to-end repo sync via ConnectGitHubWorkflow --- # Git Examples > Git and GitHub workflow examples for the [Loopstack](https://loopstack.ai) automation framework. Two workflow examples that show how to compose git tools and integrate with GitHub. ## Use in Your App Copy this directory into your app, then install what it imports: ```bash npm install @loopstack/common @loopstack/git @loopstack/github-integration @loopstack/remote-client ``` Register the module: ```typescript import { Module } from '@nestjs/common'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { GitExamplesModule } from './git/git-examples.module'; @Module({ imports: [LoopstackModule.forRoot(), GitExamplesModule], }) export class AppModule {} ``` ## Required app-module configuration Both examples invoke git tools that execute on a **remote agent**, so the workspace needs a connected `sandbox` environment. `GitExamplesModule` declares the slot via `RemoteClientModule.forFeature(...)`, but the consumer must register at least one matching environment in their root module via `RemoteClientModule.forRoot(...)`: ```typescript import { Module } from '@nestjs/common'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { RemoteClientModule } from '@loopstack/remote-client'; import { GitExamplesModule } from './git/git-examples.module'; @Module({ imports: [ LoopstackModule.forRoot(), RemoteClientModule.forRoot({ environments: { available: [ { type: 'sandbox', name: 'Local Remote Server', connectionUrl: process.env.SANDBOX_URL ?? 'http://localhost:3080', agentUrl: process.env.SANDBOX_AGENT_URL ?? 'http://localhost:3001', local: true, }, ], }, }), GitExamplesModule, ], }) export class AppModule {} ``` The `type: 'sandbox'` must match the slot type declared by `GitExamplesModule`. The simplest remote agent option is `@loopstack/remote-server` on `localhost:3001`. `GitExamplesModule` re-imports `GitModule.forFeature()` and `GitHubIntegrationModule`, which transitively brings in the global `OAuthModule` and the GitHub OAuth provider — no additional OAuth wiring required in your AppModule. You just need to set the GitHub OAuth client env vars (see [Environment](#environment) below). ## Environment The repo-sync example requires GitHub OAuth credentials: ```bash GITHUB_CLIENT_ID=... GITHUB_CLIENT_SECRET=... ``` ## Examples | Example | Studio title | Description | | ------------------------------------- | -------------------------------- | ---------------------------------------------------------------------- | | [Git Commit Flow](#git-commit-flow) | `Git - Commit Flow Example` | Scripted multi-tool git workflow — status → add → commit → log, no LLM | | [GitHub Repo Sync](#github-repo-sync) | `Git - GitHub Repo Sync Example` | Launches `ConnectGitHubWorkflow` for the full repo sync flow | --- ## Git Commit Flow A scripted workflow that orchestrates four git tools in sequence: `gitStatus`, `gitAdd`, `gitCommit`, `gitLog`. No LLM involved — demonstrates composing tools deterministically. ### Files - `git-commit-flow-example.workflow.ts` — workflow class ## GitHub Repo Sync Thin wrapper that launches `ConnectGitHubWorkflow` from `@loopstack/github-integration` as a sub-workflow. The integration handles the full sync flow: OAuth → create or pick repo → check uncommitted changes → resolve divergence → push. For examples of the GitHub API tools (repos, issues, PRs, actions, search), see [`github`](/docs/examples/github). ### Files - `github-repo-sync-example.workflow.ts` — workflow class ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/examples/github.md --- title: GitHub Examples description: GitHub integration workflow examples for Loopstack — a scripted repo overview that walks the GitHub read tools, and an interactive Claude agent with 25 GitHub tools. Both sign in through the OAuth sub-workflow when a tool reports unauthorized. --- # GitHub Examples > GitHub integration workflow examples for the [Loopstack](https://loopstack.ai) automation framework. Two ways to use the `@loopstack/github` tools: - A **scripted overview** workflow — single pass, hand-rolled tool sequence - An **interactive agent** workflow — Claude with the full GitHub tool set Both share the same sign-in pattern: when a tool returns unauthorized, launch the `OAuthWorkflow` sub-workflow inline, then retry. For syncing a workspace to a GitHub repository, see the [GitHub Repo Sync](/docs/examples/git#github-repo-sync) example in `git`. ## Use in Your App Copy this directory into your app, then install what it imports: ```bash npm install @loopstack/claude @loopstack/common @loopstack/github @loopstack/llm-provider @loopstack/oauth ``` Register the module: ```typescript import { Module } from '@nestjs/common'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { GitHubExamplesModule } from './github/github-examples.module'; @Module({ imports: [LoopstackModule.forRoot(), GitHubExamplesModule], }) export class AppModule {} ``` ## Required app-module configuration Both examples use Claude via `@loopstack/llm-provider` — `@Global`, configured once in your root module to set the default model: ```typescript import { Module } from '@nestjs/common'; import { LlmProviderModule } from '@loopstack/llm-provider'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { GitHubExamplesModule } from './github/github-examples.module'; @Module({ imports: [LoopstackModule.forRoot(), LlmProviderModule.forRoot({ model: 'claude-sonnet-4-6' }), GitHubExamplesModule], }) export class AppModule {} ``` `GitHubExamplesModule` re-imports `ClaudeModule` and `GitHubModule`. `GitHubModule` transitively pulls in the global `OAuthModule` and registers the GitHub OAuth provider — no additional OAuth wiring required in your AppModule. ## Environment ```bash ANTHROPIC_API_KEY=sk-ant-... GITHUB_CLIENT_ID=... GITHUB_CLIENT_SECRET=... ``` Refer to `@loopstack/github` for the full OAuth setup (redirect URL, scopes). ## Running Start a workflow from Studio (app **GitHub Examples**) or with the Loopstack CLI: ```bash loopstack run github_overview_example --arg owner=octocat --arg repo=Hello-World loopstack run github_agent_example ``` On the first run you are asked to sign in to GitHub; after that the overview renders a markdown summary of the repository, and the agent waits for your chat messages. ## Examples | Example | Studio title | Description | | ----------------------------------- | --------------------------- | -------------------------------------------------------- | | [GitHub Overview](#github-overview) | `GitHub - Overview Example` | Scripted walk of GitHub read tools with markdown summary | | [GitHub Agent](#github-agent) | `GitHub - Agent Example` | Interactive Claude agent with 25 GitHub tools | --- ## GitHub Overview A scripted (non-agent) GitHub workflow that walks every major GitHub read tool: user info, orgs, repo details, branches, issues, PRs, directory contents, workflow runs, and code search. On any unauthorized error it pauses, launches the `OAuthWorkflow` sub-workflow inline, then retries from the start. ### Sign in and retry This is the reference for the sign-in flow of a scripted workflow. The [Google Calendar Summary](/docs/examples/google-workspace#google-calendar-summary) example uses the same flow. It has four parts: 1. **Catch the error.** A tool with no valid token throws an error whose message contains "authenticate" ("Please authenticate first." / "Please re-authenticate."). `fetchUser` catches it and sets `requiresAuthentication` in the state. It rethrows any other error. 2. **Start the sign-in.** `authRequired` has `priority: 10` and the `needsAuth` guard, so it runs before the normal next step when the state asks for sign-in. It calls `OAuthWorkflow.run()` with the provider, the scopes and `callback: { transition: 'authCompleted' }`, and shows the sub-workflow inline. 3. **Retry.** `authCompleted` is a `wait: true` transition back to `start`. The sub-workflow's callback fires it, and the run fetches again with the new token. 4. **Stop on a failed sign-in.** `authCompleted` sets `errorPlace: 'auth_failed'`. A failed or canceled sub-workflow ends the run at `auth_failed` instead of starting the sign-in again. From there `retryAuth`, also `wait: true`, goes back to `start` once the OAuth app is configured. ### Files - `github-overview-example.workflow.ts` — workflow class - `templates/repoOverview.md` — Handlebars markdown summary template ## GitHub Agent An interactive Claude chat agent with 25 GitHub tools wired in: repos, issues, PRs, code, actions, and search. When a tool returns unauthorized, the agent calls `authenticateGitHub` to launch the OAuth sub-workflow and retries. ### Files - `github-agent-example.workflow.ts` — workflow class - `github-agent-example.ui.yaml` — chat prompt-input widget - `templates/systemMessage.md` — system prompt ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/examples/google-workspace.md --- title: Google Workspace Examples description: Google Workspace integration workflow examples for Loopstack — a scripted Google Calendar summary, and an interactive Claude agent with Calendar, Gmail and Drive tools. Both sign in through the OAuth sub-workflow when a tool reports unauthorized. --- # Google Workspace Examples > Google Workspace integration workflow examples for the [Loopstack](https://loopstack.ai) automation framework. Two ways to use the `@loopstack/google-workspace` tools: - A **scripted summary** workflow — fetches calendar events and renders them - An **interactive agent** workflow — Claude with Calendar, Gmail, and Drive tools Both share the same sign-in pattern: when a tool returns unauthorized, launch the `OAuthWorkflow` sub-workflow inline, then retry. ## Use in Your App Copy this directory into your app, then install what it imports: ```bash npm install @loopstack/claude @loopstack/common @loopstack/google-workspace @loopstack/llm-provider @loopstack/oauth ``` Register the module: ```typescript import { Module } from '@nestjs/common'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { GoogleWorkspaceExamplesModule } from './google-workspace/google-workspace-examples.module'; @Module({ imports: [LoopstackModule.forRoot(), GoogleWorkspaceExamplesModule], }) export class AppModule {} ``` ## Required app-module configuration Both examples use Claude via `@loopstack/llm-provider` — `@Global`, configured once in your root module to set the default model: ```typescript import { Module } from '@nestjs/common'; import { LlmProviderModule } from '@loopstack/llm-provider'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { GoogleWorkspaceExamplesModule } from './google-workspace/google-workspace-examples.module'; @Module({ imports: [ LoopstackModule.forRoot(), LlmProviderModule.forRoot({ model: 'claude-sonnet-4-6' }), GoogleWorkspaceExamplesModule, ], }) export class AppModule {} ``` `GoogleWorkspaceExamplesModule` re-imports `ClaudeModule` and `GoogleWorkspaceModule`. `GoogleWorkspaceModule` transitively pulls in the global `OAuthModule` and registers the Google OAuth provider — no additional OAuth wiring required in your AppModule. ## Environment ```bash ANTHROPIC_API_KEY=sk-ant-... GOOGLE_CLIENT_ID=... GOOGLE_CLIENT_SECRET=... ``` Refer to `@loopstack/google-workspace` for the full OAuth setup (redirect URL, scopes). ## Running Start a workflow from Studio (app **Google Workspace Examples**) or with the Loopstack CLI: ```bash loopstack run google_calendar_summary_example --arg calendarId=primary loopstack run google_workspace_agent_example ``` On the first run you are asked to sign in to Google; after that the summary renders your upcoming events as markdown, and the agent waits for your chat messages. ## Examples | Example | Studio title | Description | | --------------------------------------------------- | --------------------------------------------- | -------------------------------------------------------------- | | [Google Calendar Summary](#google-calendar-summary) | `Google Workspace - Calendar Summary Example` | Scripted calendar fetch + markdown summary | | [Google Workspace Agent](#google-workspace-agent) | `Google Workspace - Agent Example` | Interactive Claude agent with Calendar, Gmail, and Drive tools | --- ## Google Calendar Summary Fetches the user's upcoming calendar events with `GoogleCalendarFetchEventsTool` from `@loopstack/google-workspace` and renders a markdown summary. On unauthorized it launches the `OAuthWorkflow` sub-workflow inline and retries — the flow that [GitHub Overview](/docs/examples/github#sign-in-and-retry) explains step by step. ### Files - `google-calendar-summary-example.workflow.ts` — workflow class - `templates/calendarSummary.md` — Handlebars markdown summary ## Google Workspace Agent An interactive Claude chat agent with 11 Google Workspace tools (Calendar, Gmail, Drive). When a tool returns unauthorized, the agent calls `authenticateGoogle` to launch the OAuth sub-workflow and retries. ### Files - `google-workspace-agent-example.workflow.ts` — workflow class - `google-workspace-agent-example.ui.yaml` — chat prompt-input widget - `templates/systemMessage.md` — system prompt ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/examples/hitl.md --- title: HITL Examples description: Workflow examples for Human-in-the-Loop patterns in Loopstack — custom Document with a form widget, AskUserWorkflow / ConfirmUserWorkflow sub-workflow shortcuts, LLM agent loops with ask_clarification / ask_for_approval, and an end-to-end meeting-notes review flow. --- # HITL Examples > Human-in-the-Loop workflow examples for the [Loopstack](https://loopstack.ai) automation framework. Side-by-side examples of every way to pause a Loopstack workflow for the user. The point of this module is to answer one question: **when do I design a custom document with a widget, vs. delegate to a HITL sub-workflow, vs. let an LLM agent ask the user?** ## Use in Your App Copy this directory into your app, then install what it imports: ```bash npm install @loopstack/agent @loopstack/claude @loopstack/common @loopstack/hitl @loopstack/llm-provider ``` Register the 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 {} ``` ## Decision matrix | You are building... | Use | Examples | | --------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | | A predefined workflow with known user-input steps — form fields, structured data, a record the user edits | **Custom document with a widget** — your workflow owns the document and the `wait: true` transition | Inline Form, Prompt Input Chat, Meeting Notes | | An LLM agent loop where the LLM dynamically decides to ask the user something or request approval | **Agent tools** `ask_clarification` / `ask_for_approval` from `@loopstack/hitl` | Agent Ask Clarification, Agent Ask For Approval | | A predefined workflow that just needs a quick generic ask — one free-text field, yes/no, pick-one — and you don't want to design a form | **Sub-workflow shortcut** — `AskUserWorkflow` / `ConfirmUserWorkflow` from `@loopstack/hitl` | Ask User Text, Ask User Options, Ask User Confirm, Confirm Content | ## Required app-module configuration `HitlExamplesModule` brings its own `HitlModule`, `AgentModule`, and `ClaudeModule`. The Meeting Notes and Agent examples additionally call `LlmGenerateObjectTool` / `LlmGenerateTextTool` from `@loopstack/llm-provider`. That module is `@Global` and must be configured once in your root module to set the default model: ```typescript import { Module } from '@nestjs/common'; import { LlmProviderModule } from '@loopstack/llm-provider'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { HitlExamplesModule } from './hitl/hitl-examples.module'; @Module({ imports: [LoopstackModule.forRoot(), LlmProviderModule.forRoot({ model: 'claude-sonnet-4-6' }), HitlExamplesModule], }) export class AppModule {} ``` `ClaudeModule` (re-exported from `HitlExamplesModule`) registers the Claude provider with the LLM registry; `LlmProviderModule.forRoot(...)` sets the default model the tools dispatch to. The non-agent examples (Inline Form, Prompt Input Chat, Ask User \*, Confirm Content) work without it. ## Environment The agent and meeting-notes examples require Claude credentials: ```bash ANTHROPIC_API_KEY=sk-ant-... ``` The non-agent examples (Inline Form, Prompt Input Chat, Ask User \*, Confirm Content) work without any LLM provider. ## Examples | Example | Studio title | Description | | --------------------------------------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------- | | [Inline Form](#inline-form) | `HITL - Inline Form Example` | Custom Document with a form widget, `wait: true` payload typed by the document schema | | [Prompt Input Chat](#prompt-input-chat) | `HITL - Prompt Input Chat Example` | Workflow-level prompt-input widget; loops on user messages without an LLM | | [Ask User Text](#ask-user-text) | `HITL - Ask User Text Example` | `AskUserWorkflow` for a generic free-text question | | [Ask User Options](#ask-user-options) | `HITL - Ask User Options Example` | `AskUserWorkflow` with `mode: 'options'` and `allowCustomAnswer` | | [Ask User Confirm](#ask-user-confirm) | `HITL - Ask User Confirm Example` | `AskUserWorkflow` with `mode: 'confirm'` for yes/no decisions | | [Confirm Content](#confirm-content) | `HITL - Confirm Content Example` | `ConfirmUserWorkflow` to show a pre-rendered markdown blob for explicit approval | | [Agent Ask Clarification](#agent-ask-clarification) | `HITL - Agent Ask Clarification Example` | LLM agent with `ask_clarification` tool — pauses to request missing info | | [Agent Ask For Approval](#agent-ask-for-approval) | `HITL - Agent Ask For Approval Example` | LLM agent with `ask_for_approval` tool — drafts content and pauses for confirm/deny | | [Meeting Notes](#meeting-notes) | `HITL - Meeting Notes Example` | End-to-end document-review flow: user notes → LLM-extracted structure → user approval | --- ## Inline Form The workflow owns a `FeedbackFormDocument` whose schema doubles as the `wait: true` transition payload. The form's Submit button triggers the transition with typed data — no wrapping or unpacking. ### Files - `inline-form-example.workflow.ts` — workflow class - `feedback-form-document.ts` — `@Document` with Zod schema - `feedback-form-document.yaml` — form widget definition ## Prompt Input Chat Workflow-level `widget: prompt-input` with `enabledWhen: [waiting_for_user]`. Loops on user messages and echoes them back — no LLM and no sub-workflow involved. Demonstrates the chat-style entry pattern that LLM agent loops are built on. ### Files - `prompt-input-chat-example.workflow.ts` — workflow class - `prompt-input-chat-example.workflow.yaml` — workflow-level prompt-input widget ## Ask User Text Delegate a generic free-text question to `AskUserWorkflow`. The parent workflow only owns the callback transition that receives the answer. Use the inline-form pattern instead when you need a structured form. ### Files - `ask-user-text-example.workflow.ts` — workflow class ## Ask User Options Delegate a "pick one from a list" question to `AskUserWorkflow` with `mode: 'options'`. `allowCustomAnswer: true` adds a free-text field next to the choices. ### Files - `ask-user-options-example.workflow.ts` — workflow class ## Ask User Confirm Delegate a yes/no decision to `AskUserWorkflow` with `mode: 'confirm'`. The answer comes back as the literal string `'yes'` or `'no'`. ### Files - `ask-user-confirm-example.workflow.ts` — workflow class ## Confirm Content Hand a pre-rendered markdown blob to `ConfirmUserWorkflow` for a user-facing review. The callback receives `{ confirmed: boolean, markdown: string }`. Useful for showing a release plan, summary, or diff for explicit approval. ### Files - `confirm-content-example.workflow.ts` — workflow class ## Agent Ask Clarification Launches `AgentWorkflow` with `tools: ['ask_clarification']`. When the LLM lacks information, it issues an `ask_clarification` tool call — the loop pauses and prompts the user, then the answer flows back into the agent context. ### Files - `agent-ask-clarification-example.workflow.ts` — workflow class ## Agent Ask For Approval Launches `AgentWorkflow` with `tools: ['ask_for_approval']`. The LLM drafts content (release notes, in this example), then calls `ask_for_approval` with the markdown — the loop pauses until the user explicitly confirms or denies. ### Files - `agent-ask-for-approval-example.workflow.ts` — workflow class ## Meeting Notes A complete HITL document-review flow: 1. Save a `MeetingNotesDocument` with the user's raw notes (form widget for edits) 2. User reviews/edits and submits via `wait: true` transition 3. `LlmGenerateObjectTool` extracts structured data via Zod schema 4. Save `OptimizedNotesDocument` for the user to review/approve 5. Final approval via second `wait: true` transition Combines custom documents, LLM-driven structured output, and two HITL review steps. ### Files - `meeting-notes-example.workflow.ts` — workflow class - `documents/meeting-notes-document.{ts,yaml}` — input form document - `documents/optimized-notes-document.{ts,yaml}` — structured output document - `templates/extract-notes.md` — LLM prompt template ## Testing Every workflow ships with an inner-loop spec in its `__tests__/` folder — run them with `npm run test` (in-process, no backend, no API key). The specs double as the reference for **how to test each HITL flavor**, extending the decision matrix above: | HITL flavor | How its tests work | Spec | | ----------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | | Custom document + own `wait: true` transition | Script the submission with `answers`, keyed by the wait-transition method name | `inline-form` | | Sub-workflow shortcut (`AskUserWorkflow` / `ConfirmUserWorkflow`) | Script the _child's_ wait transition (`userAnswered`, `userConfirmed` / `userDenied`) — `answers` reaches inline sub-workflows at any depth | `ask-user-*`, `confirm-content` | | Chat loop (same wait transition parks repeatedly) | `queue('first', 'second')` submits one message per park, then the run parks again; scripted LLM replies via `replay` | `prompt-input-chat` | | LLM step inside a predefined workflow | `replay` scripts the LLM response; `answers` drives the surrounding HITL steps | `meeting-notes` | | Agent HITL (`ask_clarification` / `ask_for_approval`) | `replayTools: [LlmGenerateTextTool]` scripts only the LLM turns; the agent loop, delegation, and the real HITL child run live; `answers` resumes the nested child | `agent-ask-clarification`, `agent-ask-for-approval` | **The record/refresh loop.** The replay specs here use hand-written LLM turns for readability; for your own workflows, record fixtures from a real run instead: run the test once with `fixture: ''` and live providers (records on the first run, replays afterwards — delete the file to re-record), or derive one from a backend run started with `loopstack run --trace` via `loopstack runs --record --tools llm_generate_text`. When a replayed test fails with a drift error after a prompt change, that is the signal: run the live check-ups, and re-record when green. **Live check-ups** (`*.live.spec.ts`) run the same flows against the real model with structural assertions — `npm run test:live`, needs `ANTHROPIC_API_KEY`, on demand after prompt or model changes, never in the PR gate. **Outer loop.** Before relying on a flow, run the real thing once from the terminal and watch it: `loopstack run ` follows the run live and prompts you at every HITL step; `loopstack runs` shows the inbox of runs waiting for input. See the [testing guide](https://loopstack.ai/docs/build/testing) for the full story. ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/examples/integrations.md --- title: Integration Examples (placeholder) description: Placeholder for integration / notification workflow examples in Loopstack — Slack, email, generic HTTP webhook fire-and-forget (coming soon) --- # Integration Examples (placeholder) > Integration / notification workflow examples for the [Loopstack](https://loopstack.ai) automation framework. **Placeholder — examples coming soon.** This module is reserved for future integration examples: - Slack / Discord notifications - Transactional email - Generic HTTP webhooks (fire-and-forget API calls, no OAuth) Track progress in the [Loopstack GitHub repo](https://github.com/loopstack-ai/loopstack/issues). ## Use in Your App Copy this directory into your app, then install what it imports: ```bash npm install @loopstack/common ``` Register the module: ```typescript import { Module } from '@nestjs/common'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { IntegrationExamplesModule } from './integrations/integration-examples.module'; @Module({ imports: [LoopstackModule.forRoot(), IntegrationExamplesModule], }) export class AppModule {} ``` ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/examples/llm.md --- title: LLM Examples description: Workflow examples for LLM integration in Loopstack — simple prompts, structured output with Zod schemas, multi-provider comparison, web fetch with summarization --- # LLM Examples > LLM workflow examples for the [Loopstack](https://loopstack.ai) automation framework. A collection of workflow examples that demonstrate how to integrate LLMs into Loopstack workflows. Use these as starting points for prompts, structured output, multi-provider setups, and fetching web content. ## Use in Your App Copy this directory into your app, then install what it imports: ```bash npm install @loopstack/claude @loopstack/common @loopstack/llm-provider @loopstack/openai @loopstack/web ``` Register the module: ```typescript import { Module } from '@nestjs/common'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { LlmExamplesModule } from './llm/llm-examples.module'; @Module({ imports: [LoopstackModule.forRoot(), LlmExamplesModule], }) export class AppModule {} ``` ## Required app-module configuration Every workflow in this module calls a tool from `@loopstack/llm-provider` (`LlmGenerateTextTool`, `LlmGenerateObjectTool`). That module is `@Global` and must be configured once in your root module to set the default model: ```typescript import { Module } from '@nestjs/common'; import { LlmProviderModule } from '@loopstack/llm-provider'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { LlmExamplesModule } from './llm/llm-examples.module'; @Module({ imports: [LoopstackModule.forRoot(), LlmProviderModule.forRoot({ model: 'claude-sonnet-4-6' }), LlmExamplesModule], }) export class AppModule {} ``` `LlmExamplesModule` already re-imports `ClaudeModule`, `OpenAiModule`, and `WebModule` — the Claude and OpenAI providers register themselves with the LLM registry so the Multi-Provider example can dispatch to either. `LlmProviderModule.forRoot(...)` sets the default model the tools fall back to when a call doesn't override `{ config: { provider, model } }` explicitly. ## Environment Set provider API keys for the workflows you want to run: ```bash ANTHROPIC_API_KEY=sk-ant-... # required for Claude examples OPENAI_API_KEY=sk-... # required for the multi-provider example ``` ## Examples | Example | Studio title | Description | | --------------------------------------- | ------------------------------------------------------ | ---------------------------------------------------------------------- | | [Prompt](#prompt) | `LLM - Prompt Example (Write a haiku)` | Single-shot LLM call with a Handlebars-rendered prompt template | | [Structured Output](#structured-output) | `LLM - Structured Output Example (Hello World Script)` | Generate Zod-validated structured output with a custom document widget | | [Multi-Provider](#multi-provider) | `LLM - Multi-Provider Example` | Run the same prompt through Claude and OpenAI side by side | | [Web Fetch](#web-fetch) | `LLM - Web Fetch Example` | Fetch a URL, convert HTML to Markdown, summarize with an LLM | --- ## Prompt Single-shot LLM call using a Handlebars-rendered prompt template. Generates a haiku about a user-provided subject. ### What it demonstrates - Defining workflow input arguments with a Zod schema and default values - Using the `prompt` parameter for a simple LLM call - Rendering Handlebars templates with `this.render(path, vars)` - Automatic assistant message persistence via `LlmGenerateTextTool` ### Key code ```ts @Transition({ to: 'end' }) async prompt(state, 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' } }, ); } ``` `LlmGenerateTextTool` saves the assistant message to the document store automatically — no manual `documentStore.save()` needed. Pass `config: { save: false }` to opt out. ### Files - `prompt-example.workflow.ts` — workflow class - `templates/prompt.md` — Handlebars prompt template ## Structured Output Generates a Zod-validated object (a `FileDocument` with `filename`, `description`, `code`) using `LlmGenerateObjectTool`. Renders in Studio via a custom widget. ### What it demonstrates - Defining a `@Document` class with a Zod schema and a YAML widget - Calling `LlmGenerateObjectTool` with `outputSchema` for Zod-validated JSON output - Persisting the structured result via `this.documentStore.save(FileDocument, result.data.data)` - Multi-transition state flow: `start` → `ready` → `prompt_executed` → `end` ### Key code ```ts const result = await this.llmGenerateObject.call( { outputSchema: FileDocumentSchema, prompt: this.render(join(__dirname, 'templates', 'prompt.md'), { language: state.language }), }, { config: { provider: 'claude', model: 'claude-sonnet-4-6' } }, ); const llmResult = await this.documentStore.save(FileDocument, result.data.data as FileDocumentType); this.assignState({ llmResult }); ``` ### Files - `structured-output-example.workflow.ts` — workflow class - `documents/file-document.ts` — `@Document` class + Zod schema - `documents/file-document.yaml` — Studio widget definition - `templates/prompt.md` — Handlebars prompt template ## Multi-Provider Sends the same prompt to Claude and OpenAI and renders responses side by side for comparison. ### What it demonstrates - Using the same tool class (`LlmGenerateTextTool`) for multiple providers - Selecting provider and model at call time via `{ config: { provider, model } }` - Opting out of auto-save with `config: { save: false }`, so the workflow saves each reply itself with a provider label ### Key code ```ts const result = await this.llmGenerateText.call( { prompt: ctx.args.prompt }, { config: { save: false, provider: 'claude', model: 'claude-sonnet-4-6', }, }, ); await this.documentStore.save(LlmMessageDocument, { role: 'assistant', text: `**Claude:** ${result.data.message.text}`, }); ``` The `save: false` opt-out lets us prefix each response with the provider name so the comparison is clear in the Studio chat view. ### Files - `multi-provider-example.workflow.ts` — workflow class ## Web Fetch Fetches a URL, converts HTML to Markdown, and optionally summarizes it against a user-provided prompt using a small model via the configured LLM provider. ### What it demonstrates - Using `WebFetchTool` from `@loopstack/web` - HTML → Markdown conversion with size caps and same-origin redirect handling - Optional prompt-based summarization built into the tool ### Key code ```ts const result = await this.webFetch.call({ url: ctx.args.url, prompt: ctx.args.prompt, }); this.assignState({ summary: result.data.result }); ``` When `prompt` is omitted, `WebFetchTool` returns the raw Markdown (truncated if very long). When provided, the tool summarizes the content through the configured LLM provider (model `claude-haiku-4-5-20251001` by default) and returns the provider, model and token usage as result metadata. ### Files - `web-fetch-example.workflow.ts` — workflow class ### Related modules - `@loopstack/web` — fetch + Markdown conversion + summarization - `@loopstack/claude` — `claude_native_web_search`, Claude's server-side web search tool (alternative when you want the LLM to search rather than fetch a specific URL) ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/examples/local-file-explorer.md --- title: Local File Explorer Examples description: Local file explorer workflow example for Loopstack — build a file tree of the workspace with FileSystemService from @loopstack/local-file-explorer. --- # Local File Explorer Examples > Local file explorer workflow example for the [Loopstack](https://loopstack.ai) automation framework. Shows how a workflow reads the local disk with `FileSystemService` from `@loopstack/local-file-explorer`. The same module also lights up the Studio file panel and exposes a REST API for it. Reach for this when a workflow needs to inspect files on the machine the app runs on. ## Use in Your App Copy this directory into your app, then install what it imports: ```bash npm install @loopstack/common @loopstack/local-file-explorer ``` Register the module: ```typescript import { Module } from '@nestjs/common'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { LocalFileExplorerExamplesModule } from './local-file-explorer/local-file-explorer-examples.module'; @Module({ imports: [LoopstackModule.forRoot(), LocalFileExplorerExamplesModule], }) export class AppModule {} ``` ## Environment None — the workflow reads the local disk. No Docker, remote agent or secrets are required. ## Examples | Example | Studio title | Description | | ------------------------------------------- | ----------------------------------------- | ---------------------------------------------------- | | [Local File Explorer](#local-file-explorer) | `Local File Explorer - File Tree Example` | Build a workspace file tree with `FileSystemService` | --- ## Local File Explorer Calls `FileSystemService.buildFileTree()` on the app's working directory and renders the top-level entries (up to 50) as a markdown document. Run it from Studio (**Local File Explorer Examples → Local File Explorer - File Tree Example**) or the CLI: ```bash loopstack run local_file_explorer_example ``` ### Files - `local-file-explorer-example.workflow.ts` — workflow class ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/examples/mcp.md --- title: MCP Examples description: Workflow example for remote MCP servers in Loopstack — McpModule.forRoot with an allowedHosts allowlist and a hostHeaderEnv auth header mapping, and a chat agent that uses the mcp_list_tools and mcp_call tools against Linear's hosted MCP server. --- # MCP Examples > Remote MCP client examples for the [Loopstack](https://loopstack.ai) automation framework. Connects a chat agent to a remote Model Context Protocol server with `@loopstack/mcp`. The configuration you need to copy is in the module: which hosts the MCP tools may reach, and which env var holds each host's auth header. ## Use in Your App Copy this directory into your app, then install what it imports: ```bash npm install @loopstack/agent @loopstack/claude @loopstack/common @loopstack/mcp ``` Register the module: ```typescript import { Module } from '@nestjs/common'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { McpExamplesModule } from './mcp/mcp-examples.module'; @Module({ imports: [LoopstackModule.forRoot(), McpExamplesModule], }) export class AppModule {} ``` ## Required app-module configuration The example launches `ChatAgentWorkflow` from `@loopstack/agent`, which calls the LLM through `@loopstack/llm-provider`. That module is `@Global` and must be configured once in your root module to set the default model: ```typescript import { Module } from '@nestjs/common'; import { LlmProviderModule } from '@loopstack/llm-provider'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { McpExamplesModule } from './mcp/mcp-examples.module'; @Module({ imports: [LoopstackModule.forRoot(), LlmProviderModule.forRoot({ model: 'claude-sonnet-4-6' }), McpExamplesModule], }) export class AppModule {} ``` `McpExamplesModule` imports `AgentModule` (the `ChatAgentWorkflow` class), `ClaudeModule` (provider) and `McpModule.forRoot(...)`. `McpModule.forRoot` registers a global module with one default config for the whole app, so call it once. If your app already calls it, add the Linear host and header mapping there and remove the call from this module. ## Environment ```bash ANTHROPIC_API_KEY=sk-ant-... LINEAR_MCP_TOKEN="Bearer lin_oauth_..." ``` `LINEAR_MCP_TOKEN` holds the full `Authorization` header value, including `Bearer`. ## Examples | Example | Studio title | Description | | ----------------- | ---------------------- | ------------------------------------------------------------------------------------ | | [Linear](#linear) | `MCP - Linear Example` | Chat agent connected to Linear's hosted MCP server via `mcp_list_tools` + `mcp_call` | --- ## Linear Launches `ChatAgentWorkflow` with the `mcp_list_tools` and `mcp_call` tools and a system prompt that points at Linear's hosted MCP server. The agent discovers Linear's tools at runtime, then calls the one that answers the user's question. You can keep chatting with it after the first answer. ### What it demonstrates - `McpModule.forRoot({ allowedHosts })`: the MCP tools refuse every `serverUrl` whose host is not in the list, so a URL chosen by the model cannot reach other hosts - `hostHeaderEnv`: the `Authorization` header for `mcp.linear.app` is read from `LINEAR_MCP_TOKEN` at call time; the token is never in the config, the prompt or the logs - Giving an agent the MCP tools by name: `tools: ['mcp_list_tools', 'mcp_call']`. The agent passes `serverUrl` and `transport` on each call, as the system prompt tells it to ### Key code ```ts McpModule.forRoot({ allowedHosts: ['mcp.linear.app'], hostHeaderEnv: { 'mcp.linear.app': { Authorization: 'LINEAR_MCP_TOKEN' } }, }), ``` ```ts @Transition({ to: 'chatting' }) async startChat(_state: Record, ctx: RunContext) { await this.chatAgentWorkflow.run( { system: this.render(join(__dirname, 'templates', 'system.md')), tools: ['mcp_list_tools', 'mcp_call'], userMessage: ctx.args.initialMessage, }, { show: 'inline', label: 'Linear Agent Chat' }, ); } ``` To reach another MCP server, add its host to `allowedHosts`, map its auth header in `hostHeaderEnv`, and name its URL in the system prompt. ### Files - `mcp-examples.module.ts` — the `McpModule.forRoot` configuration - `workflows/linear/linear-example.workflow.ts` — workflow class - `workflows/linear/templates/system.md` — system prompt with the server URL and transport ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/examples/observability.md --- title: Observability Examples description: Workflow examples for observability in Loopstack — quota tracking, custom tool interceptors for tracing, custom quota calculators, event-driven audit logging, and reading a run's checkpoint history with client.workflows.checkpoints and loopstack runs --- # Observability Examples > Observability workflow examples for the [Loopstack](https://loopstack.ai) automation framework. Workflow examples for tracking and enforcing operational limits. ## Use in Your App Copy this directory into your app, then install what it imports: ```bash npm install @loopstack/common @loopstack/quota ``` Register the module: ```typescript import { Module } from '@nestjs/common'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { ObservabilityExamplesModule } from './observability/observability-examples.module'; @Module({ imports: [LoopstackModule.forRoot(), ObservabilityExamplesModule], }) export class AppModule {} ``` ## Examples | Example | Studio title | Description | | --------------------------------------------------- | ------------------------------------------------- | --------------------------------------------------------------------------------- | | [Quota](#quota) | `Observability - Quota Example` | Manual check + report usage with `@loopstack/quota`, Redis-backed when enabled | | [Tracing Interceptor](#tracing-interceptor) | `Observability - Tracing Interceptor Example` | Custom `ToolInterceptor` measuring every tool execution app-wide | | [Custom Quota Calculator](#custom-quota-calculator) | `Observability - Custom Quota Calculator Example` | Custom `ToolQuotaCalculator` metering a tool automatically via `QuotaInterceptor` | | [Audit Log](#audit-log) | `Observability - Audit Log Example` | `@OnEvent` listener recording workflow & document lifecycle events | | [Checkpoints](#checkpoints) | `Observability - Checkpoints Example` | A branching run whose checkpoint history you read with the SDK or the CLI | --- ## Quota Demonstrates the manual quota API of `@loopstack/quota`: 1. `quotaClient.checkQuota(userId, quotaType)` — verify available budget 2. Perform the (placeholder) operation if allowed 3. `quotaClient.report(userId, quotaType, amount)` — charge against the quota When `QuotaModule.forRoot({ enabled: false })`, both calls no-op. Set `enabled: true` plus Redis connection options to enforce real limits. Note: with quota enabled, a user without a limit key in Redis is blocked by default. Built-in quota types: `llm-cost` (LLM token cost in microcents) and `processing-time-ms` (tool execution time). ### Files - `quota-example.workflow.ts` — workflow class ## Tracing Interceptor Demonstrates writing a custom `ToolInterceptor`: - `@UseToolInterceptor({ priority: 10 })` registers the class app-wide — the framework discovers it via NestJS `DiscoveryService`, no manual wiring - The interceptor wraps **every** tool call (all modules), measures duration, and records entries in an injectable `ToolTraceService` - The workflow runs a few `SimulateWorkTool` calls, then filters the trace by its own `workflowId` and renders a markdown table Interceptors follow a chain pattern like NestJS interceptors: run logic before/after `next()`, transform results, short-circuit (caching), or catch errors. Lower priority runs first (outermost). ### Files - `tracing-example.workflow.ts` — workflow class - `interceptors/tracing.interceptor.ts` — the custom `ToolInterceptor` - `services/tool-trace.service.ts` — injectable trace store - `tools/simulate-work.tool.ts` — demo tool that sleeps for a configurable duration ## Custom Quota Calculator Demonstrates extending the quota system with a custom `ToolQuotaCalculator`: - `WordsProcessedQuotaCalculator` defines quota type `words-processed` and derives the charged amount from the tool result (word count) - The module registers it for `AnalyzeTextTool` in `onModuleInit` via `QuotaCalculatorRegistry` - The built-in `QuotaInterceptor` then checks the quota **before** and reports usage **after** every `AnalyzeTextTool` execution — the workflow just calls the tool, no manual check/report This is the recommended pattern for metering tools: the workflow stays clean, enforcement lives in the interceptor. ### Files - `custom-calculator-example.workflow.ts` — workflow class - `calculators/words-processed.calculator.ts` — the custom `ToolQuotaCalculator` - `tools/analyze-text.tool.ts` — demo tool whose usage is metered ## Audit Log Demonstrates subscribing to framework events for monitoring: - The framework dispatches lifecycle events on the `client.message` channel — e.g. `workflow.created`, `workflow.updated`, `document.created` - `AuditListener` uses `@OnEvent('client.message')` to capture every event into an injectable `AuditLogService` (bounded in-memory store) - The workflow saves a few documents to generate events, then renders its own audit trail filtered by `workflowId` This is the event-driven counterpart to the tracing interceptor: interceptors wrap tool calls, event listeners observe workflow and document lifecycle. Swap the in-memory store for a database or metrics exporter in production. ### Files - `audit-log-example.workflow.ts` — workflow class - `listeners/audit.listener.ts` — the `@OnEvent` listener - `services/audit-log.service.ts` — injectable audit store ## Checkpoints Demonstrates reading a run's **checkpoint history** after the fact — which places the run passed, which transitions moved it, and when: - The workflow stores an `amount`, then a `@Guard` routes it to `approved` (amount ≤ 500, the default is 250) or to `flagged`, and the run ends - The engine persists a checkpoint row as the run moves; the history of those rows is the run's path - `scripts/checkpoints-demo.mjs` starts the run through `@loopstack/client` and prints the history Each history entry has six fields: `id`, `place`, `transitionId`, `transitionFrom`, `version` and `createdAt`. The history does **not** include the state or the documents at each step — it shows the path and its timing. For what happened inside a step, read the run trace (`loopstack run --trace`, then `client.workflows.toolCalls(id)` or `loopstack runs --record`); for lifecycle events, see the [Audit Log](#audit-log) example. ### Reading the history With the CLI, `loopstack runs ` folds the history into one step line per place, with the time spent there: ```text $ loopstack run checkpoints_example $ loopstack runs checkpoints_example #1 — completed ✓ start (3ms) ✓ received (18ms) ✓ approved (7ms) ``` `loopstack runs --json` prints the raw rows under `checkpoints`. From code, use the client SDK — or the React hook in a frontend: ```typescript const checkpoints = await client.workflows.checkpoints(runId); // @loopstack/client const { data: checkpoints } = useWorkflowCheckpoints(runId); // @loopstack/react ``` `node scripts/checkpoints-demo.mjs` does the same against the running app (`node scripts/checkpoints-demo.mjs 900` takes the `flagged` branch): ```text ┌─────────┬─────────┬────────────┬────────────────┬──────────────────┐ │ (index) │ version │ place │ transitionFrom │ transitionId │ ├─────────┼─────────┼────────────┼────────────────┼──────────────────┤ │ 0 │ 1 │ 'start' │ 'start' │ 'receive' │ │ 1 │ 2 │ 'received' │ 'start' │ 'receive' │ │ 2 │ 2 │ 'received' │ 'received' │ 'autoApprove' │ │ 3 │ 3 │ 'approved' │ 'received' │ 'autoApprove' │ │ 4 │ 3 │ 'approved' │ 'approved' │ 'finishApproved' │ │ 5 │ 4 │ 'end' │ 'approved' │ 'finishApproved' │ │ 6 │ 4 │ 'end' │ 'approved' │ 'finishApproved' │ └─────────┴─────────┴────────────┴────────────────┴──────────────────┘ ``` (`createdAt` is left out above for width.) The rows come in pairs, one pair per transition: - **When a transition starts**, a row is written at the place it leaves (`place` = `transitionFrom`), with the same `version` as the row before it - **When it lands**, a row is written at the new place, with `version` one higher - **When the run settles** at the end of a processing step, one more row records the place it settled on — here `end` So `version` grows by one per completed transition, not per row, and consecutive rows of one place belong together — which is why the CLI folds them into one step line. ### Files - `checkpoints-example.workflow.ts` — workflow class - `scripts/checkpoints-demo.mjs` (in the examples app) — reads the history through `@loopstack/client` ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/examples/remote-client.md --- title: Remote Client Examples description: Remote agent workflow examples for Loopstack — run shell commands and edit files on a remote workspace, and search its files, with the @loopstack/remote-client tools; plus the Remote Files panel from @loopstack/remote-file-explorer. --- # Remote Client Examples > Remote agent workflow examples for the [Loopstack](https://loopstack.ai) automation framework. Two ways a workflow works against a remote workspace with the `@loopstack/remote-client` tools: running shell commands and editing files, and searching the workspace's files. The app also enables the Remote Files panel in Studio, so you can browse the same workspace by hand. Reach for these when a workflow operates on a machine other than the one the app runs on. ## Use in Your App Copy this directory into your app, then install what it imports: ```bash npm install @loopstack/common @loopstack/remote-client @loopstack/remote-file-explorer ``` Register the module: ```typescript import { Module } from '@nestjs/common'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { RemoteClientExamplesModule } from './remote-client/remote-client-examples.module'; @Module({ imports: [LoopstackModule.forRoot(), RemoteClientExamplesModule], }) export class AppModule {} ``` ## Required app-module configuration The remote tools (`BashTool`, `ReadTool`, `WriteTool`, `GlobTool`, `GrepTool`) are provided by the `RemoteClientModule` root. `RemoteClientExamplesModule` only declares its environment slot via `RemoteClientModule.forFeature(...)`, so the app must import `RemoteClientModule.forRoot(...)` once in its root module — without it the app fails at boot. Register at least one environment whose `type` matches the slot (`sandbox`): ```typescript import { Module } from '@nestjs/common'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { RemoteClientModule } from '@loopstack/remote-client'; import { RemoteClientExamplesModule } from './remote-client/remote-client-examples.module'; @Module({ imports: [ LoopstackModule.forRoot(), RemoteClientModule.forRoot({ environments: { available: [ { type: 'sandbox', name: 'Local Remote Server', connectionUrl: process.env.SANDBOX_URL ?? 'http://localhost:3080', agentUrl: process.env.SANDBOX_AGENT_URL ?? 'http://localhost:3001', local: true, }, ], }, }), RemoteClientExamplesModule, ], }) export class AppModule {} ``` Workspaces created in Studio auto-select the environment from the matching type. ## Environment Both workflows need a running remote agent (the simplest option is `@loopstack/remote-server` on `localhost:3001`), reachable through the environment configured above. No secrets are required. ## Examples | Example | Studio title | Description | | --------------------------- | ------------------------------------- | ---------------------------------------------------------------------------------------- | | [Command](#command) | `Remote Client - Command Example` | Run commands and edit files on a remote machine via `BashTool` + `WriteTool` | | [File Search](#file-search) | `Remote Client - File Search Example` | Find files by name and by content via `GlobTool` + `GrepTool`, then read with `ReadTool` | The app also shows the [Remote Files panel](#remote-files-panel) in Studio. It comes from a module import, not from a workflow. --- ## Command Writes a file with `WriteTool`, runs a shell command against it with `BashTool`, then reads the file back with `ReadTool`. Each step posts a message with its result. ```bash loopstack run remote_client_example ``` ### Files - `remote-client-example.workflow.ts` — workflow class ## File Search Searches the remote workspace in three steps, and each step posts a message with its result: `GlobTool` finds the Markdown files by name (`**/*.md`), `GrepTool` finds the lines in them that contain `TODO`, and `ReadTool` reads the first file with a match. When no line matches, the workflow says so and ends. ```bash loopstack run file_search_example ``` ### Files - `file-search-example.workflow.ts` — workflow class ## Remote Files panel `RemoteFileExplorerModule.forFeature()` from `@loopstack/remote-file-explorer` adds the **Remote Files** sidebar panel to this app in Studio. Open a workspace of the **Remote Client Examples** app and select **Remote Files** in the sidebar to browse the remote workspace and open its files — for example the file the Command example writes. The panel reads through two REST routes of the same module: ```http GET /api/v1/workspaces/:workspaceId/remote-files/tree?path= GET /api/v1/workspaces/:workspaceId/remote-files/read?path= ``` The module has no workflow tools. Inside a workflow, use the `@loopstack/remote-client` tools as the examples above do. ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/examples/sandbox.md --- title: Sandbox Examples description: Docker sandbox workflow example for Loopstack — init a container, run file operations inside it with the sandbox filesystem tools, and destroy it. --- # Sandbox Examples > Docker sandbox workflow example for the [Loopstack](https://loopstack.ai) automation framework. Shows how a workflow runs file operations in an isolated Docker container with `@loopstack/docker-sandbox` (container lifecycle) and `@loopstack/docker-sandbox-filesystem` (file operations inside the container). Reach for this pattern when a workflow needs to execute or inspect untrusted code without touching the host. ## Use in Your App Copy this directory into your app, then install what it imports: ```bash npm install @loopstack/common @loopstack/docker-sandbox @loopstack/docker-sandbox-filesystem ``` Register the module: ```typescript import { Module } from '@nestjs/common'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { SandboxExamplesModule } from './sandbox/sandbox-examples.module'; @Module({ imports: [LoopstackModule.forRoot(), SandboxExamplesModule], }) export class AppModule {} ``` ## Environment The workflow needs a Docker daemon reachable from the app (the default socket, `/var/run/docker.sock`). The app boots without one; the run fails at the first sandbox call if Docker isn't available. The `node:18` image is pulled on first use. No secrets are required. ## Examples | Example | Studio title | Description | | ------------------- | ------------------------------ | ------------------------------------------------------- | | [Sandbox](#sandbox) | `Sandbox - Filesystem Example` | Full Docker sandbox lifecycle — init, file ops, destroy | --- ## Sandbox Walks the complete Docker sandbox lifecycle: `sandboxInit` → directory + file operations (`sandboxCreateDirectory`, `sandboxWriteFile`, `sandboxReadFile`, `sandboxListDirectory`, `sandboxExists`, `sandboxFileInfo`, `sandboxDelete`) → `sandboxDestroy`. Each step posts a message with the tool's result. Run it from Studio (**Sandbox Examples → Sandbox - Filesystem Example**) or the CLI: ```bash loopstack run sandbox_example --arg outputDir=/tmp/sandbox-out ``` `outputDir` is the host directory mounted into the container (defaults to `./out`). ### Files - `sandbox-example.workflow.ts` — workflow class ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/examples/scheduling.md --- title: Scheduling Examples description: Runnable Loopstack examples for the scheduling fundamentals — cron (@Cron), webhook (@Post + @Public controller), delayed runs (SchedulerRegistry timeout), and batch (Promise.all fan-out). Each trigger starts a workflow with WorkflowRunner.run. --- # Scheduling Examples > Scheduling workflow examples for the [Loopstack](https://loopstack.ai) automation framework. This module demonstrates the **scheduling fundamentals** — the primitives you use to start workflows programmatically instead of clicking "Run" in Studio. Each fundamental ships as a small workflow (the _work_) plus the real trigger that fires it (the _primitive_): a cron schedule, a webhook endpoint, a delayed timeout, and a batch fan-out. Background reading: [Programmatic Execution](https://loopstack.ai/docs/build/integrations/programmatic-execution). ## Use in Your App Copy this directory into your app, then install what it imports: ```bash npm install @loopstack/common @loopstack/core ``` Register the module: ```typescript import { Module } from '@nestjs/common'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { SchedulingExamplesModule } from './scheduling/scheduling-examples.module'; @Module({ imports: [LoopstackModule.forRoot(), SchedulingExamplesModule], }) export class AppModule {} ``` ## The core primitive: `WorkflowRunner` Every trigger boils down to injecting `WorkflowRunner` (from `@loopstack/core`, globally available once `LoopstackModule.forRoot()` is imported) and calling: - **`run(WorkflowClass, args, { appName, userId })`** — enqueue on BullMQ, return a `workflowId`. Used by all triggers here. - **`runSync(WorkflowClass, args, { appName, userId, stateless? })`** — execute inline and await the result. Background triggers (cron, webhooks, timeouts) have no HTTP request, so no user context. The [`RunUserResolver`](./src/support/run-user.resolver.ts) helper picks the local Studio user to run as — open Studio once so that user exists. ## The fundamentals | Fundamental | The primitive (where it lives) | The work | | ----------- | ------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------- | | **Cron** | [`CronTriggerScheduler`](./src/workflows/cron-trigger/cron-trigger.scheduler.ts) — `@Cron(EVERY_MINUTE)` | [`CronTriggerWorkflow`](./src/workflows/cron-trigger/cron-trigger.workflow.ts) posts a message | | **Webhook** | [`WebhookTriggerController`](./src/workflows/webhook-trigger/webhook-trigger.controller.ts) — `@Public @Post('payment')` | [`WebhookTriggerWorkflow`](./src/workflows/webhook-trigger/webhook-trigger.workflow.ts) records a receipt | | **Delayed** | [`DelayedRunController`](./src/workflows/delayed-run/delayed-run.controller.ts) — `SchedulerRegistry` one-off timeout | [`DelayedRunWorkflow`](./src/workflows/delayed-run/delayed-run.workflow.ts) sends a follow-up | | **Batch** | [`BatchTriggerController`](./src/workflows/batch-trigger/batch-trigger.controller.ts) — `Promise.all` fan-out | [`BatchTriggerWorkflow`](./src/workflows/batch-trigger/batch-trigger.workflow.ts) emails one recipient | The trigger is where the scheduling primitive actually lives; the work workflow is just what it launches. > The webhook/delayed/batch controllers are marked `@Public()` so you can `curl` them without a token. > Real integrations should secure them — verify a provider signature on webhooks, require auth on > batch/admin endpoints. ### Run it all from Studio — no curl needed Studio exposes **three launchable workflows**, one per HTTP-triggered fundamental. Each makes the real HTTP `POST` to its endpoint — the same call an external caller would make — and posts the response: | Run this in Studio | What it does | | ------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | | [`CallWebhookWorkflow`](./src/workflows/webhook-trigger/call-webhook.workflow.ts) | `POST /webhooks/scheduling-examples/payment` → fires `WebhookTriggerWorkflow` | | [`CallSignupWorkflow`](./src/workflows/delayed-run/call-signup.workflow.ts) | `POST /webhooks/scheduling-examples/signup` → schedules `DelayedRunWorkflow` | | [`CallNewsletterWorkflow`](./src/workflows/batch-trigger/call-newsletter.workflow.ts) | `POST /webhooks/scheduling-examples/newsletter` → fans out `BatchTriggerWorkflow` | They go over real HTTP (`fetch` to `http://localhost:$PORT`), so they prove the whole trigger path, not just the workflow body. The cron fundamental needs no launcher — it fires on its own schedule. The `curl` commands below do the same thing from a terminal. The launched "work" workflows (`WebhookTriggerWorkflow`, etc.) are registered but not listed as standalone Studio entries. ### Cron — `@Cron` `CronTriggerScheduler.tick()` is a NestJS `@Cron(CronExpression.EVERY_MINUTE)` method that calls `WorkflowRunner.run(CronTriggerWorkflow, …)`. It is **off by default** so it doesn't spam your workspace — enable it with: ```bash SCHEDULING_EXAMPLES_CRON_ENABLED=true ``` ```ts @Cron(CronExpression.EVERY_MINUTE) async tick() { if (this.configService.get('SCHEDULING_EXAMPLES_CRON_ENABLED') !== 'true') return; const userId = await this.runUser.resolve(); if (!userId) return; await this.workflowRunner.run(CronTriggerWorkflow, { message: 'hello world' }, { appName, userId }); } ``` Swap `CronExpression.EVERY_MINUTE` for a cron string like `'0 9 * * MON'` for "every Monday at 9am". ### Webhook — `@Public @Post` ```bash curl -X POST http://localhost:3000/webhooks/scheduling-examples/payment \ -H 'content-type: application/json' \ -d '{"customerEmail":"grace@example.com","amountCents":4200,"currency":"USD"}' ``` The controller maps the request body to workflow args and calls `run()`, returning the `workflowId`. ### Delayed — `SchedulerRegistry` timeout ```bash curl -X POST http://localhost:3000/webhooks/scheduling-examples/signup \ -H 'content-type: application/json' -d '{"email":"grace@example.com"}' ``` Registers a one-off timeout (default 10s, override with `SCHEDULING_EXAMPLES_FOLLOWUP_DELAY_MS`) that fires the follow-up workflow later — the "run this in 24h after signup" pattern, sped up for the demo. > `SchedulerRegistry` timeouts live in memory: a server restart loses any pending follow-up. For a > durable long delay, enqueue a BullMQ delayed job instead. ### Batch — `Promise.all` fan-out ```bash curl -X POST http://localhost:3000/webhooks/scheduling-examples/newsletter \ -H 'content-type: application/json' \ -d '{"recipients":["ada@example.com","grace@example.com"]}' ``` Launches one workflow run per recipient in parallel and returns all the `workflowId`s. ## Using in your app ```ts import { SchedulingExamplesModule } from './scheduling/scheduling-examples.module'; @Module({ imports: [LoopstackModule.forRoot(), SchedulingExamplesModule], }) export class AppModule {} ``` ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/examples/secrets.md --- title: Secrets Examples description: Workflow examples for secrets management in Loopstack — deterministic request/verify flow and a chat agent using the get_secret_keys and request_secrets_task tools --- # Secrets Examples > Secrets workflow examples for the [Loopstack](https://loopstack.ai) automation framework. Two ways to manage workspace secrets: a scripted request/verify flow, and a chat agent that decides when to ask the user for credentials. ## Use in Your App Copy this directory into your app, then install what it imports: ```bash npm install @loopstack/agent @loopstack/claude @loopstack/common @loopstack/secrets ``` Register the module: ```typescript import { Module } from '@nestjs/common'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { SecretsExamplesModule } from './secrets/secrets-examples.module'; @Module({ imports: [LoopstackModule.forRoot(), SecretsExamplesModule], }) export class AppModule {} ``` ## Required app-module configuration The Agentic example launches `ChatAgentWorkflow` from `@loopstack/agent`, which calls the LLM through `@loopstack/llm-provider`. That module is `@Global` and must be configured once in your root module to set the default model: ```typescript import { Module } from '@nestjs/common'; import { LlmProviderModule } from '@loopstack/llm-provider'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { SecretsExamplesModule } from './secrets/secrets-examples.module'; @Module({ imports: [ LoopstackModule.forRoot(), LlmProviderModule.forRoot({ model: 'claude-sonnet-4-6' }), SecretsExamplesModule, ], }) export class AppModule {} ``` `SecretsExamplesModule` already imports `AgentModule` (the agent workflows), `ClaudeModule` (provider) and `SecretsModule.forFeature()` (entity + REST surface). `LlmProviderModule.forRoot(...)` sets the default model the agent uses. The Deterministic example doesn't call an LLM and works without it. ## Environment The agentic example requires Claude credentials: ```bash ANTHROPIC_API_KEY=sk-ant-... ``` ## Examples | Example | Studio title | Description | | ------------------------------- | --------------------------------- | ---------------------------------------------------------- | | [Deterministic](#deterministic) | `Secrets - Deterministic Example` | Scripted request/verify flow — no LLM involved | | [Agentic](#agentic) | `Secrets - Agentic Example` | Chat agent that checks and requests secrets via tool calls | --- ## Deterministic A scripted workflow that requests two secrets from the user, waits for them to be stored, then verifies they were saved. No LLM involved. ### What it demonstrates - Persisting a `SecretRequestDocument` with the expected keys so the user sees the prompt in Studio - A `wait: true` transition named `secretsSubmitted` (the transition the form fires) that resumes once the user submits the secrets - Reading current key availability via `GetSecretKeysTool` ### Key code ```ts @Transition({ to: 'requesting_secrets' }) async requestSecretsFromUser() { await this.documentStore.save(SecretRequestDocument, { variables: [{ key: 'EXAMPLE_API_KEY' }, { key: 'EXAMPLE_SECRET' }], }); } @Transition({ from: 'requesting_secrets', to: 'verifying', wait: true }) async secretsSubmitted() { const result = await this.getSecretKeys.call(); this.assignState({ secretKeys: result.data }); } ``` ### Files - `deterministic-example.workflow.ts` — workflow class - `templates/secretsVerified.md` — Handlebars summary template ## Agentic Launches `ChatAgentWorkflow` with the `get_secret_keys` and `request_secrets_task` tools. The agent checks which secrets the workspace already has and asks the user for the missing ones through a secure form. The values go straight to storage; the LLM only ever sees the key names. The user can chat with the agent until it calls `agent_finish`, which ends the run with a one-sentence summary. ### What it demonstrates - Giving an agent the secrets tools by name: `tools: ['get_secret_keys', 'request_secrets_task']` - `request_secrets_task` as a task tool: it opens the `SecretsRequestWorkflow` form, and the agent continues once the user has submitted it - `taskMode: true`, which offers the agent `agent_finish`; the agent's result arrives in the parent's `agentFinished` callback ### Key code ```ts @Transition({ to: 'running' }) async start() { await this.chatAgentWorkflow.run( { system: this.render(join(__dirname, 'templates', 'system.md')), tools: ['get_secret_keys', 'request_secrets_task'], userMessage: this.render(join(__dirname, 'templates', 'userMessage.md')), taskMode: true, }, { callback: { transition: 'agentFinished' }, show: 'inline', label: 'Secrets Agent' }, ); } @Transition({ from: 'running', to: 'end', wait: true, schema: SecretsSummarySchema }) async agentFinished(_state: Record, input: TransitionInput) { await this.documentStore.save(MessageDocument, { role: 'assistant', text: input.data.summary }); this.setResult(input.data); } ``` ### Files - `agentic-example.workflow.ts` — workflow class - `templates/system.md` — system prompt, including how to call `agent_finish` - `templates/userMessage.md` — the agent's first user message ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/examples/testing.md --- title: Testing Examples description: Runnable workflow-testing examples for Loopstack — runWorkflow() in-process workflow tests with scripted HITL answers, parkView() park assertions, coverage() gates, testTool() tool unit tests, fixture auto record/replay, and createContractFake() DI fakes. Companion package to the Testing guide. --- # Testing Examples > Runnable testing examples for the [Loopstack](https://loopstack.ai) automation framework — the patterns from the [Testing guide](https://loopstack.ai/docs/build/testing) and [Testing Methodology](https://loopstack.ai/docs/build/testing-methodology) as working code. The example under test is a small deterministic triage flow (`src/triage/`): a `classify_ticket` tool grades a support ticket, the workflow presents the severity as a yes/no approval prompt, then waits for the human decision. No LLM — the whole flow is deterministic, so every test is exact. Scenarios are named for the acceptance criterion they check (`it('C1: …')`), so the test report reads as a criteria matrix — the discipline from the methodology guide. ## Use in Your App Copy this directory into your app, then install what it imports: ```bash npm install @loopstack/common ``` Register the module: ```typescript import { Module } from '@nestjs/common'; import { LoopstackModule } from '@loopstack/loopstack-module'; import { TestingExamplesModule } from './testing/testing-examples.module'; @Module({ imports: [LoopstackModule.forRoot(), TestingExamplesModule], }) export class AppModule {} ``` ## What each spec demonstrates | Spec | Pattern | | ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `classify-ticket.tool.spec.ts` | **Tool unit test** — `testTool().forTool(...)`, assert on the envelope data (the `resultSchema` is validated by `call()`) | | `triage-ticket.workflow.spec.ts` | **In-process workflow test** — `runWorkflow()` with scripted `answers`; outcome assertions on `status`/`path`/`result`/`document()`; `parkView()` for the human touchpoint; a `coverage()` gate closing the suite | | `triage-ticket-replay.spec.ts` | **Record/replay** — the `fixture:` option (auto record/replay, CI-guarded) as the default, plus an inline `replay()` fixture for fully-scripted determinism | | `triage-ticket-contract-fake.spec.ts` | **Contract fake** — `createContractFake()` substitutes the tool with a `resultSchema`-validated response and asserts how the workflow called it | Run them: ```bash npm test ``` ## Recording fixtures from live runs The `fixture:` option records a fresh fixture when the file is missing and replays it when present. Record one from a real run: ```bash npm run start:dev # start the backend loopstack run triage_ticket --arg text="Production is down!" --trace loopstack runs --record src/triage/__tests__/__recordings__/triage.json ``` Replay is transition-scoped: recordings are matched by the transition they were captured in, then consumed in sequence. Each entry's metadata (`tool`, `workflow`, `transition`, `args`, and `config` when present) is **asserted** against the actual call — when the outgoing args or config drift from the recording the run **fails** with a drift error naming the tool and both values, the signal to re-validate live and re-record. In CI a missing fixture is an error (not a silent live run) unless `LOOPSTACK_RECORD=1` is set. ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT ---