# Registry — Packages Official Loopstack packages providing LLM providers, OAuth, human-in-the-loop, Git/GitHub tools, Docker sandboxes, secrets management, and more. --- > Source: https://loopstack.ai/llms/registry/packages/agent.md --- title: Agent Module description: Generic LLM agent workflows for Loopstack — AgentWorkflow (single-run tool loop), ChatAgentWorkflow (multi-turn chat with optional task mode), AgentFinishTool, tool resolution via NestJS DI, configurable system prompt and tool set --- # @loopstack/agent > Agent workflow module for the [Loopstack](https://loopstack.ai) automation framework. Generic, reusable LLM agent workflows for Loopstack. Run a standard agent loop (LLM → tool calls → loop) configured entirely via `run()` args — no subclassing required. ## When to Use - **You need an autonomous agent** that calls tools in a loop until it's done — use `AgentWorkflow`. - **You need a multi-turn chat agent** where the user can send messages between LLM turns — use `ChatAgentWorkflow`. - **You want task-mode chat** where the agent can explicitly finish and return a structured result — use `ChatAgentWorkflow` with `taskMode: true`. - **You need a custom agent loop** with domain-specific exit conditions, extra setup steps, or user interaction mid-loop — build your own workflow using `LlmGenerateTextTool` and `LlmDelegateToolCallsTool` directly (see [Building a Custom Agent](https://loopstack.ai/docs/build/ai/agent-workflows#building-a-custom-agent)). ## Installation ```bash npm install @loopstack/agent ``` Register the module and your tools: ```typescript import { Module } from '@nestjs/common'; import { AgentModule } from '@loopstack/agent'; import { ClaudeModule } from '@loopstack/claude'; import { MyWorkflow } from './my.workflow'; import { SearchTool } from './tools/search.tool'; import { SummarizeTool } from './tools/summarize.tool'; @Module({ imports: [ClaudeModule, AgentModule], providers: [MyWorkflow, SearchTool, SummarizeTool], exports: [MyWorkflow], }) export class MyModule {} ``` Tools registered as providers in the module are automatically available to the agent at runtime — resolved by their `@Tool({ name })` value. ## Quick Start Launch an agent from any workflow: ```typescript import { z } from 'zod'; import { AgentWorkflow } from '@loopstack/agent'; import { BaseWorkflow, MessageDocument, Transition, type TransitionInput, Workflow } from '@loopstack/common'; const AgentResponseSchema = z.object({ response: z.string() }); @Workflow({ title: 'My Workflow' }) export class MyWorkflow extends BaseWorkflow { constructor(private readonly agent: AgentWorkflow) { super(); } @Transition({ to: 'running' }) async start(state: Record) { await this.agent.run( { system: 'You are a helpful assistant with access to search and summarize tools.', tools: ['search', 'summarize'], userMessage: 'Find and summarize the latest news about AI.', }, { callback: { transition: 'agentDone' }, show: 'inline', label: 'Agent working...' }, ); } @Transition({ from: 'running', to: 'end', wait: true, schema: AgentResponseSchema }) async agentDone(state: Record, input: TransitionInput<{ response: string }>) { await this.documentStore.save(MessageDocument, { role: 'assistant', text: input.data.response, }); } } ``` The agent loops autonomously until the LLM responds without tool calls, then returns `{ response: string }` via the callback. ## How It Works ### AgentWorkflow Runs a closed-loop LLM agent cycle: ``` setup → ready → llmTurn → prompt_executed ├── [has tool calls] → executeToolCalls → awaiting_tools │ ├── [callback] → toolResultReceived (loop) │ ├── [all complete] → toolsComplete → ready (loop) │ └── [cancel button] → cancelPendingTools → ready └── [end_turn] → respond → end (returns final message) ``` 1. **Setup** — saves the `userMessage` (and optional `context`) as conversation messages. 2. **LLM turn** — calls the LLM with the `system` prompt and resolved `tools`. 3. **Tool execution** — if the LLM requests tool calls, `LlmDelegateToolCallsTool` executes them. For async tools (sub-workflows), callbacks loop through `toolResultReceived`. 4. **Loop** — after all tools complete, loops back to the LLM for the next turn. 5. **Completion** — when the LLM responds without tool calls (`end_turn`), the agent exits and returns `{ response: string }`. ### ChatAgentWorkflow Extends the agent loop with multi-turn user interaction: ``` setup → ready → llmTurn → prompt_executed ├── [has tool calls] → executeToolCalls → awaiting_tools │ ├── [finished] → end (returns finish result) │ ├── [callback] → toolResultReceived (loop) │ ├── [all complete] → toolsComplete → ready (loop) │ └── [cancel button] → cancelPendingTools → ready └── [end_turn] → respond → waiting_for_user └── userMessage → ready (loop) ``` Instead of exiting on `end_turn`, the agent pauses at `waiting_for_user`. The user sends a message via the Studio UI, and the agent loops back. With `taskMode: true`, `AgentFinishTool` is added to the tool set. When the LLM calls it, the agent exits immediately and returns the finish result. ```typescript import { ChatAgentWorkflow } from '@loopstack/agent'; import { BaseWorkflow, Transition, Workflow } from '@loopstack/common'; import type { RunContext } from '@loopstack/common'; @Workflow({ title: 'Chat Assistant', description: 'Interactive chat agent connected to Linear via MCP.', }) export class MyChatWorkflow extends BaseWorkflow { constructor(private readonly chatAgent: ChatAgentWorkflow) { super(); } @Transition({ to: 'chatting' }) async startChat(state: Record) { await this.chatAgent.run( { system: 'You are a helpful assistant.', tools: ['mcp_list_tools', 'mcp_call'], userMessage: 'What tools are available?', }, { show: 'inline', label: 'Chat Agent' }, ); } } ``` Note that `ChatAgentWorkflow.run()` does not need a callback — the chat agent stays running until the user is done (or until `agent_finish` is called in task mode). ### Tool Resolution Tools are resolved by their `@Tool({ name })` value from the NestJS dependency injection container at runtime. The agent workflows only inject their own internal tools (`LlmGenerateTextTool`, `LlmDelegateToolCallsTool`, `LlmUpdateToolResultTool`). Domain-specific tools (e.g. `search`, `glob`, `read`) are resolved from the module's providers when the LLM calls them. Register tools once in your module and they're available to the agent and all other workflows: ```typescript @Module({ imports: [AgentModule], providers: [MyWorkflow, SearchTool, GlobTool, GrepTool], }) export class MyModule {} ``` ### Cancel Pending Tools If the agent is stuck at `awaiting_tools` (e.g. a sub-workflow hasn't returned), a "Cancel pending tools" button appears in the Studio UI. Clicking it cancels all pending child workflows and returns the agent to the LLM loop. ## Args Reference ### AgentWorkflow | Arg | Type | Required | Description | | ------------- | ---------- | -------- | ------------------------------------------------------------------------ | | `system` | `string` | yes | System prompt for the LLM | | `tools` | `string[]` | yes | Tool names available to the LLM (matched by `@Tool({ name })`) | | `userMessage` | `string` | yes | Initial user message to start the conversation | | `context` | `string` | no | Hidden context message saved before `userMessage` (e.g. pre-loaded docs) | | `provider` | `string` | no | LLM provider for this run (defaults to the configured provider) | | `model` | `string` | no | LLM model for this run (defaults to the configured model) | **Returns:** `{ response: string }` — the final LLM text response ### ChatAgentWorkflow | Arg | Type | Required | Description | | ------------- | ---------- | -------- | ---------------------------------------------------------------------------------- | | `system` | `string` | yes | System prompt for the LLM | | `tools` | `string[]` | yes | Tool names available to the LLM | | `userMessage` | `string` | yes | Initial user message to start the conversation | | `context` | `string` | no | Hidden context message saved before `userMessage` | | `taskMode` | `boolean` | no | When `true`, adds `AgentFinishTool` so the agent can exit with a structured result | | `provider` | `string` | no | LLM provider for this run (defaults to the configured provider) | | `model` | `string` | no | LLM model for this run (defaults to the configured model) | **Returns (task mode):** the result passed to `AgentFinishTool` ## Tools Reference ### AgentFinishTool Used internally by `ChatAgentWorkflow` in task mode. The LLM calls this tool when it has completed its task. | Property | Value | | --------------- | ----------------------------------------------------------------------------------------- | | **Name** | `agent_finish` | | **Description** | Call this tool when you have completed the task and are ready to return the final result. | | Arg | Type | Required | Description | | -------- | --------- | -------- | ----------------------------------------- | | `result` | `unknown` | no | The final result to return from the agent | You don't call this tool directly — it's added to the LLM's tool set automatically when `taskMode: true`. ## Configuration ### LLM Provider By default, `AgentModule` uses whatever LLM provider is configured in your app. To configure a specific provider: ```typescript import { AgentModule } from '@loopstack/agent'; @Module({ imports: [ AgentModule.forFeature({ llm: { provider: 'claude', model: 'claude-sonnet-4-5' }, }), ], providers: [MyWorkflow], }) export class MyModule {} ``` To use a different provider or model for a single run, pass `provider` / `model` as args: ```typescript await this.agentWorkflow.run({ system: 'You are a helpful assistant.', tools: [], userMessage: 'Summarize this repository.', provider: 'openai', model: 'gpt-4o', }); ``` ## Public API - **Module:** `AgentModule` (with `forFeature()` for LLM config) - **Workflows:** `AgentWorkflow`, `ChatAgentWorkflow` - **Tools:** `AgentFinishTool` - **Schemas:** `AgentResultSchema`, `AgentFinishResultSchema` - **Types:** `AgentResult`, `AgentFinishResult` ## Dependencies - `@loopstack/common` — `BaseWorkflow`, `BaseTool`, decorators - `@loopstack/core` — `LoopCoreModule`, `WorkflowOrchestrator` - `@loopstack/llm-provider` — `LlmGenerateTextTool`, `LlmDelegateToolCallsTool`, `LlmUpdateToolResultTool`, `LlmMessageDocument` ## Related - [Agent Workflows](https://loopstack.ai/docs/build/ai/agent-workflows) — conceptual guide with custom agent loop examples - [AI Tool Calling](https://loopstack.ai/docs/build/ai/tool-calling) — how LLMs invoke workflow tools via function calling - [Tutorial: Chat Agent with Tools](https://loopstack.ai/docs/tutorials/chat-agent-with-tools) — step-by-step tutorial building a chat agent from scratch - [Creating Tools](https://loopstack.ai/docs/build/fundamentals/tools) — defining custom tools the agent can call - [@loopstack/code-agent](https://loopstack.ai/docs/registry/code-agent) — code exploration agent built on `AgentWorkflow` ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/registry/packages/claims.md --- title: Claims Module description: '@loopstack/claims — resource claims for Loopstack workflows. Exclusive and pooled resources claimed by a run or a workspace, released when their scope ends. Covers mutex, pool-of-N and reader/writer lock patterns with ClaimsModule, the claim tools and run/workspace claim scopes.' --- # @loopstack/claims Resource claims for Loopstack workflows. A workflow that must not run beside another says so by claiming a resource; a claim is a row that lives as long as the run or the workspace it is scoped to. One primitive covers a mutex, a pool of N, and a reader/writer lock: | want | how | | ------------------------- | -------------------------------------------------------------------------------------- | | a resource claimable once | any key, claimed `exclusive` | | five workers | a key with `capacity: 5`, claimed `shared` | | many readers, one writer | a key with `capacity: null`, claimed `shared` by readers and `exclusive` by the writer | ## Install ```bash npm install @loopstack/claims ``` Requires PostgreSQL — the claim transaction takes a `pg_advisory_xact_lock` per resource — and a root `TypeOrmModule.forRoot()` whose schema includes `ResourceClaimEntity`. ## Register ```ts import { ClaimsModule } from '@loopstack/claims'; @Module({ imports: [ ClaimsModule.forRoot({ resources: [ { key: 'engineer:runs', capacity: 6 }, { key: 'area:core', capacity: null }, ], }), ], }) export class AppModule {} ``` A key that is not listed has capacity **1**, which is what lets a key be invented on demand — `pkg:@loopstack/core`, `area:234` — and still be claimable exactly once. Capacity is configured and never passed with a claim: two callers disagreeing about the size of a pool would be a bug with no right answer. ## Claim ```ts const result = await this.claims.claim({ claimedByWorkflowId: ctx.workflowId, label: 'loopstack#432', resources: [ { key: 'engineer:runs', mode: 'shared', scope: 'workflow', workspaceId, scopeWorkflowId: runId }, { key: 'area:core', mode: 'shared', scope: 'workflow', workspaceId, scopeWorkflowId: runId }, { key: 'pkg:@loopstack/core', mode: 'exclusive', scope: 'workflow', workspaceId, scopeWorkflowId: runId }, { key: 'engineer:checkouts', mode: 'shared', scope: 'workspace', workspaceId }, ], }); if (!result.claimed) { // result.blocked names each resource, its capacity, why, and who holds it. } ``` Three properties worth knowing before you use it: - **All or nothing.** Every resource in the request, or none. The list may mix scopes, which is the point: one decision can take a unit of a pool for a workspace and a set of areas for a run. - **Idempotent per resource and scope target.** Claiming a resource an owner already holds, in the same mode, succeeds and writes nothing. So two callers can claim the same thing for the same owner without either knowing about the other — a coordinator claiming on a run's behalf and the run claiming for itself. - **It never waits.** There is no blocking acquire: a task that waits inside its transition holds a queue slot and its workspace lock while doing nothing. A claim either succeeds now or says what blocked it, and the caller decides whether to hold back, park and try later, or report it. ## Scope: how long a claim lives ```ts type ClaimScope = 'workflow' | 'workspace'; ``` - `workflow` — as long as one run. Released when that run settles or is deleted. - `workspace` — as long as the workspace. Released when the workspace is deleted, whatever happens to the run that took it. Scope is declared rather than inferred from who claimed, because the two come apart: a run may take a claim meant to outlive it. `claimedByWorkflowId` records who took it and releases nothing. Scope governs **automatic** release only. Any caller may release early, by claim id, by the run a claim is scoped to, or by workspace. ## A claim cannot be left behind Every read reconciles against the scope target: a claim scoped to a run that has settled or been deleted, or to a workspace that is gone, is ignored. A crashed holder, a cascade delete that emitted no event, a missed event, a process that died between claiming and releasing — none of them hold a resource. The listeners on `workflow.settled`, `workflow.deleted` and `workspace.deleted` mark those rows released so a report reads cleanly. Correctness does not depend on the events arriving. ## Read ```ts const states = await this.claims.availability(['engineer:runs', 'area:core']); // [{ key, capacity, holders: [{ scope, scopeWorkflowId, workspaceId, label, since, mode }], free }] const held = await this.claims.heldBy({ workspaceId }); ``` `free` is the shared units left — `null` when the capacity is unlimited, and `0` while an exclusive holder has it however large the capacity. Availability is **advisory**: between reading it and claiming, anything may change. It is what a decision is made from; the claim is what makes the decision real. `GET /api/v1/workspaces/:workspaceId/claims` lists what a workspace holds, for answering "why has nothing started" without running a workflow to ask. ## Tools `claim_resource`, `release_resource` and `check_resources` wrap the service for workflows that prefer the tool pipeline. They are host-side tools: a claim decides what may run beside what, which is not an agent's decision, so do not expose them to one. --- > Source: https://loopstack.ai/llms/registry/packages/claude.md --- title: Claude Module description: A collection of tools for performing AI actions using the Anthropic Claude API directly via the official SDK. --- # @loopstack/claude ## Installation ```sh npm install @loopstack/claude ``` Register the module in your app module: ```ts import { Module } from '@nestjs/common'; import { ClaudeModule } from '@loopstack/claude'; @Module({ imports: [ClaudeModule], }) export class AppModule {} ``` `ClaudeModule` registers the `claude` provider into the LLM provider registry on startup, so import it alongside `LlmProviderModule` (from `@loopstack/llm-provider`). The module reads the Anthropic API key from the `ANTHROPIC_API_KEY` environment variable: ```env ANTHROPIC_API_KEY=sk-ant-... ``` --- > Source: https://loopstack.ai/llms/registry/packages/claude-tools.md --- title: Claude Tools Module description: Claude-specific tools that consume the LLM provider (e.g. web search using Claude server tools). --- # @loopstack/claude-tools ## Installation ```sh npm install @loopstack/claude-tools ``` Register the module in your app module: ```ts import { Module } from '@nestjs/common'; import { ClaudeToolsModule } from '@loopstack/claude-tools'; @Module({ imports: [ClaudeToolsModule], }) export class AppModule {} ``` `ClaudeToolsModule` requires `LlmProviderModule` to be available in the app and a registered Claude provider (import `ClaudeModule` alongside it), since the tools execute through the `claude` provider — make sure `ANTHROPIC_API_KEY` is set: ```env ANTHROPIC_API_KEY=sk-ant-... ``` To scope the LLM provider/model configuration for these tools, use `forFeature()` instead of the bare import: ```ts ClaudeToolsModule.forFeature({ llm: { model: 'claude-sonnet-4-5' } }); ``` --- > Source: https://loopstack.ai/llms/registry/packages/code-agent.md --- title: Code Agent Module description: AI-powered codebase exploration for Loopstack — ExploreTask tool launches AgentWorkflow sub-agent with glob/grep/read tools, CodeAgentModule registration, forFeature() LLM config, TransitionInput envelope for sub-workflow completion --- # @loopstack/code-agent > Agent workflow module for the [Loopstack](https://loopstack.ai) automation framework. AI-powered code exploration for Loopstack workflows. Provides a tool that launches a sub-agent workflow to search, read, and synthesize findings from a remote workspace using `glob`, `grep`, and `read` tools from `@loopstack/remote-client`. ## When to Use - You need a workflow to **answer questions about a codebase** before acting — locating functions, summarizing features, understanding architecture - You want to **delegate exploration as a single tool call** from a parent workflow or agent - You need a self-contained agent that **iteratively searches and reads files** on a remote workspace and returns a synthesized answer - Use `@loopstack/remote-client` directly if you only need individual file operations without the agent loop ## Installation ```sh npm install @loopstack/code-agent ``` Register the module in your application: ```ts import { Module } from '@nestjs/common'; import { CodeAgentModule } from '@loopstack/code-agent'; @Module({ imports: [CodeAgentModule], }) export class AppModule {} ``` Your app must also configure: - `LlmProviderModule` with a registered LLM provider — `CodeAgentModule` imports `AgentModule` from `@loopstack/agent`, which needs it. - `RemoteClientModule` from `@loopstack/remote-client` (bare or `forRoot`) — it supplies the `glob`, `grep` and `read` tools the `explore_task` sub-agent uses. Without it the app fails at boot with an error naming `RemoteClientModule`. To override the LLM provider or model for this module specifically: ```ts @Module({ imports: [CodeAgentModule.forFeature({ llm: { provider: 'claude', model: 'claude-sonnet-4-20250514' } })], }) export class AppModule {} ``` ## Quick Start The most common pattern is launching the code agent from a parent workflow using `AgentWorkflow` directly: ```ts import { Module } from '@nestjs/common'; import { z } from 'zod'; import { AgentWorkflow } from '@loopstack/agent'; import { CodeAgentModule } from '@loopstack/code-agent'; import { BaseWorkflow, MessageDocument, Transition, type TransitionInput, Workflow } from '@loopstack/common'; const ExploreResponseSchema = z.object({ response: z.string() }); @Workflow({ title: 'Code Agent Example' }) export class MyWorkflow extends BaseWorkflow { constructor(private readonly agentWorkflow: AgentWorkflow) { super(); } @Transition({ to: 'exploring' }) async start(state: Record) { await this.agentWorkflow.run( { system: 'You are a codebase exploration agent. Search and read source code to answer the question thoroughly.', tools: ['glob', 'grep', 'read'], userMessage: 'Find the entry-point module and list its top-level providers.', }, { callback: { transition: 'onExploreComplete' }, show: 'inline', label: 'Exploring codebase...' }, ); } @Transition({ from: 'exploring', to: 'end', wait: true, schema: ExploreResponseSchema }) async onExploreComplete(state: Record, input: TransitionInput<{ response: string }>) { await this.documentStore.save(MessageDocument, { role: 'assistant', text: input.data.response, }); } } @Module({ imports: [CodeAgentModule], providers: [MyWorkflow], exports: [MyWorkflow, CodeAgentModule], }) export class MyModule {} ``` ## How It Works ### State Machine ``` start ──► exploring (wait) ──► end │ ▲ └── callback ───────┘ ``` 1. The parent workflow calls `agentWorkflow.run()` with a system prompt, tool list, and user message 2. The `AgentWorkflow` sub-workflow starts its own agent loop: LLM generates text, calls tools (`glob`, `grep`, `read`), loops until it produces a final answer 3. The orchestrator renders the sub-workflow inline in the parent's UI based on the `show` option (`'inline'` by default) 4. When the agent finishes, it calls back to the parent workflow's wait transition with `{ data: { response } }` 5. The parent receives the synthesized answer and can display it or act on it ### ExploreTask Tool The module also provides `ExploreTask`, a tool wrapper around `AgentWorkflow` that can be used by other agents: ``` Parent Agent ──► explore_task tool call ──► AgentWorkflow sub-agent │ glob/grep/read loop │ synthesized answer │ ◄── complete() callback ``` `ExploreTask` launches the sub-agent and returns `{ workflowId }` with `pending` status. The orchestrator renders the sub-agent inline in the parent's view. When the sub-agent completes, `ExploreTask.complete()` returns the response text. ## Args Reference ### AgentWorkflow.run() | Arg | Type | Required | Description | | ------------- | ---------- | -------- | -------------------------------------------------------------- | | `system` | `string` | Yes | System prompt for the agent | | `tools` | `string[]` | Yes | Tool names to make available (e.g. `['glob', 'grep', 'read']`) | | `userMessage` | `string` | Yes | The question or instruction for the agent | | `context` | `string` | No | Additional context to include in the conversation | Second argument (options): | Arg | Type | Required | Description | | --------------------- | -------- | -------- | ----------------------------------------------- | | `callback.transition` | `string` | No | Transition name to call when the agent finishes | **Returns:** `QueueResult` with `{ workflowId: string }` ### Callback Envelope The parent's wait transition receives a `TransitionInput`. Pass only the `data` shape as the schema — the framework wraps it: ```ts const ExploreResponseSchema = z.object({ response: z.string() }); // Receiver: input: TransitionInput<{ response: string }> ``` | Field | Type | Description | | --------------------- | ---------------- | --------------------------------------------------------- | | `input.workflowId` | `string` | ID of the completed sub-workflow | | `input.status` | enum | `'completed'` / `'failed'` / `'canceled'` | | `input.hasError` | `boolean` | Whether the sub-agent terminated in failure | | `input.errorMessage` | `string \| null` | Error description when `hasError` | | `input.data.response` | `string` | The agent's synthesized text answer (validated by schema) | ## Tools Reference ### explore_task | Field | Value | | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Name** | `explore_task` | | **Description** | Launch a sub-agent to explore and analyze the codebase. The agent uses glob, grep, and read tools to search for files and code patterns, then returns a synthesized summary. | **Args (Zod schema):** | Arg | Type | Required | Description | | -------------- | -------- | -------- | --------------------------------------------------------- | | `instructions` | `string` | Yes | Detailed instructions for what to explore in the codebase | **Returns:** `ToolEnvelope` - On launch: `{ data: { workflowId }, pending: { workflowId } }` - On complete: `{ data: string }` — the agent's synthesized response text ## Configuration ### CodeAgentModule.forFeature() Override the LLM provider or model for the code agent specifically: ```ts CodeAgentModule.forFeature({ llm: { provider: 'claude', // LLM provider name model: 'claude-sonnet-4-20250514', // Model identifier }, }); ``` | Option | Type | Required | Description | | -------------- | -------- | -------- | ----------------- | | `llm.provider` | `string` | No | LLM provider name | | `llm.model` | `string` | No | Model identifier | ## Public API - **Module:** `CodeAgentModule` - **Tool:** `ExploreTask` - **Schema:** `ExploreTaskResultSchema` - **Type:** `ExploreTaskResult` ## Dependencies | Package | Role | | -------------------------- | ------------------------------------------------------------- | | `@loopstack/agent` | `AgentWorkflow` — generic LLM agent loop with tool calling | | `@loopstack/common` | `BaseTool`, `BaseWorkflow`, decorators, document types | | `@loopstack/core` | Workflow engine, scheduling, state management | | `@loopstack/remote-client` | `glob`, `grep`, `read` tools executed on the remote workspace | | `@nestjs/common` | NestJS dependency injection | | `zod` | Schema validation | ## Related - [Code Agent example](/docs/examples/agent#code-agent) — full working example showing `AgentWorkflow` with glob/grep/read - [Agent Workflows](https://loopstack.ai/docs/build/ai/agent-workflows) — how the agent loop, tool resolution, and callbacks work - [`@loopstack/agent`](https://loopstack.ai/docs/registry/agent) — the generic `AgentWorkflow` that powers the code agent - [`@loopstack/remote-client`](https://loopstack.ai/docs/registry/remote-client) — the `glob`, `grep`, and `read` tools used by the agent ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/registry/packages/code-workspace.md --- title: Code Workspace Module description: '@loopstack/code-workspace — one checkout per workspace from shared generational bases, worked in disposable Docker containers. Provisioning, inventory and reclamation of repos, checkouts, containers and volumes with CodeWorkspaceModule and CodeWorkspaceMaintenanceModule.' --- # @loopstack/code-workspace One checkout of a codebase per workspace, cloned from a shared base and worked in disposable Docker containers. Provisioning, inventory and reclamation — the whole life of that state. Domain-neutral: it knows about repos, checkouts, containers and volumes, and nothing about what you do in them. ## Install ```bash npm install @loopstack/code-workspace ``` Requires **PostgreSQL** (the inventory joins against the workflow and workspace tables) and **Docker on the host**, reachable by the process. ## Register ```ts import { CodeWorkspaceModule } from '@loopstack/code-workspace'; @Module({ imports: [ CodeWorkspaceModule.forRoot({ stateDir: '~/.my-app', namespace: 'acme.sandbox', }), ], }) export class AppModule {} ``` `forRootAsync({ inject, useFactory })` is there for configuration that comes from the environment. **`namespace`** is how the module finds its own things again: every container and volume it creates is labelled `.workspace` and `.workflow` and named from the same string, and every sweep filters on exactly those. Two applications with different namespaces never see — or remove — each other's containers. It defaults to `loopstack`, which yields `loopstack.workspace` and `loopstack.workflow`. ❗ Changing it on a running installation makes everything created under the old one invisible to the sweep. Reclaim first, then change it. ## Provisioning Inject the provisioner through its token, never the class, so another implementation can take its place: ```ts constructor(@Inject(CODE_WORKSPACE_PROVISIONER) private readonly workspace: CodeWorkspaceProvisioner) {} ``` - **Bases** are shared, immutable and generational, keyed by the hash of their provision config — the repos, the setup commands, the seed images. A build holds its base with an exclusive claim scoped to the run doing it, so two runs cannot build the same generation twice and a build whose process died frees its base by itself. A second provision of a base already being built is refused, not queued. Several workspaces with the same config share one, and a published generation is never mutated: a refresh copies it, updates the copy, and swaps a `current` pointer, so a checkout reads the generation it resolved and nothing else changes under it. - **Checkouts** are one clone of a base per workspace, created by the first run that needs it and used as it is by every later run in that workspace — nothing fetches, resets or re-clones it. Cheap (the git object store and the build output are cloned copy-on-write or hardlinked) and safe (git and npm unlink and rewrite, so a workspace never mutates the base). - **Containers** mount the checkout and are explicitly torn down, so a crashed one keeps its logs until something removes it. Containers and dind volumes belong to the run that started them. ## Reclamation Three ways, and the first needs nothing from you: 1. **Automatic.** A listener on `workspace.deleted` releases that workspace's containers, volumes and files. It runs in the background — `emit` does not await an async listener — and never throws, because nothing is waiting to catch it. A run owns no files; it tears its own containers down. 2. **By inventory.** `WorkspaceInventoryService.scan()` returns what exists on disk and in Docker, joined against the workflow and workspace tables, and `orphanPlan(inventory, knownBaseKeys)` says what has no owner left: workspace state whose row was deleted, containers and volumes of deleted runs, and bases no config declares any more. `renderInventory` and `renderOrphanPlan` give you the Markdown. 3. **Directly.** `removeWorkspaceState`, `removeWorkflowContainers` with `removeWorkflowVolumes`, `removeBase` and `collectBaseGenerations`, all idempotent, all in dependency order: containers, then volumes, then files, so a failure at any step leaves the operation re-runnable. Nothing here asks before it removes. **Whether to confirm is the application's decision** — put a confirmation in front of calls 2 and 3 if your users should have one. `CodeWorkspaceMaintenanceModule` is one ready-made answer, imported separately: ```ts import { CodeWorkspaceMaintenanceModule } from '@loopstack/code-workspace'; ``` It adds a Studio app with two workflows. **State Report** lists every workspace with its sizes, checkouts, containers and volumes, and flags what has no owner left — read-only, and the only view that shows state which is _not_ an orphan, which is what you decide against when choosing what to delete. **Clean Up Orphaned State** then removes what nothing owns, after showing you exactly what that is. Both read `knownBaseKeys` from the module's options. Leave it unset and no base is ever proposed for removal, which is the safe reading of "none declared". ## The git routes `RepoGitClient` posts to `/git/clone`, `/git/fetch` and `/git/push` on the in-container agent. Those three carry a **token**, and the agent applies it through a throwaway `GIT_ASKPASS` so it never reaches the URL, the argv or `.git/config`. Every other git command is a plain `executeCommand(agentUrl, cmd, dir)`. So a consumer needs an agent image whose server implements those three routes. Everything else the module asks of the container is ordinary command execution. --- > Source: https://loopstack.ai/llms/registry/packages/docker-sandbox.md --- title: Sandbox Tool description: Docker sandbox tool for Loopstack — SandboxToolModule, SandboxInit, SandboxCommand, SandboxDestroy tools, DockerContainerManagerService. Create isolated Docker containers, execute commands, manage container lifecycle in workflows. --- # @loopstack/docker-sandbox > Sandbox execution module for the [Loopstack](https://loopstack.ai) automation framework. Provides isolated Docker-based execution environments for running untrusted or experimental code safely within Loopstack workflows. It manages container lifecycle (create, execute, destroy) and mounts host directories into containers for file exchange. ## When to Use - You need to run untrusted or AI-generated code in a sandboxed environment - Your workflow requires executing commands in specific runtime environments (Node.js, Python, etc.) without affecting the host - You want disposable containers that are created, used, and destroyed within a single workflow run - Pair with [`@loopstack/docker-sandbox-filesystem`](https://loopstack.ai/docs/registry/docker-sandbox-filesystem) when you also need file read/write operations inside the container ## Installation ```bash npm install @loopstack/docker-sandbox ``` **Prerequisite:** Docker must be installed and running on the host system. Register the module in your NestJS module: ```typescript import { Module } from '@nestjs/common'; import { SandboxToolModule } from '@loopstack/docker-sandbox'; @Module({ imports: [SandboxToolModule], providers: [MyWorkflow], exports: [MyWorkflow], }) export class MyModule {} ``` ## Quick Start Inject the tool classes via the constructor, then call them in your transitions: ```typescript import { z } from 'zod'; import { BaseWorkflow, Transition, Workflow } from '@loopstack/common'; import type { RunContext } from '@loopstack/common'; import { SandboxCommand, SandboxDestroy, SandboxInit } from '@loopstack/docker-sandbox'; interface SandboxState { containerId?: string; } const MySandboxArgsSchema = z.object({ outputDir: z.string().default(process.cwd() + '/out'), }); type MySandboxArgs = z.infer; @Workflow({ schema: MySandboxArgsSchema, }) export class MySandboxWorkflow extends BaseWorkflow { constructor( private readonly sandboxInit: SandboxInit, private readonly sandboxCommand: SandboxCommand, private readonly sandboxDestroy: SandboxDestroy, ) { super(); } @Transition({ to: 'sandbox_ready' }) async createSandbox(state: SandboxState, ctx: RunContext) { const result = await this.sandboxInit.call({ containerId: 'my-sandbox', imageName: 'node:18', containerName: 'my-node-sandbox', projectOutPath: ctx.args.outputDir, rootPath: 'workspace', }); this.assignState({ containerId: result.data.containerId }); } @Transition({ from: 'sandbox_ready', to: 'code_executed' }) async runCode(state: SandboxState) { await this.sandboxCommand.call({ containerId: state.containerId!, executable: 'node', args: ['-e', "console.log('Hello from sandbox!')"], workingDirectory: '/workspace', timeout: 30000, }); } @Transition({ from: 'code_executed', to: 'end' }) async cleanup(state: SandboxState) { await this.sandboxDestroy.call({ containerId: state.containerId!, removeContainer: true, }); } } ``` ## How It Works The module manages Docker containers through a three-step lifecycle: ``` sandbox_init --> sandbox_command (repeatable) --> sandbox_destroy ``` 1. **Init** creates (or reuses) a Docker container from a specified image, mounts a host directory, and keeps the container alive with `sleep infinity`. `sandbox_init` is **idempotent** — calling it again with the same `containerId` reuses the existing container instead of creating a duplicate, so workflows don't need to track container state themselves. 2. **Command** executes shell commands inside the running container via `docker exec`. Commands are shell-escaped to prevent injection. `stdout` and `stderr` are captured **separately** on the result. By default, output is trimmed of leading and trailing whitespace. A configurable timeout (default 30s) kills runaway processes — when a timeout fires, the result has `timedOut: true` and `exitCode: -1`, and stdout/stderr contain whatever was emitted before the kill. 3. **Destroy** stops and optionally removes the container, freeing resources. The `DockerContainerManagerService` handles the underlying Docker operations: image pulling, container creation, volume binding, stream demuxing, and concurrent access serialization via per-container locks. It implements `OnModuleDestroy` to stop all managed containers when the NestJS application shuts down. ### Security - **Path traversal prevention** — working directories are normalized and checked for `..` sequences - **Shell argument escaping** — all executable names and arguments are single-quote escaped - **Isolated containers** — code runs in Docker containers with only the mounted volume accessible - **Configurable timeouts** — commands that exceed the timeout are killed and return `timedOut: true` ## Tools Reference ### `sandbox_init` Initialize a new sandbox container. | Arg | Type | Required | Description | | ---------------- | -------- | ------------------------- | ----------------------------------------------------------- | | `containerId` | `string` | Yes | Unique identifier for this container instance | | `imageName` | `string` | Yes | Docker image to use (e.g., `node:18`, `python:3.11`) | | `containerName` | `string` | Yes | Name for the Docker container | | `projectOutPath` | `string` | Yes | Host path to mount into the container | | `rootPath` | `string` | No (default: `workspace`) | Path inside the container where `projectOutPath` is mounted | **Returns:** `{ containerId: string; dockerId: string }` ### `sandbox_command` Execute a command inside a running sandbox container. | Arg | Type | Required | Description | | ------------------ | ---------- | --------------------- | ------------------------------------------------- | | `containerId` | `string` | Yes | ID of the registered container | | `executable` | `string` | Yes | Executable to run (e.g., `npm`, `node`, `python`) | | `args` | `string[]` | No | Arguments to pass to the executable | | `workingDirectory` | `string` | No (default: `/`) | Working directory for execution | | `envVars` | `string[]` | No | Environment variables in `KEY=VALUE` format | | `timeout` | `number` | No (default: `30000`) | Timeout in milliseconds | **Returns:** `{ stdout: string; stderr: string; exitCode: number; timedOut: boolean }` ### `sandbox_destroy` Stop and destroy a sandbox container. | Arg | Type | Required | Description | | ----------------- | --------- | -------------------- | ----------------------------------------------- | | `containerId` | `string` | Yes | ID of the container to destroy | | `removeContainer` | `boolean` | No (default: `true`) | Whether to remove the container or just stop it | **Returns:** `{ containerId: string; removed: boolean }` ## Public API **Module** - `SandboxToolModule` — NestJS module that registers all tools and services **Tools** - `SandboxInit` — `@Tool({ name: 'sandbox_init' })` — create and start a container - `SandboxCommand` — `@Tool({ name: 'sandbox_command' })` — execute a command in a container - `SandboxDestroy` — `@Tool({ name: 'sandbox_destroy' })` — stop/remove a container **Services** - `DockerContainerManagerService` — low-level Docker container management (register, ensure, execute, stop, remove) **Types** - `ContainerConfig` — configuration for a registered container - `CommandExecutionResult` — stdout, stderr, exitCode, timedOut - `DOCKER_CLIENT` — injection token for providing a custom `Docker` (dockerode) instance ## Dependencies | Package | Role | | ------------------- | -------------------------------------------- | | `@loopstack/common` | Base tool class, decorators, types | | `@nestjs/common` | NestJS dependency injection | | `zod` | Schema validation for tool args | | `dockerode` | Docker Engine API client (direct dependency) | ## Related - [Sandbox Execution docs](https://loopstack.ai/docs/build/integrations/sandbox) — setup guide, available tools across both sandbox packages, and security details - [@loopstack/docker-sandbox-filesystem](https://loopstack.ai/docs/registry/docker-sandbox-filesystem) — file read/write/delete/list operations inside sandbox containers - [Sandbox example](/docs/examples/sandbox#sandbox) — full sandbox lifecycle example using both `@loopstack/docker-sandbox` and `@loopstack/docker-sandbox-filesystem` ## About Author: Tobias Blattermann, Jakob Klippel License: MIT --- > Source: https://loopstack.ai/llms/registry/packages/docker-sandbox-filesystem.md --- title: Sandbox Filesystem description: SandboxFilesystemModule providing SandboxWriteFile, SandboxReadFile, SandboxListDirectory, SandboxCreateDirectory, SandboxDelete, SandboxExists, SandboxFileInfo tools for secure file operations inside Docker containers. Depends on @loopstack/docker-sandbox. --- # @loopstack/docker-sandbox-filesystem > Sandbox filesystem module for the [Loopstack](https://loopstack.ai) automation framework. Provides secure filesystem operations inside Docker sandbox containers. Use it alongside `@loopstack/docker-sandbox` to read, write, list, create, delete, and inspect files and directories in isolated environments without risking the host system. ## When to Use - You need to read or write files inside an isolated Docker container (e.g., code execution sandboxes, build pipelines) - Your workflow generates untrusted or AI-produced files and you want filesystem access confined to a container - You want structured directory listing, existence checks, or file metadata from inside a sandbox - You already use `@loopstack/docker-sandbox` for container lifecycle and need filesystem operations on top ## Installation ```bash npm install @loopstack/docker-sandbox-filesystem @loopstack/docker-sandbox ``` Import `SandboxFilesystemModule` in your module. It automatically imports `SandboxToolModule`, so container lifecycle tools (`SandboxInit`, `SandboxDestroy`, `SandboxCommand`) are available too. ```typescript import { Module } from '@nestjs/common'; import { SandboxFilesystemModule } from '@loopstack/docker-sandbox-filesystem'; @Module({ imports: [SandboxFilesystemModule], providers: [MyWorkflow], exports: [MyWorkflow], }) export class MyModule {} ``` ## Quick Start ```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, 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({ 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, }); } } ``` ## How It Works All filesystem tools delegate to `SandboxCommand` from `@loopstack/docker-sandbox`, which executes shell commands (`cat`, `mkdir`, `rm`, `stat`, `find`) inside the Docker container via the Docker exec API. Content is transferred safely using base64 encoding. ``` start ──> sandbox_ready ──> file_written ──> file_read ──> end | | | | | v v v v v SandboxInit mkdir/write read cleanup SandboxDestroy ``` Container lifecycle (`SandboxInit` / `SandboxDestroy`) comes from `@loopstack/docker-sandbox`. This module adds the filesystem layer on top. ## Tools Reference Every tool requires a `containerId` argument that references a container created by `SandboxInit`. ### sandbox_write_file Write content to a file in a sandbox container. | Arg | Type | Required | Description | | ------------------ | -------------------- | --------------------- | ------------------------------------ | | `containerId` | `string` | Yes | Container ID | | `path` | `string` | Yes | File path inside the container | | `content` | `string` | Yes | Content to write | | `encoding` | `'utf8' \| 'base64'` | No (default `'utf8'`) | Content encoding | | `createParentDirs` | `boolean` | No (default `true`) | Create parent directories if missing | **Returns:** `{ path: string, bytesWritten: number }` ### sandbox_read_file Read file contents from a sandbox container. | Arg | Type | Required | Description | | ------------- | -------------------- | --------------------- | ------------------------------ | | `containerId` | `string` | Yes | Container ID | | `path` | `string` | Yes | File path inside the container | | `encoding` | `'utf8' \| 'base64'` | No (default `'utf8'`) | Encoding to use when reading | **Returns:** `{ content: string, encoding: string }` ### sandbox_list_directory List files and directories in a sandbox container. | Arg | Type | Required | Description | | ------------- | --------- | -------------------- | ----------------------------------- | | `containerId` | `string` | Yes | Container ID | | `path` | `string` | Yes | Directory path inside the container | | `recursive` | `boolean` | No (default `false`) | List recursively | **Returns:** `{ path: string, entries: Array<{ name: string, type: 'file' | 'directory' | 'symlink' | 'other', size: number, path: string }> }` ### sandbox_create_directory Create a directory in a sandbox container. | Arg | Type | Required | Description | | ------------- | --------- | ------------------- | ------------------------------------ | | `containerId` | `string` | Yes | Container ID | | `path` | `string` | Yes | Directory path to create | | `recursive` | `boolean` | No (default `true`) | Create parent directories if missing | **Returns:** `{ path: string, created: boolean }` ### sandbox_delete Delete a file or directory in a sandbox container. | Arg | Type | Required | Description | | ------------- | --------- | -------------------- | ----------------------------------- | | `containerId` | `string` | Yes | Container ID | | `path` | `string` | Yes | Path to delete | | `recursive` | `boolean` | No (default `false`) | Recursively delete directories | | `force` | `boolean` | No (default `false`) | Force deletion without confirmation | **Returns:** `{ path: string, deleted: boolean }` ### sandbox_exists Check if a file or directory exists in a sandbox container. | Arg | Type | Required | Description | | ------------- | -------- | -------- | ------------- | | `containerId` | `string` | Yes | Container ID | | `path` | `string` | Yes | Path to check | **Returns:** `{ path: string, exists: boolean, type: 'file' | 'directory' | 'symlink' | 'other' | null }` ### sandbox_file_info Get detailed information about a file or directory in a sandbox container. | Arg | Type | Required | Description | | ------------- | -------- | -------- | --------------- | | `containerId` | `string` | Yes | Container ID | | `path` | `string` | Yes | Path to inspect | **Returns:** `{ path: string, name: string, type: 'file' | 'directory' | 'symlink' | 'other', size: number, permissions: string, owner: string, group: string, modifiedAt: string, accessedAt: string, createdAt: string }` ## Public API - **Module:** `SandboxFilesystemModule` - **Tools:** `SandboxWriteFile`, `SandboxReadFile`, `SandboxListDirectory`, `SandboxCreateDirectory`, `SandboxDelete`, `SandboxExists`, `SandboxFileInfo` ## Dependencies | Package | Role | | --------------------------- | ------------------------------------------------------------------------------------------------------------------ | | `@loopstack/common` | Base tool class, decorators, types | | `@loopstack/docker-sandbox` | Container lifecycle (`SandboxInit`, `SandboxDestroy`) and `SandboxCommand` used internally by all filesystem tools | | `@nestjs/common` | NestJS dependency injection | | `zod` | Schema validation | ## Related - [Sandbox Execution](https://loopstack.ai/docs/build/integrations/sandbox) -- Setup guide, full tool table, and security details for sandbox containers - [Sandbox example](/docs/examples/sandbox#sandbox) -- Complete example covering init, create directory, write/read files, list, exists, file info, delete, and destroy - [@loopstack/docker-sandbox](https://loopstack.ai/docs/registry/docker-sandbox) -- Container lifecycle and command execution (required companion package) ## About Author: Tobias Blattermann, Jakob Klippel License: MIT --- > Source: https://loopstack.ai/llms/registry/packages/git.md --- title: Git Module description: Git version control tools for Loopstack workflows — GitStatusTool, GitAddTool, GitCommitTool, GitPushTool, GitPullTool, GitLogTool, GitDiffTool, GitFetchTool, GitCheckoutTool, GitBranchTool, GitRemoteConfigureTool, GitConfigUserTool, GitWorktreeAddTool, GitWorktreeListTool, GitWorktreeRemoveTool, GitWorktreePruneTool, GitModule, GitController REST API, forFeature configuration --- # @loopstack/git > Git version control module for the [Loopstack](https://loopstack.ai) automation framework. Provides 16 workflow tools that cover the full git lifecycle -- status, staging, commits, branches, remotes, worktrees, and more. Every tool delegates to a remote agent via `RemoteClient`, so the actual `git` commands run on the machine that hosts the repository, not on the workflow host. ## When to Use - You need a workflow to inspect, stage, commit, or push changes in a git repository. - You want to automate branch management (create, checkout, list) as part of a CI or agent workflow. - You need parallel working directories via git worktrees for concurrent tasks. - You want REST endpoints for a UI (e.g. the Loopstack Studio diff viewer) to trigger git operations without starting a workflow. ## Installation ```sh npm install @loopstack/git ``` Register the module in your app module: ```ts import { Module } from '@nestjs/common'; import { GitModule } from '@loopstack/git'; @Module({ imports: [GitModule], }) export class AppModule {} ``` `GitModule` depends on `RemoteClientModule` being available in the DI container (typically wired up in your app's root module). ### Feature gating Use `forFeature()` to restrict the module to specific environments: ```ts GitModule.forFeature({ enabled: true, environments: ['production'] }); ``` ## Quick Start A workflow that checks status, stages all files, commits, and reads back the log: ```ts import { BaseWorkflow, MessageDocument, Transition, Workflow } from '@loopstack/common'; import { GitAddTool, GitCommitTool, GitLogTool, GitStatusTool } from '@loopstack/git'; @Workflow({ title: 'Git Commit Flow' }) export class CommitWorkflow extends BaseWorkflow { constructor( private readonly gitStatus: GitStatusTool, private readonly gitAdd: GitAddTool, private readonly gitCommit: GitCommitTool, private readonly gitLog: GitLogTool, ) { super(); } @Transition({ to: 'staged' }) async checkAndStage(state: Record) { const status = await this.gitStatus.call(); await this.documentStore.save(MessageDocument, { role: 'assistant', text: `Status: ${JSON.stringify(status.data, null, 2)}`, }); await this.gitAdd.call({ files: ['.'] }); } @Transition({ from: 'staged', to: 'end' }) async commitAndLog(_state: Record) { await this.gitCommit.call({ message: 'chore: automated commit' }); const log = await this.gitLog.call({ limit: 1 }); await this.documentStore.save(MessageDocument, { role: 'assistant', text: `Committed: ${JSON.stringify(log.data, null, 2)}`, }); } } ``` Register the workflow alongside `GitModule`: ```ts import { Module } from '@nestjs/common'; import { GitModule } from '@loopstack/git'; import { CommitWorkflow } from './commit.workflow'; @Module({ imports: [GitModule], providers: [CommitWorkflow], exports: [CommitWorkflow], }) export class CommitModule {} ``` ## Tools Reference Every tool is a NestJS provider resolved via `@Tool({ name })`. Inject the tool class directly in your workflow constructor. ### Core Operations #### `git_status` Gets the git status of the workspace. Returns current branch, staged, modified, untracked, and deleted files. | Arg | Type | Required | Description | | -------- | ---- | -------- | ------------ | | _(none)_ | | | No arguments | **Returns:** `{ branch: string; staged: string[]; modified: string[]; untracked: string[]; deleted: string[] }` --- #### `git_add` Stages files for the next git commit. | Arg | Type | Required | Description | | ------- | ---------- | -------- | ------------------------------------------------------ | | `files` | `string[]` | Yes | File paths to stage. Use `["."]` to stage all changes. | **Returns:** `{ success: boolean }` --- #### `git_commit` Creates a git commit with the currently staged changes. | Arg | Type | Required | Description | | --------- | -------- | -------- | ------------------ | | `message` | `string` | Yes | The commit message | **Returns:** `{ hash: string; message: string }` --- #### `git_diff` Shows changed files in the workspace. Returns file paths and their change status. | Arg | Type | Required | Description | | -------- | --------- | -------- | --------------------------------------- | | `staged` | `boolean` | No | Show staged changes instead of unstaged | **Returns:** `{ files: { path: string; status: string }[] }` --- #### `git_log` Shows the git commit log for the workspace repository. | Arg | Type | Required | Description | | ------- | -------- | -------- | ----------------------------------------------------- | | `limit` | `number` | No | Maximum number of log entries to return (default: 20) | **Returns:** `{ commits: { hash: string; shortHash: string; message: string; author: string; date: string }[] }` ### Remote Operations #### `git_fetch` Fetches refs and objects from a remote repository without merging. | Arg | Type | Required | Description | | -------- | -------- | -------- | -------------------------------- | | `remote` | `string` | No | Remote name (defaults to origin) | | `token` | `string` | No | Access token for authentication | **Returns:** `{ success: boolean; output?: string }` --- #### `git_pull` Pulls changes from a remote repository. | Arg | Type | Required | Description | | -------- | -------- | -------- | -------------------------------- | | `remote` | `string` | No | Remote name (defaults to origin) | | `branch` | `string` | No | Branch to pull | | `token` | `string` | No | Access token for authentication | **Returns:** `{ success: boolean; output?: string }` --- #### `git_push` Pushes commits to a remote repository. | Arg | Type | Required | Description | | -------- | --------- | -------- | -------------------------------- | | `remote` | `string` | No | Remote name (defaults to origin) | | `branch` | `string` | No | Branch to push | | `force` | `boolean` | No | Force push | | `token` | `string` | No | Access token for authentication | **Returns:** `{ success: boolean; output?: string }` --- #### `git_remote_configure` Configures a git remote. Adds the remote if not present, or updates its URL. | Arg | Type | Required | Description | | ----- | -------- | -------- | ----------------------------- | | `url` | `string` | Yes | Remote repository URL (HTTPS) | **Returns:** `{ success: boolean }` ### Branch Operations #### `git_branch` Lists all local git branches and indicates the current branch. | Arg | Type | Required | Description | | -------- | ---- | -------- | ------------ | | _(none)_ | | | No arguments | **Returns:** `{ current: string; branches: { name: string; isCurrent: boolean }[] }` --- #### `git_checkout` Switches to a different git branch, optionally creating it. | Arg | Type | Required | Description | | -------- | --------- | -------- | -------------------------------------- | | `branch` | `string` | Yes | Branch name to switch to | | `create` | `boolean` | No | Create the branch if it does not exist | **Returns:** `{ branch: string }` ### Configuration #### `git_config_user` Configures git user.name and user.email for the workspace repository. | Arg | Type | Required | Description | | ------- | -------- | -------- | --------------------------- | | `name` | `string` | Yes | Git user name (user.name) | | `email` | `string` | Yes | Git user email (user.email) | **Returns:** `{ success: boolean }` ### Worktree Operations #### `git_worktree_add` Creates a new git worktree at the given path. Optionally checks out an existing branch or creates a new one. | Arg | Type | Required | Description | | ----------- | --------- | -------- | -------------------------------------------------------------- | | `path` | `string` | Yes | Filesystem path for the new worktree (relative or absolute) | | `branch` | `string` | No | Branch to check out in the new worktree | | `newBranch` | `boolean` | No | Create the branch as part of adding the worktree (passes `-b`) | | `force` | `boolean` | No | Pass `--force` to git worktree add | **Returns:** `{ success: boolean; path: string; output?: string }` --- #### `git_worktree_list` Lists all git worktrees attached to the repository. | Arg | Type | Required | Description | | -------- | ---- | -------- | ------------ | | _(none)_ | | | No arguments | **Returns:** `{ worktrees: { path: string; head?: string; branch?: string; bare: boolean; detached: boolean; locked?: string; prunable?: string }[] }` --- #### `git_worktree_remove` Removes a git worktree at the given path. | Arg | Type | Required | Description | | ------- | --------- | -------- | ---------------------------------------------------------------- | | `path` | `string` | Yes | Path of the worktree to remove | | `force` | `boolean` | No | Remove even if the worktree has uncommitted changes or is locked | **Returns:** `{ success: boolean }` --- #### `git_worktree_prune` Prunes worktree administrative files for worktrees whose directories no longer exist. | Arg | Type | Required | Description | | -------- | ---- | -------- | ------------ | | _(none)_ | | | No arguments | **Returns:** `{ success: boolean; output?: string }` ## REST API `GitController` exposes endpoints under `/api/v1/workspaces/:workspaceId/git` for use by frontends (e.g. the Studio diff viewer): | Method | Path | Description | | -------- | -------------- | ----------------- | | `GET` | `/status` | Get git status | | `GET` | `/log?limit=N` | Get commit log | | `GET` | `/remote` | Get remote info | | `GET` | `/branches` | List branches | | `DELETE` | `/remote` | Remove the remote | ## Public API - **Module:** `GitModule` (with `forFeature()` for environment gating) - **Controller:** `GitController` - **Tools:** `GitStatusTool`, `GitAddTool`, `GitCommitTool`, `GitPushTool`, `GitPullTool`, `GitLogTool`, `GitDiffTool`, `GitFetchTool`, `GitCheckoutTool`, `GitBranchTool`, `GitRemoteConfigureTool`, `GitConfigUserTool`, `GitWorktreeAddTool`, `GitWorktreeListTool`, `GitWorktreeRemoveTool`, `GitWorktreePruneTool` - **Types:** `GitStatusResult`, `GitAddArgs`, `GitAddResult`, `GitCommitArgs`, `GitCommitResult`, `GitPushArgs`, `GitPushResult`, `GitPullArgs`, `GitPullResult`, `GitLogArgs`, `GitCommit`, `GitLogResult`, `GitDiffArgs`, `GitDiffFile`, `GitDiffResult`, `GitFetchArgs`, `GitFetchResult`, `GitCheckoutArgs`, `GitCheckoutResult`, `GitBranchResult`, `GitRemoteConfigureArgs`, `GitRemoteConfigureResult`, `GitConfigUserArgs`, `GitConfigUserResult`, `GitWorktreeAddArgs`, `GitWorktreeAddResult`, `GitWorktreeListResult`, `GitWorktree`, `GitWorktreeRemoveArgs`, `GitWorktreeRemoveResult`, `GitWorktreePruneResult` - **Schemas:** `GitWorktreeAddSchema`, `GitWorktreeRemoveSchema` ## Dependencies | Package | Role | | ----------------------------- | ------------------------------------------------------------------------------------------ | | `@loopstack/common` | `BaseTool`, `@Tool`, `@Transition`, `@Workflow` decorators, `RunContext` | | `@loopstack/remote-client` | `RemoteClient` and `EnvironmentService` -- every tool delegates git commands through these | | `@nestjs/common` | NestJS module and DI infrastructure | | `@nestjs/typeorm` / `typeorm` | Workspace persistence | | `zod` | Tool argument schemas | ## Related - [Git examples](/docs/examples/git) -- includes the Git Commit Flow workflow: status, add, commit, and log in a multi-step workflow - [`@loopstack/github`](https://loopstack.ai/docs/registry/github) -- GitHub integration (PRs, issues, actions) that pairs well with git operations - [`@loopstack/remote-client`](https://loopstack.ai/docs/registry/remote-client) -- the underlying transport layer that git tools delegate to - [Tools documentation](https://loopstack.ai/docs/build/fundamentals/tools) -- how `@Tool`, `BaseTool`, and tool DI work in Loopstack ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/registry/packages/github.md --- title: GitHub Module description: GitHub OAuth provider and 25 API tools for Loopstack workflows — GitHubModule, GitHubOAuthProvider, OAuthProviderInterface, repositories, issues, pull requests, actions, content/git ops, search, users/orgs. Covers installation, tool args, auth pattern, and env vars. --- # @loopstack/github > GitHub integration module for the [Loopstack](https://loopstack.ai) automation framework. Provides a GitHub OAuth 2.0 provider and 25 tools for interacting with the GitHub API. The module registers a GitHub OAuth provider with `@loopstack/oauth` so workflows can authenticate users and then call GitHub tools for repositories, issues, pull requests, file content, actions, search, and user/org data. ## When to Use - You need to **authenticate users via GitHub OAuth** and call GitHub APIs from workflows - You want to **manage repositories, issues, and pull requests** programmatically (list, create, merge) - You need to **read or write file content**, browse directories, or inspect commits in GitHub repos - You want to **trigger and monitor GitHub Actions** workflow runs, or **search** code/repos/issues across GitHub Use `@loopstack/git` instead if you need local Git operations (commit, push, branch) on a cloned repository. ## Installation ```bash npm install @loopstack/github @loopstack/oauth ``` Import `GitHubModule` in your module. It automatically imports `OAuthModule` and registers the GitHub OAuth provider on startup: ```typescript import { Module } from '@nestjs/common'; import { GitHubModule } from '@loopstack/github'; @Module({ imports: [GitHubModule], providers: [MyWorkflow], exports: [MyWorkflow], }) export class MyModule {} ``` Set the required environment variables: ```env GITHUB_CLIENT_ID=your_client_id GITHUB_CLIENT_SECRET=your_client_secret GITHUB_OAUTH_REDIRECT_URI=/oauth/callback ``` ## Quick Start ### Agent workflow The fastest way to use GitHub tools is through `AgentWorkflow` — pass tool names as strings and let the LLM call them on demand: ```typescript import { AgentWorkflow } from '@loopstack/agent'; import { BaseWorkflow, Transition, Workflow } from '@loopstack/common'; @Workflow({ title: 'GitHub Assistant' }) export class GitHubAssistantWorkflow extends BaseWorkflow { constructor(private readonly agent: AgentWorkflow) { super(); } @Transition({ to: 'chatting' }) async start(state: Record) { await this.agent.run( { system: 'You are a GitHub assistant. Help the user manage repos, issues, PRs, and actions.', tools: [ 'github_get_authenticated_user', 'github_list_repos', 'github_get_repo', 'github_list_issues', 'github_create_issue', 'github_list_pull_requests', 'github_get_pull_request', 'github_list_workflow_runs', 'github_search_code', ], userMessage: 'List my five most recently updated repositories.', }, { callback: { transition: 'agentDone' }, show: 'inline', label: 'Working...' }, ); } } ``` Every GitHub tool returns `{ error: 'unauthorized' }` when no valid token is available, so the agent loop can detect missing auth and trigger the OAuth flow as a sub-workflow when needed. ### Structured workflow with explicit OAuth For full control over the auth flow, inject the individual tools and `OAuthWorkflow`. When a tool returns `error: 'unauthorized'`, launch the OAuth sub-workflow so the user can sign in, then retry. ```typescript import { z } from 'zod'; import { BaseWorkflow, Guard, Transition, Workflow } from '@loopstack/common'; import type { RunContext, TransitionInput } from '@loopstack/common'; import { GitHubGetAuthenticatedUserTool, GitHubListReposTool } from '@loopstack/github'; import { OAuthWorkflow } from '@loopstack/oauth'; interface State { requiresAuth?: boolean; repos?: Array<{ fullName: string; htmlUrl: string }>; } @Workflow({ name: 'my_github_workflow', title: 'My GitHub Workflow', schema: z.object({}).strict(), }) export class MyGitHubWorkflow extends BaseWorkflow { constructor( private readonly gitHubGetAuthenticatedUser: GitHubGetAuthenticatedUserTool, private readonly gitHubListRepos: GitHubListReposTool, private readonly oAuthWorkflow: OAuthWorkflow, ) { super(); } @Transition({ to: 'user_checked' }) async checkUser(state: State) { const result = await this.gitHubGetAuthenticatedUser.call(); this.assignState({ requiresAuth: result.data.error === 'unauthorized' }); } @Transition({ from: 'user_checked', to: 'awaiting_auth', priority: 10 }) @Guard('needsAuth') async startAuth(state: State) { await this.oAuthWorkflow.run( { provider: 'github', scopes: ['repo', 'read:org', 'workflow'] }, { callback: { transition: 'authCompleted' }, show: 'inline', label: 'GitHub authentication required' }, ); } needsAuth(state: State): boolean { return !!state.requiresAuth; } @Transition({ from: 'awaiting_auth', to: 'start', wait: true }) authCompleted(state: State, _input: TransitionInput) {} @Transition({ from: 'user_checked', to: 'end' }) async listRepos(state: State) { const result = await this.gitHubListRepos.call({ sort: 'updated', perPage: 10 }); this.assignState({ repos: result.data.repos }); } } ``` ## How It Works ### Provider Registration `GitHubOAuthProvider` implements `OAuthProviderInterface` and `OnModuleInit`. On startup it registers itself with the `OAuthProviderRegistry`: ```typescript onModuleInit(): void { this.providerRegistry.register(this); } ``` After registration, the generic `OAuthWorkflow` from `@loopstack/oauth` handles authentication for `provider: 'github'` automatically. | Property | Value | | --------------- | --------------------------------------------- | | `providerId` | `'github'` | | `defaultScopes` | `repo`, `user`, `workflow`, `read:org` | | Auth endpoint | `https://github.com/login/oauth/authorize` | | Token endpoint | `https://github.com/login/oauth/access_token` | > GitHub OAuth tokens do not expire and do not support refresh. The `refreshToken()` method throws an error. ### Authentication Pattern There is no dedicated authentication tool — authentication is triggered at the workflow level when any tool returns `{ error: 'unauthorized' }`. All 25 tools follow the same pattern: they read the user's stored OAuth token via `OAuthTokenStore.getValidAccessToken(ctx.userId, 'github')`. If no token exists, they return `{ error: 'unauthorized' }` instead of throwing. Your workflow checks for this error and launches `OAuthWorkflow` with `provider: 'github'` as a sub-workflow: ``` start --> checkUser --> [needsAuth?] --> startAuth --> awaiting_auth \ | \ authCompleted \ | +----> listRepos --> end <----- (retries from start) ``` ### Tool Resolution Tools are NestJS providers resolved by their `@Tool({ name })` value from the DI container. Inject the tool class into your workflow constructor and call it with `.call(args)` or `.call(args, options)`. ## Tools Reference All tools return `{ error: string, message: string }` when authentication fails or the GitHub API returns an error. ### Repositories | Tool name | Description | Args | Return | | ---------------------- | --------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `github_list_repos` | Lists repositories for the authenticated user | `visibility?` (`'all'`\|`'public'`\|`'private'`, default `'all'`), `sort?` (`'created'`\|`'updated'`\|`'pushed'`\|`'full_name'`, default `'updated'`), `perPage?` (default 30), `page?` (default 1) | `{ repos: [{ id, fullName, name, owner, private, htmlUrl, description, language, defaultBranch, updatedAt }] }` | | `github_get_repo` | Gets detailed repo information | `owner`, `repo` | `{ repo: { id, fullName, name, owner, ownerAvatar, private, htmlUrl, description, language, defaultBranch, stars, forks, openIssues, createdAt, updatedAt, topics, license } }` | | `github_create_repo` | Creates a new repository | `name`, `description?`, `private?` (default false), `autoInit?` (default false) | `{ repo: { id, fullName, name, htmlUrl, private, defaultBranch } }` | | `github_list_branches` | Lists branches for a repository | `owner`, `repo`, `perPage?` (default 30) | `{ branches: [{ name, commitSha, protected }] }` | ### Issues | Tool name | Description | Args | Return | | ----------------------------- | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | `github_list_issues` | Lists issues for a repository | `owner`, `repo`, `state?` (`'open'`\|`'closed'`\|`'all'`, default `'open'`), `labels?`, `assignee?`, `perPage?` (default 30), `page?` (default 1) | `{ issues: [{ id, number, title, state, user, labels, assignees, createdAt, updatedAt, htmlUrl, isPullRequest }] }` | | `github_get_issue` | Gets detailed issue information | `owner`, `repo`, `issueNumber` | `{ issue: { id, number, title, body, state, user, labels, assignees, milestone, createdAt, updatedAt, closedAt, htmlUrl, comments } }` | | `github_create_issue` | Creates a new issue | `owner`, `repo`, `title`, `body?`, `labels?` (string[]), `assignees?` (string[]) | `{ issue: { id, number, title, htmlUrl, state } }` | | `github_create_issue_comment` | Comments on an issue or pull request | `owner`, `repo`, `issueNumber`, `body` | `{ comment: { id, htmlUrl, createdAt, user } }` | ### Pull Requests | Tool name | Description | Args | Return | | ---------------------------- | -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `github_list_pull_requests` | Lists pull requests for a repository | `owner`, `repo`, `state?` (`'open'`\|`'closed'`\|`'all'`, default `'open'`), `base?`, `perPage?` (default 30), `page?` (default 1) | `{ pullRequests: [{ id, number, title, state, user, head, headSha, base, createdAt, updatedAt, htmlUrl, draft }] }` | | `github_get_pull_request` | Gets detailed pull request information | `owner`, `repo`, `pullNumber` | `{ pullRequest: { id, number, title, body, state, user, head, headSha, base, merged, mergeable, draft, additions, deletions, changedFiles, createdAt, updatedAt, mergedAt, htmlUrl, comments, reviewComments } }` | | `github_create_pull_request` | Creates a new pull request | `owner`, `repo`, `title`, `head`, `base`, `body?`, `draft?` (default false) | `{ pullRequest: { id, number, title, htmlUrl, state, draft } }` | | `github_merge_pull_request` | Merges a pull request | `owner`, `repo`, `pullNumber`, `mergeMethod?` (`'merge'`\|`'squash'`\|`'rebase'`, default `'merge'`), `commitTitle?`, `commitMessage?` | `{ merge: { sha, merged, message } }` | | `github_list_pr_reviews` | Lists reviews on a pull request | `owner`, `repo`, `pullNumber` | `{ reviews: [{ id, user, body, state, submittedAt, htmlUrl }] }` | ### Content / Git Ops | Tool name | Description | Args | Return | | ------------------------------ | --------------------------------------------------- | ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `github_get_file_content` | Gets file content (base64-decoded) | `owner`, `repo`, `path`, `ref?` | `{ file: { name, path, sha, size, type, content, htmlUrl } }` | | `github_create_or_update_file` | Creates or updates a file (provide `sha` to update) | `owner`, `repo`, `path`, `content` (plain text), `message` (commit message), `sha?`, `branch?` | `{ file: { name, path, sha, htmlUrl }, commit: { sha, message } }` | | `github_list_directory` | Lists directory contents | `owner`, `repo`, `path?` (default `''`), `ref?` | `{ entries: [{ name, path, sha, size, type, htmlUrl }] }` | | `github_get_commit` | Gets commit details with file stats | `owner`, `repo`, `ref` | `{ commit: { sha, message, author: { name, email, date, login }, committer: { name, date }, htmlUrl, stats: { additions, deletions, total }, files: [{ filename, status, additions, deletions, changes }] } }` | ### Actions | Tool name | Description | Args | Return | | --------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | `github_list_workflow_runs` | Lists workflow runs | `owner`, `repo`, `branch?`, `status?` (enum), `perPage?` (default 30), `page?` (default 1) | `{ totalCount, runs: [{ id, name, status, conclusion, headBranch, headSha, event, createdAt, updatedAt, htmlUrl }] }` | | `github_trigger_workflow` | Triggers a workflow dispatch event | `owner`, `repo`, `workflowId` (string), `ref`, `inputs?` (Record) | `{ triggered: true, message }` | | `github_get_workflow_run` | Gets workflow run details | `owner`, `repo`, `runId` (number) | `{ run: { id, name, status, conclusion, headBranch, headSha, event, workflowId, runNumber, runAttempt, createdAt, updatedAt, runStartedAt, htmlUrl } }` | ### Search | Tool name | Description | Args | Return | | ---------------------- | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | | `github_search_code` | Searches code across repositories | `query`, `perPage?` (default 30), `page?` (default 1) | `{ totalCount, results: [{ name, path, sha, htmlUrl, repository }] }` | | `github_search_repos` | Searches repositories | `query`, `sort?` (`'stars'`\|`'forks'`\|`'help-wanted-issues'`\|`'updated'`), `perPage?` (default 30), `page?` (default 1) | `{ totalCount, results: [{ id, fullName, description, htmlUrl, language, stars, forks, updatedAt }] }` | | `github_search_issues` | Searches issues and pull requests | `query`, `sort?` (`'comments'`\|`'reactions'`\|`'created'`\|`'updated'`\|...), `perPage?` (default 30), `page?` (default 1) | `{ totalCount, results: [{ id, number, title, state, user, htmlUrl, createdAt, updatedAt, isPullRequest }] }` | ### Users & Orgs | Tool name | Description | Args | Return | | ------------------------------- | -------------------------------------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------- | | `github_get_authenticated_user` | Gets the authenticated user's profile | _(none)_ | `{ user: { id, login, name, email, avatarUrl, htmlUrl, bio, publicRepos, followers, following, createdAt } }` | | `github_list_user_orgs` | Lists the authenticated user's organizations | `perPage?` (default 30) | `{ orgs: [{ id, login, description, avatarUrl }] }` | ## Configuration | Variable | Required | Description | | --------------------------- | -------- | -------------------------------------------- | | `GITHUB_CLIENT_ID` | Yes | GitHub OAuth App client ID | | `GITHUB_CLIENT_SECRET` | Yes | GitHub OAuth App client secret | | `GITHUB_OAUTH_REDIRECT_URI` | No | Redirect URI (defaults to `/oauth/callback`) | Create a GitHub OAuth App at [github.com/settings/developers](https://github.com/settings/developers) to obtain client credentials. ## Public API **Module** - `GitHubModule` -- NestJS module; imports `OAuthModule`, provides and exports all tools and the provider **Provider** - `GitHubOAuthProvider` -- implements `OAuthProviderInterface`, self-registers with `OAuthProviderRegistry` **Tools -- Repositories** - `GitHubListReposTool`, `GitHubGetRepoTool`, `GitHubCreateRepoTool`, `GitHubListBranchesTool` **Tools -- Issues** - `GitHubListIssuesTool`, `GitHubGetIssueTool`, `GitHubCreateIssueTool`, `GitHubCreateIssueCommentTool` **Tools -- Pull Requests** - `GitHubListPullRequestsTool`, `GitHubGetPullRequestTool`, `GitHubCreatePullRequestTool`, `GitHubMergePullRequestTool`, `GitHubListPrReviewsTool` **Tools -- Content / Git Ops** - `GitHubGetFileContentTool`, `GitHubCreateOrUpdateFileTool`, `GitHubListDirectoryTool`, `GitHubGetCommitTool` **Tools -- Actions** - `GitHubListWorkflowRunsTool`, `GitHubTriggerWorkflowTool`, `GitHubGetWorkflowRunTool` **Tools -- Search** - `GitHubSearchCodeTool`, `GitHubSearchReposTool`, `GitHubSearchIssuesTool` **Tools -- Users & Orgs** - `GitHubGetAuthenticatedUserTool`, `GitHubListUserOrgsTool` **Types** (exported per tool) - `GitHub*Args`, `GitHub*Result` -- Zod-inferred arg types and result types for each tool ## Dependencies | Package | Role | | ------------------- | ------------------------------------------------------------------------------------- | | `@loopstack/common` | Base classes (`BaseTool`, `Tool`, `Workflow`, `Transition`), documents, context types | | `@loopstack/oauth` | `OAuthProviderRegistry`, `OAuthProviderInterface`, `OAuthTokenStore`, `OAuthWorkflow` | | `zod` | Schema definitions for tool args | ## Related - [OAuth Authentication](https://loopstack.ai/docs/build/integrations/oauth) -- how to use `OAuthWorkflow` as a sub-workflow, token management, and the guard-based auth pattern - [`@loopstack/oauth`](https://loopstack.ai/docs/registry/oauth) -- the provider-agnostic OAuth framework this module plugs into - [GitHub examples](/docs/examples/github) -- full example with a repo overview workflow and a GitHub chat agent using all 25 tools - [`@loopstack/git`](https://loopstack.ai/docs/registry/git) -- local Git operations (commit, push, branch, diff) for cloned repositories ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/registry/packages/github-integration.md --- title: GitHub Integration Module description: ConnectGitHubWorkflow — end-to-end guided workflow that authenticates via OAuth, creates or links a GitHub repo, configures git remotes, resolves branch divergence via HITL, and pushes. Uses GitHubIntegrationModule, OAuthWorkflow, AskUserWorkflow, git tools. --- # @loopstack/github-integration > GitHub integration workflow module for the [Loopstack](https://loopstack.ai) automation framework. Provides `ConnectGitHubWorkflow`, a guided multi-step workflow that takes a workspace from "not connected" to "pushed to GitHub". It composes OAuth authentication, repo creation/linking, remote configuration, and branch divergence resolution into a single reusable workflow with human-in-the-loop decision points. ## When to Use - You need a one-click "Connect to GitHub" experience that handles OAuth, repo setup, and push in a single workflow. - You want to embed GitHub onboarding into a larger workflow by calling `ConnectGitHubWorkflow` as a sub-workflow. - You need guided divergence resolution when connecting to a repo that already has commits. - **Use `@loopstack/github` instead** if you only need individual GitHub API tools (repos, issues, PRs, actions) without the guided connection flow. ## Installation ```sh npm install @loopstack/github-integration @loopstack/github @loopstack/git @loopstack/hitl @loopstack/oauth @loopstack/remote-client ``` Register the module: ```ts import { Module } from '@nestjs/common'; import { GitHubIntegrationModule } from '@loopstack/github-integration'; @Module({ imports: [GitHubIntegrationModule], }) export class AppModule {} ``` `GitHubIntegrationModule` imports `GitModule`, `GitHubModule`, `HitlModule`, and `OAuthModule` internally. You do not need to import those yourself, but their packages must be installed. A GitHub OAuth app must be configured in your OAuth provider setup (client ID and secret). See the [`@loopstack/oauth`](https://loopstack.ai/docs/registry/oauth) and [`@loopstack/github`](https://loopstack.ai/docs/registry/github) docs for details. ## Quick Start Inject `ConnectGitHubWorkflow` into your own workflow and run it as a sub-workflow: ```ts import { z } from 'zod'; import { BaseWorkflow, Transition, type TransitionInput, Workflow } from '@loopstack/common'; import { ConnectGitHubWorkflow } from '@loopstack/github-integration'; @Workflow({ title: 'Setup Project', description: 'Initialises a project and connects it to GitHub.', schema: z.object({}).strict(), }) export class SetupProjectWorkflow extends BaseWorkflow { constructor(private readonly connectGitHub: ConnectGitHubWorkflow) { super(); } @Transition({ to: 'awaiting_github' }) async start(state: Record) { await this.connectGitHub.run( {}, { callback: { transition: 'onGitHubConnected' }, show: 'inline', label: 'Connect to GitHub' }, ); } @Transition({ from: 'awaiting_github', to: 'end', wait: true }) async onGitHubConnected(state: Record, input: TransitionInput) { this.setResult({ github: input.data }); } } ``` ## How It Works `ConnectGitHubWorkflow` is a state-machine workflow that orchestrates multiple sub-workflows and tools: ``` start │ ▼ check_auth ──[needs auth]──► awaiting_auth ──[callback]──► check_auth │ ▼ awaiting_choice ──[callback]──► route_choice │ │ │ ┌─────────────────┼─────────────────┐ │ ▼ ▼ │ createRepo (wait) repoSelected (wait) │ │ │ │ └─────────────────┬─────────────────┘ │ ▼ │ configure_remote │ │ │ ▼ │ check_uncommitted │ │ │ │ [clean]────┘ └────[dirty] │ │ │ │ ▼ ▼ │ setup_remote awaiting_commit_confirm │ │ │ │ │ [callback]───┘ │ │ │ │ └────────┬───────┘ │ ▼ │ check_divergence │ │ │ │ [can push]──┘ └──[diverged] │ │ │ │ ▼ ▼ │ done awaiting_sync_choice │ │ │ │ │ [callback]───┘ │ │ │ │ └────────┬───────┘ │ ▼ │ done │ │ │ ▼ │ end ``` ### Step-by-step 1. **Check auth** -- calls `GitHubGetAuthenticatedUserTool` to see if the user already has a valid token. 2. **OAuth** -- if not authenticated, launches `OAuthWorkflow` with `provider: 'github'` and `scopes: ['repo', 'user']`. The sign-in UI is embedded in the parent's run view via the default `show: 'inline'`. 3. **Repo choice** -- uses `AskUserWorkflow` (HITL) to let the user choose between creating a new repo or connecting an existing one. 4. **Create or select** -- either calls `GitHubCreateRepoTool` or `GitHubListReposTool` followed by a second HITL prompt to pick from the list. 5. **Uncommitted changes** -- checks `GitStatusTool` for uncommitted work. If dirty, asks the user whether to auto-commit or cancel. 6. **Remote setup** -- configures the git remote URL via `GitRemoteConfigureTool`, sets the user identity via `GitConfigUserTool`, and fetches remote refs. 7. **Divergence resolution** -- for a linked repo, compares the checked-out branch with the same branch on `origin`. If the workspace is ahead, or the remote does not have that branch yet, it is pushed directly. If the remote is ahead or the histories differ, asks the user to choose: pull, merge, force-push, or cancel. A detached HEAD or a failing git command fails the run. 8. **Push** -- calls `GitPushTool` to finalize the connection. 9. **Result** -- saves a `MarkdownDocument` summarizing the outcome and dispatches a `git.updated` workspace event. ### Return value On success: ```json { "repo": "user/repo-name", "url": "https://github.com/user/repo-name" } ``` On cancellation: ```json { "cancelled": true } ``` ## Args Reference `ConnectGitHubWorkflow` takes no arguments (empty object schema): | Arg | Type | Required | Description | | -------- | ---- | -------- | ---------------------------------------------------------------------------------------- | | _(none)_ | -- | -- | The workflow requires no input args. OAuth and repo details are collected interactively. | ## Configuration No module-level configuration. OAuth credentials are managed by `@loopstack/oauth` and the GitHub OAuth provider from `@loopstack/github`. ## Public API - **Module:** `GitHubIntegrationModule` - **Workflow:** `ConnectGitHubWorkflow` ## Dependencies | Package | Role | | -------------------------- | -------------------------------------------------------------------------------------------------------- | | `@loopstack/common` | Framework types, decorators (`@Workflow`, `@Transition`, `@Guard`), documents (`MarkdownDocument`) | | `@loopstack/core` | `ClientMessageService` for dispatching workspace events | | `@loopstack/git` | Git tools: `GitStatusTool`, `GitPushTool`, `GitFetchTool`, `GitRemoteConfigureTool`, `GitConfigUserTool` | | `@loopstack/github` | GitHub API tools: `GitHubGetAuthenticatedUserTool`, `GitHubCreateRepoTool`, `GitHubListReposTool` | | `@loopstack/hitl` | `AskUserWorkflow` for interactive decision points | | `@loopstack/oauth` | `OAuthWorkflow` and `OAuthTokenStore` for GitHub authentication | | `@loopstack/remote-client` | `BashTool` for running git commands on the remote server | | `zod` | Schema validation | ## Related - [`@loopstack/github`](https://loopstack.ai/docs/registry/github) -- low-level GitHub API tools (repos, issues, PRs, actions, search) used by this workflow - [`@loopstack/git`](https://loopstack.ai/docs/registry/git) -- git tools for commit, push, pull, branch, and remote operations - [`@loopstack/oauth`](https://loopstack.ai/docs/registry/oauth) -- provider-agnostic OAuth framework; required for the GitHub OAuth flow - [`@loopstack/hitl`](https://loopstack.ai/docs/registry/hitl) -- human-in-the-loop workflows used for interactive prompts - [Workflows](https://loopstack.ai/docs/build/fundamentals/workflows) -- how to build and compose workflows in Loopstack - [Sub-workflows](https://loopstack.ai/docs/build/patterns/sub-workflows) -- pattern for calling one workflow from another with callbacks ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/registry/packages/google-workspace.md --- title: Google Workspace Module description: Google Calendar, Gmail, and Drive tools for Loopstack — 11 tools across 3 domains, Google OAuth provider, OAuthProviderInterface, token-based API access with automatic unauthorized error handling --- # @loopstack/google-workspace > Google Workspace integration module for the [Loopstack](https://loopstack.ai) automation framework. Provides a Google OAuth 2.0 provider and 11 tools for interacting with Google Calendar, Gmail, and Drive. Registers a Google OAuth provider with `@loopstack/oauth` so any workflow can authenticate users via their Google account. ## When to Use - **Your workflow needs to read or create calendar events** — use the Calendar tools. - **Your workflow needs to search, read, or send emails** — use the Gmail tools. - **Your workflow needs to browse, download, or upload files in Google Drive** — use the Drive tools. - **You're building an agent that works across Google services** — register all tools and let the LLM pick the right one. ## Installation ```bash npm install @loopstack/google-workspace ``` Register the module alongside `OAuthModule`: ```typescript import { Module } from '@nestjs/common'; import { GoogleWorkspaceModule } from '@loopstack/google-workspace'; import { OAuthModule } from '@loopstack/oauth'; @Module({ imports: [OAuthModule, GoogleWorkspaceModule], providers: [MyWorkflow], }) export class MyModule {} ``` ### Environment Variables | Variable | Required | Default | Description | | --------------------------- | -------- | ----------------- | -------------------------- | | `GOOGLE_CLIENT_ID` | yes | — | Google OAuth client ID | | `GOOGLE_CLIENT_SECRET` | yes | — | Google OAuth client secret | | `GOOGLE_OAUTH_REDIRECT_URI` | no | `/oauth/callback` | OAuth redirect URI | Obtain credentials from the [Google Cloud Console](https://console.cloud.google.com/apis/credentials). ## Quick Start Use Google tools in an agent workflow: ```typescript import { AgentWorkflow } from '@loopstack/agent'; import { BaseWorkflow, Transition, Workflow } from '@loopstack/common'; @Workflow({ title: 'Google Assistant' }) export class GoogleAssistantWorkflow extends BaseWorkflow { constructor(private readonly agent: AgentWorkflow) { super(); } @Transition({ to: 'chatting' }) async start(state: Record) { await this.agent.run( { system: 'You are a Google Workspace assistant with access to Calendar, Gmail, and Drive.', tools: [ 'google_calendar_list_calendars', 'google_calendar_fetch_events', 'google_calendar_create_event', 'gmail_search_messages', 'gmail_get_message', 'gmail_send_message', 'gmail_reply_to_message', 'google_drive_list_files', 'google_drive_get_file_metadata', 'google_drive_download_file', 'google_drive_upload_file', ], userMessage: 'Summarize my calendar events for today.', }, { callback: { transition: 'agentDone' }, show: 'inline', label: 'Working...' }, ); } } ``` All tools return `{ error: 'unauthorized' }` when no valid token is available, so your workflow can trigger authentication on demand. ## How It Works ### Provider Registration `GoogleWorkspaceOAuthProvider` implements `OAuthProviderInterface` and registers itself with the `OAuthProviderRegistry` at startup. After that, the generic `OAuthWorkflow` from `@loopstack/oauth` handles `provider: 'google'` automatically. | Property | Value | | --------------- | ------------------------------------ | | `providerId` | `'google'` | | `defaultScopes` | `userinfo.email`, `userinfo.profile` | Additional scopes (Calendar, Gmail, Drive) should be requested when launching the OAuth flow depending on which tools your workflow uses. ### Authentication Pattern Tools check for a valid OAuth token via `OAuthTokenStore`. When no token exists (or it's expired), the tool returns `{ error: 'unauthorized' }`. Your workflow should catch this and launch the OAuth flow: ```typescript const result = await this.oAuth.run( { provider: 'google', scopes: ['https://www.googleapis.com/auth/calendar.readonly'] }, { callback: { transition: 'authCompleted' } }, ); ``` See the [Google Calendar Summary example](/docs/examples/google-workspace#google-calendar-summary) for a complete implementation of this pattern. ## Tools Reference ### Calendar #### `google_calendar_list_calendars` Lists all calendars the authenticated user has access to. | Arg | Type | Required | Description | | ------------ | --------- | -------- | ------------------------ | | `showHidden` | `boolean` | no | Include hidden calendars | #### `google_calendar_fetch_events` Fetches events from a calendar within a time range. | Arg | Type | Required | Description | | ------------ | -------- | -------- | ---------------------------------- | | `calendarId` | `string` | no | Calendar ID (default: `'primary'`) | | `timeMin` | `string` | yes | Start of range (ISO 8601) | | `timeMax` | `string` | yes | End of range (ISO 8601) | | `maxResults` | `number` | no | Maximum events to return | | `query` | `string` | no | Free-text search within events | #### `google_calendar_create_event` Creates a new calendar event. | Arg | Type | Required | Description | | ------------- | --------------------- | -------- | ---------------------------------- | | `calendarId` | `string` | no | Calendar ID (default: `'primary'`) | | `summary` | `string` | yes | Event title | | `description` | `string` | no | Event description | | `start` | `string` | yes | Start time (ISO 8601) | | `end` | `string` | yes | End time (ISO 8601) | | `location` | `string` | no | Event location | | `attendees` | `{ email: string }[]` | no | Attendee list | | `reminders` | `object` | no | Reminder overrides | ### Gmail #### `gmail_search_messages` Searches Gmail messages using Gmail query syntax. | Arg | Type | Required | Description | | ------------ | ---------- | -------- | ---------------------------------------------------------- | | `query` | `string` | no | Gmail query (e.g. `from:user@example.com subject:invoice`) | | `labelIds` | `string[]` | no | Filter by label IDs | | `maxResults` | `number` | no | Max results (default: `10`) | | `pageToken` | `string` | no | Pagination token | #### `gmail_get_message` Gets full content of a single message including body and attachment metadata. | Arg | Type | Required | Description | | ----------- | ----------------------------------- | -------- | ----------------------------------- | | `messageId` | `string` | yes | Message ID | | `format` | `'full' \| 'metadata' \| 'minimal'` | no | Response format (default: `'full'`) | #### `gmail_send_message` Sends a new email. | Arg | Type | Required | Description | | ---------- | ---------- | -------- | --------------------- | | `to` | `string[]` | yes | Recipient emails | | `cc` | `string[]` | no | CC recipients | | `bcc` | `string[]` | no | BCC recipients | | `subject` | `string` | yes | Email subject | | `body` | `string` | yes | Plain text body | | `htmlBody` | `string` | no | HTML alternative body | #### `gmail_reply_to_message` Replies to an existing message in-thread. | Arg | Type | Required | Description | | ----------- | --------- | -------- | ------------------------------------------ | | `messageId` | `string` | yes | Message ID to reply to | | `threadId` | `string` | yes | Thread ID | | `body` | `string` | yes | Plain text body | | `htmlBody` | `string` | no | HTML alternative body | | `replyAll` | `boolean` | no | Reply to all recipients (default: `false`) | ### Drive #### `google_drive_list_files` Lists and searches files. Supports Drive query syntax and folder browsing. | Arg | Type | Required | Description | | ------------ | -------- | -------- | -------------------------------- | | `query` | `string` | no | Drive query syntax | | `folderId` | `string` | no | Folder ID to search within | | `maxResults` | `number` | no | Max results (default: `20`) | | `pageToken` | `string` | no | Pagination token | | `orderBy` | `string` | no | Sort order (e.g. `modifiedTime`) | #### `google_drive_get_file_metadata` Gets detailed metadata for a single file. | Arg | Type | Required | Description | | -------- | -------- | -------- | ----------- | | `fileId` | `string` | yes | File ID | #### `google_drive_download_file` Downloads or exports a file. Automatically handles Google Docs/Sheets/Slides export. | Arg | Type | Required | Description | | ---------------- | -------- | -------- | ------------------------------------------------- | | `fileId` | `string` | yes | File ID | | `exportMimeType` | `string` | no | Export format for Google Docs (e.g. `text/plain`) | #### `google_drive_upload_file` Uploads a new file using multipart upload. | Arg | Type | Required | Description | | ------------- | -------- | -------- | --------------------------------- | | `name` | `string` | yes | Filename | | `content` | `string` | yes | File content | | `mimeType` | `string` | no | MIME type (default: `text/plain`) | | `folderId` | `string` | no | Parent folder ID | | `description` | `string` | no | File description | ## Public API - **Module:** `GoogleWorkspaceModule` - **Provider:** `GoogleWorkspaceOAuthProvider` - **Calendar Tools:** `GoogleCalendarListCalendarsTool`, `GoogleCalendarFetchEventsTool`, `GoogleCalendarCreateEventTool` - **Gmail Tools:** `GmailSearchMessagesTool`, `GmailGetMessageTool`, `GmailSendMessageTool`, `GmailReplyToMessageTool` - **Drive Tools:** `GoogleDriveListFilesTool`, `GoogleDriveGetFileMetadataTool`, `GoogleDriveDownloadFileTool`, `GoogleDriveUploadFileTool` ## Dependencies - `@loopstack/oauth` — `OAuthProviderRegistry`, `OAuthProviderInterface`, `OAuthTokenStore` ## Related - [OAuth Integration](https://loopstack.ai/docs/build/integrations/oauth) — OAuth flow patterns and token management - [google-workspace examples](/docs/examples/google-workspace) — full example with agent workflow, Calendar/Gmail/Drive tools, and authentication handling ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/registry/packages/handoff.md --- title: Handoff Module description: Hand-offs from a Loopstack run to the user's machine — HandoffModule.forFeature() lights up the Studio Handoff panel; HandoffDocument (copy-a-command or open-a-URL card), ChangedFilesDocument (changed-file tree with Zed / VS Code / file-explorer actions) and TerminalHandoffDocument (CLI terminal-handoff widget). --- # @loopstack/handoff > Hand-off documents for the [Loopstack](https://loopstack.ai) automation framework. Lets a run hand work over to the user's own tools: a command to copy and run, a URL to open, a tree of changed files to open in an IDE, or — under `loopstack run` — the terminal itself. ## When to Use - **The run prepared something the user continues locally** — a shell command, an IDE to open, a preview URL. Save a `HandoffDocument`; it shows as a card in the Studio "Handoff" panel and in the run timeline. - **The run edited files the user should review** — save a `ChangedFilesDocument` with the root directory and the changed paths; Studio renders a file tree with "open in Zed", "open in VS Code" and file-explorer actions. - **The run should hand the terminal to an interactive process** — save a `TerminalHandoffDocument` and wait on `handoffDone`; the CLI runs the command with an inherited TTY and fires the transition when it exits. Studio shows the command to copy and an "End session" button that fires the transition by hand. ## Installation ```sh npm install @loopstack/handoff ``` Register the Studio feature in the module graph of your `@StudioApp`: ```ts import { Module } from '@nestjs/common'; import { HandoffModule } from '@loopstack/handoff'; @Module({ imports: [HandoffModule.forFeature()], }) export class AppModule {} ``` `forFeature()` registers the `handoff` feature: Studio shows the "Handoff" sidebar panel and renders the `handoff`, `changed-files` and `terminal-handoff` widgets. Without it, those documents show as an unknown document type. The CLI renders `TerminalHandoffDocument` on its own, with or without the feature. ## Quick Start ```ts import { BaseWorkflow, Transition, Workflow } from '@loopstack/common'; import { HandoffDocument } from '@loopstack/handoff'; @Workflow({ title: 'Preview', description: 'Starts a preview and hands its URL to the user.' }) export class PreviewWorkflow extends BaseWorkflow { @Transition({ to: 'end' }) async publish() { await this.documentStore.save( HandoffDocument, { title: 'Open the app', description: 'The preview is running.', url: 'http://localhost:3000' }, { key: 'preview' }, ); } } ``` Save each hand-off under a stable `key` so re-saving updates the card instead of adding another. ## Documents | Document | Name | Widget | Tag | Content | | ------------------------- | ------------------ | ------------------ | --------- | --------------------------------------------------------- | | `HandoffDocument` | `handoff` | `handoff` | `handoff` | `title`, `description?`, and one of `command` / `url` | | `ChangedFilesDocument` | `changed_files` | `changed-files` | `handoff` | `hostRoot` (absolute path on the user's machine), `paths` | | `TerminalHandoffDocument` | `terminal_handoff` | `terminal-handoff` | — | `command`, `cwd?`; `handoffDone` on exit or "End session" | Every document tagged `handoff` (`HANDOFF_TAG`) appears in the Studio panel. Studio builds the `ChangedFilesDocument` actions (`zed "/"`, `vscode://file/`) on the user's machine, so `hostRoot` must be a path that exists there — e.g. a checkout bind-mounted into the container the run works in. --- > Source: https://loopstack.ai/llms/registry/packages/hitl.md --- title: Human-in-the-Loop Module description: HITL workflows and tools for Loopstack — AskUserWorkflow (free-text, confirm, multiple-choice), ConfirmUserWorkflow (markdown review + confirm/deny), AskClarificationTool, AskForApprovalTool, document types for UI rendering --- # @loopstack/hitl > Human-in-the-loop module for the [Loopstack](https://loopstack.ai) automation framework. Pause a running workflow or agent loop, ask the user a question or request confirmation, and resume once they answer. Ships with ready-to-use workflows, agent tools, and document types that render prompts in the Studio UI. ## When to Use - **Your workflow needs user input** before it can continue — a name, a choice, a yes/no decision. Use `AskUserWorkflow` as a sub-workflow. - **Your workflow needs explicit approval** of generated content (e.g. a plan, a summary, a code diff). Use `ConfirmUserWorkflow`. - **Your LLM agent needs to ask the user a question** mid-loop without exiting. Use `AskClarificationTool` — it pauses the agent, collects the answer, and resumes. - **Your LLM agent needs user approval** before proceeding. Use `AskForApprovalTool` — it shows markdown content and waits for confirm/deny. ## Installation ```bash npm install @loopstack/hitl ``` Register the module: ```typescript import { Module } from '@nestjs/common'; import { HitlModule } from '@loopstack/hitl'; @Module({ imports: [HitlModule], providers: [MyWorkflow], }) export class MyModule {} ``` ## Quick Start ### Sub-workflow: Ask a question ```typescript import { z } from 'zod'; import { BaseWorkflow, MessageDocument, Transition, type TransitionInput, Workflow } from '@loopstack/common'; import { AskUserWorkflow } from '@loopstack/hitl'; const AnswerSchema = z.object({ answer: z.string() }); @Workflow({ title: 'My Workflow' }) export class MyWorkflow extends BaseWorkflow { constructor(private readonly askUser: AskUserWorkflow) { super(); } @Transition({ to: 'waiting' }) async start(state: Record) { await this.askUser.run( { question: 'What is your name?' }, { callback: { transition: 'answerReceived' }, show: 'inline', label: 'Waiting for answer...' }, ); } @Transition({ from: 'waiting', to: 'end', wait: true, schema: AnswerSchema }) async answerReceived(state: Record, input: TransitionInput<{ answer: string }>) { await this.documentStore.save(MessageDocument, { role: 'assistant', text: `Hello, ${input.data.answer}!`, }); } } ``` ### Agent tool: Ask for clarification Register the tool in your module so an LLM agent can call it mid-loop: ```typescript import { Module } from '@nestjs/common'; import { AgentModule } from '@loopstack/agent'; import { HitlModule } from '@loopstack/hitl'; import { AskClarificationTool } from '@loopstack/hitl'; @Module({ imports: [AgentModule, HitlModule], providers: [MyWorkflow, AskClarificationTool], }) export class MyModule {} ``` Then include it in the agent's tool list: ```typescript await this.agent.run({ system: 'You are a helpful assistant. Ask the user for clarification when needed.', tools: ['search', 'ask_clarification'], userMessage: 'Help me plan my project.', }); ``` ## How It Works ### AskUserWorkflow A sub-workflow with three modes, selected via the `mode` arg: ``` start → show_question → waiting_for_user → end ``` The `show_question` state uses guard-based routing to save the correct document type: - **text** (default) — saves `AskUserDocument`, renders a free-text input - **options** — saves `AskUserOptionsDocument`, renders a choice list - **confirm** — saves `AskUserConfirmDocument`, renders yes/no buttons **Immediate return from `.run()`:** `QueueResult` — `{ workflowId: string }`. `.run()` schedules the child and returns synchronously; it does **not** wait for the user. Use `workflowId` to embed the child in the parent's UI via `LinkDocument` (or pass `show: 'inline'` on `.run()` to do this automatically). **Callback `input.data`:** `{ answer: string }` — delivered as the `data` field of a `TransitionInput<{ answer: string }>` to the wait transition named in `options.callback.transition`. The `schema:` on the wait transition validates `input.data` only; the surrounding envelope (`workflowId`, `status`, `hasError`, `errorMessage`) is added by the framework. For the full sub-workflow callback pattern — typing `data` via the wait transition schema, branching on `input.hasError` / `input.status`, and embedding the child UI with `show: 'inline'` — see [the sub-workflow example](/docs/examples/advanced-workflows#sub-workflow). #### Multiple-choice and confirmation modes ```typescript // Multiple choice await this.askUser.run( { question: 'Which environment?', mode: 'options', options: ['staging', 'production'], allowCustomAnswer: false, }, { callback: { transition: 'envSelected' } }, ); // Yes/No confirmation await this.askUser.run( { question: 'Proceed with deletion?', mode: 'confirm', }, { callback: { transition: 'confirmed' } }, ); ``` ### ConfirmUserWorkflow Shows markdown content and waits for a confirm or deny response: ``` start → waiting_for_confirmation → end ``` Two wait transitions (`userConfirmed` / `userDenied`) resolve to different results. **Immediate return from `.run()`:** `QueueResult` — `{ workflowId: string }`. **Callback `input.data`:** `{ confirmed: boolean, markdown: string }` — accessed as `input.data.confirmed` / `input.data.markdown` in the wait transition. ```typescript import { ConfirmUserWorkflow } from '@loopstack/hitl'; const result = await this.confirmUser.run( { markdown: '## About to commit\n\n- 3 files changed' }, { callback: { transition: 'decisionReceived' } }, ); ``` ### Agent Tools Both tools follow the same pattern: launch the corresponding sub-workflow, return a `pending` result, and complete when the user responds. The agent loop pauses automatically while waiting. ## Args Reference ### AskUserWorkflow | Arg | Type | Required | Description | | ------------------- | ---------------------------------- | -------- | -------------------------------------- | | `question` | `string` | yes | The question to display | | `mode` | `'text' \| 'options' \| 'confirm'` | no | Presentation mode (default: `'text'`) | | `options` | `string[]` | no | Choices when mode is `'options'` | | `allowCustomAnswer` | `boolean` | no | Show free-text input alongside options | **Immediate return from `.run()`:** `QueueResult` — `{ workflowId: string }` **Callback `input.data`:** `{ answer: string }` ### ConfirmUserWorkflow | Arg | Type | Required | Description | | ---------- | -------- | -------- | ----------------------------------- | | `markdown` | `string` | yes | Markdown content to show for review | **Immediate return from `.run()`:** `QueueResult` — `{ workflowId: string }` **Callback `input.data`:** `{ confirmed: boolean, markdown: string }` ## Tools Reference ### `ask_clarification` Ask the user a clarification question mid-agent-loop. Pauses the agent, waits for user input, resumes with the answer. | Arg | Type | Required | Description | | ------------------- | ---------------------------------- | -------- | --------------------------------- | | `question` | `string` | yes | The clarification question | | `mode` | `'text' \| 'options' \| 'confirm'` | no | Presentation mode | | `options` | `string[]` | no | Choices when mode is `'options'` | | `allowCustomAnswer` | `boolean` | no | Allow free-text alongside options | **Returns:** the user's answer as a string ### `ask_for_approval` Present markdown content to the user for approval. Pauses the agent until the user confirms or denies. | Arg | Type | Required | Description | | --------- | -------- | -------- | ---------------------------------------- | | `concept` | `string` | yes | Markdown content to present for approval | **Returns:** `{ concept: string }` if approved, `{ denied: true }` if denied ## Public API - **Module:** `HitlModule` - **Workflows:** `AskUserWorkflow`, `ConfirmUserWorkflow` - **Tools:** `AskClarificationTool`, `AskForApprovalTool` - **Documents:** `AskUserDocument`, `AskUserConfirmDocument`, `AskUserOptionsDocument`, `ConfirmUserDocument` ## Dependencies - `@loopstack/common` — `BaseWorkflow`, `BaseTool`, decorators - `@loopstack/core` — `LoopCoreModule` ## Related - [Human-in-the-Loop Patterns](https://loopstack.ai/docs/build/patterns/human-in-the-loop) — wait transitions, document actions, conditional widgets - [hitl examples](/docs/examples/hitl) — comprehensive HITL examples: custom document with widget, AskUserWorkflow / ConfirmUserWorkflow shortcuts, and agent-tool flows ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/registry/packages/llm-provider.md --- title: LLM Provider Module description: Shared LLM provider contracts, registry, and helper services for the Loopstack automation framework. Provider modules (Claude, OpenAI, etc.) implement the LlmProviderInterface and register themselves at module init. --- # @loopstack/llm-provider ## Installation ```sh npm install @loopstack/llm-provider ``` Register the module in your app module: ```ts import { Module } from '@nestjs/common'; import { LlmProviderModule } from '@loopstack/llm-provider'; @Module({ imports: [LlmProviderModule], }) export class AppModule {} ``` Pair it with at least one provider module (e.g. `ClaudeModule` from `@loopstack/claude` or `OpenAiModule` from `@loopstack/openai`) — this module holds the registry, the provider modules populate it. To set an app-wide default provider and model, use `forRoot()` instead of the bare import; `forFeature()` overrides the config for one module's tools: ```ts LlmProviderModule.forRoot({ provider: 'claude', model: 'claude-sonnet-4-5' }); ``` --- > Source: https://loopstack.ai/llms/registry/packages/local-file-explorer.md --- title: Local File Explorer Module description: Loopstack registry package exposing the local filesystem of a workspace as a REST API. LocalFileExplorerModule, LocalFileExplorerController endpoints for /local-files/tree and /local-files/read, FileApiService, FileSystemService, FileExplorerNodeDto, FileContentDto, path traversal protection, 10 MB file size limit, workflow YAML parsing. --- # @loopstack/local-file-explorer > Local filesystem browsing module for the [Loopstack](https://loopstack.ai) automation framework. Exposes the local files belonging to a workspace as a workspace-scoped REST API. Used by Studio's file-explorer panel to browse and read project files without giving the browser direct disk access. Drop the module into your app and the endpoints are wired up automatically. ## When to Use - You want Studio (or any frontend) to render a project file tree for a workspace. - You want to read individual source files — including parsed workflow YAML — through an authenticated HTTP endpoint. - You're running the Loopstack backend on the same machine as the project files. For remote machines, use [`@loopstack/remote-file-explorer`](https://loopstack.ai/docs/registry/remote-file-explorer) instead. ## Installation ```bash npm install @loopstack/local-file-explorer ``` Import the module in your app: ```typescript import { Module } from '@nestjs/common'; import { LocalFileExplorerModule } from '@loopstack/local-file-explorer'; @Module({ imports: [LocalFileExplorerModule], }) export class AppModule {} ``` Use `LocalFileExplorerModule.forFeature({ enabled: true, environments: ['local'] })` if you want to register it as a Studio feature (lights up the file-explorer panel for that workspace). ## Quick Start Once the module is imported, the endpoints are live. From a client: ``` GET /api/v1/workspaces/:workspaceId/local-files/tree GET /api/v1/workspaces/:workspaceId/local-files/read?path=src/index.ts ``` Both require an authenticated user (via the standard `@CurrentUser()` mechanism) and resolve the workspace's `appName` to scope file access to that workspace's project directory. ## How It Works ``` HTTP request ──► LocalFileExplorerController │ ├─► WorkspaceService.getWorkspace(workspaceId, userId) // auth + scoping │ └─► FileApiService ──► FileSystemService ──► fs ``` `LocalFileExplorerController` is mounted at `/api/v1/workspaces/:workspaceId/local-files`. Every request first resolves the workspace through `WorkspaceService` — this verifies the current user owns the workspace and yields its `appName`, which becomes the root for all file operations. `FileApiService` then delegates to `FileSystemService` for raw filesystem access. ### Security - **Workspace scoping** — file paths are resolved relative to the workspace's `appName` directory. There is no way to read files outside that root through the API. - **Authenticated routes** — `@CurrentUser()` is required on every endpoint; unauthenticated requests are rejected by the standard Loopstack auth layer. - **Path traversal protection** — `FileSystemService` rejects paths that escape the workspace root. - **Symlink resolution** — before a read, the root and the requested path are resolved to their real locations; a symlink whose target lies outside the root is rejected, while symlinks that stay inside it are followed. - **File size limit** — single-file reads are capped at **10 MB**. Larger files return an empty content payload and a warning is logged. ### Ignored directories `FileSystemService` skips the following directories when walking the tree: ``` node_modules, .git, .next, .nuxt, dist, build, .cache, .turbo ``` This keeps responses small and prevents accidentally walking into vendored or generated trees. ### YAML workflow parsing When `read` returns a `.yaml` / `.yml` file whose content parses to an object containing a `transitions` array, the parsed config is also returned on `workflowConfig`. Studio uses this to render workflow files with extra UI affordances without re-parsing on the client. ## Endpoints | Method | Path | Auth | Returns | | ------ | --------------------------------------------------------- | ---------------- | ---------------------------------------------------------------------- | | `GET` | `/api/v1/workspaces/:workspaceId/local-files/tree` | `@CurrentUser()` | `FileExplorerNodeDto[]` — recursive tree under the workspace's project | | `GET` | `/api/v1/workspaces/:workspaceId/local-files/read?path=…` | `@CurrentUser()` | `FileContentDto` — file content (+ `workflowConfig` for workflow YAML) | ### `FileExplorerNodeDto` Each node represents a file or directory under the workspace root. | Field | Type | Description | | ---------- | ------------------------ | ----------------------------------------- | | `name` | `string` | File or directory name | | `path` | `string` | Workspace-relative path | | `type` | `'file' \| 'directory'` | Node type | | `children` | `FileExplorerNodeDto[]?` | Present for directories; absent for files | ### `FileContentDto` | Field | Type | Description | | ---------------- | -------------------------- | --------------------------------------------------------------- | | `path` | `string` | Workspace-relative path requested | | `content` | `string` | UTF-8 file content (empty when the file exceeds the size limit) | | `workflowConfig` | `Record?` | Parsed YAML config when the file is a workflow YAML | ## Public API - `LocalFileExplorerModule` — NestJS module to import. - `LocalFileExplorerController` — REST controller (auto-registered when the module is imported). - `FileApiService` — high-level service used by the controller; safe to inject into your own code. - `FileSystemService` — low-level filesystem helper. ## Dependencies - `@loopstack/common`, `@loopstack/contracts`, `@loopstack/core` — workspace resolution, auth decorator, feature registration. - `@nestjs/common`, `@nestjs/config`, `@nestjs/typeorm`, `typeorm` — standard Loopstack backend stack. - `yaml` — for parsing workflow YAML files on read. ## Related - [`@loopstack/remote-file-explorer`](https://loopstack.ai/docs/registry/remote-file-explorer) — same API surface but proxies to a remote agent for remote machines. ## About Part of the [Loopstack](https://loopstack.ai) registry. MIT-licensed. --- > Source: https://loopstack.ai/llms/registry/packages/mcp.md --- title: MCP Module description: Remote MCP client tools for Loopstack — McpModule.forRoot(), McpCallTool (mcp_call), McpListToolsTool (mcp_list_tools), McpToolConfig with allowedHosts, hostHeaderEnv, SSRF allowlist, Streamable HTTP and SSE transports, McpClientService, error hierarchy, McpMetricsPort --- # @loopstack/mcp > Remote-MCP client module for the [Loopstack](https://loopstack.ai) automation framework. Lets a Loopstack agent list and call tools on remote Model Context Protocol (MCP) servers over HTTPS — Streamable HTTP or legacy SSE — with a strict SSRF allowlist and zero-trust handling of authentication secrets. ## When to Use - **Connect an agent to hosted MCP servers** (Linear, GitHub, internal tools) without writing custom tool wrappers for each API. - **Dynamically discover remote tool schemas** at runtime via `mcp_list_tools`, then invoke them with `mcp_call`. - **Reach multiple MCP servers from one workflow** — `serverUrl` is a per-call argument, so a single agent can hop between any allowlisted host. - **Not an MCP server** — this module does not expose your workflows over MCP. It is a client only. ## Installation ```sh npm install @loopstack/mcp ``` Register the module with `McpModule.forRoot()`: ```ts import { Module } from '@nestjs/common'; import { McpModule } from '@loopstack/mcp'; @Module({ imports: [ McpModule.forRoot({ allowedHosts: ['mcp.linear.app'], hostHeaderEnv: { 'mcp.linear.app': { Authorization: 'LINEAR_MCP_TOKEN' }, }, }), ], }) export class AppModule {} ``` Set the corresponding env var. The value is sent raw — include `Bearer ` if the server expects it: ```env LINEAR_MCP_TOKEN="Bearer lin_oauth_..." ``` ## Quick Start This example mirrors the Linear workflow in the [MCP examples](/docs/examples/mcp). It starts a `ChatAgentWorkflow` sub-workflow with both MCP tools available. ```ts // mcp-linear.module.ts import { Module } from '@nestjs/common'; import { AgentModule } from '@loopstack/agent'; import { McpModule } from '@loopstack/mcp'; import { McpLinearWorkflow } from './mcp-linear.workflow'; @Module({ imports: [ McpModule.forRoot({ allowedHosts: ['mcp.linear.app'], hostHeaderEnv: { 'mcp.linear.app': { Authorization: 'LINEAR_MCP_TOKEN' } }, }), AgentModule, ], providers: [McpLinearWorkflow], exports: [McpLinearWorkflow], }) export class McpLinearModule {} ``` ```ts // mcp-linear.workflow.ts import { z } from 'zod'; import { ChatAgentWorkflow } from '@loopstack/agent'; import { BaseWorkflow, Transition, Workflow } from '@loopstack/common'; import type { RunContext } from '@loopstack/common'; const ArgsSchema = z.object({ initialMessage: z.string().optional().default('List available Linear tools, then fetch my top 5 issues.'), }); @Workflow({ title: 'MCP Linear', description: 'Chat with an agent connected to Linear via MCP.', schema: ArgsSchema, }) export class McpLinearWorkflow extends BaseWorkflow> { constructor(private readonly chatAgentWorkflow: ChatAgentWorkflow) { super(); } @Transition({ to: 'chatting' }) async startChat(state: Record, ctx: RunContext>) { await this.chatAgentWorkflow.run( { system: 'You are a Linear assistant. Use mcp_list_tools to discover tools, then mcp_call to invoke them.', tools: ['mcp_list_tools', 'mcp_call'], userMessage: ctx.args.initialMessage, }, { show: 'inline', label: 'Linear Agent Chat' }, ); } } ``` Tools are referenced by their `@Tool({ name })` values (`'mcp_list_tools'`, `'mcp_call'`) and resolved from the NestJS DI container at runtime. ## How It Works ``` Agent LLM loop │ ├─ mcp_list_tools(serverUrl, transport?) │ └─ McpClientService.listTools() → connect, list, disconnect │ └─ mcp_call(serverUrl, toolName, arguments, transport?) └─ McpClientService.callTool() → connect, call, disconnect ``` Each tool call creates a fresh MCP client connection. Before any bytes go out, the URL passes through the security pipeline (allowlist, scheme, DNS resolution). Headers are merged from config and env vars are resolved at call time. The agent decides which `serverUrl` and `toolName` to use per call, so a single workflow can reach any host in `allowedHosts`. ### Security Model Every connection passes three checks: 1. **Allowlist** — `serverUrl`'s hostname must match `allowedHosts`. Exact match or `*.example.com` (which also matches `example.com`). 2. **Scheme** — `https://` by default; `http://` only if `allowInsecureHttp: true`. 3. **Public-IP resolution** — DNS (or a literal IP) must resolve to a routable public address. Loopback, RFC1918, link-local, ULA, and IPv4-mapped equivalents are rejected. Override with `allowPrivateHosts: true` for trusted local MCP proxies. Userinfo in the URL (`https://user:pw@host/...`) is rejected — credentials must flow through headers. ### Authentication Three knobs, in increasing specificity: | Knob | Use for | | ---------------- | ------------------------------------------------------------------------------------------------------------------ | | `defaultHeaders` | Static, **non-secret** values (e.g. `X-Trace: on`). Sensitive header names like `Authorization` are rejected here. | | `headerEnv` | `header -> env-var` mapping applied to every host. Value is read from `process.env` at call time. | | `hostHeaderEnv` | `host -> { header -> env-var }`. Use `'*'` for all hosts. Host-specific entries override the wildcard. | Precedence (later wins): `defaultHeaders` -> `headerEnv` -> `hostHeaderEnv['*']` -> `hostHeaderEnv[hostname]`. Header names are logged on connect (e.g. `headers=[Authorization]`); values never are. If a referenced env var is unset or empty, the header is silently omitted. ### Transport | Server | Transport | | ------------------------- | -------------------------- | | Linear (`mcp.linear.app`) | `sse` | | Most modern hosted MCP | `streamableHttp` (default) | Pass `transport: 'sse'` per call when needed. ### Multiple MCP Servers `serverUrl` is a per-call argument. An agent can reach any host listed in `allowedHosts`. To add a new server: 1. Add its hostname to `allowedHosts`. 2. Add its auth mapping to `hostHeaderEnv`. 3. Set the corresponding env var. Dynamic, end-user-driven server registration (paste any URL mid-chat) is deliberately not supported — the allowlist exists to prevent agents from being tricked into hitting internal hosts. ## Tools Reference ### `mcp_list_tools` Lists tool definitions exposed by a remote MCP server. **Class:** `McpListToolsTool` | Arg | Type | Required | Description | | ----------- | --------------------------- | -------- | ----------------------------------------------------------- | | `serverUrl` | `z.url()` | Yes | MCP endpoint URL (https recommended). | | `transport` | `'streamableHttp' \| 'sse'` | No | Default `'streamableHttp'`. Use `'sse'` for legacy servers. | | `timeoutMs` | `number` (1–900000) | No | Per-request timeout in milliseconds. | **Config:** `McpToolConfig` (via `configSchema` / `options.config` / `McpModule.forRoot()`) **Returns:** `{ data: { tools: unknown } }` — the MCP `tools/list` response. ### `mcp_call` Calls a tool on a remote MCP server. **Class:** `McpCallTool` | Arg | Type | Required | Description | | ----------- | --------------------------- | -------- | ----------------------------------------------------------- | | `serverUrl` | `z.url()` | Yes | MCP endpoint URL (https recommended). | | `toolName` | `string` | Yes | Name of the remote MCP tool to invoke. | | `arguments` | `Record` | No | JSON object passed to the tool. Defaults to `{}`. | | `transport` | `'streamableHttp' \| 'sse'` | No | Default `'streamableHttp'`. Use `'sse'` for legacy servers. | | `timeoutMs` | `number` (1–900000) | No | Per-request timeout in milliseconds. | **Config:** `McpToolConfig` (via `configSchema` / `options.config` / `McpModule.forRoot()`) **Returns:** `{ data: McpCallToolResult }` — either `{ kind: 'callToolResult', content, structuredContent?, isError? }` or `{ kind: 'legacyToolResult', toolResult }`. ## Configuration ### `McpModule.forRoot(config?)` Registers the module globally. Config is optional — if omitted, each tool call must provide config via `options.config`. | Option | Type | Default | Description | | ------------------- | ---------------------------------------- | ------- | ------------------------------------------------------------------------------------------ | | `allowedHosts` | `string[]` | — | Required. Hostnames allowed for `serverUrl`. Use `*.example.com` for wildcard. | | `allowInsecureHttp` | `boolean` | `false` | Allow `http://` URLs. | | `allowPrivateHosts` | `boolean` | `false` | Skip public-IP DNS check. For trusted local MCP proxies only. | | `defaultHeaders` | `Record` | — | Static non-secret headers. Sensitive names (`Authorization`, `Cookie`, etc.) are rejected. | | `headerEnv` | `Record` | — | `headerName -> envVarName` applied to every host. | | `hostHeaderEnv` | `Record>` | — | `hostname -> { headerName -> envVarName }`. Use `'*'` for all hosts. | ### Per-call config override Inject the tool and pass config via `options.config`: ```ts await this.mcpCallTool.call(args, { config: { allowedHosts: ['mcp.linear.app'], hostHeaderEnv: { 'mcp.linear.app': { Authorization: 'LINEAR_MCP_TOKEN' } }, }, }); ``` Per-call config overrides `McpModule.forRoot()` defaults entirely. If no config is provided at either level, the tool throws. ### Provider tokens | Token | Default | Description | | -------------------- | ------------------ | ---------------------------------------------------------------------------------------- | | `MCP_METRICS` | `NoopMcpMetrics` | Implement `McpMetricsPort` for OpenTelemetry or custom metrics. | | `MCP_ENV_READER` | `ProcessEnvReader` | Implement `EnvReader` to source secrets from a secrets manager instead of `process.env`. | | `MCP_DEFAULT_CONFIG` | `null` | Set by `McpModule.forRoot()`. Can also be provided manually. | ## Errors All failures throw subclasses of `McpError`: | Error class | Cause | | --------------------- | ------------------------------------------------ | | `McpUrlSecurityError` | SSRF / allowlist / scheme / userinfo violations. | | `McpAuthError` | 401 / 403 from the remote server. | | `McpTimeoutError` | Call exceeded `timeoutMs`. | | `McpProtocolError` | Malformed MCP response (JSON-RPC parse/invalid). | | `McpTransportError` | DNS, TCP, TLS, abort, or fallback failures. | Catch `McpError` for any failure, or a specific subclass to react to a category. ## Observability The service logs structured events with header names only, never values: ``` mcp.connect host=mcp.linear.app transport=sse headers=[Authorization] mcp.connect.done host=mcp.linear.app transport=sse outcome=success latencyMs=412 mcp.callTool host=mcp.linear.app transport=sse toolName=createIssue outcome=success latencyMs=623 ``` Override `MCP_METRICS` for custom metric collection: ```ts @Module({ providers: [{ provide: MCP_METRICS, useClass: MyOtelMetrics }], }) ``` ## Public API - **Module:** `McpModule` - **Tools:** `McpCallTool`, `McpListToolsTool`, `McpToolBase` - **Services:** `McpClientService` - **Schemas:** `McpToolConfigSchema`, `McpCallToolArgsSchema`, `McpListToolsArgsSchema`, `McpConnectionArgsSchema` - **Types:** `McpToolConfig`, `McpToolConfigInput`, `McpTransportKind`, `McpCallToolResult`, `McpClientCallOptions` - **Errors:** `McpError`, `McpUrlSecurityError`, `McpAuthError`, `McpTimeoutError`, `McpProtocolError`, `McpTransportError` - **Tokens:** `MCP_DEFAULT_CONFIG`, `MCP_METRICS`, `MCP_ENV_READER` - **Interfaces:** `McpMetricsPort`, `McpConnectSample`, `McpCallSample`, `McpCallOutcome`, `EnvReader` - **Utilities:** `hostMatchesAllowlist`, `assertIpIsPublic`, `assertResolvableHostIsPublic`, `assertMcpUrlSafe` - **Implementations:** `ProcessEnvReader`, `NoopMcpMetrics` ## Dependencies | Package | Role | | -------------------------------- | ---------------------------------------------------- | | `@modelcontextprotocol/sdk` | MCP client, Streamable HTTP and SSE transports | | `@loopstack/common` | `BaseTool`, `@Tool`, `ToolCallOptions`, `RunContext` | | `@loopstack/core` | `LoopCoreModule` (NestJS integration) | | `@nestjs/common`, `@nestjs/core` | Dependency injection, module system | | `zod` | Schema validation | ## Related - [MCP Linear example](https://loopstack.ai/docs/examples/mcp#linear) — Full working example connecting a ChatAgentWorkflow to Linear via MCP. - [Agent Workflows](https://loopstack.ai/docs/build/ai/agent-workflows) — How `ChatAgentWorkflow` and tool resolution work. - [Tool Configuration](https://loopstack.ai/docs/build/fundamentals/tools) — How `configSchema` and `options.config` are merged at call time. - [`@loopstack/claude`](https://loopstack.ai/docs/registry/claude) — LLM provider that powers the agent loop calling MCP tools. ## About **Author:** Jakob Klippel **License:** MIT --- > Source: https://loopstack.ai/llms/registry/packages/oauth.md --- title: OAuth Module description: Provider-agnostic OAuth 2.0 framework for Loopstack — OAuthModule, OAuthWorkflow, OAuthProviderRegistry, OAuthTokenStore, OAuthProviderInterface, BuildOAuthUrlTool, ExchangeOAuthTokenTool, OAuthPromptDocument, token storage with Redis fallback, pluggable provider interface, authorization code flow --- # @loopstack/oauth > OAuth module for the [Loopstack](https://loopstack.ai) automation framework. A provider-agnostic OAuth 2.0 framework that handles the full authorization code flow — URL generation, code exchange, token storage, and automatic refresh. Any provider (Google, GitHub, Microsoft, etc.) can be plugged in by implementing a single interface. ## When to Use - You need OAuth 2.0 authentication in your workflows (e.g. accessing Google Calendar, GitHub repos, or any third-party API) - You want a reusable sub-workflow that handles the entire auth flow (popup, code exchange, token storage) and resumes the parent workflow on completion - You are building a custom OAuth provider integration and need a standardized registration and token management layer - Use `@loopstack/google-workspace` or `@loopstack/github` directly if you only need Google or GitHub — they include their own providers and import `OAuthModule` internally ## Installation ```bash npm install @loopstack/oauth ``` Register the module in your NestJS module. `OAuthModule` is `@Global()`, so a single import makes its services available everywhere: ```typescript import { Module } from '@nestjs/common'; import { OAuthModule } from '@loopstack/oauth'; @Module({ imports: [OAuthModule], }) export class AppModule {} ``` ## Quick Start Inject `OAuthWorkflow` into your workflow and launch it as a sub-workflow when authentication is needed: ```typescript import { BaseWorkflow, Guard, Transition, Workflow } from '@loopstack/common'; import type { RunContext, TransitionInput } from '@loopstack/common'; import { OAuthWorkflow } from '@loopstack/oauth'; const CalendarSchema = z.object({ calendarId: z.string().default('primary') }).strict(); type CalendarArgs = z.infer; @Workflow({ schema: CalendarSchema, }) 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, }); } @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; } @Transition({ from: 'awaiting_auth', to: 'start', wait: true }) authCompleted(state: CalendarState, _input: TransitionInput) {} @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 }), }); } } ``` `show: 'inline'` (the default) renders the OAuth sub-workflow as an embedded iframe in the parent's run view, so the user can complete authentication without leaving the page. ## How It Works ### Architecture ``` oauth-module (generic) provider module (e.g. google) ┌──────────────────────────────┐ ┌──────────────────────────────┐ │ OAuthProviderRegistry │◄───│ GoogleWorkspaceOAuthProvider│ │ OAuthTokenStore │ │ (implements interface, │ │ BuildOAuthUrlTool │ │ registers on init) │ │ ExchangeOAuthTokenTool │ └──────────────────────────────┘ │ OAuthWorkflow │ │ OAuthPromptDocument │ consumer workflow └──────────────────────────────┘ ┌──────────────────────────────┐ │ uses OAuthTokenStore │ │ launches OAuthWorkflow │ │ via constructor injection │ └──────────────────────────────┘ ``` The module is split into four layers: 1. **Provider registry** — provider modules implement `OAuthProviderInterface` and self-register via `OnModuleInit` 2. **OAuth workflow** — a generic workflow that builds the auth URL, shows a sign-in prompt, waits for the callback, then exchanges the code for tokens 3. **Token store** — persists tokens per user per provider in Redis (falls back to in-memory if Redis is unavailable) 4. **Public callback endpoints** — complete the flow from `code` + `state` alone; the single-use state token (10 minute TTL, registered via `OAuthSessionService` when the auth URL is built) resolves the pending workflow server-side ### Callback / Redirect URI Modes The provider's `*_OAUTH_REDIRECT_URI` can point at either of two supported targets (register the one you use in the provider console): | Redirect URI | How the flow completes | | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `/api/v1/oauth/callback` | **Backend callback.** The API completes the exchange server-side and renders a minimal confirmation page. Works without the Studio frontend — CLI-printed auth URLs and headless deployments. | | `/oauth/callback` | **Studio callback page.** Opened as a popup from Studio it posts `code`/`state` back to the opener (classic flow); opened directly (e.g. from a CLI link) it falls back to `POST /api/v1/oauth/complete`. | Both paths fire the waiting workflow's `exchangeToken` transition as the user who started the flow; the state parameter stays the CSRF anchor and is additionally single-use server-side. ### OAuthWorkflow State Machine ``` start ──► initiateOAuth ──► awaiting_auth ──► exchangeToken ──► end │ │ │ Builds auth URL via │ Validates CSRF state, │ BuildOAuthUrlTool, │ exchanges code via │ saves OAuthPromptDocument │ ExchangeOAuthTokenTool, │ with sign-in prompt │ stores tokens, updates │ │ document to 'success' ▼ ▼ (waits for user to (callback resumes complete OAuth in browser) parent workflow) ``` ### Token Lifecycle 1. `OAuthWorkflow` calls `BuildOAuthUrlTool` to generate an auth URL with a CSRF state parameter 2. The user completes OAuth in the browser popup 3. The callback triggers `exchangeToken`, which validates the state and calls `ExchangeOAuthTokenTool` 4. Tokens are stored per user per provider via `OAuthTokenStore` 5. `OAuthTokenStore.getValidAccessToken()` automatically refreshes expired tokens using the provider's `refreshToken()` method 6. Tools return `{ error: 'unauthorized' }` when no valid token exists, triggering the workflow guard ### Using Tokens in Custom Tools Inject `OAuthTokenStore` to access stored tokens: ```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: 'my_api_fetch', description: 'Fetches data from an OAuth-protected API.', schema: z.object({ query: z.string() }).strict(), }) export class MyApiFetchTool extends BaseTool { constructor(private readonly tokenStore: OAuthTokenStore) { super(); } protected async handle(args: { query: string }, ctx: RunContext): Promise { const accessToken = await this.tokenStore.getValidAccessToken(ctx.userId, 'my-provider'); if (!accessToken) { return { data: { error: 'unauthorized' } }; } const response = await fetch('https://api.example.com/data', { headers: { Authorization: `Bearer ${accessToken}` }, }); return { data: await response.json() }; } } ``` ## Args Reference ### OAuthWorkflow | Arg | Type | Required | Description | | ---------- | ---------- | -------- | ---------------------------------------------------------------- | | `provider` | `string` | Yes | Provider ID (e.g. `'google'`, `'github'`) | | `scopes` | `string[]` | No | OAuth scopes to request (defaults to provider's `defaultScopes`) | **Run options:** | Option | Type | Description | | ---------- | -------- | ---------------------------------------------------------------------------------------- | | `callback` | `object` | `{ transition: string }` — transition to call on the parent workflow when auth completes | **Returns:** `{ authenticated: boolean }` ## Tools Reference ### `build_oauth_url` Builds an OAuth 2.0 authorization URL for the given provider with a CSRF state parameter. | Arg | Type | Required | Description | | ---------- | ---------- | -------- | ----------------------- | | `provider` | `string` | Yes | Provider ID | | `scopes` | `string[]` | Yes | OAuth scopes to request | **Returns:** `{ authUrl: string, state: string }` ### `exchange_oauth_token` Exchanges an OAuth 2.0 authorization code for access and refresh tokens, validates the CSRF state, and stores the tokens globally for the user. | Arg | Type | Required | Description | | --------------- | -------- | -------- | -------------------------------------- | | `provider` | `string` | Yes | Provider ID | | `code` | `string` | Yes | Authorization code from OAuth callback | | `state` | `string` | Yes | State parameter from callback | | `expectedState` | `string` | Yes | Expected state for CSRF validation | **Returns:** `{ accessToken: string, refreshToken: string | undefined, expiresIn: number | undefined, scope: string | undefined }` ## Configuration ### Redis (Token Storage) `OAuthTokenStore` connects to Redis for persistent token storage. If Redis is unavailable, it falls back to in-memory storage. | Env Variable | Default | Description | | ---------------- | ----------- | -------------- | | `REDIS_HOST` | `localhost` | Redis host | | `REDIS_PORT` | `6379` | Redis port | | `REDIS_PASSWORD` | — | Redis password | Tokens with refresh tokens are stored with a 30-day TTL. Access-only tokens expire based on their `expiresIn` value; a token set without `expiresIn` is treated as never expiring and stored with a 30-day TTL. When a refresh returns a new refresh token (rotation) or scope, the store replaces the stored one; otherwise it keeps the previous value. ## Service Reference ### OAuthProviderRegistry Manages registered OAuth providers at runtime. | Method | Description | | -------------------- | ---------------------------------------- | | `register(provider)` | Register a provider instance | | `get(providerId)` | Get a provider by ID (throws if missing) | | `has(providerId)` | Check if a provider is registered | ### OAuthTokenStore Stores and retrieves OAuth tokens per user and provider. Uses Redis with in-memory fallback. | Method | Description | | -------------------------------------------- | ----------------------------------------------------------------- | | `storeTokens(userId, providerId, tokens)` | Store a `StoredTokens` object for a user/provider pair | | `storeFromTokenSet(userId, providerId, set)` | Store tokens from an `OAuthTokenSet` (auto-calculates expiry) | | `getTokens(userId, providerId)` | Get stored tokens (may be expired) | | `getValidAccessToken(userId, providerId)` | Get a valid access token, auto-refreshing if expired and possible | ## Provider Interface Reference Implement `OAuthProviderInterface` to add a new OAuth provider: ```typescript interface OAuthProviderInterface { readonly providerId: string; // Unique identifier, e.g. 'google', 'github' readonly defaultScopes: string[]; // Fallback scopes when none are specified buildAuthUrl(scopes: string[], state: string): string; exchangeCode(code: string): Promise; refreshToken(refreshToken: string): Promise; } interface OAuthTokenSet { accessToken: string; refreshToken?: string; expiresIn?: number; // Seconds until expiry; omit when the provider reports none (never expires) scope: string; } ``` | 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 | The provider self-registers via NestJS `OnModuleInit`: ```typescript @Injectable() export class MyOAuthProvider implements OAuthProviderInterface, OnModuleInit { readonly providerId = 'my-provider'; readonly defaultScopes = ['read', 'write']; constructor(private readonly registry: OAuthProviderRegistry) {} onModuleInit(): void { this.registry.register(this); } buildAuthUrl(scopes: string[], state: string): string { /* ... */ } async exchangeCode(code: string): Promise { /* ... */ } async refreshToken(refreshToken: string): Promise { /* ... */ } } ``` Wrap it in a module that imports `OAuthModule`: ```typescript @Module({ imports: [OAuthModule], providers: [MyOAuthProvider], exports: [MyOAuthProvider], }) export class MyOAuthModule {} ``` ### Existing Providers | Provider | Module | Provider ID | | -------- | ----------------------------- | ----------- | | Google | `@loopstack/google-workspace` | `'google'` | | GitHub | `@loopstack/github` | `'github'` | ## Document Types ### OAuthPromptDocument Rendered by the `oauth-prompt` widget. Used internally by the `OAuthWorkflow` to show the sign-in prompt with a popup-based authentication flow. | Field | Type | Description | | ---------- | ----------------------------------- | --------------------------- | | `provider` | `string` | Provider ID | | `authUrl` | `string` | The OAuth authorization URL | | `state` | `string` | CSRF state parameter | | `status` | `'pending' \| 'success' \| 'error'` | Current auth status | | `message` | `string` (optional) | Status message | ## Public API **Module** - `OAuthModule` — global NestJS module, registers all providers/services/tools/workflows **Services** - `OAuthProviderRegistry` — runtime registry for OAuth providers - `OAuthTokenStore` — token persistence with Redis/in-memory fallback **Tools** - `BuildOAuthUrlTool` (`build_oauth_url`) — generates authorization URLs - `ExchangeOAuthTokenTool` (`exchange_oauth_token`) — exchanges codes for tokens **Workflows** - `OAuthWorkflow` — generic OAuth 2.0 authorization code flow **Documents** - `OAuthPromptDocument` — sign-in prompt rendered by `oauth-prompt` widget **Contracts** - `OAuthProviderInterface` — interface for pluggable OAuth providers - `OAuthTokenSet` — token response shape returned by providers - `StoredTokens` — internal token storage shape (includes `expiresAt`) ## Dependencies | Package | Role | | ------------------- | ------------------------------------- | | `@loopstack/common` | Base classes, decorators, types | | `@loopstack/core` | Workflow engine, sub-workflow support | | `ioredis` | Redis client for token storage | | `zod` | Schema validation | ## Related - [OAuth Authentication](https://loopstack.ai/docs/build/integrations/oauth) — guide for integrating OAuth into workflows, using tokens in tools, and the try-then-authenticate pattern - [Creating OAuth Providers](https://loopstack.ai/docs/extend/oauth-providers) — step-by-step guide for implementing `OAuthProviderInterface` - [google-workspace examples](/docs/examples/google-workspace) — Google Calendar fetch with OAuth sub-workflow and Google Workspace agent - [github examples](/docs/examples/github) — GitHub OAuth with repos overview workflow and 25+ GitHub tools ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/registry/packages/openai.md --- title: OpenAI Module description: OpenAI LLM provider for the Loopstack automation framework. Implements LlmProviderInterface with the OpenAI SDK. --- # @loopstack/openai ## Installation ```sh npm install @loopstack/openai ``` Register the module in your app module: ```ts import { Module } from '@nestjs/common'; import { OpenAiModule } from '@loopstack/openai'; @Module({ imports: [OpenAiModule], }) export class AppModule {} ``` `OpenAiModule` registers the `openai` provider into the LLM provider registry on startup, so import it alongside `LlmProviderModule` (from `@loopstack/llm-provider`). The module reads the OpenAI API key from the `OPENAI_API_KEY` environment variable: ```env OPENAI_API_KEY=sk-... ``` --- > Source: https://loopstack.ai/llms/registry/packages/quota.md --- title: Quota Module description: Opt-in quota tracking and enforcement for Loopstack tool calls — QuotaModule.forRoot(), QuotaInterceptor, QuotaCalculatorRegistry, QuotaClientService, AiGenerateTextQuotaCalculator, ProcessingTimeQuotaCalculator, Redis-backed usage counters, model pricing lookup --- # @loopstack/quota > Quota tracking module for the [Loopstack](https://loopstack.ai) automation framework. Opt-in, Redis-backed quota tracking and enforcement for tool calls. Ships with calculators for AI token cost (USD-based, per-model pricing) and processing time, and lets you register custom calculators for any tool. ## When to Use - You run workflows that call LLM tools and need to track or cap per-user spend - You want to enforce processing-time limits across all tool calls - You need a pluggable quota system where different tools report different cost metrics - You are building a multi-tenant platform and need per-user usage counters backed by Redis If you only need simple rate limiting (requests per minute), a standard NestJS throttler may be simpler. This module is designed for cumulative usage tracking with heterogeneous cost models. ## Installation ```sh npm install @loopstack/quota ``` Register the module with explicit options: ```ts import { QuotaModule } from '@loopstack/quota'; @Module({ imports: [ QuotaModule.forRoot({ enabled: true, redisHost: 'localhost', redisPort: 6379, redisPassword: process.env.REDIS_PASSWORD, }), ], }) export class AppModule {} ``` Or read configuration from environment variables: ```ts @Module({ imports: [QuotaModule.forRootAsync()], }) export class AppModule {} ``` `forRootAsync()` reads `QUOTA_ENABLED`, `QUOTA_REDIS_HOST` (fallback `REDIS_HOST`), `QUOTA_REDIS_PORT` (fallback `REDIS_PORT`), and `QUOTA_REDIS_PASSWORD` (fallback `REDIS_PASSWORD`). When `enabled` is `false` (the default), the Redis connection is skipped and the interceptor becomes a no-op — safe to leave wired up in development. ## Quick Start Once the module is registered, the `QuotaInterceptor` is automatically discovered via `@UseToolInterceptor()` and runs on every tool call. No additional wiring is needed for the built-in calculators. The module auto-registers `AiGenerateTextQuotaCalculator` for `LlmGenerateTextTool`, `LlmGenerateObjectTool` and `WebFetchTool` (`@loopstack/web`, metered when it summarizes with a `prompt`) on startup. To read or manipulate quota counters directly, inject `QuotaClientService`: ```ts import { Injectable } from '@nestjs/common'; import { QuotaClientService } from '@loopstack/quota'; @Injectable() export class BillingService { constructor(private readonly quotaClient: QuotaClientService) {} async getUserUsage(userId: string) { const llmCost = await this.quotaClient.checkQuota(userId, 'llm-cost'); const processingTime = await this.quotaClient.checkQuota(userId, 'processing-time-ms'); return { llmCost, processingTime }; } } ``` ## How It Works The `QuotaInterceptor` wraps every tool call with a pre-check / post-report cycle: ``` Tool call starts | v Check processing-time quota --> exceeded? --> throw Error | v Look up tool-specific calculator in QuotaCalculatorRegistry | v Check tool-specific quota --> exceeded? --> throw Error | v Execute tool | v Report processing-time usage (wall-clock ms) | v Report tool-specific usage (e.g. LLM cost in microcents) | v Return result ``` ### Quota types Two quota types are tracked out of the box: | Quota Type | Calculator | Unit | Description | | -------------------- | ------------------------------- | -------------------------------- | -------------------------------------------------------------------- | | `llm-cost` | `AiGenerateTextQuotaCalculator` | Microcents (1 USD = 100,000,000) | Computes cost from input/output/cache tokens using per-model pricing | | `processing-time-ms` | `ProcessingTimeQuotaCalculator` | Milliseconds | Wall-clock duration of each tool call | ### Model pricing `AiGenerateTextQuotaCalculator` uses `getModelPricing(provider, model)` to look up per-token rates. The pricing table includes Claude (Opus 4, Sonnet 4, Haiku 4, 3.5 Sonnet, 3.5 Haiku) and OpenAI (GPT-4o, GPT-4.1, o3, o4-mini, and variants). Lookup uses longest-prefix matching with provider-level fallbacks. ### Redis key structure Counters are stored as Redis keys with the pattern: ``` user:{userId}:quota:{quotaType}:used — cumulative usage (INCRBY) user:{userId}:quota:{quotaType}:limit — configured limit (-1 = unlimited) ``` If no `limit` key exists in Redis, the quota is blocked by default. Set the limit key to `-1` for unlimited access. ### Fail-open behavior If Redis is unreachable, both `checkQuota` and `report` fail open — the tool call proceeds and a warning is logged. ### Registering a custom calculator Inject `QuotaCalculatorRegistry` and register from any module's `onModuleInit`: ```ts import { Module, OnModuleInit } from '@nestjs/common'; import { ToolEnvelope, ToolExecutionContext } from '@loopstack/common'; import { QuotaCalculatorRegistry, ToolQuotaCalculator } from '@loopstack/quota'; class ApiCallQuotaCalculator implements ToolQuotaCalculator { quotaType = 'api-calls'; calculateQuotaUsage(_context: ToolExecutionContext, _result: ToolEnvelope) { return { quotaType: this.quotaType, actualAmount: 1 }; } } @Module({}) export class MyModule implements OnModuleInit { constructor(private readonly registry: QuotaCalculatorRegistry) {} onModuleInit() { this.registry.register('MyApiTool', new ApiCallQuotaCalculator()); } } ``` The registry key is the tool's **class name** (not the `@Tool({ name })` value). ## Configuration ### `QuotaModule.forRoot(options)` | Option | Type | Default | Description | | --------------- | --------- | ------------- | ------------------------------------------ | | `enabled` | `boolean` | `false` | Enable quota tracking and Redis connection | | `redisHost` | `string` | `'localhost'` | Redis host | | `redisPort` | `number` | `6379` | Redis port | | `redisPassword` | `string` | — | Redis password | ### Environment variables (`forRootAsync`) | Variable | Fallback | Description | | ---------------------- | ---------------- | ------------------------- | | `QUOTA_ENABLED` | — | Set to `'true'` to enable | | `QUOTA_REDIS_HOST` | `REDIS_HOST` | Redis host | | `QUOTA_REDIS_PORT` | `REDIS_PORT` | Redis port | | `QUOTA_REDIS_PASSWORD` | `REDIS_PASSWORD` | Redis password | ## Public API - **Module:** `QuotaModule` — `forRoot(options)`, `forRootAsync()` - **Services:** `QuotaClientService` — `checkQuota(userId, quotaType)`, `report(userId, quotaType, amount)` - **Services:** `QuotaCalculatorRegistry` — `register(toolClassName, calculator)`, `get(toolClassName)`, `has(toolClassName)` - **Interceptor:** `QuotaInterceptor` — auto-discovered via `@UseToolInterceptor({ priority: 50 })` - **Calculators:** `AiGenerateTextQuotaCalculator` (quota type: `llm-cost`), `ProcessingTimeQuotaCalculator` (quota type: `processing-time-ms`) - **Interfaces:** `ToolQuotaCalculator`, `QuotaClientServiceInterface`, `QuotaCheckResult`, `QuotaUsage` - **Tokens:** `QUOTA_CLIENT_SERVICE`, `QUOTA_REDIS` - **Utilities:** `getModelPricing(provider, model)`, `ModelPricing` ## Dependencies | Package | Role | | ------------------- | -------------------------------------------------------------------------------- | | `@loopstack/common` | `ToolInterceptor`, `ToolExecutionContext`, `ToolEnvelope`, `@UseToolInterceptor` | | `@nestjs/common` | NestJS dependency injection | | `ioredis` | Redis client for quota counters | ## Related - [LLM Providers](https://loopstack.ai/docs/build/ai/llm-providers) — how LLM tools report token usage metadata consumed by the quota calculator - [@loopstack/claude](https://loopstack.ai/docs/registry/claude) — Claude integration whose tools are metered by the built-in `AiGenerateTextQuotaCalculator` ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/registry/packages/remote-client.md --- title: Remote Client Module description: HTTP client and workflow tools for Loopstack remote servers — RemoteClientModule, RemoteClient service, EnvironmentService, ReadTool, WriteTool, EditTool, BashTool, GlobTool, GrepTool, RebuildAppTool, ResetWorkspaceTool, LogsTool, SyncSecretsTool, file operations, shell commands, environment management on remote workspaces --- # @loopstack/remote-client > Remote environment module for the [Loopstack](https://loopstack.ai) automation framework. HTTP client and workflow tools for communicating with a Loopstack remote server — the sandboxed process that owns a workspace's filesystem and shell. This module provides the foundation that other registry packages (git, code-agent, remote-file-explorer) build on top of. The server it talks to ships in this package's `server/` directory — see [Server](#server). ## When to Use - You need to read, write, or edit files on a remote workspace from within a workflow - You need to execute shell commands on a remote instance - You need to manage application lifecycle (rebuild, reset, logs) on a remote environment - You are building a module that needs low-level access to the remote server API — inject `RemoteClient` directly ## Installation ```sh npm install @loopstack/remote-client ``` Register the module with `forRoot()`: ```ts import { RemoteClientModule } from '@loopstack/remote-client'; @Module({ imports: [RemoteClientModule.forRoot()], }) export class AppModule {} ``` `RemoteClientModule.forRoot()` registers globally and depends on `SecretsModule` and TypeORM entities (`WorkspaceEntity`, `WorkspaceEnvironmentEntity`). ## Quick Start Inject tools directly into your workflow via the constructor — they are NestJS providers resolved by their `@Tool({ name })` value through DI: ```ts import { BaseWorkflow, Transition, Workflow } from '@loopstack/common'; import { BashTool, EditTool, ReadTool } from '@loopstack/remote-client'; @Workflow({ widget: './my.ui.yaml' }) export class MyWorkflow extends BaseWorkflow { constructor( private readonly read: ReadTool, private readonly edit: EditTool, private readonly bash: BashTool, ) { super(); } @Transition({ from: 'ready', to: 'done' }) async bumpVersion(state: unknown, ctx: RunContext) { const { data } = await this.read.call({ file_path: 'package.json' }); await this.edit.call({ file_path: 'package.json', old_string: '"version": "0.1.0"', new_string: '"version": "0.2.0"', }); await this.bash.call({ command: 'npm install' }); } } ``` Every tool automatically resolves the remote agent URL from the current execution scope — you never pass connection details manually. ## How It Works A Loopstack workspace runs inside a remote server (container, VM, or local process) that exposes an HTTP API for file operations, shell commands, and environment management. ``` Workflow / Tool | v EnvironmentService --> resolves agent URL from execution scope | v RemoteClient --> typed HTTP client (fetch-based) | v Remote Server --> /files/*, /exec, /app/*, /git/* ``` **`EnvironmentService`** resolves the correct remote agent URL for the current workflow execution. It caches environments per execution scope and prefers the `sandbox` slot by default. **`RemoteClient`** is a plain `@Injectable()` service that wraps all HTTP calls to the remote server. It handles file operations, shell execution, app lifecycle, and git operations. You can inject it directly for advanced use cases. ### Using `RemoteClient` directly For cases where tools are not sufficient, inject `RemoteClient` and `EnvironmentService`: ```ts import { Injectable } from '@nestjs/common'; import { EnvironmentService, RemoteClient } from '@loopstack/remote-client'; @Injectable() export class MyService { constructor( private readonly client: RemoteClient, private readonly env: EnvironmentService, ) {} async listFiles(path: string): Promise { const url = await this.env.getAgentUrl(); const result = await this.client.glob(url, `${path}/**/*`); return result.files; } } ``` ### `forFeature()` — Registering environment slots Use `RemoteClientModule.forFeature()` to register environment slot configurations from other modules: ```ts RemoteClientModule.forFeature({ slots: [{ id: 'sandbox', label: 'Sandbox', type: 'fly' }], }); ``` ## Tools Reference All tools resolve the remote agent URL automatically from the execution scope. ### File Operations #### `read` Reads a file from a remote instance. Returns file content. Supports offset and limit for reading specific line ranges. | Arg | Type | Required | Description | | ----------- | -------- | -------- | --------------------------------------------- | | `file_path` | `string` | Yes | The file path to read | | `offset` | `number` | No | Line number to start reading from (1-indexed) | | `limit` | `number` | No | Number of lines to read | **Returns:** `{ content: string, path: string }` #### `write` Writes a file to a remote instance. Creates parent directories if needed. Overwrites existing files. | Arg | Type | Required | Description | | ----------- | -------- | -------- | -------------------------------- | | `file_path` | `string` | Yes | The file path to write | | `content` | `string` | Yes | The content to write to the file | **Returns:** `{ success: boolean, path: string }` #### `edit` Performs exact string replacement in a file on a remote instance. Fails if `old_string` is not unique unless `replace_all` is true. | Arg | Type | Required | Description | | ------------- | --------- | -------- | ---------------------------------------- | | `file_path` | `string` | Yes | The file path to edit | | `old_string` | `string` | Yes | The exact string to find and replace | | `new_string` | `string` | Yes | The replacement string | | `replace_all` | `boolean` | No | Replace all occurrences (default: false) | **Returns:** `{ success: boolean, path: string, replacements: number }` ### Search #### `glob` Finds files by glob pattern on a remote instance. Returns relative file paths. | Arg | Type | Required | Description | | --------- | -------- | -------- | -------------------------------------------------- | | `pattern` | `string` | Yes | Glob pattern to match files (e.g. `**/*.ts`) | | `path` | `string` | No | Directory to search in, relative to workspace root | **Returns:** `{ files: string[] }` #### `grep` Searches file contents by regex pattern on a remote instance. Returns matching lines with file paths and line numbers. | Arg | Type | Required | Description | | ------------------ | --------- | -------- | -------------------------------------------------- | | `pattern` | `string` | Yes | Regex pattern to search for in file contents | | `path` | `string` | No | Directory to search in, relative to workspace root | | `glob` | `string` | No | Glob pattern to filter files (e.g. `*.ts`) | | `type` | `string` | No | File type filter (e.g. `js`, `ts`, `py`) | | `case_insensitive` | `boolean` | No | Case-insensitive search | **Returns:** `{ matches: { file: string, line: number, content: string }[] }` ### Shell #### `bash` Executes a shell command on a remote instance. Streams output live; returns the merged output (`output`) and exit code (`exitCode`). | Arg | Type | Required | Description | | --------- | -------- | -------- | ---------------------------- | | `command` | `string` | Yes | The shell command to execute | | `timeout` | `number` | No | Timeout in milliseconds | **Returns:** `{ stdout: string, stderr: string, exitCode: number }` ### App Lifecycle #### `rebuild_app` Rebuilds and restarts the app on a remote instance. Takes no arguments. **Returns:** `{ success: boolean, message: string }` #### `reset_workspace` Resets the workspace to its initial state, clearing all changes, temp files, database, and Redis. Takes no arguments. **Returns:** `{ success: boolean, message: string }` #### `logs` Retrieves application logs from the remote instance. Returns stdout and/or stderr output from the running application. | Arg | Type | Required | Description | | ------- | --------------------------- | -------- | ------------------------------------------------------------ | | `lines` | `number` | No | Number of recent log lines to return (default 100, max 5000) | | `type` | `"out" \| "error" \| "all"` | No | Which logs to retrieve (default `"all"`) | **Returns:** `{ stdout: string, stderr: string }` ### Secrets #### `sync_secrets` Syncs all workspace secrets to the remote environment as `.env` variables and restarts the app. Call this before or during app restart to ensure secrets (API keys, config values) are available. Takes no arguments. **Returns:** `{ success: boolean, count: number }` or `{ success: true, count: 0, message: string }` when no secrets exist. ## Configuration ### `forRoot()` options ```ts RemoteClientModule.forRoot({ environments: { available: [{ type: 'fly', label: 'Fly.io Machine' }], }, }); ``` | Option | Type | Description | | ------------------------ | --------------------------------- | ------------------------------------------------------- | | `environments.available` | `AvailableEnvironmentInterface[]` | List of available environment types users can provision | ## Public API - **Module:** `RemoteClientModule` - **Services:** `RemoteClient`, `EnvironmentService`, `EnvironmentConfigService` - **Controller:** `EnvironmentController` - **Tools:** `ReadTool`, `WriteTool`, `EditTool`, `BashTool`, `GlobTool`, `GrepTool`, `RebuildAppTool`, `ResetWorkspaceTool`, `LogsTool`, `SyncSecretsTool` - **Entities:** `WorkspaceEnvironmentEntity` - **DTOs:** `WorkspaceEnvironmentContextDto`, `WorkspaceEnvironmentDto` - **Types:** `RemoteClientModuleOptions`, `RemoteClientFeatureOptions`, `BashArgs`, `BashResult`, `EditArgs`, `EditResult`, `GlobArgs`, `GlobResult`, `GrepArgs`, `GrepResult`, `LogsArgs`, `LogsResult`, `ReadArgs`, `ReadResult`, `RebuildAppResult`, `ResetWorkspaceResult`, `SyncSecretsResult`, `WriteArgs`, `WriteResult`, `FileReadResponse`, `FileEditResponse`, `ExecResponse`, `GlobResponse`, `GrepMatch`, `GrepResponse` ## Server `server/` holds `@loopstack/remote-server`, the process that owns a workspace's filesystem and shell and serves the HTTP API this client wraps (`/files/*`, `/exec`, `/app/*`, `/git/*`). It is a private workspace package, not published to npm, and ships as a Docker image for remote machines. Client and server change together, which is why they live together. Run it locally for development: ```bash npm run start:dev -w @loopstack/remote-server # serves on http://localhost:3001 ``` See [`server/README.md`](server/README.md) for the Docker image and deployment. ## Dependencies - `@loopstack/common` — framework utilities, `BaseTool`, `@Tool`, `@Transition`, `EXECUTION_SCOPE` - `@loopstack/secrets` — consumed by `SyncSecretsTool` to read workspace secrets - `@nestjs/common`, `@nestjs/core` — NestJS framework and `DiscoveryModule` - `@nestjs/typeorm`, `typeorm` — workspace and environment entity persistence - `zod` — tool argument schema validation ## Related - [`@loopstack/code-agent`](https://loopstack.ai/docs/registry/code-agent) — AI-powered codebase exploration agent that uses remote-client tools (glob, grep, read) under the hood - [`@loopstack/git`](https://loopstack.ai/docs/registry/git) — Git tools that build on `RemoteClient` git methods - [`@loopstack/remote-file-explorer`](https://loopstack.ai/docs/registry/remote-file-explorer) — File tree browsing via remote-client - [`@loopstack/secrets`](https://loopstack.ai/docs/registry/secrets) — Manages the secrets that `SyncSecretsTool` pushes to remote environments ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/registry/packages/remote-file-explorer.md --- title: Remote File Explorer Module description: REST API controller for browsing files on remote Loopstack workspaces — RemoteFileExplorerModule, RemoteFileExplorerController, file tree and file content endpoints, proxies requests via RemoteClient and EnvironmentService --- # @loopstack/remote-file-explorer > File browsing module for the [Loopstack](https://loopstack.ai) automation framework. Exposes REST endpoints that let a frontend (like Loopstack Studio) browse the file system of a remote workspace. The controller resolves the workspace's remote agent URL and proxies requests through `RemoteClient` from `@loopstack/remote-client`. ## When to Use - You are building a UI that needs to render a **file tree** and display **file contents** for a remote workspace. - You want authenticated REST endpoints that proxy file requests to a remote agent without exposing the agent URL to the client. - Use `@loopstack/local-file-explorer` instead if the files are on the local machine. - Use `GlobTool` / `GrepTool` / `ReadTool` from `@loopstack/remote-client` instead if you need file access inside a workflow (this module provides no workflow tools). ## Installation ```sh npm install @loopstack/remote-file-explorer ``` Register the module in your app: ```ts import { Module } from '@nestjs/common'; import { RemoteFileExplorerModule } from '@loopstack/remote-file-explorer'; @Module({ imports: [RemoteFileExplorerModule], }) export class AppModule {} ``` `RemoteFileExplorerModule` depends on `RemoteClient` and `EnvironmentService` from `@loopstack/remote-client`, which must be available in the DI container (import `RemoteClientModule` in a parent module). ### Feature gating Use `forFeature()` to register the module with optional feature-flag configuration: ```ts RemoteFileExplorerModule.forFeature({ enabled: true, environments: ['production'] }); ``` ## Quick Start Once imported, the controller is available at `/api/v1/workspaces/:workspaceId/remote-files`. No additional setup is required beyond having `RemoteClientModule` registered. ```http GET /api/v1/workspaces/:workspaceId/remote-files/tree?path=src GET /api/v1/workspaces/:workspaceId/remote-files/read?path=src/index.ts ``` Both endpoints require an authenticated user (resolved via `@CurrentUser()`). ## How It Works ``` Frontend (Studio) | | GET /api/v1/workspaces/:workspaceId/remote-files/tree?path=src v RemoteFileExplorerController | | EnvironmentService.getAgentUrlForWorkspace(workspaceId) | -> resolves the remote agent URL for the workspace | | RemoteClient.getFileTree(agentUrl, path) v Remote server (@loopstack/remote-server) | | reads filesystem, returns FileTreeNode[] v Response -> Frontend ``` The controller has two endpoints: 1. **`GET tree`** -- calls `RemoteClient.getFileTree()`. Walks the workspace root when no `path` query param is provided. 2. **`GET read`** -- calls `RemoteClient.readFile()`. Requires a `path` query param. Both endpoints resolve the workspace's agent URL via `EnvironmentService.getAgentUrlForWorkspace()` before proxying. ## Endpoints Reference ### GET `/api/v1/workspaces/:workspaceId/remote-files/tree` Returns the directory tree for the given path. | Parameter | In | Type | Required | Description | | ------------- | ----- | -------- | -------- | -------------------------------------------------- | | `workspaceId` | path | `string` | yes | The workspace ID | | `path` | query | `string` | no | Base path to list (defaults to the workspace root) | **Response:** `FileTreeNode[]` ```ts interface FileTreeNode { id: string; name: string; path: string; type: 'file' | 'folder'; children?: FileTreeNode[]; } ``` ### GET `/api/v1/workspaces/:workspaceId/remote-files/read` Returns the content of a single file. | Parameter | In | Type | Required | Description | | ------------- | ----- | -------- | -------- | ----------------- | | `workspaceId` | path | `string` | yes | The workspace ID | | `path` | query | `string` | yes | File path to read | **Response:** `FileReadResponse` ```ts interface FileReadResponse { content: string; } ``` ## Configuration `RemoteFileExplorerModule.forFeature()` accepts an optional config object: | Option | Type | Default | Description | | -------------- | ---------- | ------- | -------------------------------------- | | `enabled` | `boolean` | `true` | Whether the feature is active | | `environments` | `string[]` | all | Restrict to specific environment names | No environment variables are required by this module itself. The remote agent URL is resolved at runtime by `EnvironmentService` from `@loopstack/remote-client`. ## Public API - **Module:** `RemoteFileExplorerModule` -- NestJS module with `forFeature()` static method - **Controller:** `RemoteFileExplorerController` -- REST controller with `getFileTree()` and `readFile()` endpoints ## Dependencies | Package | Role | | -------------------------- | ----------------------------------------------- | | `@loopstack/common` | Shared utilities, `CurrentUser` decorator | | `@loopstack/remote-client` | `RemoteClient` service and `EnvironmentService` | | `@nestjs/common` | NestJS framework | | `@nestjs/typeorm` | TypeORM integration | | `typeorm` | ORM | ## Related - [`@loopstack/remote-client`](https://loopstack.ai/docs/registry/remote-client) -- the underlying client this module proxies through; also provides `GlobTool`, `ReadTool`, and other workflow tools for remote file operations - [`@loopstack/local-file-explorer`](https://loopstack.ai/docs/registry/local-file-explorer) -- same concept for local filesystems instead of remote agents - [Remote Files panel in the Remote Client examples](/docs/examples/remote-client#remote-files-panel) -- an example app that enables this module with `forFeature()`, next to workflows that use the `@loopstack/remote-client` tools ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/registry/packages/secrets.md --- title: Secrets Module description: Workspace-scoped secrets storage for Loopstack workflows — SecretEntity, SecretService, SecretController REST API, GetSecretKeysTool (get_secret_keys), RequestSecretsTask (request_secrets_task), SecretsRequestWorkflow, SecretRequestDocument. CRUD service, upsert, request secrets from users at runtime. --- # @loopstack/secrets > Secrets management module for the [Loopstack](https://loopstack.ai) automation framework. Provides workspace-scoped storage for API keys, tokens, and other credentials. Workflows can request secrets from users at runtime, store them securely, and check which secrets are available -- all without exposing values to the LLM. ## When to Use - **Your workflow needs credentials at runtime** -- an API key, OAuth token, or webhook secret that isn't known until the user provides it. - **You want to check whether secrets exist before branching** -- use `GetSecretKeysTool` to inspect available keys without reading values. - **You need a secure input form in the Studio** -- `SecretRequestDocument` renders a form where users enter secrets that are stored server-side, never sent to the LLM. Scripted workflows save it themselves; agents call `RequestSecretsTask`. - **You need CRUD access to secrets from backend code** -- inject `SecretService` directly for programmatic reads, writes, and upserts. ## Installation ```sh npm install @loopstack/secrets ``` Register the module in your app module. `SecretsModule` registers `SecretEntity` with TypeORM via `forFeature` internally, so your root `TypeOrmModule.forRoot()` must include `SecretEntity` (or load entities via glob). ```ts import { Module } from '@nestjs/common'; import { SecretsModule } from '@loopstack/secrets'; @Module({ imports: [SecretsModule], }) export class AppModule {} ``` Use `SecretsModule.forFeature()` to register with the feature registry (enables opt-in feature toggling): ```ts @Module({ imports: [SecretsModule.forFeature()], }) export class AppModule {} ``` ## Quick Start Save a `SecretRequestDocument` to ask the user for secrets, wait for the submission, then use `GetSecretKeysTool` to verify they were stored: ```ts import { BaseWorkflow, MarkdownDocument, Transition, Workflow } from '@loopstack/common'; import { GetSecretKeysTool, SecretRequestDocument } from '@loopstack/secrets'; interface SecretsState { secretKeys?: Array<{ key: string; hasValue: boolean }>; } @Workflow({ title: 'Secrets Update Example', description: 'Requests secrets from the user and verifies they were stored.', }) 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 ### Requesting secrets from a user Saving a `SecretRequestDocument` renders the secure form in the Studio. The workflow pauses on a `wait: true` transition named `secretsSubmitted` -- the transition the form fires -- until the user submits it. Values are stored on `SecretEntity` and never returned to the LLM. ``` start ──> requesting_secrets ──(wait)──> verifying ──> end save user submits check keys SecretRequestDocument secrets & continue ``` ### Using RequestSecretsTask in agent workflows `RequestSecretsTask` is the tool for agents. It launches `SecretsRequestWorkflow` as a sub-workflow with a callback (rendered inline in the parent's view via the default `show: 'inline'`), and resolves when the user completes the form. Use this when an LLM agent decides at runtime which secrets to request. ```ts import { RequestSecretsTask, GetSecretKeysTool, SecretsRequestWorkflow } from '@loopstack/secrets'; // In the workflow constructor: constructor( private readonly requestSecrets: RequestSecretsTask, private readonly getSecretKeys: GetSecretKeysTool, private readonly secretsRequest: SecretsRequestWorkflow, ) { super(); } // Register tools with the LLM: tools: ['get_secret_keys', 'request_secrets_task'] ``` ### Reading secrets in server-side code Inject `SecretService` for direct CRUD access: ```ts import { Injectable } from '@nestjs/common'; import { SecretService } from '@loopstack/secrets'; @Injectable() export class MyService { constructor(private readonly secrets: SecretService) {} async getToken(workspaceId: string) { const all = await this.secrets.findAllByWorkspace(workspaceId); return all.find((s) => s.key === 'GITHUB_TOKEN')?.value; } } ``` ### REST API `SecretController` exposes CRUD endpoints scoped to a workspace. The GET endpoint returns keys and `hasValue` flags only -- never the actual secret values. | Method | Endpoint | Description | | -------- | ------------------------------------------------ | --------------------- | | `GET` | `/api/v1/workspaces/:workspaceId/secrets` | List secret keys | | `POST` | `/api/v1/workspaces/:workspaceId/secrets` | Create a secret | | `PUT` | `/api/v1/workspaces/:workspaceId/secrets/upsert` | Create or update | | `PUT` | `/api/v1/workspaces/:workspaceId/secrets/:id` | Update a secret by ID | | `DELETE` | `/api/v1/workspaces/:workspaceId/secrets/:id` | Delete a secret by ID | ## Tools Reference ### `get_secret_keys` Returns the list of secret keys available in the current workspace. Does not return secret values. | Arg | Type | Required | Description | | ---- | ---- | -------- | --------------------- | | none | -- | -- | No arguments required | **Returns:** `Array<{ key: string; hasValue: boolean }>` ### `request_secrets_task` Requests secret values from the user. Launches `SecretsRequestWorkflow` as a sub-workflow, displays an embedded link document, and completes via callback when the user submits secrets. Must be the only tool call in the response. | Arg | Type | Required | Description | | ----------- | ------------------------ | -------- | -------------------------------------------- | | `variables` | `Array<{ key: string }>` | Yes | List of secret keys to request from the user | **Returns:** `{ workflowId: string }` (pending), then `"Secrets have been stored securely by the user."` (on completion) ## Configuration `SecretsModule.forFeature()` accepts an optional config object: ```ts SecretsModule.forFeature({ enabled: true }); ``` | Option | Type | Default | Description | | --------- | --------- | ------- | --------------------------------------------- | | `enabled` | `boolean` | -- | Opt-in feature toggle for the secrets feature | ## Public API - **Module:** `SecretsModule` - **Entity:** `SecretEntity` - **Service:** `SecretService` -- `findAllByWorkspace`, `create`, `update`, `upsert`, `delete` - **Controller:** `SecretController` -- REST CRUD under `/api/v1/workspaces/:workspaceId/secrets` - **Tools:** `GetSecretKeysTool`, `RequestSecretsTask` - **Workflow:** `SecretsRequestWorkflow` - **Document:** `SecretRequestDocument` - **Types:** `GetSecretKeysResult`, `RequestSecretsTaskResult` ## Dependencies | Package | Role | | ------------------- | ----------------------------------- | | `@loopstack/common` | Base classes, decorators, types | | `@loopstack/core` | Framework runtime, WorkspaceService | | `@nestjs/common` | NestJS dependency injection | | `@nestjs/typeorm` | TypeORM integration for NestJS | | `typeorm` | Database ORM (SecretEntity) | | `zod` | Tool input schema validation | ## Related - [Secrets Management docs](https://loopstack.ai/docs/build/integrations/secrets) -- overview of secret tools, how-it-works flow, and template examples - [Secrets examples](/docs/examples/secrets) -- example with both a direct workflow and an agent-based approach using `RequestSecretsTask` ## About Author: [Jakob Klippel](https://www.linkedin.com/in/jakob-klippel/) License: MIT --- > Source: https://loopstack.ai/llms/registry/packages/typesafe.md --- title: TypeSafe Module description: Typed decisions and classifications with TypeSafe AI. Ask yes/no, choice and score questions about any state from a workflow or agent and get probabilities back. --- # @loopstack/typesafe Answers named questions about a state with [TypeSafe AI](https://typesafe.ai) (`jev` models). Use it for decisions and classifications: yes/no (`noul`), pick-one-label (`choice`) and rubric (`score`) questions. ## Installation ```sh npm install @loopstack/typesafe ``` Register the module in your app module: ```ts import { Module } from '@nestjs/common'; import { TypeSafeModule } from '@loopstack/typesafe'; @Module({ imports: [TypeSafeModule], }) export class AppModule {} ``` Provide the API key. The model defaults to `TYPESAFE_DEFAULT_MODEL`, then `jev-latest`: ```env TYPESAFE_API_KEY=... ``` ## From a workflow: `typesafe_system_one` Inject `TypeSafeSystemOneTool` and build questions with the `noul`, `choice` and `score` helpers: ```ts import { BaseWorkflow, Transition, Workflow } from '@loopstack/common'; import { TypeSafeSystemOneTool, choice, noul, score } from '@loopstack/typesafe'; @Workflow({ title: 'Triage' }) export class TriageWorkflow extends BaseWorkflow { constructor(private readonly typesafe: TypeSafeSystemOneTool) { super(); } @Transition({ to: 'end' }) async triage() { const { data } = await this.typesafe.call( { state: { ticket: 'I was charged twice. Please fix this ASAP.' }, questions: { category: choice('What is this ticket about?', { billing: null, technical: null, other: null }), urgent: noul('Does the customer need a reply today?'), tone: score('How upset is the customer?', ['calm', 'annoyed', 'angry']), }, }, { config: { model: 'jev-latest' } }, ); const category = data.answers.category; if (category.type === 'choice') { this.setResult({ category: category.choice, confidence: category.confidence }); } } } ``` The result is `{ model, answers, usage }`, with one answer per question name: | Question | Answer | | -------- | ------------------------------------------------------------- | | `noul` | `{ type: 'noul', noul }` — probability of yes, 0 to 1 | | `choice` | `{ type: 'choice', choice, confidence, probabilities }` | | `score` | `{ type: 'score', score, confidence, legend, probabilities }` | The metadata is `{ provider: 'typesafe', model, usage: { inputTokens, outputTokens } }`. Agents can call the tool too: list `typesafe_system_one` in an LLM call's `tools`. ## Label-typed answers: `TypeSafeClientService` The tool validates at runtime, so its answers are typed per question kind (`choice: string`). When you want answer types inferred from your own labels, inject `TypeSafeClientService` and call `systemOne()` directly: ```ts const { answers } = await this.typesafeClient.systemOne({ state: 'I was charged twice.', questions: { category: choice('What is this ticket about?', { billing: null, other: null }) }, }); answers.category.choice; // 'billing' | 'other' ``` ## Configuration | Config | Default | Description | | ----------- | ------------------------------------------- | --------------------------------------- | | `model` | `TYPESAFE_DEFAULT_MODEL`, then `jev-latest` | Model that answers the questions | | `envApiKey` | `TYPESAFE_API_KEY` | Name of the env var holding the API key | API failures surface as the SDK's error classes (`RateLimitError`, `AuthenticationError`, …), which this package re-exports. --- > Source: https://loopstack.ai/llms/registry/packages/web.md --- title: Web Module description: Fetch and process web content. Converts HTML to Markdown, optionally summarizes against a prompt via the configured LLM provider, with URL validation, same-origin redirect handling, LRU caching, and a preapproved-host allowlist. --- # @loopstack/web ## Installation ```sh npm install @loopstack/web ``` Register the module in your app module: ```ts import { Module } from '@nestjs/common'; import { ClaudeModule } from '@loopstack/claude'; import { LlmProviderModule } from '@loopstack/llm-provider'; import { WebModule } from '@loopstack/web'; @Module({ imports: [LlmProviderModule, ClaudeModule, WebModule], }) export class AppModule {} ``` The optional summarization step (triggered when a `prompt` arg is passed to the tool) runs through the LLM provider layer: the tool's `provider` arg, else the `LlmProviderModule` default provider, else `claude`. The model is the tool's `model` arg, else `CLAUDE_WEB_FETCH_MODEL`, else `claude-haiku-4-5-20251001` — pass `model` when summarizing with a provider other than `claude`. The step needs that provider's API key: ```env ANTHROPIC_API_KEY=sk-ant-... ``` A summarized result returns the provider, model and token usage as `LlmResultMeta` metadata, which `@loopstack/quota` charges to the `llm-cost` quota. ---