# Build / Integrations --- > Source: https://loopstack.ai/llms/build/integrations/lifecycle-events.md --- title: Lifecycle Events description: In-process lifecycle events a host app listens to with @OnEvent from @nestjs/event-emitter — workflow.settled (WORKFLOW_SETTLED, WorkflowSettledEvent from @loopstack/core) when a run completes, fails or is canceled, and workflow.deleted / workspace.deleted when a run or workspace is deleted. Payload fields, when each event is emitted, the cascade rule for workspace and sub-workflow deletes, error handling, and why listeners must be idempotent. --- # Lifecycle Events An app often holds something for a run or a workspace that Loopstack does not know about: a checkout on disk, a container, a reserved slot, a row in its own tables. Loopstack emits in-process events when a run ends and when a run or workspace is deleted, so the app can release those resources without polling. ## The events | Event | Emitted when | Payload | | ------------------- | ------------------------------------------------- | ------------------------------------------------------------------------------------------- | | `workflow.settled` | A run reaches `completed`, `failed` or `canceled` | `WorkflowSettledEvent` — `id`, `workspaceId`, `workflowName`, `parentId?`, `status`, `user` | | `workflow.deleted` | A run is deleted through the API | `{ id, workspaceId, user }` | | `workspace.deleted` | A workspace is deleted through the API | `{ id, appName, user }` | `user` is the ID of the user the run or workspace belongs to. ### `workflow.settled` `@loopstack/core` exports the event name as `WORKFLOW_SETTLED` and the payload type as `WorkflowSettledEvent`. The event fires once a run reaches a state it does not leave by itself: `completed`, `failed` or `canceled`. Every path that ends a run emits it — a processing pass that reaches a terminal state, a job the queue gave up on, and a cancellation. - It is emitted after the run's own persistence has committed. - It is emitted for sub-workflows as well as root runs. `parentId` is set only for a sub-workflow, so a listener that cares only about root runs checks that `parentId` is absent. ### `workflow.deleted` and `workspace.deleted` `@loopstack/api` emits these after the delete has committed — once per deleted run or workspace, from the single delete and from the batch delete endpoint. In a batch delete, only the items that were actually deleted emit an event; IDs that were not found or not deleted emit nothing. The database removes dependent rows by cascade, and a **cascaded delete emits no event of its own**: - Deleting a workspace deletes all its runs, but emits only `workspace.deleted`. A `workspace.deleted` listener must release everything the workspace owned, including what it holds per run. - Deleting a run deletes its sub-workflows, but emits `workflow.deleted` only for the run that was deleted. Rows deleted directly in the database, outside the API, emit nothing. ## Listening to an event The events go through the NestJS event emitter that `LoopstackModule` registers. They do not leave the process: a listener is an `@Injectable()` provider with an `@OnEvent()` method, registered in a module of your app. `OnEvent` comes from `@nestjs/event-emitter`; add it to your app's dependencies. ```typescript import { Injectable, Logger } from '@nestjs/common'; import { OnEvent } from '@nestjs/event-emitter'; import { WORKFLOW_SETTLED, type WorkflowSettledEvent } from '@loopstack/core'; @Injectable() export class PreviewCleanupListener { private readonly logger = new Logger(PreviewCleanupListener.name); constructor(private readonly previews: PreviewService) {} @OnEvent(WORKFLOW_SETTLED) async onSettled(event: WorkflowSettledEvent) { if (event.parentId) return; // only root runs hold a preview await this.previews.stopForRun(event.id); } @OnEvent('workflow.deleted') async onWorkflowDeleted(payload: { id: string; workspaceId: string; user: string }) { await this.previews.removeForRun(payload.id); } @OnEvent('workspace.deleted') async onWorkspaceDeleted(payload: { id: string; appName: string; user: string }) { // Runs deleted with the workspace emit no workflow.deleted — release them here. await this.previews.removeForWorkspace(payload.id); } } ``` ```typescript @Module({ providers: [PreviewService, PreviewCleanupListener], }) export class MyAppModule {} ``` ### Rules for listeners - **Make them idempotent.** There is no guarantee that an event arrives exactly once, and a process that stops before the listener ran never sees it. Release operations must tolerate a second call. When correctness depends on the release, also reconcile against the stored state (for example, sweep for resources whose run or workspace no longer exists) and treat the event as the prompt to do it early. - **Do not depend on the caller waiting.** The emitter does not await an async listener. The delete request returns and the run continues while your listener is still working, so a slow cleanup does not block anything. - **Errors do not reach the caller.** `@OnEvent` catches and logs an error thrown by its listener by default, so a failing listener does not fail the delete or the run. A failed `workflow.settled` listener also does not stop the parent run's callback. Log what you could not release, so the next sweep can find it. ## Real listeners Two registry packages release their resources this way: - [`@loopstack/claims`](/docs/registry/claims#a-claim-cannot-be-left-behind) releases resource claims on `workflow.settled`, `workflow.deleted` and `workspace.deleted`. - [`@loopstack/code-workspace`](/docs/registry/code-workspace#reclamation) removes checkouts, containers and volumes on `workflow.deleted` and `workspace.deleted`, and runs an orphan sweep for anything a listener missed. For events that describe what happens _inside_ a run — workflow and document updates as they stream to Studio — see the `client.message` listener in the [Audit Log example](/docs/examples/observability#audit-log). --- > Source: https://loopstack.ai/llms/build/integrations/oauth.md --- title: OAuth Authentication description: Integrating OAuth 2.0 authentication using @loopstack/oauth. Covers setup with Google Workspace provider, token management, and accessing OAuth-protected APIs from workflows. --- # OAuth Authentication Add OAuth 2.0 authentication to your workflows using the provider-agnostic `@loopstack/oauth`. Register providers like Google Workspace or GitHub, and access OAuth-protected APIs from any workflow or tool. ## How It Works The module is split into three layers: 1. **Provider registry** — provider modules (Google, GitHub, etc.) implement `OAuthProviderInterface` and self-register at module init. The registry resolves a provider by name at call time. 2. **OAuth workflow** — a generic `OAuthWorkflow` that builds the auth URL, surfaces a sign-in prompt via `OAuthPromptDocument`, waits for the browser callback, and exchanges the auth code for tokens. Run it as a sub-workflow from any parent workflow. 3. **Token store** — `OAuthTokenStore` persists access/refresh tokens per user per provider in Redis (falls back to in-memory when Redis is unavailable). `getValidAccessToken()` automatically refreshes expired tokens via the provider's `refreshToken()` method. ``` start ──► initiateOAuth ──► awaiting_auth ──► exchangeToken ──► end │ │ │ Builds auth URL, │ Validates CSRF state, │ saves OAuthPromptDocument │ exchanges code, │ with sign-in prompt │ stores tokens ▼ ▼ (waits for user to (callback resumes complete OAuth in browser) parent workflow) ``` Tools that need an access token call `OAuthTokenStore.getValidAccessToken(userId, provider)` and return `{ error: 'unauthorized' }` if no valid token exists, which lets the parent workflow guard branch into running `OAuthWorkflow`. ## Setup ```typescript import { Module } from '@nestjs/common'; import { GoogleWorkspaceModule } from '@loopstack/google-workspace'; @Module({ imports: [GoogleWorkspaceModule], providers: [MyWorkflow], exports: [MyWorkflow], }) export class MyModule {} ``` `GoogleWorkspaceModule` and `GitHubModule` import `OAuthModule` internally — you don't need to add it explicitly. For a custom provider, import `OAuthModule` directly alongside your provider module: ```typescript import { OAuthModule } from '@loopstack/oauth'; import { MyCustomOAuthModule } from './my-custom-oauth.module'; @Module({ imports: [OAuthModule, MyCustomOAuthModule], providers: [MyWorkflow], }) export class MyModule {} ``` `OAuthModule` is decorated with `@Global()`, so a single import makes the registry, token store, and OAuth tools available throughout your app. ## OAuth as Sub-Workflow The simplest approach: launch the built-in `OAuthWorkflow` when authentication is needed. ```typescript import { BaseWorkflow, Guard, Transition, Workflow } from '@loopstack/common'; import type { RunContext, TransitionInput } from '@loopstack/common'; import { MarkdownDocument } from '@loopstack/common'; import { OAuthWorkflow } from '@loopstack/oauth'; interface CalendarState { events?: CalendarEvent[]; requiresAuthentication?: boolean; } type CalendarArgs = { calendarId: string }; @Workflow({ widget: './calendar.ui.yaml' }) export class CalendarWorkflow extends BaseWorkflow { constructor( private readonly calendarFetchEvents: CalendarFetchEventsTool, private readonly oAuth: OAuthWorkflow, ) { super(); } @Transition({ to: 'calendar_fetched' }) async fetchEvents(state: CalendarState, ctx: RunContext) { const result = await this.calendarFetchEvents.call({ calendarId: ctx.args.calendarId, }); this.assignState({ requiresAuthentication: result.data.error === 'unauthorized', events: result.data.events, }); } // If unauthorized -> launch OAuth sub-workflow @Transition({ from: 'calendar_fetched', to: 'awaiting_auth', priority: 10 }) @Guard('needsAuth') async authRequired(state: CalendarState) { await this.oAuth.run( { provider: 'google', scopes: ['https://www.googleapis.com/auth/calendar.readonly'] }, { callback: { transition: 'authCompleted' }, show: 'inline', label: 'Google authentication required' }, ); } needsAuth(state: CalendarState): boolean { return !!state.requiresAuthentication; } // After auth -> retry from start @Transition({ from: 'awaiting_auth', to: 'start', wait: true }) authCompleted(state: CalendarState, _input: TransitionInput) {} // Success -> display results @Transition({ from: 'calendar_fetched', to: 'end' }) async displayResults(state: CalendarState) { await this.documentStore.save(MarkdownDocument, { markdown: this.render(join(__dirname, 'templates', 'summary.md'), { events: state.events }), }); } } ``` ## Using Tokens in Custom Tools ```typescript import { z } from 'zod'; import { BaseTool, Tool, ToolEnvelope } from '@loopstack/common'; import type { RunContext } from '@loopstack/common'; import { OAuthTokenStore } from '@loopstack/oauth'; @Tool({ name: 'calendar_fetch_events', description: 'Fetches Google Calendar events.', schema: z.object({ calendarId: z.string().default('primary') }).strict(), }) export class CalendarFetchEventsTool extends BaseTool { constructor(private readonly tokenStore: OAuthTokenStore) { super(); } protected async handle(args: { calendarId: string }, ctx: RunContext): Promise { const accessToken = await this.tokenStore.getValidAccessToken(ctx.userId, 'google'); if (!accessToken) { return { data: { error: 'unauthorized' } }; } const response = await fetch(`https://www.googleapis.com/calendar/v3/calendars/${args.calendarId}/events`, { headers: { Authorization: `Bearer ${accessToken}` }, }); return { data: await response.json() }; } } ``` ## Creating a Custom OAuth Provider See [Creating OAuth Providers](../../extend/oauth-providers.md) for how to implement `OAuthProviderInterface` and register a custom provider. ## Environment Variables Each OAuth provider reads its own credentials from env, conventionally named `_CLIENT_ID`, `_CLIENT_SECRET`, and `_OAUTH_REDIRECT_URI`: ``` # Google Workspace GOOGLE_CLIENT_ID=... GOOGLE_CLIENT_SECRET=... GOOGLE_OAUTH_REDIRECT_URI=... # GitHub GITHUB_CLIENT_ID=... GITHUB_CLIENT_SECRET=... GITHUB_OAUTH_REDIRECT_URI=... ``` The token store also reads `REDIS_HOST`, `REDIS_PORT`, and `REDIS_PASSWORD` — see [Configuration Reference](../../reference/configuration.md) for defaults. Redis is optional; an in-memory fallback is used when unavailable. ## Token Lifecycle 1. `OAuthWorkflow` generates auth URL and shows it to the user 2. User completes OAuth in browser 3. Token is exchanged and stored per user per provider 4. `OAuthTokenStore.getValidAccessToken()` auto-refreshes expired tokens 5. Tools return `{ error: 'unauthorized' }` if no token exists 6. Workflow guard detects the error and launches OAuth sub-workflow ## Registry References - [Google Workspace examples](/docs/examples/google-workspace) — Google Calendar fetch with OAuth sub-workflow and Google Workspace agent with tool calling - [GitHub examples](/docs/examples/github) — GitHub OAuth integration with repos overview and GitHub agent with 25 tools --- > Source: https://loopstack.ai/llms/build/integrations/programmatic-execution.md --- title: Scheduling & Programmatic Execution description: Scheduling and programmatic workflow execution with WorkflowRunner — cron (@Cron), webhook endpoints, delayed runs (SchedulerRegistry), batch fan-out, and triggering from API requests or internal events. run vs runSync, appName/userId context. --- # Scheduling & Programmatic Execution Start and manage workflows programmatically from your NestJS application — in response to API requests, webhook events, cron jobs, or internal application logic — without going through the Studio UI. ## Overview Use the `WorkflowRunner` to execute workflows in response to: - External API requests - Webhook events - Scheduled cron jobs - Internal application events - Batch processing tasks For a runnable version of every pattern below — cron, webhook, delayed run, and batch — see the [scheduling examples](/docs/examples/scheduling). Each fundamental ships as a small workflow plus the real trigger that fires it, and you can drive the HTTP-triggered ones straight from Studio. ## Basic Example ### Create a Controller ```typescript import { Body, Controller, Post } from '@nestjs/common'; import { WorkflowRunner } from '@loopstack/core'; import { MyWorkflow } from './workflows/my.workflow'; @Controller() export class AppController { constructor(private readonly workflowRunner: WorkflowRunner) {} @Post('run-my-workflow') async runMyWorkflow(@Body() payload: any) { const userId = '...'; // define a user id to run the workflow const result = await this.workflowRunner.run(MyWorkflow, payload, { appName: 'default', userId, }); return { message: 'Workflow run is queued.', workflowId: result.workflowId }; } } ``` ### WorkflowRunner Methods ```typescript // Async (queued via BullMQ) await this.workflowRunner.run( workflow, // Workflow class reference args, // Data passed as workflow args (type-safe) { appName, // App name for workspace resolution userId, // User ID for execution context }, ); // Sync (inline execution, awaits result) await this.workflowRunner.runSync( workflow, // Workflow class reference args, // Data passed as workflow args (type-safe) { appName, // App name for workspace resolution userId, // User ID for execution context stateless, // Optional: skip persistence (default: false) }, ); ``` ## Advanced Examples ### Webhook Handler Trigger a workflow when receiving a webhook: ```typescript import { Body, Controller, Headers, Post } from '@nestjs/common'; import { WorkflowRunner } from '@loopstack/core'; @Controller('webhooks') export class WebhookController { constructor(private readonly workflowRunner: WorkflowRunner) {} @Post('stripe') async handleStripeWebhook(@Body() webhookData: any, @Headers('stripe-signature') signature: string) { await this.workflowRunner.run( ProcessWebhookWorkflow, { source: 'stripe', event: webhookData, receivedAt: new Date().toISOString(), }, { appName: 'main', userId: webhookData.userId, }, ); return { received: true }; } } ``` ### Scheduled Task Execute a workflow on a schedule using NestJS's `@Cron` decorator: ```typescript import { Injectable } from '@nestjs/common'; import { Cron, CronExpression } from '@nestjs/schedule'; import { WorkflowRunner } from '@loopstack/core'; @Injectable() export class TaskScheduler { constructor(private readonly workflowRunner: WorkflowRunner) {} @Cron(CronExpression.EVERY_DAY_AT_9AM) async generateDailyReports() { const users = await this.getUsersWithReportsEnabled(); for (const user of users) { await this.workflowRunner.run( DailyReportWorkflow, { reportDate: new Date().toISOString(), reportType: 'daily', }, { appName: 'reports', userId: user.id, }, ); } } } ``` ### Delayed Run Run a workflow once after a delay — e.g. "follow up 24h after signup". Register a one-off timeout with NestJS's `SchedulerRegistry`, then trigger the workflow when it fires: ```typescript import { Injectable } from '@nestjs/common'; import { SchedulerRegistry } from '@nestjs/schedule'; import { randomUUID } from 'node:crypto'; import { WorkflowRunner } from '@loopstack/core'; @Injectable() export class SignupFollowupService { constructor( private readonly workflowRunner: WorkflowRunner, private readonly scheduler: SchedulerRegistry, ) {} scheduleFollowup(email: string, userId: string, delayMs = 24 * 60 * 60 * 1000) { const name = `signup-followup-${randomUUID()}`; const timeout = setTimeout(() => { this.scheduler.deleteTimeout(name); void this.workflowRunner.run(SignupFollowupWorkflow, { email }, { appName: 'onboarding', userId }); }, delayMs); this.scheduler.addTimeout(name, timeout); } } ``` `SchedulerRegistry` timeouts live in memory, so a server restart loses any pending run. For delays that must survive restarts, enqueue a [BullMQ delayed job](https://docs.bullmq.io/guide/jobs/delayed) instead. ### Batch Processing Process multiple items by triggering workflows in parallel: ```typescript import { Injectable } from '@nestjs/common'; import { WorkflowRunner } from '@loopstack/core'; @Injectable() export class OrderProcessingService { constructor(private readonly workflowRunner: WorkflowRunner) {} async processPendingOrders() { const pendingOrders = await this.getPendingOrders(); const promises = pendingOrders.map((order) => this.workflowRunner.run( ProcessOrderWorkflow, { orderId: order.id, orderData: order, }, { appName: 'orders', userId: order.userId, }, ), ); await Promise.all(promises); return { processed: pendingOrders.length }; } } ``` ## Registry References - [Scheduling examples](/docs/examples/scheduling) — Runnable examples of every scheduling fundamental: cron (`@Cron` + `WorkflowRunner.run`), webhook (`@Public @Post` controller), delayed run (`SchedulerRegistry` timeout), and batch (`Promise.all` fan-out). Includes Studio-launchable workflows that make the real HTTP call to each trigger endpoint. --- > Source: https://loopstack.ai/llms/build/integrations/sandbox.md --- title: Sandbox Execution description: Executing untrusted code in Docker containers using @loopstack/docker-sandbox and @loopstack/docker-sandbox-filesystem. Setup, file I/O inside sandboxes, and cleanup. --- # Sandbox Execution Run untrusted or AI-generated code safely in isolated Docker containers. The sandbox packages provide tools for creating disposable execution environments with filesystem access, letting workflows execute arbitrary code without risking the host system. ## Prerequisites Docker must be installed and running on the host system before any sandbox tool is invoked. The sandbox tools shell out to the local Docker daemon to create, start, exec into, and remove containers — `sandbox_init` will fail at runtime if Docker isn't available. Any Docker image works — `imageName` is passed straight through to Docker, so anything you'd put after `docker pull` (`node:18`, `python:3.11-slim`, your own private image) is valid. Images are pulled automatically on first use, so the first init for an unfamiliar image may be slow. ## Host ↔ Container Filesystem `sandbox_init` takes two related paths: - `projectOutPath` — an absolute path on the **host** machine. - `rootPath` — a path **inside** the container (defaults to `workspace`). The host directory at `projectOutPath` is bind-mounted into the container at `/`. Anything the container writes under `/` shows up at `projectOutPath` on the host, and vice versa — it's the same set of files viewed from two sides. Use this to feed inputs into the sandbox, read outputs back out, and persist artifacts across container destroys. ## Setup ```typescript import { Module } from '@nestjs/common'; import { SandboxFilesystemModule } from '@loopstack/docker-sandbox-filesystem'; @Module({ imports: [SandboxFilesystemModule], providers: [SandboxWorkflow], exports: [SandboxWorkflow], }) export class SandboxModule {} ``` ## Example Workflow ```typescript import { z } from 'zod'; import { BaseWorkflow, Transition, Workflow } from '@loopstack/common'; import type { RunContext } from '@loopstack/common'; import { SandboxDestroy, SandboxInit } from '@loopstack/docker-sandbox'; import { SandboxCreateDirectory, SandboxDelete, SandboxReadFile, SandboxWriteFile, } from '@loopstack/docker-sandbox-filesystem'; interface SandboxState { containerId?: string; } const SandboxArgsSchema = z.object({ outputDir: z.string().default(process.cwd() + '/out') }); type SandboxArgs = z.infer; @Workflow({ widget: './sandbox.ui.yaml', schema: SandboxArgsSchema, }) export class SandboxWorkflow extends BaseWorkflow { constructor( private readonly sandboxInit: SandboxInit, private readonly sandboxDestroy: SandboxDestroy, private readonly sandboxWriteFile: SandboxWriteFile, private readonly sandboxReadFile: SandboxReadFile, private readonly sandboxCreateDirectory: SandboxCreateDirectory, ) { super(); } @Transition({ to: 'sandbox_ready' }) async initSandbox(state: SandboxState, ctx: RunContext) { const result = await this.sandboxInit.call({ containerId: 'my-sandbox', imageName: 'node:18', containerName: 'sandbox-container', projectOutPath: ctx.args.outputDir, rootPath: 'workspace', }); this.assignState({ containerId: result.data.containerId }); } @Transition({ from: 'sandbox_ready', to: 'file_written' }) async writeFile(state: SandboxState) { await this.sandboxCreateDirectory.call({ containerId: state.containerId!, path: '/workspace/src', recursive: true, }); await this.sandboxWriteFile.call({ containerId: state.containerId!, path: '/workspace/src/hello.js', content: "console.log('Hello from sandbox!');", encoding: 'utf8', createParentDirs: true, }); } @Transition({ from: 'file_written', to: 'file_read' }) async readFile(state: SandboxState) { await this.sandboxReadFile.call({ containerId: state.containerId!, path: '/workspace/src/hello.js', encoding: 'utf8', }); } @Transition({ from: 'file_read', to: 'end' }) async destroySandbox(state: SandboxState) { await this.sandboxDestroy.call({ containerId: state.containerId!, removeContainer: true, }); } } ``` ## Available Tools ### Container Lifecycle | Tool | Args | Description | | ---------------- | ----------------------------------------------------------------- | -------------------------- | | `sandboxInit` | `containerId, imageName, containerName, projectOutPath, rootPath` | Create and start container | | `sandboxDestroy` | `containerId, removeContainer` | Stop/remove container | ### Filesystem Operations | Tool | Args | Description | | ------------------------ | ---------------------------------------------------------- | ---------------------- | | `sandboxWriteFile` | `containerId, path, content, encoding?, createParentDirs?` | Write file | | `sandboxReadFile` | `containerId, path, encoding?` | Read file content | | `sandboxListDirectory` | `containerId, path, recursive?` | List directory entries | | `sandboxCreateDirectory` | `containerId, path, recursive?` | Create directory | | `sandboxDelete` | `containerId, path, recursive?, force?` | Delete file/directory | | `sandboxExists` | `containerId, path` | Check if path exists | | `sandboxFileInfo` | `containerId, path` | Get file metadata | ### Command Execution | Tool | Args | Description | | ---------------- | ----------------------------------------------------------------------- | ------------------------ | | `sandboxCommand` | `containerId, executable, args?, workingDirectory?, envVars?, timeout?` | Run command in container | ## Security - Path traversal detection and prevention - Shell argument escaping - Isolated Docker containers with volume mounting - Configurable timeouts on command execution ## Registry References - [Sandbox example](/docs/examples/sandbox#sandbox) — Full sandbox lifecycle: init, create directory, write/read files, list directory, check existence, get file info, delete, and destroy --- > Source: https://loopstack.ai/llms/build/integrations/secrets.md --- title: Secrets Management description: Requesting, storing, and retrieving secrets (API keys, tokens) at runtime using SecretRequestDocument, RequestSecretsTask, and GetSecretKeysTool from @loopstack/secrets. --- # Secrets Management Loopstack provides built-in tools for requesting and retrieving secrets (API keys, tokens, etc.) from users at runtime. ## Overview Secrets are requested from the user via a `SecretRequestDocument` form (or `RequestSecretsTask` in agent loops) and persisted in the database via `SecretEntity`, scoped per workspace. Values are never exposed to the LLM — only key names and availability flags (`GetSecretKeysTool`) are returned to workflow code. ### Providing Secrets to Remote Environments When a workflow runs commands on a remote sandbox or Fly.io machine via `@loopstack/remote-client-module`, secrets must reach that environment to be useful. The `SyncSecretsTool` (`sync_secrets`) reads all workspace secrets, ships them to the remote agent over its authenticated control channel, and writes them as `.env` variables before restarting the app. Values stay on the server side of the control channel and are not surfaced to the LLM. Call `sync_secrets` before launching long-running commands or whenever a secret changes: ```typescript constructor(private readonly syncSecrets: SyncSecretsTool) { super(); } @Transition({ from: 'secrets_received', to: 'ready' }) async pushSecrets(state: SecretsState) { await this.syncSecrets.call({}); } ``` ## Available Tools | Tool | Source | Description | | ----------------------- | -------------------- | -------------------------------------------------------- | | `RequestSecretsTask` | `@loopstack/secrets` | Agent-friendly task that launches a secrets sub-workflow | | `GetSecretKeysTool` | `@loopstack/secrets` | List stored secret keys and their availability | | `SecretRequestDocument` | `@loopstack/secrets` | Document displaying the secret input form | ## Example Workflow ```typescript import { BaseWorkflow, Transition, Workflow } from '@loopstack/common'; import { MarkdownDocument } from '@loopstack/common'; import { GetSecretKeysTool, SecretRequestDocument } from '@loopstack/secrets'; interface SecretsState { secretKeys?: Array<{ key: string; hasValue: boolean }>; } @Workflow({ widget: './secrets-example.ui.yaml' }) export class SecretsExampleWorkflow extends BaseWorkflow { constructor(private readonly getSecretKeys: GetSecretKeysTool) { super(); } @Transition({ to: 'requesting_secrets' }) async requestSecretsFromUser(state: SecretsState) { await this.documentStore.save(SecretRequestDocument, { variables: [{ key: 'EXAMPLE_API_KEY' }, { key: 'EXAMPLE_SECRET' }], }); } @Transition({ from: 'requesting_secrets', to: 'verifying', wait: true }) async secretsSubmitted(state: SecretsState) { const result = await this.getSecretKeys.call({}); this.assignState({ secretKeys: result.data }); } @Transition({ from: 'verifying', to: 'end' }) async showResult(state: SecretsState) { await this.documentStore.save(MarkdownDocument, { markdown: this.render(join(__dirname, 'templates', 'secretsVerified.md'), { secretKeys: state.secretKeys, }), }); } } ``` ## How It Works 1. **Request** — saving a `SecretRequestDocument` with the needed keys shows a secure input form in the UI 2. **Wait** — The workflow pauses on a `wait: true` transition named `secretsSubmitted` (the transition the form fires) until the user submits the secrets 3. **Verify** — `GetSecretKeysTool` checks which secrets are now stored 4. **Use** — Secrets are available as environment variables in subsequent tool calls ## Template Example ```markdown # Secrets Verification {{#each secretKeys}} - **{{this.key}}**: {{#if this.hasValue}}Stored{{else}}Missing{{/if}} {{/each}} ``` ## Registry References - [Secrets examples](/docs/examples/secrets) — Request secrets from user, verify storage, and display results with both direct workflow and agent-based approaches ---