# Extend How to add custom LLM providers and OAuth providers to the Loopstack registry. --- > Source: https://loopstack.ai/llms/extend/custom-bootstrap.md --- title: Custom Bootstrap description: Advanced — replace LoopstackModule.forRoot() by wiring its underlying modules (ConfigModule, TypeOrmModule, EventEmitterModule, LoopCoreModule, LoopstackApiModule) yourself for granular control over database, config, and Nest bootstrap. --- # Custom Bootstrap `LoopstackModule.forRoot()` is the supported way to bootstrap a Loopstack app — it wires up config loading, TypeORM, the event emitter, the core engine, and the REST API in one call. For most apps you should use it as-is. If you need finer-grained control — for example to reuse an existing TypeORM connection that has special pool settings, register a different `ConfigModule`, or co-locate Loopstack with another Nest framework — you can skip `LoopstackModule` and import its underlying modules directly. This is an advanced setup and you become responsible for reproducing the same wiring. ## What `LoopstackModule.forRoot()` Does It registers these modules with sensible defaults: - `ConfigModule.forRoot({ isGlobal: true, envFilePath: '.env', load: [...] })` - `TypeOrmModule.forRoot({ type: 'postgres', autoLoadEntities: true, synchronize: true, ... })` — skipped when `database.reuseExistingConnection` is `true` (you register the default connection yourself) - `EventEmitterModule.forRoot()` - `LoopCoreModule.forRoot({ redis })` — the workflow engine - `LoopstackApiModule.register({ cors, corsOrigins, sse })` — the REST API and controllers See `loopstack/packages/loopstack-module/src/loopstack.module.ts` for the exact wiring. ## Bootstrapping Manually To replace `LoopstackModule.forRoot()` with a custom setup, import these modules yourself: ```typescript import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import { EventEmitterModule } from '@nestjs/event-emitter'; import { TypeOrmModule } from '@nestjs/typeorm'; import { LoopstackApiModule } from '@loopstack/api'; import { LoopCoreModule } from '@loopstack/core'; @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true /* your own config setup */ }), TypeOrmModule.forRoot({ /* your own database setup, must point at PostgreSQL */ }), EventEmitterModule.forRoot(), LoopCoreModule.forRoot({ redis: { /* ... */ }, }), LoopstackApiModule.register({ corsOrigins: ['https://studio.example.com'] }), ], }) export class AppModule {} ``` `LoopstackApiModule.register()` takes the same `cors` and `corsOrigins` options as `LoopstackModule.forRoot()`. Leave `cors` unset to keep the default policy — localhost plus `corsOrigins` — as described under [`cors`](../reference/configuration.md#cors) and [`corsOrigins`](../reference/configuration.md#corsorigins). The app and auth configs that `LoopstackModule` loads (`app`, `auth` namespaces with the keys documented in [Configuration](../reference/configuration.md)) must also be provided — feed them in via your own `ConfigModule.forRoot({ load: [...] })`. If you skip `LoopCoreModule.forRoot()` or `LoopstackApiModule.register()` your app will be missing the workflow engine or the REST API, respectively. --- > Source: https://loopstack.ai/llms/extend/features.md --- title: Studio Features description: How Loopstack features (Git, File Explorer, Secrets, etc.) are registered, discovered, and surfaced in Studio. Covers the registerFeature() helper, forFeature() module pattern, and the backend → frontend feature flow. --- # Studio Features A **feature** in Loopstack is an optional capability that a module opts into and that the Studio UI can render a dedicated surface for — typically a sidebar panel or a document widget. Built-in examples are the `git`, `localFileExplorer`, `remoteFileExplorer`, `secrets`, and `handoff` features. Features are an advanced extension point: most apps never need to create one. ## When to Use a Feature Use a feature when a module wants Studio to: - show an extra UI panel (e.g. a Git history panel) only when the app opts in - expose runtime config to the frontend (e.g. which environments a panel applies to) If you only need workflows, tools, and documents, you don't need a feature — those are surfaced automatically. ## How It Works 1. A feature module exposes a `forFeature(config)` static method that registers a tagged provider via `registerFeature(id, config)`. 2. At bootstrap, the framework walks the import graph of each `@StudioApp` module and collects every registered feature reachable from it. 3. The Studio API returns the active features per app. The frontend has an `AVAILABLE_FEATURES` registry that maps each feature `id` to a UI surface (panel, widget, etc.). The feature `id` on the backend must match the key in the frontend's `AVAILABLE_FEATURES` registry. ## Example — Enabling the Git Feature ```typescript import { Module } from '@nestjs/common'; import { StudioApp } from '@loopstack/common'; import { GitModule } from '@loopstack/git'; import { MyWorkflow } from './workflows/my.workflow'; @StudioApp({ title: 'My App', workflows: [MyWorkflow], }) @Module({ imports: [GitModule.forFeature({ enabled: true })], providers: [MyWorkflow], }) export class MyAppModule {} ``` Importing `GitModule` alone provides the Git tools. Calling `GitModule.forFeature(...)` additionally registers the `git` feature for this app, which makes Studio render the Git sidebar panel. ## Example — Hand-offs to the User's Machine `HandoffModule.forFeature()` from `@loopstack/handoff` registers the `handoff` feature. Studio then shows a "Handoff" sidebar panel with every document tagged `handoff` for the run in view, and renders two document widgets: | Document | Widget | Content | | ---------------------- | --------------- | --------------------------------------------------------------------------------- | | `HandoffDocument` | `handoff` | `title`, `description?`, and a `command` to copy or a `url` to open | | `ChangedFilesDocument` | `changed-files` | `hostRoot` (absolute path on the user's machine) and the changed `paths` under it | ```typescript import { HandoffDocument } from '@loopstack/handoff'; await this.documentStore.save( HandoffDocument, { title: 'Open in Zed', command: 'zed "/home/me/project"' }, { key: 'open_in_zed' }, ); ``` The package also ships `TerminalHandoffDocument`, which drives the CLI's `terminal-handoff` widget: under `loopstack run` it hands the terminal to a local `command` and fires the `handoffDone` transition when it exits. With the feature enabled, Studio renders the same document as a copy-the-command card with an "End session" button that fires `handoffDone` by hand, for a run nobody is following. ## Defining a Custom Feature A custom feature module uses `registerFeature()` inside `forFeature()`: ```typescript import { DynamicModule, Module } from '@nestjs/common'; import { registerFeature } from '@loopstack/common'; @Module({ /* providers, controllers… */ }) export class MyFeatureModule { static forFeature(config?: { enabled?: boolean } & Record): DynamicModule { return { module: MyFeatureModule, providers: [registerFeature('myFeature', config)], }; } } ``` To make the feature visible in Studio, the frontend must register a matching entry in its `AVAILABLE_FEATURES` registry under the same `id` (`myFeature` here). Without that frontend entry the feature is registered on the backend but has no UI surface. ## Studio Extensions (advanced) Some feature modules also contribute arbitrary config sections to a `@StudioApp` via `registerStudioExtension(section, data)`. The collected payloads are grouped by `section` and exposed on the resolved `StudioAppConfig.extensions[section]`. This is an internal extension point (currently used by `RemoteClientModule` to register environment slots) and not a stable public API — refer to the JSDoc on `registerStudioExtension` for details before using it. ## References - `loopstack/packages/common/src/utils/feature-registration.ts` — `registerFeature()` helper - `loopstack/packages/core/src/workflow-processor/services/studio-discovery.service.ts` — bootstrap-time feature discovery - `loopstack/registry/git/src/git.module.ts` — reference implementation --- > Source: https://loopstack.ai/llms/extend/llm-providers.md --- title: Creating Custom LLM Providers description: Implementing a new LLM provider by extending LlmProviderInterface and registering with LlmProviderRegistry. Covers the provider architecture, required methods, replaying message history written by other providers (meta.response, meta.provider, toProviderMessage), rejecting unsupported server tools, and module setup. --- # Creating LLM Providers Add a new LLM provider to Loopstack by implementing `LlmProviderInterface` and registering it with the `LlmProviderRegistry`. ## Architecture ``` @loopstack/llm-provider ← contracts, registry, adapter tools, helpers ↑ ↑ ↑ @loopstack/claude @loopstack/openai your provider ``` - **`@loopstack/llm-provider`** — shared interfaces, `LlmProviderRegistry`, adapter tools (`LlmGenerateTextTool`, `LlmGenerateObjectTool`, `LlmDelegateToolCallsTool`, `LlmUpdateToolResultTool`), shared helpers, and `LlmMessageDocument` - **Provider modules** (e.g. `@loopstack/claude`, `@loopstack/openai`) — implement `LlmProviderInterface`, self-register at module init - Adapter tools route to the correct provider at runtime based on the `provider` config value ## Implement `LlmProviderInterface` ```typescript import { Injectable, OnModuleInit } from '@nestjs/common'; import type { LlmContext, LlmGenerateObjectArgs, LlmGenerateObjectResult, LlmGenerateTextArgs, LlmGenerateTextResult, LlmNormalizedMessage, LlmProviderInterface, LlmUsage, } from '@loopstack/llm-provider'; import { LlmProviderRegistry } from '@loopstack/llm-provider'; @Injectable() export class OllamaLlmProvider implements LlmProviderInterface, OnModuleInit { readonly providerId = 'ollama'; constructor(private readonly registry: LlmProviderRegistry) {} onModuleInit(): void { this.registry.register(this); } async generateText(args: LlmGenerateTextArgs, ctx: LlmContext): Promise { // 1. Resolve messages from ctx.documents (or use args.messages / args.prompt) // 2. Call your LLM API // 3. Normalize the response to LlmNormalizedMessage format // 4. Return { message, response } const nativeResponse = await this.callOllamaApi(args, ctx); return { message: this.normalizeResponse(nativeResponse), response: nativeResponse, // preserve native response for round-trips }; } async generateObject(args: LlmGenerateObjectArgs, ctx: LlmContext): Promise { // Similar to generateText, but force structured output // Use args.outputSchema to constrain the response const nativeResponse = await this.callOllamaStructuredApi(args, ctx); return { data: nativeResponse.parsedOutput, response: nativeResponse, }; } extractUsage(response: unknown): LlmUsage | undefined { // Extract token usage from the native API response const r = response as { usage?: { prompt_tokens: number; completion_tokens: number } }; if (!r.usage) return undefined; return { inputTokens: r.usage.prompt_tokens, outputTokens: r.usage.completion_tokens, }; } toProviderMessage(message: LlmNormalizedMessage): unknown { // Convert normalized message back to provider-specific message format // Used by resolveMessages() for API round-trips return { role: message.role, content: message.blocks ? message.blocks.map((block) => this.convertBlock(block)) : message.text, }; } } ``` ## The Interface ```typescript interface LlmProviderInterface> { /** Unique provider identifier (e.g. 'ollama'). Used in config. */ readonly providerId: string; /** Invoke the LLM and return a normalized response. */ generateText(args: LlmGenerateTextArgs, ctx: LlmContext): Promise; /** Generate a structured object conforming to a JSON Schema. */ generateObject(args: LlmGenerateObjectArgs, ctx: LlmContext): Promise; /** Extract usage stats from the native API response. */ extractUsage(response: unknown): LlmUsage | undefined; /** Convert normalized message to provider-specific message format. */ toProviderMessage(message: LlmNormalizedMessage): unknown; } ``` ### Method responsibilities | Method | Purpose | | ------------------- | ----------------------------------------------------------------------------------------- | | `generateText` | Call the LLM API, return normalized `LlmNormalizedMessage` + native response | | `generateObject` | Same but force structured output matching `args.outputSchema` | | `extractUsage` | Parse token usage from native response (for logging/quota) | | `toProviderMessage` | Convert a normalized message to provider format (for history this provider did not write) | ### Replaying history A conversation may switch provider between turns, so the history your provider reads can hold messages another provider wrote. Follow these rules in your message resolution: 1. **Replay `meta.response` only when you wrote it.** `LlmGenerateTextTool` saves the native response in `doc.meta.response` and your `providerId` in `doc.meta.provider`. Pass the native response back to your API only when `doc.meta.provider === this.providerId`; any other response is in another provider's format. 2. **Convert everything else with `toProviderMessage`.** Map every block your API can express — `text`, `tool_call`, `tool_result` — and leave out the blocks it cannot, such as another provider's `thinking` or `server_tool_use` / `server_tool_result` blocks. 3. **Reject server tools you cannot run.** A `server_tool` entry in `args.tools` carries one provider's native tool spec in `config`. Throw an error that names the tool instead of dropping it. ```typescript const ownResponse = doc.meta?.provider === this.providerId ? doc.meta.response : undefined; const message = ownResponse ? this.fromNativeResponse(ownResponse) : this.toProviderMessage(doc.content as LlmNormalizedMessage); ``` ### What you DON'T implement Tool delegation (`delegateToolCalls`, `updateToolResult`) is handled by the shared `LlmDelegateService` and `LlmToolsHelperService` — they work identically for all providers. You only need to implement the LLM call itself. ## `LlmContext` The context passed to provider methods: ```typescript interface LlmContext { /** Runtime documents for the current workflow execution (used for message history). */ documents: DocumentEntity[]; } ``` Use `ctx.documents` with `args.messagesSearchTag` to resolve message history from saved documents. ## `LlmGenerateTextArgs` The args your `generateText` method receives: | Field | Type | Description | | ------------------- | -------------------- | --------------------------------------------------------- | | `system` | `string?` | System prompt | | `messages` | `LlmMessage[]?` | Explicit messages (alternative to document-based history) | | `prompt` | `string?` | Simple prompt string | | `messagesSearchTag` | `string?` | Tag to filter documents as message history | | `tools` | `LlmResolvedTool[]?` | Tool definitions the LLM can call | | `model` | `string?` | Model name | | `providerConfig` | `TProviderConfig?` | Provider-specific config (temperature, maxTokens, etc.) | | `onStream` | `LlmStreamHandler?` | Optional streaming callback | | `streamMessageId` | `string?` | Message ID for correlating stream events | ## Normalized message format All providers must normalize their responses to `LlmNormalizedMessage`: ```typescript interface LlmNormalizedMessage { id?: string; role: 'user' | 'assistant'; text: string; blocks?: LlmContentBlock[]; stopReason?: 'end_turn' | 'tool_use' | 'max_tokens' | 'stop_sequence'; } ``` `text` is the plain-text projection (always populated). `blocks` is the structured form, present when the message contains non-text blocks (thinking, tool calls, tool results). Content blocks are a union of: - `{ type: 'text', text: string }` — text output - `{ type: 'thinking', text: string }` — reasoning/thinking output - `{ type: 'tool_call', id: string, name: string, args: Record }` — tool call - `{ type: 'tool_result', toolCallId: string, content: string, isError: boolean }` — tool result - `{ type: 'server_tool_use', id: string, name: string, input: Record }` — a server tool call the provider ran - `{ type: 'server_tool_result', toolUseId: string, content: unknown }` — the result of that server tool call ## Create the module ```typescript import { Module } from '@nestjs/common'; import { OllamaLlmProvider } from './ollama-llm-provider'; import { OllamaClientService } from './services/ollama-client.service'; @Module({ providers: [OllamaClientService, OllamaLlmProvider], exports: [OllamaClientService, OllamaLlmProvider], }) export class OllamaModule {} ``` ## Usage Users import your module — no other changes needed: ```typescript @Module({ imports: [LoopstackModule.forRoot(), OllamaModule], }) export class AppModule {} ``` Then use it via config: ```typescript const result = await this.llmGenerateText.call( { prompt: 'Hello' }, { config: { provider: 'ollama', model: 'llama3' } }, ); ``` ## Streaming support If your provider supports streaming, use the `args.onStream` callback: ```typescript async generateText(args: LlmGenerateTextArgs, ctx: LlmContext): Promise { const stream = this.client.stream(/* ... */); if (args.onStream) { const messageId = args.streamMessageId ?? crypto.randomUUID(); await args.onStream({ type: 'start', messageId }); for await (const chunk of stream) { await args.onStream({ type: 'text_delta', messageId, delta: chunk.text }); } const finalMessage = this.normalizeResponse(stream.finalResponse); await args.onStream({ type: 'done', messageId, message: finalMessage }); } // Always return the complete final response regardless of streaming return { message: finalMessage, response: stream.finalResponse }; } ``` ## Key types reference | Type | Description | | ------------------------- | ------------------------------------------------------------------------------------------------------------ | | `LlmProviderInterface` | Contract for provider implementations | | `LlmProviderRegistry` | Runtime registry — `register()`, `get()`, `has()` | | `LlmGenerateTextArgs` | Input for text generation | | `LlmGenerateTextResult` | Response: `{ message, response }` | | `LlmGenerateObjectArgs` | Input for structured output (includes `outputSchema`) | | `LlmGenerateObjectResult` | Response: `{ data, response }` | | `LlmNormalizedMessage` | Normalized message: `role`, `content`, `stopReason` | | `LlmContentBlock` | Content block union: `text`, `thinking`, `tool_call`, `tool_result`, `server_tool_use`, `server_tool_result` | | `LlmStopReason` | `'end_turn'` \| `'tool_use'` \| `'max_tokens'` \| `'stop_sequence'` | | `LlmToolCall` | Normalized tool call: `id`, `name`, `args` | | `LlmContext` | Execution context with `documents` | | `LlmUsage` | Token usage: `inputTokens`, `outputTokens`, optional cache/reasoning | | `LlmResultMeta` | Metadata from adapter tools: `provider`, `model`, `usage` | | `LlmConfigSchema` | Shared Zod schema for model config passthrough | | `LlmStreamEvent` | Stream event union: `start`, `text_delta`, `thinking_delta`, `tool_call`, `done`, `error` | | `LlmDelegateResult` | Tool execution results: `allCompleted`, `toolResults`, `pendingCount`, `errorCount`, `hasErrors`, `errors` | --- > Source: https://loopstack.ai/llms/extend/oauth-providers.md --- title: Creating Custom OAuth Providers description: Implementing a new OAuth provider by extending OAuthProviderInterface and registering with OAuthProviderRegistry. Covers required methods, token handling, and module setup. --- # Creating OAuth Providers Add a new OAuth provider to Loopstack by implementing `OAuthProviderInterface` and registering it with the `OAuthProviderRegistry`. ## The Interface ```typescript import { Injectable, OnModuleInit } from '@nestjs/common'; import { OAuthProviderInterface, OAuthProviderRegistry, OAuthTokenSet } from '@loopstack/oauth'; @Injectable() export class MyOAuthProvider implements OAuthProviderInterface, OnModuleInit { readonly providerId = 'my-provider'; readonly defaultScopes = ['read', 'write']; constructor(private registry: OAuthProviderRegistry) {} onModuleInit() { this.registry.register(this); } buildAuthUrl(scopes: string[], state: string): string { const params = new URLSearchParams({ client_id: process.env.MY_CLIENT_ID!, redirect_uri: process.env.MY_REDIRECT_URI!, scope: scopes.join(' '), state, response_type: 'code', }); return `https://my-provider.com/oauth/authorize?${params}`; } async exchangeCode(code: string): Promise { // POST to token endpoint, return { accessToken, refreshToken, expiresIn, scope } } async refreshToken(refreshToken: string): Promise { // POST to refresh endpoint, return new token set } } ``` ## Method Responsibilities | Method | Purpose | | -------------- | ----------------------------------------------------------- | | `buildAuthUrl` | Construct the OAuth authorization URL for the user to visit | | `exchangeCode` | Exchange the authorization code for tokens after redirect | | `refreshToken` | Refresh an expired access token using the refresh token | ## `OAuthTokenSet` The return type for `exchangeCode` and `refreshToken`: ```typescript interface OAuthTokenSet { accessToken: string; refreshToken?: string; expiresIn?: number; // seconds until expiry; omit when the provider reports none (never expires) scope: string; } ``` ## Registration The provider self-registers via `OnModuleInit`. Once registered, it's available to the built-in `OAuthWorkflow` and `OAuthTokenStore`. ## Create the Module ```typescript import { Module } from '@nestjs/common'; import { OAuthModule } from '@loopstack/oauth'; import { MyOAuthProvider } from './my-oauth-provider'; @Module({ imports: [OAuthModule], providers: [MyOAuthProvider], exports: [MyOAuthProvider], }) export class MyOAuthModule {} ``` ## Usage Users import your module — no other changes needed: ```typescript @Module({ imports: [LoopstackModule.forRoot(), MyOAuthModule], }) export class AppModule {} ``` Then use it in workflows: ```typescript await this.oAuth.run( { provider: 'my-provider', scopes: ['read', 'write'] }, { callback: { transition: 'authCompleted' } }, ); ``` ## Token Lifecycle 1. `OAuthWorkflow` calls `buildAuthUrl()` and shows the URL to the user 2. User completes OAuth in browser, gets redirected back with a code 3. Framework calls `exchangeCode()` to get tokens 4. Tokens are stored per user per provider via `OAuthTokenStore` 5. `OAuthTokenStore.getValidAccessToken()` auto-calls `refreshToken()` when expired 6. Tools check for valid tokens and return `{ error: 'unauthorized' }` if missing ## Existing Providers | Provider | Module | Provider ID | | -------- | ----------------------------- | ----------- | | Google | `@loopstack/google-workspace` | `'google'` | | GitHub | `@loopstack/github` | `'github'` | --- > Source: https://loopstack.ai/llms/extend/tool-interceptors.md --- title: Tool Interceptors description: Advanced — register chain-based interceptors around every tool.call() for cross-cutting concerns (quota tracking, caching, structured logging, error handling). Covers the ToolInterceptor interface, @UseToolInterceptor() decorator, ToolExecutionContext, priority ordering, and the shipped interceptors (QuotaInterceptor, RecordToolInterceptor/ReplayToolInterceptor, TracingInterceptor example). Tool timing is recorded on the run trace, not in metadata. --- # Tool Interceptors Tool interceptors are a chain-based extension point that wraps every `tool.call()` in your app. They are the right surface for cross-cutting concerns that should run around _every_ tool call without changing tool implementations — quota enforcement, response caching, structured tracing, custom error handling, billing accounting. This is an advanced extension point. Most apps don't need a custom interceptor — the tool pipeline already times and logs every call and records it on the run trace, and the `@loopstack/quota` registry package includes a working `QuotaInterceptor` you can copy. ## How They Work Interceptors form a NestJS-style chain. Each interceptor calls `next()` to pass control to the next interceptor (or, eventually, to the tool's `handle()`). You can: - run logic before and after the tool call - transform the result - short-circuit by not calling `next()` (e.g. cache hit returns a result directly) - handle errors with `try/catch` around `next()` The chain is built once at app bootstrap from every NestJS provider decorated with `@UseToolInterceptor()`. Ordering is controlled by `priority` — **lower runs first / outermost**. The framework itself registers no interceptors — the chain holds only the ones your app and its imported modules provide. ``` caller → TracingInterceptor(10) → QuotaInterceptor(50) → CacheInterceptor(60) → tool.handle() ``` In this chain the quota check wraps the cache, so cache hits still count against the quota. Give the cache a priority below `50` to let hits skip it. Timing and logging are not part of the chain: the tool pipeline measures each call around the whole chain and records the duration on the `tool.completed` / `tool.failed` events of the [run trace](../build/fundamentals/workflows.md#the-run-trace). ## Implementing an Interceptor Implement `ToolInterceptor` and decorate with `@UseToolInterceptor({ priority? })`. The decorator applies `@Injectable()` for you, so the class only needs to be registered in a NestJS module like any other provider. ```typescript import { ToolEnvelope, ToolExecutionContext, ToolInterceptor, UseToolInterceptor } from '@loopstack/common'; @UseToolInterceptor({ priority: 60 }) export class CacheInterceptor implements ToolInterceptor { private readonly cache = new Map(); async intercept(context: ToolExecutionContext, next: () => Promise): Promise { const key = `${context.tool.constructor.name}:${JSON.stringify(context.args)}`; const hit = this.cache.get(key); if (hit) { context.metadata.cacheHit = true; return hit; // short-circuit — `next()` not called, tool doesn't run } const result = await next(); this.cache.set(key, result); return result; } } ``` Register it in a module: ```typescript @Module({ providers: [CacheInterceptor /*, ...your tools and workflows */], }) export class MyAppModule {} ``` That's it — bootstrap-time discovery picks it up via `@UseToolInterceptor()` metadata. No manual registration list. ## `ToolExecutionContext` The first argument to `intercept()` carries everything an interceptor needs. | Field | Type | Notes | | ------------ | -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tool` | `object` | The tool instance. Use `context.tool.constructor.name` for the class name. | | `args` | `Record \| undefined` | The arguments passed to `tool.call()` (post-validation when reaching `handle()`). | | `config` | `Record` | Optional. The call's validated config — present only when the tool was called with one. | | `runContext` | `RunContext` | The per-job framework context: `userId`, `workspaceId`, `workflowId`, `args`. | | `metadata` | `Record` | **Mutable.** Use this to pass data between interceptors in the chain (e.g. cache key, timings, quota cost). Starts empty on every call — the framework writes nothing here. | ## Priority Ordering `priority` is a number. **Lower runs first / outermost** — that interceptor wraps every later one. | Priority | Position | Use for | | -------- | --------- | --------------------------------------------------------------- | | `0` | outermost | Logging, tracing — see everything that happens inside. | | `1–50` | early | Auth gates, request validation, kill-switches. | | `50–100` | middle | Caching, idempotency, response transformation. | | `>100` | inner | Per-tool accounting (quota debit, billing) close to `handle()`. | `@UseToolInterceptor()` defaults to `100` when omitted. ## Shipped Interceptors The core registers no interceptors. These ship in Loopstack packages and join the chain when their module or option is used: - **`QuotaInterceptor`** (priority `50`) — `@loopstack/quota`, registered by `QuotaModule.forRoot()`. Checks the user's quotas before the call and reports usage after it. Source: `loopstack/registry/quota/src/services/quota.interceptor.ts`. - **`ReplayToolInterceptor`** / **`RecordToolInterceptor`** (priority `10`) — `@loopstack/testing`, registered by `runWorkflow()` only when a test replays or records tool responses (see [Record and replay tool responses](../build/testing.md#record-and-replay-tool-responses)). Source: `loopstack/packages/testing/src/facade/replay.ts` and `record.ts`. - **`TracingInterceptor`** (priority `10`) — example in the [observability examples](/docs/examples/observability) that measures every tool call and stores trace entries in an injectable service. Source: `examples/src/observability/workflows/tracing/interceptors/tracing.interceptor.ts`. ## Real-world Example: Quota The `@loopstack/quota` package ships a `QuotaInterceptor` that uses the chain pattern to enforce per-user quotas before the tool runs and report usage after: ```typescript @UseToolInterceptor({ priority: 50 }) export class QuotaInterceptor implements ToolInterceptor { async intercept(context: ToolExecutionContext, next: () => Promise): Promise { const userId = context.runContext.userId; await this.checkQuota(userId, context.tool); const result = await next(); await this.reportUsage(userId, context.tool, result); return result; } } ``` See `loopstack/registry/quota/src/services/quota.interceptor.ts` for the full implementation. ---