# Reference / API --- > Source: https://loopstack.ai/llms/reference/api/agent.md --- title: 'API: @loopstack/agent' description: 'Public API reference for @loopstack/agent' includeInLlmsFullTxt: false --- # API: @loopstack/agent ## Classes ### AgentFinishTool Tool that signals the agent has completed its task and returns the final result. The LLM calls this to end the loop, passing the final `result` as a structured object or string. Returns an `AgentFinishResult` the agent workflow uses to exit. ```ts import { AgentFinishTool } from '@loopstack/agent'; ``` **Provided by:** `AgentModule` ```ts export class AgentFinishTool extends BaseTool { protected handle(args: AgentFinishInput): Promise>; } ``` ### AgentModule NestJS module that provides the agent workflows (`AgentWorkflow`, `ChatAgentWorkflow`) and the `AgentFinishTool`. Registration: - `AgentModule` (bare import) — registers the agent workflows; the LLM provider/model defaults come from whatever `LlmProviderModule` is configured app-wide. - `AgentModule.forFeature({ llm })` — same workflows, but with a feature-scoped `LlmProviderModule.forFeature(llm)` so this scope uses its own provider/model defaults. Requires: `LlmProviderModule` plus a registered provider module (e.g. `ClaudeModule` / `OpenAiModule`) available in the app — the agent loop runs its turns through that provider. ```ts import { AgentModule } from '@loopstack/agent'; ``` ```ts export class AgentModule { static forFeature(config?: { llm?: LlmModuleConfig }): DynamicModule; } ``` ### AgentWorkflow Workflow that runs a generic LLM agent loop: prompt the LLM, delegate any tool calls, feed their results back, and repeat until the model returns `end_turn`. Args (per `run()`): `system`, `tools`, `userMessage`, and optional `context`, `provider` and `model`. Tool names in `tools` are resolved by their `@Tool({ name })` value from the app-wide tool registry. On completion it publishes an `AgentResult` with the final assistant `response`. ```ts import { AgentWorkflow } from '@loopstack/agent'; ``` **Provided by:** `AgentModule` ```ts export class AgentWorkflow extends BaseWorkflow { constructor( llmGenerateText: LlmGenerateTextTool, llmDelegateToolCalls: LlmDelegateToolCallsTool, llmUpdateToolResult: LlmUpdateToolResultTool, orchestrator: WorkflowOrchestrator, ); setup(state: AgentState, ctx: RunContext): Promise; llmTurn(state: AgentState): Promise; executeToolCalls(state: AgentState): Promise; toolResultReceived(state: AgentState, input: TransitionInput): Promise; toolsComplete(_state: AgentState): void; cancelPendingTools(state: AgentState, ctx: RunContext): Promise; respond(state: AgentState): void; } ``` ### ChatAgentWorkflow Workflow that runs an interactive LLM agent loop with user chat between turns. Behaves like `AgentWorkflow `, but instead of exiting on `end_turn` it transitions to `waiting_for_user` and resumes on the next user message. When the `taskMode` arg is set, the `agent_finish` tool is added and the LLM calling it ends the workflow with that tool's result. ```ts import { ChatAgentWorkflow } from '@loopstack/agent'; ``` **Provided by:** `AgentModule` ```ts export class ChatAgentWorkflow extends BaseWorkflow { constructor( llmGenerateText: LlmGenerateTextTool, llmDelegateToolCalls: LlmDelegateToolCallsTool, llmUpdateToolResult: LlmUpdateToolResultTool, agentFinish: AgentFinishTool, orchestrator: WorkflowOrchestrator, ); setup(state: ChatAgentState, ctx: RunContext): Promise; llmTurn(state: ChatAgentState): Promise; executeToolCalls(state: ChatAgentState): Promise; toolResultReceived(state: ChatAgentState, payload: unknown): Promise; finished(state: ChatAgentState): void; toolsComplete(_state: ChatAgentState): void; cancelPendingTools(state: ChatAgentState, ctx: RunContext): Promise; respond(_state: ChatAgentState): void; userMessage(state: ChatAgentState, input: TransitionInput): Promise; } ``` ## Type Aliases ### AgentArgs Args for `AgentWorkflow` (passed to `run()`). Holds `system`, `tools`, `userMessage`, and optional `context`, `provider` and `model`. ```ts import { AgentArgs } from '@loopstack/agent'; ``` ```ts export type AgentArgs = z.infer; ``` ### AgentFinishResult Result returned by `AgentFinishTool` — a sentinel marking agent completion with the final `result`. ```ts import { AgentFinishResult } from '@loopstack/agent'; ``` ```ts export type AgentFinishResult = { __agentFinish: true; result: unknown; }; ``` ### AgentResult Result returned by AgentWorkflow, inferred from `AgentResultSchema`. Holds the final assistant `response` text. ```ts import { AgentResult } from '@loopstack/agent'; ``` ```ts export type AgentResult = z.infer; ``` ### ChatAgentArgs Args for `ChatAgentWorkflow` (passed to `run()`). Holds `system`, `tools`, `userMessage`, and optional `context`, `taskMode`, `provider` and `model`. ```ts import { ChatAgentArgs } from '@loopstack/agent'; ``` ```ts export type ChatAgentArgs = z.infer; ``` ## Variables ### AgentArgsSchema Zod schema for `AgentWorkflow` args (what callers pass to `run()`). ```ts import { AgentArgsSchema } from '@loopstack/agent'; ``` ```ts AgentArgsSchema: z.ZodObject< { system: z.ZodString; tools: z.ZodArray; userMessage: z.ZodString; context: z.ZodOptional; provider: z.ZodOptional; model: z.ZodOptional; }, z.core.$strip >; ``` ### AgentFinishResultSchema Zod schema for `AgentFinishResult`. ```ts import { AgentFinishResultSchema } from '@loopstack/agent'; ``` ```ts AgentFinishResultSchema: z.ZodObject< { __agentFinish: z.ZodLiteral; result: z.ZodUnknown; }, z.core.$strict >; ``` ### AgentResultSchema Zod schema for the result published by AgentWorkflow. Validates a single `response` string holding the final assistant message. Reusable as the `schema:` on a parent's callback wait-transition. ```ts import { AgentResultSchema } from '@loopstack/agent'; ``` ```ts AgentResultSchema: z.ZodObject< { response: z.ZodString; }, z.core.$strip >; ``` ### ChatAgentArgsSchema Zod schema for `ChatAgentWorkflow` args (what callers pass to `run()`). ```ts import { ChatAgentArgsSchema } from '@loopstack/agent'; ``` ```ts ChatAgentArgsSchema: z.ZodObject< { system: z.ZodString; tools: z.ZodArray; userMessage: z.ZodString; context: z.ZodOptional; taskMode: z.ZodOptional; provider: z.ZodOptional; model: z.ZodOptional; }, z.core.$strip >; ``` --- > Source: https://loopstack.ai/llms/reference/api/claude-tools.md --- title: 'API: @loopstack/claude-tools' description: 'Public API reference for @loopstack/claude-tools' includeInLlmsFullTxt: false --- # API: @loopstack/claude-tools ## Classes ### ClaudeToolsModule NestJS module that provides Claude-specific workflow tools that consume the LLM provider — currently the `ClaudeWebSearchStepTool` workflow step (`claude_web_search_step`), which runs a web search as its own Claude request through `claude_native_web_search`. Registration: - `ClaudeToolsModule` — bare import registers the tool providers; use this when `LlmProviderModule` is already configured elsewhere in the app and you just want the tools available. - `ClaudeToolsModule.forFeature(config: { llm: LlmModuleConfig })` — use to scope the LLM provider/model configuration for these tools; it imports `LlmProviderModule.forFeature(config.llm)` alongside the providers. Requires: `LlmProviderModule` must be available (it supplies the `LlmGenerateTextTool` the tool injects) — either configured app-wide or via `forFeature`; and a registered Claude provider (import `ClaudeModule`) with a valid `ANTHROPIC_API_KEY`, since the search executes through the `claude` provider. ```ts import { ClaudeToolsModule } from '@loopstack/claude-tools'; ``` ```ts export class ClaudeToolsModule { static forFeature(config: { llm: LlmModuleConfig }): DynamicModule; } ``` ### ClaudeWebSearchStepTool Workflow step that runs a web search as its own Claude request, returning search hits and model commentary. The request uses `claude_native_web_search`, and its reply is not saved to the conversation. To give an agent web search, list `claude_native_web_search` in its `tools` instead — attaching this tool to an agent costs a second LLM call per search. ```ts import { ClaudeWebSearchStepTool } from '@loopstack/claude-tools'; ``` **Provided by:** `ClaudeToolsModule` ```ts export class ClaudeWebSearchStepTool extends BaseTool< ClaudeWebSearchStepArgs, ClaudeWebSearchStepConfig, WebSearchResult > { protected handle( args: ClaudeWebSearchStepArgs, ctx: RunContext, options?: ToolCallOptions, ): Promise>; } ``` ## Interfaces ### WebSearchHit A single web search hit (title + URL) returned by `ClaudeWebSearchStepTool`. ```ts import { WebSearchHit } from '@loopstack/claude-tools'; ``` ```ts export interface WebSearchHit { title: string; url: string; } ``` ### WebSearchResult Result for `ClaudeWebSearchStepTool` — the query, interleaved hit blocks and text commentary, a sources reminder, and timing. ```ts import { WebSearchResult } from '@loopstack/claude-tools'; ``` ```ts export interface WebSearchResult { query: string; results: Array; sourcesReminder: string; durationSeconds: number; } ``` ### WebSearchResultBlock A block of web search hits tied to a single server tool use, returned by `ClaudeWebSearchStepTool`. ```ts import { WebSearchResultBlock } from '@loopstack/claude-tools'; ``` ```ts export interface WebSearchResultBlock { tool_use_id: string; content: WebSearchHit[]; } ``` ## Type Aliases ### ClaudeWebSearchStepArgs Args for `ClaudeWebSearchStepTool`. ```ts import { ClaudeWebSearchStepArgs } from '@loopstack/claude-tools'; ``` ```ts export type ClaudeWebSearchStepArgs = z.infer; ``` ### ClaudeWebSearchStepConfig Config for `ClaudeWebSearchStepTool`. ```ts import { ClaudeWebSearchStepConfig } from '@loopstack/claude-tools'; ``` ```ts export type ClaudeWebSearchStepConfig = z.infer; ``` ## Variables ### ClaudeWebSearchStepArgsSchema Zod schema for `ClaudeWebSearchStepTool` arguments. ```ts import { ClaudeWebSearchStepArgsSchema } from '@loopstack/claude-tools'; ``` ```ts ClaudeWebSearchStepArgsSchema: z.ZodObject< { query: z.ZodString; }, z.core.$strict >; ``` ### ClaudeWebSearchStepConfigSchema Zod schema for `ClaudeWebSearchStepTool` configuration. ```ts import { ClaudeWebSearchStepConfigSchema } from '@loopstack/claude-tools'; ``` ```ts ClaudeWebSearchStepConfigSchema: z.ZodObject< { model: z.ZodOptional; maxTokens: z.ZodOptional; envApiKey: z.ZodOptional; cache: z.ZodOptional; }, z.core.$strip >; ``` ### WebSearchHitSchema Zod schema for `WebSearchHit`. ```ts import { WebSearchHitSchema } from '@loopstack/claude-tools'; ``` ```ts WebSearchHitSchema: z.ZodObject< { title: z.ZodString; url: z.ZodString; }, z.core.$strict >; ``` ### WebSearchResultBlockSchema Zod schema for `WebSearchResultBlock`. ```ts import { WebSearchResultBlockSchema } from '@loopstack/claude-tools'; ``` ```ts WebSearchResultBlockSchema: z.ZodObject< { tool_use_id: z.ZodString; content: z.ZodArray< z.ZodObject< { title: z.ZodString; url: z.ZodString; }, z.core.$strict > >; }, z.core.$strict >; ``` ### WebSearchResultSchema Zod schema for `WebSearchResult` — the `resultSchema` of `claude_web_search_step`. ```ts import { WebSearchResultSchema } from '@loopstack/claude-tools'; ``` ```ts WebSearchResultSchema: z.ZodObject< { query: z.ZodString; results: z.ZodArray< z.ZodUnion< readonly [ z.ZodObject< { tool_use_id: z.ZodString; content: z.ZodArray< z.ZodObject< { title: z.ZodString; url: z.ZodString; }, z.core.$strict > >; }, z.core.$strict >, z.ZodString, ] > >; sourcesReminder: z.ZodString; durationSeconds: z.ZodNumber; }, z.core.$strict >; ``` --- > Source: https://loopstack.ai/llms/reference/api/claude.md --- title: 'API: @loopstack/claude' description: 'Public API reference for @loopstack/claude' includeInLlmsFullTxt: false --- # API: @loopstack/claude ## Classes ### ClaudeModule NestJS module that provides the Claude LLM provider (`ClaudeLlmProvider`, registered under provider id `claude`), the `ClaudeClientService`, and the `ClaudeNativeWebSearchTool` server tool. Registration: - `ClaudeModule` — bare import is all that is needed; there are no static methods. On startup the provider registers itself into the LLM provider registry, after which `claude` can be selected as a provider in LLM tools and workflows. Requires: must be co-imported with `LlmProviderModule`, which supplies the `LlmProviderRegistry` the provider registers into; and an Anthropic API key, read from the `ANTHROPIC_API_KEY` env var by default (override the env var name per call via `envApiKey`). ```ts import { ClaudeModule } from '@loopstack/claude'; ``` ```ts export class ClaudeModule {} ``` ### ClaudeNativeWebSearchTool Claude's provider-native web search. List it in an LLM call's `tools` (an agent or `llm_generate_text`) and Claude runs the search inside that same call. It is not callable from workflow code — for a standalone search step, use `ClaudeWebSearchStepTool` (`claude_web_search_step`) from `@loopstack/claude-tools`. ```ts import { ClaudeNativeWebSearchTool } from '@loopstack/claude'; ``` **Provided by:** `ClaudeModule` ```ts export class ClaudeNativeWebSearchTool extends ServerTool { toServerToolConfig(config?: ClaudeNativeWebSearchToolConfig): unknown; } ``` ## Interfaces ### ClaudeProviderConfig Provider-specific configuration for the Claude LLM provider. Passed via `providerConfig` in LlmGenerateTextArgs / LlmGenerateObjectArgs. ```ts import { ClaudeProviderConfig } from '@loopstack/claude'; ``` ```ts export interface ClaudeProviderConfig { maxTokens?: number; temperature?: number; stopSequences?: string[]; cache?: boolean; envApiKey?: string; } ``` ## Type Aliases ### ClaudeNativeWebSearchToolConfig Config for `ClaudeNativeWebSearchTool`. ```ts import { ClaudeNativeWebSearchToolConfig } from '@loopstack/claude'; ``` ```ts export type ClaudeNativeWebSearchToolConfig = z.infer; ``` ## Variables ### ClaudeNativeWebSearchToolConfigSchema Zod schema for `ClaudeNativeWebSearchTool` configuration. ```ts import { ClaudeNativeWebSearchToolConfigSchema } from '@loopstack/claude'; ``` ```ts ClaudeNativeWebSearchToolConfigSchema: z.ZodObject< { maxUses: z.ZodDefault; allowedDomains: z.ZodOptional>; blockedDomains: z.ZodOptional>; }, z.core.$strip >; ``` --- > Source: https://loopstack.ai/llms/reference/api/code-agent.md --- title: 'API: @loopstack/code-agent' description: 'Public API reference for @loopstack/code-agent' includeInLlmsFullTxt: false --- # API: @loopstack/code-agent ## Classes ### CodeAgentModule NestJS module that provides the codebase-exploration tool `ExploreTask` (`explore_task`), which launches an `AgentWorkflow` sub-agent that searches and reads a remote workspace with the `glob`/`grep`/`read` tools and returns a synthesized answer. Registration: - `CodeAgentModule` — bare import registers `ExploreTask` and re-exports `AgentModule`; use this when the agent's default LLM configuration is fine. - `CodeAgentModule.forFeature(config?: { llm?: LlmModuleConfig })` — use to override the LLM provider/model for the code agent; it imports `AgentModule.forFeature(config)`. Requires, configured in your app: - `LlmProviderModule` with a registered LLM provider — needed by the imported `AgentModule`. - `RemoteClientModule` (bare or `forRoot`) — supplies the `glob`/`grep`/`read` tools the `explore_task` sub-agent uses. Without it the app fails at boot with an error naming `RemoteClientModule`. ```ts import { CodeAgentModule } from '@loopstack/code-agent'; ``` ```ts export class CodeAgentModule { static forFeature(config?: { llm?: LlmModuleConfig }): DynamicModule; } ``` ### ExploreTask Tool that launches an `AgentWorkflow` sub-agent to explore and analyze a codebase with the `glob`/`grep`/`read` tools and return a synthesized summary. Those tools come from `RemoteClientModule`. Constructing `ExploreTask` without them throws, so an app that has not wired the remote client fails at boot instead of on the first `explore_task` call. ```ts import { ExploreTask } from '@loopstack/code-agent'; ``` **Provided by:** `CodeAgentModule` ```ts export class ExploreTask extends BaseTool { constructor(agentWorkflow: AgentWorkflow, globTool?: GlobTool, grepTool?: GrepTool, readTool?: ReadTool); protected handle( args: ExploreTaskInput, ctx: RunContext, options?: ToolCallOptions, ): Promise>; complete(result: Record): Promise>; } ``` ## Type Aliases ### ExploreTaskInput Args for `ExploreTask`. ```ts import { ExploreTaskInput } from '@loopstack/code-agent'; ``` ```ts export type ExploreTaskInput = z.infer; ``` ### ExploreTaskResult Result for `ExploreTask` (`explore_task`) — the synthesized exploration summary or its pending workflow reference. ```ts import { ExploreTaskResult } from '@loopstack/code-agent'; ``` ```ts export type ExploreTaskResult = | { workflowId: string; } | string | Record; ``` ## Variables ### ExploreTaskInputSchema Zod schema for `ExploreTask` args. ```ts import { ExploreTaskInputSchema } from '@loopstack/code-agent'; ``` ```ts ExploreTaskInputSchema: z.ZodObject< { instructions: z.ZodString; }, z.core.$strict >; ``` ### ExploreTaskResultSchema Zod schema for `ExploreTaskResult` — the synthesized summary string or, when the sub-workflow returned no response text, its raw result record. ```ts import { ExploreTaskResultSchema } from '@loopstack/code-agent'; ``` ```ts ExploreTaskResultSchema: z.ZodUnion]>; ``` --- > Source: https://loopstack.ai/llms/reference/api/common.md --- title: 'API: @loopstack/common' description: 'Public API reference for @loopstack/common' includeInLlmsFullTxt: false --- # API: @loopstack/common ## Classes ### BaseTool Abstract base class for tools. Tool authors extend this class and implement `handle(args, ctx, options?)`. Consumers call `tool.call(args, options?)` — the base class routes through `ToolPipelineService` which handles validation, config merging, and interceptors. ```ts import { BaseTool } from '@loopstack/common'; ``` ```ts export abstract class BaseTool< TArgs extends object = object, TConfig extends object = object, TResult = unknown, TMeta = Record, > { protected readonly documentStore: DocumentStore; protected readonly render: TemplateRenderFn; call(args?: TArgs, options?: ToolCallOptions): Promise>; protected abstract handle( args: TArgs, ctx: RunContext, options?: ToolCallOptions, ): Promise>; complete(_result: Record): Promise; } ``` ### BaseWorkflow Abstract base class for workflows. Generic parameters: - `TArgs` — the **storage contract**: what is validated, persisted, and arrives in `ctx.args` inside transitions (via `ctx: RunContext`). - `TInput` — the **call-site contract**: what callers pass to `run(input)`. Defaults to `TArgs`, so workflows whose call shape equals their storage shape only need a single generic. The two diverge when the workflow's `@Workflow({ schema })` is a transforming zod schema (`schema.transform(input => args)`). In that case, infer the types from the schema: `BaseWorkflow, z.input>`. State and result are mutated via setters, never via the return value: - `this.assignState(partial)` — shallow-merge into state - `this.setState(full)` — replace state - `this.assignResult(partial)` — shallow-merge into result - `this.setResult(full)` — replace result Transitions return nothing. Returning a non-undefined value throws at runtime. Use `async` only when the body awaits. Setters are immediately visible to subsequent code in the same transition; on error, the framework discards the draft as part of the transition rollback. Workflows are singletons. State flows through the `state` parameter: - All transitions receive `(state, ctx)` and return nothing - Wait transitions receive `(state, payload, ctx)` and return nothing - `ctx` is optional (trailing param can be omitted) - Args are available via `ctx.args` — type with `RunContext` to drop the cast - Use `from: 'start'` (or omit `from`) for initial, `to: 'end'` for final Launch sub-workflows by injecting the workflow class and calling `run()` with a `callback.transition` that resumes the parent when the child completes. ```ts import { BaseWorkflow } from '@loopstack/common'; ``` ```ts export abstract class BaseWorkflow, TInput = TArgs> { protected readonly documentStore: DocumentStore; protected readonly render: TemplateRenderFn; run(input?: TInput, options?: RunOptions): Promise; protected assignState(partial: Record): void; protected setState(next: Record): void; protected assignResult(partial: Record): void; protected setResult(next: Record): void; } ``` ### ErrorDocument Document that renders an error message in Studio. ```ts import { ErrorDocument } from '@loopstack/common'; ``` ```ts export class ErrorDocument { error: string; } ``` ### MarkdownDocument Document that renders Markdown content in Studio. ```ts import { MarkdownDocument } from '@loopstack/common'; ``` ```ts export class MarkdownDocument { markdown: string; } ``` ### MessageDocument Document that renders a chat message (`role` plus optional `text`) in Studio. ```ts import { MessageDocument } from '@loopstack/common'; ``` ```ts export class MessageDocument { role: string; text?: string; } ``` ### PlainDocument Document that renders plain text in Studio. ```ts import { PlainDocument } from '@loopstack/common'; ``` ```ts export class PlainDocument { text: string; } ``` ### ServerTool Abstract base class for server-side tools — tools executed by the LLM provider rather than locally by the framework. Server tools (e.g. Anthropic's `web_search`, `code_execution`) are configured at API call time and the provider handles execution. The framework passes the validated config from `toServerToolConfig` directly to the provider. Use the standard `@Tool()` decorator for metadata and constructor injection. Configuration from `options.config` is validated against the `configSchema` and passed as the `config` argument to `toServerToolConfig`. ```ts import { ServerTool } from '@loopstack/common'; ``` ```ts export abstract class ServerTool { abstract toServerToolConfig(config?: TConfig): unknown; } ``` ### TerminalDocument Document that renders raw terminal output in Studio — a monospaced, dark terminal card that interprets ANSI color escape codes (so NestJS logs, npm/tsx output, git, etc. keep their colors instead of showing raw `\x1b[..m` noise). `text` is the raw stream (ANSI intact); `title` is an optional header. ```ts import { TerminalDocument } from '@loopstack/common'; ``` ```ts export class TerminalDocument { text: string; title?: string; } ``` ## Interfaces ### Clock The framework's time source — inject via the `CLOCK` token instead of calling `Date.now()` or `setTimeout` directly, so time-dependent logic stays deterministic under a test clock. ```ts import { Clock } from '@loopstack/common'; ``` ```ts export interface Clock { now(): number; schedule(fn: () => void, ms: number): () => void; } ``` ### DocumentOptions Options for the `@Document()` decorator. ```ts import { DocumentOptions } from '@loopstack/common'; ``` ```ts export interface DocumentOptions { name?: string; title?: string; description?: string; widget?: WidgetRef | WidgetRef[]; schema?: z.ZodType; tags?: string[]; meta?: StaticDocumentMeta; internal?: boolean; } ``` ### DocumentStore Document store for workflow and tool authors — `create`, `save`, and lookup of typed documents that render in Studio. Available as `this.documentStore` on `BaseWorkflow` and `BaseTool` (no manual injection needed). ```ts import { DocumentStore } from '@loopstack/common'; ``` ```ts export interface DocumentStore { create(documentClass: DocumentClass, data: T): T; save( classOrInstance: DocumentClass | T, dataOrOptions?: T | DocumentSaveOptions, maybeOptions?: DocumentSaveOptions, ): Promise; findAll(documentClass: DocumentClass): T[]; findAllDocuments(): DocumentEntity[]; findByTag(tag: string): DocumentEntity[]; } ``` ### RedisConnectionOptions Redis connection settings a Loopstack deployment uses. ```ts import { RedisConnectionOptions } from '@loopstack/common'; ``` ```ts export interface RedisConnectionOptions { host?: string; port?: number; password?: string; db?: number; } ``` ### ResolvedRedisConnection The settings after defaults are applied, ready to hand to ioredis or BullMQ. ```ts import { ResolvedRedisConnection } from '@loopstack/common'; ``` ```ts export interface ResolvedRedisConnection { host: string; port: number; password?: string; db: number; } ``` ### RunContext Unified per-job framework context. Used by both tools (passed as `ctx` parameter to `handle()`) and workflows (passed as the trailing parameter to transition methods). - `args` — validated workflow input args (frozen at job start) - `execution` — present in workflow transitions, absent in tools ```ts import { RunContext } from '@loopstack/common'; ``` ```ts export interface RunContext { userId: string; workspaceId: string; workflowId: string; args: TArgs; signal: AbortSignal; execution?: { place: string; retryCount: number; }; } ``` ### RunResult Result of `WorkflowRunner.run` — a workflow enqueued via BullMQ. ```ts import { RunResult } from '@loopstack/common'; ``` ```ts export interface RunResult { workflowId: string; workspaceId: string; workerId: string; } ``` ### StatelessRunResult Result of a stateless `WorkflowRunner.runSync` (no persistence) — the final `status` and published `result`, plus the in-memory run record: `place`, the run `trace`, produced `documents`, currently `availableTransitions`, and error info. ```ts import { StatelessRunResult } from '@loopstack/common'; ``` ```ts export interface StatelessRunResult { status: WorkflowState; result: unknown; place: string; trace: RunTraceEvent[]; documents: DocumentEntity[]; availableTransitions: WorkflowTransitionType[]; hasError: boolean; errorMessage?: string; } ``` ### StudioAppOptions Options for the `@StudioApp()` decorator — the app identity, title, workflows, and UI config that make a module appear as a launchable app in Studio. ```ts import { StudioAppOptions } from '@loopstack/common'; ``` ```ts export interface StudioAppOptions { app?: string; title: string; description?: string; ui?: StudioUiConfig; workflows?: Type>[]; } ``` ### SyncRunResult Result of `WorkflowRunner.runSync` with persistence — the final `status` and published `result`. ```ts import { SyncRunResult } from '@loopstack/common'; ``` ```ts export interface SyncRunResult extends RunResult { status: WorkflowState; result: unknown; } ``` ### ToolCallOptions Options passed as the second argument to `BaseTool.call()`. ```ts import { ToolCallOptions } from '@loopstack/common'; ``` ```ts export interface ToolCallOptions { callback?: { transition: string; metadata?: Record; }; config?: TConfig; } ``` ### ToolDocumentDeclaration A document a tool declares as part of its result envelope instead of writing it inside `handle()`. The tool pipeline applies declarations through the document store after the interceptor chain, so declared documents appear identically for live and replayed tool calls. `documentName` is the document's registered name (the `@Document({ name })` option, or the kebab-case derivation of the class name). `options` mirror `DocumentSaveOptions`. ```ts import { ToolDocumentDeclaration } from '@loopstack/common'; ``` ```ts export interface ToolDocumentDeclaration { documentName: string; content: Record; options?: { key?: string; position?: 'keep' | 'end'; meta?: Record; validate?: 'strict' | 'safe' | 'skip'; }; } ``` ### ToolOptions Options for the `@Tool()` decorator. ```ts import { ToolOptions } from '@loopstack/common'; ``` ```ts export interface ToolOptions { name?: string; description?: string; widget?: WidgetRef | WidgetRef[]; schema?: z.ZodType; configSchema?: z.ZodType; resultSchema?: z.ZodType; effects?: 'none' | 'external'; } ``` ### ToolResult Narrowed success-path return of `BaseTool.call()`. `data` and `metadata` are non-optional — `call()` throws when the underlying envelope carries `error` or `pending`, so workflow authors never observe those states from this API. ```ts import { ToolResult } from '@loopstack/common'; ``` ```ts export interface ToolResult> { data: TData; metadata: TMeta; type?: 'text' | 'image' | 'file'; } ``` ### TransitionInput Shape delivered to every `@Transition({ wait: true })` method, regardless of trigger source (sub-workflow completion or frontend / API resume). The `schema` option on `@Transition` validates `data` only — the framework constructs the surrounding envelope. `meta` carries whatever the parent passed to `callback.metadata` (used by `FanOut`/`Sequence` for per-child correlation, by the LLM tool loop for `toolUseId`, etc.); it is `undefined` for user-driven resumes. `hasError` / `errorMessage` / `status` reflect the terminal state of the trigger so the receiver can branch on failure without separate lookups. ```ts import { TransitionInput } from '@loopstack/common'; ``` ```ts export interface TransitionInput { workflowId: string; status: 'completed' | 'failed' | 'canceled'; hasError: boolean; errorMessage: string | null; data: TData; meta?: TMeta; } ``` ### TransitionOptions Options for the `@Transition()` decorator — routing (`from`/`to`), `wait`, `priority`, the payload/args `schema`, and the retry / error-place / timeout controls. ```ts import { TransitionOptions } from '@loopstack/common'; ``` ```ts export interface TransitionOptions { from?: string; to: string; wait?: boolean; priority?: number; schema?: z.ZodType; retryAttempts?: number; retryDelay?: number; retryBackoff?: 'fixed' | 'exponential'; retryMaxDelay?: number; retryTarget?: string; errorPlace?: string; timeout?: number; } ``` ### WorkflowOptions Options for the `@Workflow()` decorator. ```ts import { WorkflowOptions } from '@loopstack/common'; ``` ```ts export interface WorkflowOptions { name?: string; title?: string; description?: string; widget?: WidgetRef | WidgetRef[]; schema?: z.ZodType; configSchema?: z.ZodType; stateSchema?: z.ZodType; } ``` ### WorkflowRunnerOptions Options for starting a workflow via `WorkflowRunner` (`run` / `runSync`) — `userId`, `appName`, and optional `workspaceId` / `labels`. ```ts import { WorkflowRunnerOptions } from '@loopstack/common'; ``` ```ts export interface WorkflowRunnerOptions { userId: string; appName: string; workspaceId?: string; labels?: string[]; } ``` ### WorkflowRunnerSyncOptions Options for `WorkflowRunner.runSync` — extends `WorkflowRunnerOptions` with `stateless` to skip all DB persistence. ```ts import { WorkflowRunnerSyncOptions } from '@loopstack/common'; ``` ```ts export interface WorkflowRunnerSyncOptions extends WorkflowRunnerOptions { stateless?: boolean; } ``` ## Type Aliases ### ToolEnvelope Raw envelope returned by `BaseTool.handle()` and `ToolPipeline.execute()`. Models all three legitimate tool outcomes: - success: `data` (+ optional `metadata`, `type`) - recoverable failure: `error` (read by the LLM agent tool-call loop and packaged as `is_error: true`) - async pending: `pending` (the tool launched a sub-workflow; result arrives via callback) Tool authors return this shape from `handle()`. Consumers go through `BaseTool.call()`, which returns the narrowed `ToolResult` and throws on `error` / `pending`. ```ts import { ToolEnvelope } from '@loopstack/common'; ``` ```ts export type ToolEnvelope> = { type?: 'text' | 'image' | 'file'; data?: TData; error?: string; metadata?: TMeta; pending?: { workflowId: string; }; documents?: ToolDocumentDeclaration[]; }; ``` ### WorkflowArgs Extracts the `TArgs` type from a `BaseWorkflow` subclass — the args shape you pass to `WorkflowRunner.run(WorkflowClass, args, …)`. ```ts import { WorkflowArgs } from '@loopstack/common'; ``` ```ts export type WorkflowArgs = W extends BaseWorkflow ? A : never; ``` ## Functions ### Document Marks a class as a Document DTO. Unlike `@Tool` and `@Workflow`, documents are NOT injectable NestJS providers — they are plain data classes. Their schema, widget, and meta are read from decorator metadata when documents are saved via `documentStore.save(DocClass, …)`. Identifier resolution: `options.name` ?? class name with `Document` suffix stripped, snake_cased (e.g. `AskUserDocument` → `ask_user`). ```ts import { Document } from '@loopstack/common'; ``` ```ts export function Document(options?: DocumentOptions): ClassDecorator; ``` ### Guard Gates a transition behind a guard predicate method. `guardMethodName` names a pure, side-effect-free method on the workflow that returns a boolean. When several transitions share a `from` place, the highest-priority transition whose guard returns true is the one that fires. ```ts import { Guard } from '@loopstack/common'; ``` ```ts export function Guard(guardMethodName: string): MethodDecorator; ``` ### resolveRedisConnection Resolves the Redis connection every Redis-backed feature shares — the task queue, the OAuth token and session stores, and the quota counters. Precedence: explicit options, then a single `REDIS_URL` (managed and hosted environments), then the discrete `REDIS_HOST` / `REDIS_PORT` / `REDIS_PASSWORD` / `REDIS_DB` vars, then the defaults `localhost:6379` on database `0`. A `REDIS_URL` path sets the database, so `redis://localhost:6379/2` resolves to database `2`. ```ts import { resolveRedisConnection } from '@loopstack/common'; ``` ```ts export function resolveRedisConnection(options?: RedisConnectionOptions): ResolvedRedisConnection; ``` ### StudioApp Marks a NestJS module as a Loopstack App — the single source of truth for app identity, UI config, and developer-defined settings. ```ts import { StudioApp } from '@loopstack/common'; ``` ```ts export function StudioApp(options: StudioAppOptions): ClassDecorator; ``` ### Tool Marks a class as a Loopstack tool. The class must extend `BaseTool`. Also applies `@Injectable()` so the tool can be registered as a NestJS provider and constructor-injected into workflows and other tools. Identifier resolution: `options.name` ?? class name (as-is). Always set `options.name` to a snake_case identifier — it appears in the LLM tool-calling wire format. Relative `widget:` paths (`./foo.ui.yaml`, `../shared/foo.ui.yaml`) are resolved against this file's directory at decorator-evaluation time. ```ts import { Tool } from '@loopstack/common'; ``` ```ts export function Tool(options?: ToolOptions): ClassDecorator; ``` ### Transition Marks a workflow method as a transition between two states (places). The method fires when the workflow is in its `from` place and moves it to `to`. `from` defaults to `'start'` (the initial transition); use `to: 'end'` for the final transition. Set `wait: true` to pause until an external trigger (user input or a sub-workflow callback) resumes the workflow. Transitions mutate state via setters and return nothing. ```ts import { Transition } from '@loopstack/common'; ``` ```ts export function Transition(options: TransitionOptions): MethodDecorator; ``` ### Workflow Marks a class as a Loopstack workflow. The class must extend `BaseWorkflow`. Also applies `@Injectable()` so the workflow can be registered as a NestJS provider and constructor-injected (tools, sub-workflows, services). Identifier resolution: `options.name` ?? class name with `Workflow` suffix stripped, snake_cased (e.g. `ChatWorkflow` → `chat`). Relative `widget:` paths (`./foo.ui.yaml`, `../shared/foo.ui.yaml`) are resolved against this file's directory at decorator-evaluation time. ```ts import { Workflow } from '@loopstack/common'; ``` ```ts export function Workflow(options?: WorkflowOptions): ClassDecorator; ``` --- > Source: https://loopstack.ai/llms/reference/api/core.md --- title: 'API: @loopstack/core' description: 'Public API reference for @loopstack/core' includeInLlmsFullTxt: false --- # API: @loopstack/core ## Classes ### FanOutWorkflow Workflow that launches N sub-workflows in parallel, awaits all of them, and fires a single aggregated callback to the parent. Sub-workflows are referenced by their canonical name (string) — set via `@Workflow({ name })` or auto-derived from the class name. Items may be passed as an array or a keyed record. Modes: - `'all'` (default) — first failure cancels in-flight siblings; the callback fires once every child has settled (canceled siblings also send callbacks). - `'allSettled'` — every child runs to completion; the callback aggregates all results. ```ts import { FanOutWorkflow } from '@loopstack/core'; ``` **Provided by:** `LoopCoreModule` ```ts export class FanOutWorkflow extends BaseWorkflow { constructor(orchestrator: WorkflowOrchestrator, registry: WorkflowRegistryService); start(state: FanOutState, ctx: RunContext): Promise; onChildComplete( state: FanOutState, input: TransitionInput< unknown, { key?: string; } >, ctx: RunContext, ): Promise; done(state: FanOutState): void; } ``` ### SequenceWorkflow Workflow that runs N sub-workflows one at a time, awaits each, and fires a single aggregated callback to the parent. Sub-workflows are referenced by their canonical name (string) — set via `@Workflow({ name })` or auto-derived from the class name. Items may be passed as an array or a keyed record. Modes: - `'all'` (default) — first failure aborts the sequence; remaining items are marked as `'skipped'` in the result. - `'allSettled'` — every item runs regardless of prior failures. ```ts import { SequenceWorkflow } from '@loopstack/core'; ``` **Provided by:** `LoopCoreModule` ```ts export class SequenceWorkflow extends BaseWorkflow { constructor(orchestrator: WorkflowOrchestrator, registry: WorkflowRegistryService); start(state: SequenceState, ctx: RunContext): Promise; onChildComplete(state: SequenceState, input: TransitionInput, ctx: RunContext): Promise; done(state: SequenceState): void; } ``` ### WorkflowRunner Service for starting workflows from code (API requests, webhooks, cron jobs, delayed timeouts, batch fan-out) instead of the Studio "Run" button. Inject it anywhere — it is globally available once `LoopstackModule.forRoot()` is imported. - `run(WorkflowClass, args, options)` — enqueue on BullMQ and return a `RunResult` (`workflowId`). - `runSync(WorkflowClass, args, options)` — execute inline and await a `SyncRunResult`; pass `{ stateless: true }` to skip persistence. - `execute(workflow, payload, options)` — controller-facing entry that starts, resumes, or retries based on the payload. - `runById(workflowId, userId, options)` — resume/re-run an existing workflow by id. ```ts import { WorkflowRunner } from '@loopstack/core'; ``` ```ts export class WorkflowRunner { constructor( configService: ConfigService, createWorkflowService: CreateWorkflowService, workspaceService: WorkspaceService, workflowService: WorkflowService, taskSchedulerService: TaskSchedulerService, rootProcessorService: RootProcessorService, workflowRegistryService: WorkflowRegistryService, orchestrator: WorkflowOrchestrator, ); execute( workflow: Type> | string, payload: WorkflowPayload, options: { userId: string; appName: string; labels?: string[]; }, ): Promise; run( workflow: Type, args: WorkflowArgs, options: WorkflowRunnerOptions, ): Promise; runSync( workflow: Type, args: WorkflowArgs, options: WorkflowRunnerSyncOptions, ): Promise; runById( workflowId: string, userId: string, payload?: { transition?: { id?: string; workflowId?: string; payload?: unknown; }; }, ): Promise; cancel(workflowId: string, userId: string): Promise; } ``` ## Interfaces ### WorkflowSettledEvent Emitted once a run has reached a state it will not leave by itself: completed, failed, or canceled. The counterpart of `workspace.deleted` / `workflow.deleted`, for the end of a run rather than the end of its record — so a host application can release what it was holding for that run (a claimed resource, a reserved slot) without polling for it. Emitted after the run's own persistence has committed, and for sub-workflows as well as root runs — a consumer that only cares about root runs checks `parentId`. A consumer must be **idempotent**: there is no guarantee the event arrives exactly once per run, and a process that dies before its listener ran will never see it at all. Anything whose correctness depends on it should reconcile against the run's status instead, and treat the event as what makes that prompt. ```ts import { WorkflowSettledEvent } from '@loopstack/core'; ``` ```ts export interface WorkflowSettledEvent { id: string; workspaceId: string; workflowName: string; parentId?: string; status: SettledWorkflowState; user: string; } ``` ## Type Aliases ### FanOutArgs Validated/persisted args for `FanOutWorkflow` (the parsed form of `FanOutInput`). ```ts import { FanOutArgs } from '@loopstack/core'; ``` ```ts export type FanOutArgs = z.output; ``` ### FanOutInput Call-site input for `FanOutWorkflow.run()` — the workflow to fan out, the items (array or keyed record), and the `mode` (`'all'` | `'allSettled'`). ```ts import { FanOutInput } from '@loopstack/core'; ``` ```ts export type FanOutInput = z.input; ``` ### SequenceArgs Validated/persisted args for `SequenceWorkflow` (the parsed form of `SequenceInput`). ```ts import { SequenceArgs } from '@loopstack/core'; ``` ```ts export type SequenceArgs = z.output; ``` ### SequenceInput Call-site input for `SequenceWorkflow.run()` — the workflow to run, the items (array or keyed record), and the `mode` (`'all'` | `'allSettled'`). ```ts import { SequenceInput } from '@loopstack/core'; ``` ```ts export type SequenceInput = z.input; ``` ## Variables ### FanOutResultSchema Zod schema for the aggregated `FanOutWorkflow` result delivered as the `data` field of the `TransitionInput` in a parent's callback. Fields: - `results` — an array of entries (each with a `key`) if items were an array, otherwise a keyed record of entries; every entry carries a `status`, optional `data`, and optional `error`. - `hasErrors` — true when any child did not complete successfully. - `errorCount` — number of children that did not complete successfully. ```ts import { FanOutResultSchema } from '@loopstack/core'; ``` ```ts FanOutResultSchema: z.ZodObject< { results: z.ZodUnion< readonly [ z.ZodArray< z.ZodObject< { status: z.ZodEnum<{ completed: 'completed'; failed: 'failed'; canceled: 'canceled'; }>; data: z.ZodOptional; error: z.ZodOptional; key: z.ZodString; }, z.core.$strip > >, z.ZodRecord< z.ZodString, z.ZodObject< { status: z.ZodEnum<{ completed: 'completed'; failed: 'failed'; canceled: 'canceled'; }>; data: z.ZodOptional; error: z.ZodOptional; }, z.core.$strip > >, ] >; hasErrors: z.ZodBoolean; errorCount: z.ZodNumber; }, z.core.$strip >; ``` ### SequenceResultSchema Zod schema for the aggregated `SequenceWorkflow` result delivered as the `data` field of the `TransitionInput` in a parent's callback. Fields: - `results` — an array of entries (each with a `key`) if items were an array, otherwise a keyed record of entries; every entry carries a `status`, optional `data`, and optional `error`. - `hasErrors` — true when any item did not complete successfully. - `errorCount` — number of items that did not complete successfully. ```ts import { SequenceResultSchema } from '@loopstack/core'; ``` ```ts SequenceResultSchema: z.ZodObject< { results: z.ZodUnion< readonly [ z.ZodArray< z.ZodObject< { status: z.ZodEnum<{ completed: 'completed'; failed: 'failed'; canceled: 'canceled'; skipped: 'skipped'; }>; data: z.ZodOptional; error: z.ZodOptional; key: z.ZodString; }, z.core.$strip > >, z.ZodRecord< z.ZodString, z.ZodObject< { status: z.ZodEnum<{ completed: 'completed'; failed: 'failed'; canceled: 'canceled'; skipped: 'skipped'; }>; data: z.ZodOptional; error: z.ZodOptional; }, z.core.$strip > >, ] >; hasErrors: z.ZodBoolean; errorCount: z.ZodNumber; }, z.core.$strip >; ``` ### WORKFLOW_SETTLED In-process event name for `WorkflowSettledEvent`. ```ts import { WORKFLOW_SETTLED } from '@loopstack/core'; ``` ```ts WORKFLOW_SETTLED = 'workflow.settled'; ``` --- > Source: https://loopstack.ai/llms/reference/api/docker-sandbox-filesystem.md --- title: 'API: @loopstack/docker-sandbox-filesystem' description: 'Public API reference for @loopstack/docker-sandbox-filesystem' includeInLlmsFullTxt: false --- # API: @loopstack/docker-sandbox-filesystem ## Classes ### SandboxCreateDirectory Tool that creates a directory in a sandbox container, optionally creating parent directories. ```ts import { SandboxCreateDirectory } from '@loopstack/docker-sandbox-filesystem'; ``` **Provided by:** `SandboxFilesystemModule` ```ts export class SandboxCreateDirectory extends BaseTool { constructor(sandboxCommand: SandboxCommand); protected handle(args: SandboxCreateDirectoryArgs): Promise>; } ``` ### SandboxDelete Tool that deletes a file or directory in a sandbox container, with optional recursive and force flags. ```ts import { SandboxDelete } from '@loopstack/docker-sandbox-filesystem'; ``` **Provided by:** `SandboxFilesystemModule` ```ts export class SandboxDelete extends BaseTool { constructor(sandboxCommand: SandboxCommand); protected handle(args: SandboxDeleteArgs): Promise>; } ``` ### SandboxExists Tool that checks whether a path exists in a sandbox container and reports its type. ```ts import { SandboxExists } from '@loopstack/docker-sandbox-filesystem'; ``` **Provided by:** `SandboxFilesystemModule` ```ts export class SandboxExists extends BaseTool { constructor(sandboxCommand: SandboxCommand); protected handle(args: SandboxExistsArgs): Promise>; } ``` ### SandboxFileInfo Tool that returns detailed metadata for a file or directory in a sandbox container — type, size, permissions, owner/group, and timestamps. ```ts import { SandboxFileInfo } from '@loopstack/docker-sandbox-filesystem'; ``` **Provided by:** `SandboxFilesystemModule` ```ts export class SandboxFileInfo extends BaseTool { constructor(sandboxCommand: SandboxCommand); protected handle(args: SandboxFileInfoArgs): Promise>; } ``` ### SandboxFilesystemModule NestJS module that provides filesystem tools for operating inside Docker sandbox containers — read, write, list, create-directory, delete, exists, and file-info (`SandboxReadFile`, `SandboxWriteFile`, `SandboxListDirectory`, `SandboxCreateDirectory`, `SandboxDelete`, `SandboxExists`, `SandboxFileInfo`). Registration: - `SandboxFilesystemModule` — bare import; registers all sandbox filesystem tools. Requires: a running Docker daemon on the host; imports `SandboxToolModule` automatically, so the container lifecycle tools (`SandboxInit`, `SandboxCommand`, `SandboxDestroy`) are available too. ```ts import { SandboxFilesystemModule } from '@loopstack/docker-sandbox-filesystem'; ``` ```ts export class SandboxFilesystemModule {} ``` ### SandboxListDirectory Tool that lists files and directories in a sandbox container, optionally recursively, with type and size. ```ts import { SandboxListDirectory } from '@loopstack/docker-sandbox-filesystem'; ``` **Provided by:** `SandboxFilesystemModule` ```ts export class SandboxListDirectory extends BaseTool { constructor(sandboxCommand: SandboxCommand); protected handle(args: SandboxListDirectoryArgs): Promise>; } ``` ### SandboxReadFile Tool that reads a file's contents from a sandbox container, as utf8 or base64. ```ts import { SandboxReadFile } from '@loopstack/docker-sandbox-filesystem'; ``` **Provided by:** `SandboxFilesystemModule` ```ts export class SandboxReadFile extends BaseTool { constructor(sandboxCommand: SandboxCommand); protected handle(args: SandboxReadFileArgs): Promise>; } ``` ### SandboxWriteFile Tool that writes content to a file in a sandbox container, optionally creating parent directories. ```ts import { SandboxWriteFile } from '@loopstack/docker-sandbox-filesystem'; ``` **Provided by:** `SandboxFilesystemModule` ```ts export class SandboxWriteFile extends BaseTool { constructor(sandboxCommand: SandboxCommand); protected handle(args: SandboxWriteFileArgs): Promise>; } ``` ## Interfaces ### SandboxCreateDirectoryResult Result of `SandboxCreateDirectory`. Reports the directory path and whether it was created. ```ts import { SandboxCreateDirectoryResult } from '@loopstack/docker-sandbox-filesystem'; ``` ```ts export interface SandboxCreateDirectoryResult { path: string; created: boolean; } ``` ### SandboxDeleteResult Result of `SandboxDelete`. Reports the target path and whether it was deleted. ```ts import { SandboxDeleteResult } from '@loopstack/docker-sandbox-filesystem'; ``` ```ts export interface SandboxDeleteResult { path: string; deleted: boolean; } ``` ### SandboxExistsResult Result of `SandboxExists`. Reports whether the path exists and, if so, its type (or `null` when absent). ```ts import { SandboxExistsResult } from '@loopstack/docker-sandbox-filesystem'; ``` ```ts export interface SandboxExistsResult { path: string; exists: boolean; type: 'file' | 'directory' | 'symlink' | 'other' | null; } ``` ### SandboxFileInfoResult Result of `SandboxFileInfo`. Detailed metadata for a path — type, size, permissions, owner/group, and timestamps. ```ts import { SandboxFileInfoResult } from '@loopstack/docker-sandbox-filesystem'; ``` ```ts export interface SandboxFileInfoResult { path: string; name: string; type: 'file' | 'directory' | 'symlink' | 'other'; size: number; permissions: string; owner: string; group: string; modifiedAt: string; accessedAt: string; createdAt: string; } ``` ### SandboxListDirectoryResult Result of `SandboxListDirectory`. Reports the listed directory path and its entries (name, type, size, path). ```ts import { SandboxListDirectoryResult } from '@loopstack/docker-sandbox-filesystem'; ``` ```ts export interface SandboxListDirectoryResult { path: string; entries: FileEntry[]; } ``` ### SandboxReadFileResult Result of `SandboxReadFile`. Reports the file content and the encoding it was read with. ```ts import { SandboxReadFileResult } from '@loopstack/docker-sandbox-filesystem'; ``` ```ts export interface SandboxReadFileResult { content: string; encoding: string; } ``` ### SandboxWriteFileResult Result of `SandboxWriteFile`. Reports the written path and the number of bytes written. ```ts import { SandboxWriteFileResult } from '@loopstack/docker-sandbox-filesystem'; ``` ```ts export interface SandboxWriteFileResult { path: string; bytesWritten: number; } ``` ## Type Aliases ### SandboxCreateDirectoryArgs Args for `SandboxCreateDirectory`. Identifies the container and target directory path, with an optional recursive flag. ```ts import { SandboxCreateDirectoryArgs } from '@loopstack/docker-sandbox-filesystem'; ``` ```ts export type SandboxCreateDirectoryArgs = z.infer; ``` ### SandboxDeleteArgs Args for `SandboxDelete`. Identifies the container and target path, with optional recursive and force flags. ```ts import { SandboxDeleteArgs } from '@loopstack/docker-sandbox-filesystem'; ``` ```ts export type SandboxDeleteArgs = z.infer; ``` ### SandboxExistsArgs Args for `SandboxExists`. Identifies the container and the path to check for existence. ```ts import { SandboxExistsArgs } from '@loopstack/docker-sandbox-filesystem'; ``` ```ts export type SandboxExistsArgs = z.infer; ``` ### SandboxFileInfoArgs Args for `SandboxFileInfo`. Identifies the container and the path to inspect. ```ts import { SandboxFileInfoArgs } from '@loopstack/docker-sandbox-filesystem'; ``` ```ts export type SandboxFileInfoArgs = z.infer; ``` ### SandboxListDirectoryArgs Args for `SandboxListDirectory`. Identifies the container and directory path, with an optional recursive flag. ```ts import { SandboxListDirectoryArgs } from '@loopstack/docker-sandbox-filesystem'; ``` ```ts export type SandboxListDirectoryArgs = z.infer; ``` ### SandboxReadFileArgs Args for `SandboxReadFile`. Identifies the container, file path, and read encoding (utf8 or base64). ```ts import { SandboxReadFileArgs } from '@loopstack/docker-sandbox-filesystem'; ``` ```ts export type SandboxReadFileArgs = z.infer; ``` ### SandboxWriteFileArgs Args for `SandboxWriteFile`. Identifies the container, target path, content, encoding, and whether to create parent directories. ```ts import { SandboxWriteFileArgs } from '@loopstack/docker-sandbox-filesystem'; ``` ```ts export type SandboxWriteFileArgs = z.infer; ``` ## Variables ### SandboxCreateDirectoryResultSchema Zod schema for `SandboxCreateDirectoryResult` — the `resultSchema` of `sandbox_create_directory`. ```ts import { SandboxCreateDirectoryResultSchema } from '@loopstack/docker-sandbox-filesystem'; ``` ```ts SandboxCreateDirectoryResultSchema: z.ZodObject< { path: z.ZodString; created: z.ZodBoolean; }, z.core.$strict >; ``` ### SandboxDeleteResultSchema Zod schema for `SandboxDeleteResult` — the `resultSchema` of `sandbox_delete`. ```ts import { SandboxDeleteResultSchema } from '@loopstack/docker-sandbox-filesystem'; ``` ```ts SandboxDeleteResultSchema: z.ZodObject< { path: z.ZodString; deleted: z.ZodBoolean; }, z.core.$strict >; ``` ### SandboxExistsResultSchema Zod schema for `SandboxExistsResult` — the `resultSchema` of `sandbox_exists`. ```ts import { SandboxExistsResultSchema } from '@loopstack/docker-sandbox-filesystem'; ``` ```ts SandboxExistsResultSchema: z.ZodObject< { path: z.ZodString; exists: z.ZodBoolean; type: z.ZodNullable< z.ZodEnum<{ file: 'file'; directory: 'directory'; symlink: 'symlink'; other: 'other'; }> >; }, z.core.$strict >; ``` ### SandboxFileInfoResultSchema Zod schema for `SandboxFileInfoResult` — the `resultSchema` of `sandbox_file_info`. ```ts import { SandboxFileInfoResultSchema } from '@loopstack/docker-sandbox-filesystem'; ``` ```ts SandboxFileInfoResultSchema: z.ZodObject< { path: z.ZodString; name: z.ZodString; type: z.ZodEnum<{ file: 'file'; directory: 'directory'; symlink: 'symlink'; other: 'other'; }>; size: z.ZodNumber; permissions: z.ZodString; owner: z.ZodString; group: z.ZodString; modifiedAt: z.ZodString; accessedAt: z.ZodString; createdAt: z.ZodString; }, z.core.$strict >; ``` ### SandboxListDirectoryResultSchema Zod schema for `SandboxListDirectoryResult` — the `resultSchema` of `sandbox_list_directory`. ```ts import { SandboxListDirectoryResultSchema } from '@loopstack/docker-sandbox-filesystem'; ``` ```ts SandboxListDirectoryResultSchema: z.ZodObject< { path: z.ZodString; entries: z.ZodArray< z.ZodObject< { name: z.ZodString; type: z.ZodEnum<{ file: 'file'; directory: 'directory'; symlink: 'symlink'; other: 'other'; }>; size: z.ZodNumber; path: z.ZodString; }, z.core.$strict > >; }, z.core.$strict >; ``` ### SandboxReadFileResultSchema Zod schema for `SandboxReadFileResult` — the `resultSchema` of `sandbox_read_file`. ```ts import { SandboxReadFileResultSchema } from '@loopstack/docker-sandbox-filesystem'; ``` ```ts SandboxReadFileResultSchema: z.ZodObject< { content: z.ZodString; encoding: z.ZodString; }, z.core.$strict >; ``` ### SandboxWriteFileResultSchema Zod schema for `SandboxWriteFileResult` — the `resultSchema` of `sandbox_write_file`. ```ts import { SandboxWriteFileResultSchema } from '@loopstack/docker-sandbox-filesystem'; ``` ```ts SandboxWriteFileResultSchema: z.ZodObject< { path: z.ZodString; bytesWritten: z.ZodNumber; }, z.core.$strict >; ``` --- > Source: https://loopstack.ai/llms/reference/api/docker-sandbox.md --- title: 'API: @loopstack/docker-sandbox' description: 'Public API reference for @loopstack/docker-sandbox' includeInLlmsFullTxt: false --- # API: @loopstack/docker-sandbox ## Classes ### DockerContainerManagerService Service that manages the lifecycle of Docker sandbox containers — registering configs, ensuring containers run, executing commands, and stopping/removing them; inject it for direct container control beyond what the sandbox tools expose. ```ts import { DockerContainerManagerService } from '@loopstack/docker-sandbox'; ``` **Provided by:** `SandboxToolModule` ```ts export class DockerContainerManagerService implements OnModuleDestroy { constructor(docker?: Docker); registerContainer(containerId: string, config: ContainerConfig): void; unregisterContainer(containerId: string): void; getRegisteredContainerIds(): string[]; ensureContainer(containerId: string): Promise; executeCommand(options: ExecuteCommandOptions): Promise; getDockerContainerId(containerId: string): string | undefined; getContainerStatus(containerId: string): Promise<{ registered: boolean; exists: boolean; running: boolean; dockerId?: string; }>; stopContainer(containerId: string): Promise; removeContainer(containerId: string): Promise; onModuleDestroy(): Promise; } ``` ### SandboxCommand Tool that executes a command inside a sandbox container and captures its stdout, stderr, and exit code. ```ts import { SandboxCommand } from '@loopstack/docker-sandbox'; ``` **Provided by:** `SandboxToolModule` ```ts export class SandboxCommand extends BaseTool { protected handle(args: SandboxCommandArgs): Promise>; } ``` ### SandboxDestroy Tool that stops a sandbox container and optionally removes it, then unregisters its config. ```ts import { SandboxDestroy } from '@loopstack/docker-sandbox'; ``` **Provided by:** `SandboxToolModule` ```ts export class SandboxDestroy extends BaseTool { protected handle(args: SandboxDestroyArgs): Promise>; } ``` ### SandboxInit Tool that initializes a new Docker sandbox container from an image and mounts a host directory into it. ```ts import { SandboxInit } from '@loopstack/docker-sandbox'; ``` **Provided by:** `SandboxToolModule` ```ts export class SandboxInit extends BaseTool { protected handle(args: SandboxInitArgs): Promise>; } ``` ### SandboxToolModule NestJS module that provides Docker sandbox tools — initialize, run commands in, and destroy isolated containers (`SandboxInit`, `SandboxCommand`, `SandboxDestroy`) — plus the `DockerContainerManagerService` that manages container lifecycle. Registration: - `SandboxToolModule` — bare import; registers the sandbox tools and the container manager service. Requires: a running Docker daemon on the host; no other Loopstack modules. ```ts import { SandboxToolModule } from '@loopstack/docker-sandbox'; ``` ```ts export class SandboxToolModule {} ``` ## Interfaces ### CommandExecutionResult Result of executing a command in a sandbox container: captured stdout/stderr, exit code, and whether the command timed out. ```ts import { CommandExecutionResult } from '@loopstack/docker-sandbox'; ``` ```ts export interface CommandExecutionResult { stdout: string; stderr: string; exitCode: number; timedOut: boolean; } ``` ### ContainerConfig Config for a sandbox container — the Docker image, container name, and the host directory mounted into the container at `rootPath`. ```ts import { ContainerConfig } from '@loopstack/docker-sandbox'; ``` ```ts export interface ContainerConfig { imageName: string; containerName: string; projectOutPath: string; rootPath: string; } ``` ### SandboxDestroyResult Result of `SandboxDestroy`. Reports the affected container id and whether it was removed. ```ts import { SandboxDestroyResult } from '@loopstack/docker-sandbox'; ``` ```ts export interface SandboxDestroyResult { containerId: string; removed: boolean; } ``` ### SandboxInitResult Result of `SandboxInit`. Reports the registered container id and the underlying Docker container id. ```ts import { SandboxInitResult } from '@loopstack/docker-sandbox'; ``` ```ts export interface SandboxInitResult { containerId: string; dockerId: string; } ``` ## Type Aliases ### SandboxCommandArgs Args for `SandboxCommand`. Identifies the target container and the executable to run, with optional args, working directory, environment variables, and timeout. ```ts import { SandboxCommandArgs } from '@loopstack/docker-sandbox'; ``` ```ts export type SandboxCommandArgs = z.infer; ``` ### SandboxDestroyArgs Args for `SandboxDestroy`. Identifies the container to destroy and whether to remove it or merely stop it. ```ts import { SandboxDestroyArgs } from '@loopstack/docker-sandbox'; ``` ```ts export type SandboxDestroyArgs = z.infer; ``` ### SandboxInitArgs Args for `SandboxInit`. Specifies the container id, Docker image, container name, and the host path to mount. ```ts import { SandboxInitArgs } from '@loopstack/docker-sandbox'; ``` ```ts export type SandboxInitArgs = z.infer; ``` ## Variables ### CommandExecutionResultSchema Zod schema for `CommandExecutionResult` — the `resultSchema` of `sandbox_command`. ```ts import { CommandExecutionResultSchema } from '@loopstack/docker-sandbox'; ``` ```ts CommandExecutionResultSchema: z.ZodObject< { stdout: z.ZodString; stderr: z.ZodString; exitCode: z.ZodNumber; timedOut: z.ZodBoolean; }, z.core.$strict >; ``` ### SandboxDestroyResultSchema Zod schema for `SandboxDestroyResult` — the `resultSchema` of `sandbox_destroy`. ```ts import { SandboxDestroyResultSchema } from '@loopstack/docker-sandbox'; ``` ```ts SandboxDestroyResultSchema: z.ZodObject< { containerId: z.ZodString; removed: z.ZodBoolean; }, z.core.$strict >; ``` ### SandboxInitResultSchema Zod schema for `SandboxInitResult` — the `resultSchema` of `sandbox_init`. ```ts import { SandboxInitResultSchema } from '@loopstack/docker-sandbox'; ``` ```ts SandboxInitResultSchema: z.ZodObject< { containerId: z.ZodString; dockerId: z.ZodString; }, z.core.$strict >; ``` --- > Source: https://loopstack.ai/llms/reference/api/git.md --- title: 'API: @loopstack/git' description: 'Public API reference for @loopstack/git' includeInLlmsFullTxt: false --- # API: @loopstack/git ## Classes ### GitAddTool Tool that stages files for the next git commit. ```ts import { GitAddTool } from '@loopstack/git'; ``` **Provided by:** `GitModule` ```ts export class GitAddTool extends BaseTool { constructor(env: EnvironmentService, remote: RemoteClient); protected handle(args: GitAddArgs): Promise>; } ``` ### GitBranchTool Tool that lists all local git branches and indicates the current branch. ```ts import { GitBranchTool } from '@loopstack/git'; ``` **Provided by:** `GitModule` ```ts export class GitBranchTool extends BaseTool { constructor(env: EnvironmentService, remote: RemoteClient); protected handle(): Promise>; } ``` ### GitCheckoutTool Tool that switches to a different git branch, optionally creating it. ```ts import { GitCheckoutTool } from '@loopstack/git'; ``` **Provided by:** `GitModule` ```ts export class GitCheckoutTool extends BaseTool { constructor(env: EnvironmentService, remote: RemoteClient); protected handle(args: GitCheckoutArgs): Promise>; } ``` ### GitCommitTool Tool that creates a git commit from the currently staged changes. ```ts import { GitCommitTool } from '@loopstack/git'; ``` **Provided by:** `GitModule` ```ts export class GitCommitTool extends BaseTool { constructor(env: EnvironmentService, remote: RemoteClient); protected handle(args: GitCommitArgs): Promise>; } ``` ### GitConfigUserTool Tool that configures git `user.name` and `user.email` for the workspace repository. ```ts import { GitConfigUserTool } from '@loopstack/git'; ``` **Provided by:** `GitModule` ```ts export class GitConfigUserTool extends BaseTool { constructor(env: EnvironmentService, remote: RemoteClient); protected handle(args: GitConfigUserArgs): Promise>; } ``` ### GitDiffTool Tool that lists changed files in the workspace with their change status. ```ts import { GitDiffTool } from '@loopstack/git'; ``` **Provided by:** `GitModule` ```ts export class GitDiffTool extends BaseTool { constructor(env: EnvironmentService, remote: RemoteClient); protected handle(args: GitDiffArgs): Promise>; } ``` ### GitFetchTool Tool that fetches refs and objects from a remote repository without merging. ```ts import { GitFetchTool } from '@loopstack/git'; ``` **Provided by:** `GitModule` ```ts export class GitFetchTool extends BaseTool { constructor(env: EnvironmentService, remote: RemoteClient); protected handle(args: GitFetchArgs): Promise>; } ``` ### GitLogTool Tool that returns the git commit log for the workspace repository. ```ts import { GitLogTool } from '@loopstack/git'; ``` **Provided by:** `GitModule` ```ts export class GitLogTool extends BaseTool { constructor(env: EnvironmentService, remote: RemoteClient); protected handle(args: GitLogArgs): Promise>; } ``` ### GitModule NestJS module that provides the git version control tools (status, add, commit, push, pull, log, diff, fetch, checkout, branch, remote/user config, worktree operations) and the `GitController` REST API. Registration: - `GitModule` — bare import; registers all git tools and the REST controller unconditionally. - `GitModule.forFeature({ enabled?: boolean; environments?: string[] })` — use to feature-gate the module so its tools are only active when enabled and/or limited to specific environments. Requires: `RemoteClientModule` must be available in the DI container — every git tool delegates to a remote agent via `RemoteClient`, so the git commands run on the repository host. ```ts import { GitModule } from '@loopstack/git'; ``` ```ts export class GitModule { static forFeature(config?: { enabled?: boolean; environments?: string[] }): DynamicModule; } ``` ### GitPullTool Tool that pulls changes from a remote repository. ```ts import { GitPullTool } from '@loopstack/git'; ``` **Provided by:** `GitModule` ```ts export class GitPullTool extends BaseTool { constructor(env: EnvironmentService, remote: RemoteClient); protected handle(args: GitPullArgs): Promise>; } ``` ### GitPushTool Tool that pushes commits to a remote repository. ```ts import { GitPushTool } from '@loopstack/git'; ``` **Provided by:** `GitModule` ```ts export class GitPushTool extends BaseTool { constructor(env: EnvironmentService, remote: RemoteClient); protected handle(args: GitPushArgs): Promise>; } ``` ### GitRemoteConfigureTool Tool that configures a git remote, adding it if absent or updating its URL. ```ts import { GitRemoteConfigureTool } from '@loopstack/git'; ``` **Provided by:** `GitModule` ```ts export class GitRemoteConfigureTool extends BaseTool { constructor(env: EnvironmentService, remote: RemoteClient); protected handle(args: GitRemoteConfigureArgs): Promise>; } ``` ### GitStatusTool Tool that reports the git status of the workspace: current branch plus staged, modified, untracked, and deleted files. ```ts import { GitStatusTool } from '@loopstack/git'; ``` **Provided by:** `GitModule` ```ts export class GitStatusTool extends BaseTool { constructor(env: EnvironmentService, remote: RemoteClient); protected handle(): Promise>; } ``` ### GitWorktreeAddTool Tool that creates a new git worktree at the given path, optionally checking out or creating a branch. ```ts import { GitWorktreeAddTool } from '@loopstack/git'; ``` **Provided by:** `GitModule` ```ts export class GitWorktreeAddTool extends BaseTool { constructor(env: EnvironmentService, remote: RemoteClient); protected handle(args: GitWorktreeAddArgs): Promise>; } ``` ### GitWorktreeListTool Tool that lists all git worktrees attached to the repository, including path, HEAD, branch, and flags. ```ts import { GitWorktreeListTool } from '@loopstack/git'; ``` **Provided by:** `GitModule` ```ts export class GitWorktreeListTool extends BaseTool { constructor(env: EnvironmentService, remote: RemoteClient); protected handle(): Promise>; } ``` ### GitWorktreePruneTool Tool that prunes worktree administrative files for worktrees whose directories no longer exist. ```ts import { GitWorktreePruneTool } from '@loopstack/git'; ``` **Provided by:** `GitModule` ```ts export class GitWorktreePruneTool extends BaseTool { constructor(env: EnvironmentService, remote: RemoteClient); protected handle(): Promise>; } ``` ### GitWorktreeRemoveTool Tool that removes a git worktree at the given path, optionally forcing removal of dirty or locked worktrees. ```ts import { GitWorktreeRemoveTool } from '@loopstack/git'; ``` **Provided by:** `GitModule` ```ts export class GitWorktreeRemoveTool extends BaseTool { constructor(env: EnvironmentService, remote: RemoteClient); protected handle(args: GitWorktreeRemoveArgs): Promise>; } ``` ## Type Aliases ### GitAddArgs Args for `GitAddTool`. ```ts import { GitAddArgs } from '@loopstack/git'; ``` ```ts export type GitAddArgs = { files: string[]; }; ``` ### GitAddResult Result for `GitAddTool`. ```ts import { GitAddResult } from '@loopstack/git'; ``` ```ts export type GitAddResult = { success: boolean; }; ``` ### GitBranchResult Result for `GitBranchTool`. ```ts import { GitBranchResult } from '@loopstack/git'; ``` ```ts export type GitBranchResult = { current: string; branches: { name: string; isCurrent: boolean; }[]; }; ``` ### GitCheckoutArgs Args for `GitCheckoutTool`. ```ts import { GitCheckoutArgs } from '@loopstack/git'; ``` ```ts export type GitCheckoutArgs = { branch: string; create?: boolean; }; ``` ### GitCheckoutResult Result for `GitCheckoutTool`. ```ts import { GitCheckoutResult } from '@loopstack/git'; ``` ```ts export type GitCheckoutResult = { branch: string; }; ``` ### GitCommit A single commit entry returned by `GitLogTool`. ```ts import { GitCommit } from '@loopstack/git'; ``` ```ts export type GitCommit = { hash: string; shortHash: string; message: string; author: string; date: string; }; ``` ### GitCommitArgs Args for `GitCommitTool`. ```ts import { GitCommitArgs } from '@loopstack/git'; ``` ```ts export type GitCommitArgs = { message: string; }; ``` ### GitCommitResult Result for `GitCommitTool`. ```ts import { GitCommitResult } from '@loopstack/git'; ``` ```ts export type GitCommitResult = { hash: string; message: string; }; ``` ### GitConfigUserArgs Args for `GitConfigUserTool`. ```ts import { GitConfigUserArgs } from '@loopstack/git'; ``` ```ts export type GitConfigUserArgs = { name: string; email: string; }; ``` ### GitConfigUserResult Result for `GitConfigUserTool`. ```ts import { GitConfigUserResult } from '@loopstack/git'; ``` ```ts export type GitConfigUserResult = { success: boolean; }; ``` ### GitDiffArgs Args for `GitDiffTool`. ```ts import { GitDiffArgs } from '@loopstack/git'; ``` ```ts export type GitDiffArgs = { staged?: boolean; }; ``` ### GitDiffFile A single changed file entry returned by `GitDiffTool`. ```ts import { GitDiffFile } from '@loopstack/git'; ``` ```ts export type GitDiffFile = { path: string; status: string; }; ``` ### GitDiffResult Result for `GitDiffTool`. ```ts import { GitDiffResult } from '@loopstack/git'; ``` ```ts export type GitDiffResult = { files: GitDiffFile[]; }; ``` ### GitFetchArgs Args for `GitFetchTool`. ```ts import { GitFetchArgs } from '@loopstack/git'; ``` ```ts export type GitFetchArgs = { remote?: string; token?: string; }; ``` ### GitFetchResult Result for `GitFetchTool`. ```ts import { GitFetchResult } from '@loopstack/git'; ``` ```ts export type GitFetchResult = { success: boolean; output?: string; }; ``` ### GitLogArgs Args for `GitLogTool`. ```ts import { GitLogArgs } from '@loopstack/git'; ``` ```ts export type GitLogArgs = { limit?: number; }; ``` ### GitLogResult Result for `GitLogTool`. ```ts import { GitLogResult } from '@loopstack/git'; ``` ```ts export type GitLogResult = { commits: GitCommit[]; }; ``` ### GitPullArgs Args for `GitPullTool`. ```ts import { GitPullArgs } from '@loopstack/git'; ``` ```ts export type GitPullArgs = { remote?: string; branch?: string; token?: string; }; ``` ### GitPullResult Result for `GitPullTool`. ```ts import { GitPullResult } from '@loopstack/git'; ``` ```ts export type GitPullResult = { success: boolean; output?: string; }; ``` ### GitPushArgs Args for `GitPushTool`. ```ts import { GitPushArgs } from '@loopstack/git'; ``` ```ts export type GitPushArgs = { remote?: string; branch?: string; force?: boolean; token?: string; }; ``` ### GitPushResult Result for `GitPushTool`. ```ts import { GitPushResult } from '@loopstack/git'; ``` ```ts export type GitPushResult = { success: boolean; output?: string; }; ``` ### GitRemoteConfigureArgs Args for `GitRemoteConfigureTool`. ```ts import { GitRemoteConfigureArgs } from '@loopstack/git'; ``` ```ts export type GitRemoteConfigureArgs = { url: string; }; ``` ### GitRemoteConfigureResult Result for `GitRemoteConfigureTool`. ```ts import { GitRemoteConfigureResult } from '@loopstack/git'; ``` ```ts export type GitRemoteConfigureResult = { success: boolean; }; ``` ### GitStatusResult Result for `GitStatusTool`. ```ts import { GitStatusResult } from '@loopstack/git'; ``` ```ts export type GitStatusResult = { branch: string; staged: string[]; modified: string[]; untracked: string[]; deleted: string[]; }; ``` ### GitWorktree A single worktree entry returned by `GitWorktreeListTool`. ```ts import { GitWorktree } from '@loopstack/git'; ``` ```ts export type GitWorktree = { path: string; head?: string; branch?: string; bare: boolean; detached: boolean; locked?: string; prunable?: string; }; ``` ### GitWorktreeAddArgs Args for `GitWorktreeAddTool`. ```ts import { GitWorktreeAddArgs } from '@loopstack/git'; ``` ```ts export type GitWorktreeAddArgs = z.infer; ``` ### GitWorktreeAddResult Result for `GitWorktreeAddTool`. ```ts import { GitWorktreeAddResult } from '@loopstack/git'; ``` ```ts export type GitWorktreeAddResult = { success: boolean; path: string; output?: string; }; ``` ### GitWorktreeListResult Result for `GitWorktreeListTool`. ```ts import { GitWorktreeListResult } from '@loopstack/git'; ``` ```ts export type GitWorktreeListResult = { worktrees: GitWorktree[]; }; ``` ### GitWorktreePruneResult Result for `GitWorktreePruneTool`. ```ts import { GitWorktreePruneResult } from '@loopstack/git'; ``` ```ts export type GitWorktreePruneResult = { success: boolean; output?: string; }; ``` ### GitWorktreeRemoveArgs Args for `GitWorktreeRemoveTool`. ```ts import { GitWorktreeRemoveArgs } from '@loopstack/git'; ``` ```ts export type GitWorktreeRemoveArgs = z.infer; ``` ### GitWorktreeRemoveResult Result for `GitWorktreeRemoveTool`. ```ts import { GitWorktreeRemoveResult } from '@loopstack/git'; ``` ```ts export type GitWorktreeRemoveResult = { success: boolean; }; ``` ## Variables ### GitAddResultSchema Zod schema for `GitAddResult`. ```ts import { GitAddResultSchema } from '@loopstack/git'; ``` ```ts GitAddResultSchema: z.ZodObject< { success: z.ZodBoolean; }, z.core.$strict >; ``` ### GitBranchResultSchema Zod schema for `GitBranchResult`. ```ts import { GitBranchResultSchema } from '@loopstack/git'; ``` ```ts GitBranchResultSchema: z.ZodObject< { current: z.ZodString; branches: z.ZodArray< z.ZodObject< { name: z.ZodString; isCurrent: z.ZodBoolean; }, z.core.$strict > >; }, z.core.$strict >; ``` ### GitCheckoutResultSchema Zod schema for `GitCheckoutResult`. ```ts import { GitCheckoutResultSchema } from '@loopstack/git'; ``` ```ts GitCheckoutResultSchema: z.ZodObject< { branch: z.ZodString; }, z.core.$strict >; ``` ### GitCommitResultSchema Zod schema for `GitCommitResult`. ```ts import { GitCommitResultSchema } from '@loopstack/git'; ``` ```ts GitCommitResultSchema: z.ZodObject< { hash: z.ZodString; message: z.ZodString; }, z.core.$strict >; ``` ### GitConfigUserResultSchema Zod schema for `GitConfigUserResult`. ```ts import { GitConfigUserResultSchema } from '@loopstack/git'; ``` ```ts GitConfigUserResultSchema: z.ZodObject< { success: z.ZodBoolean; }, z.core.$strict >; ``` ### GitDiffResultSchema Zod schema for `GitDiffResult`. ```ts import { GitDiffResultSchema } from '@loopstack/git'; ``` ```ts GitDiffResultSchema: z.ZodObject< { files: z.ZodArray< z.ZodObject< { path: z.ZodString; status: z.ZodString; }, z.core.$strict > >; }, z.core.$strict >; ``` ### GitFetchResultSchema Zod schema for `GitFetchResult`. ```ts import { GitFetchResultSchema } from '@loopstack/git'; ``` ```ts GitFetchResultSchema: z.ZodObject< { success: z.ZodBoolean; output: z.ZodOptional; }, z.core.$strict >; ``` ### GitLogResultSchema Zod schema for `GitLogResult`. ```ts import { GitLogResultSchema } from '@loopstack/git'; ``` ```ts GitLogResultSchema: z.ZodObject< { commits: z.ZodArray< z.ZodObject< { hash: z.ZodString; shortHash: z.ZodString; message: z.ZodString; author: z.ZodString; date: z.ZodString; }, z.core.$strict > >; }, z.core.$strict >; ``` ### GitPullResultSchema Zod schema for `GitPullResult`. ```ts import { GitPullResultSchema } from '@loopstack/git'; ``` ```ts GitPullResultSchema: z.ZodObject< { success: z.ZodBoolean; output: z.ZodOptional; }, z.core.$strict >; ``` ### GitPushResultSchema Zod schema for `GitPushResult`. ```ts import { GitPushResultSchema } from '@loopstack/git'; ``` ```ts GitPushResultSchema: z.ZodObject< { success: z.ZodBoolean; output: z.ZodOptional; }, z.core.$strict >; ``` ### GitRemoteConfigureResultSchema Zod schema for `GitRemoteConfigureResult`. ```ts import { GitRemoteConfigureResultSchema } from '@loopstack/git'; ``` ```ts GitRemoteConfigureResultSchema: z.ZodObject< { success: z.ZodBoolean; }, z.core.$strict >; ``` ### GitStatusResultSchema Zod schema for `GitStatusResult`. ```ts import { GitStatusResultSchema } from '@loopstack/git'; ``` ```ts GitStatusResultSchema: z.ZodObject< { branch: z.ZodString; staged: z.ZodArray; modified: z.ZodArray; untracked: z.ZodArray; deleted: z.ZodArray; }, z.core.$strict >; ``` ### GitWorktreeAddResultSchema Zod schema for `GitWorktreeAddResult`. ```ts import { GitWorktreeAddResultSchema } from '@loopstack/git'; ``` ```ts GitWorktreeAddResultSchema: z.ZodObject< { success: z.ZodBoolean; path: z.ZodString; output: z.ZodOptional; }, z.core.$strict >; ``` ### GitWorktreeAddSchema Zod schema for `GitWorktreeAddTool` arguments. ```ts import { GitWorktreeAddSchema } from '@loopstack/git'; ``` ```ts GitWorktreeAddSchema: z.ZodObject< { path: z.ZodString; branch: z.ZodOptional; newBranch: z.ZodOptional; force: z.ZodOptional; }, z.core.$strict >; ``` ### GitWorktreeListResultSchema Zod schema for `GitWorktreeListResult`. ```ts import { GitWorktreeListResultSchema } from '@loopstack/git'; ``` ```ts GitWorktreeListResultSchema: z.ZodObject< { worktrees: z.ZodArray< z.ZodObject< { path: z.ZodString; head: z.ZodOptional; branch: z.ZodOptional; bare: z.ZodBoolean; detached: z.ZodBoolean; locked: z.ZodOptional; prunable: z.ZodOptional; }, z.core.$strict > >; }, z.core.$strict >; ``` ### GitWorktreePruneResultSchema Zod schema for `GitWorktreePruneResult`. ```ts import { GitWorktreePruneResultSchema } from '@loopstack/git'; ``` ```ts GitWorktreePruneResultSchema: z.ZodObject< { success: z.ZodBoolean; output: z.ZodOptional; }, z.core.$strict >; ``` ### GitWorktreeRemoveResultSchema Zod schema for `GitWorktreeRemoveResult`. ```ts import { GitWorktreeRemoveResultSchema } from '@loopstack/git'; ``` ```ts GitWorktreeRemoveResultSchema: z.ZodObject< { success: z.ZodBoolean; }, z.core.$strict >; ``` ### GitWorktreeRemoveSchema Zod schema for `GitWorktreeRemoveTool` arguments. ```ts import { GitWorktreeRemoveSchema } from '@loopstack/git'; ``` ```ts GitWorktreeRemoveSchema: z.ZodObject< { path: z.ZodString; force: z.ZodOptional; }, z.core.$strict >; ``` --- > Source: https://loopstack.ai/llms/reference/api/github-integration.md --- title: 'API: @loopstack/github-integration' description: 'Public API reference for @loopstack/github-integration' includeInLlmsFullTxt: false --- # API: @loopstack/github-integration ## Classes ### ConnectGitHubWorkflow Workflow that connects a workspace to a GitHub repository: it authenticates via OAuth, lets the user create or link a repo, configures git remotes and user identity, resolves branch divergence through HITL prompts, and pushes. ```ts import { ConnectGitHubWorkflow } from '@loopstack/github-integration'; ``` **Provided by:** `GitHubIntegrationModule` ```ts export class ConnectGitHubWorkflow extends BaseWorkflow { constructor( gitHubGetAuthenticatedUser: GitHubGetAuthenticatedUserTool, gitHubCreateRepo: GitHubCreateRepoTool, gitHubListRepos: GitHubListReposTool, gitRemoteConfigure: GitRemoteConfigureTool, gitConfigUser: GitConfigUserTool, gitStatus: GitStatusTool, gitPush: GitPushTool, gitFetch: GitFetchTool, bash: BashTool, oAuth: OAuthWorkflow, askUser: AskUserWorkflow, tokenStore: OAuthTokenStore, clientMessageService: ClientMessageService, ); start(_state: ConnectGitHubState): Promise; launchOAuth(_state: ConnectGitHubState): Promise; authCompleted(_state: ConnectGitHubState, _input: TransitionInput): Promise; askCreateOrLink(_state: ConnectGitHubState): Promise; choiceReceived( state: ConnectGitHubState, input: TransitionInput<{ answer: string; }>, ): Promise; createRepo( state: ConnectGitHubState, input: TransitionInput<{ answer: string; }>, ): Promise; repoSelected( state: ConnectGitHubState, input: TransitionInput<{ answer: string; }>, ): void; checkForUncommittedChanges(state: ConnectGitHubState): Promise; skipCommitCheck(_state: ConnectGitHubState): void; askCommitChanges(_state: ConnectGitHubState): Promise; uncommittedChangesHandled( state: ConnectGitHubState, input: TransitionInput<{ answer: string; }>, ): Promise; setupRemote(state: ConnectGitHubState, ctx: RunContext): Promise; pushDirectly(state: ConnectGitHubState, ctx: RunContext): Promise; askSyncStrategy(state: ConnectGitHubState): Promise; syncStrategyChosen( state: ConnectGitHubState, input: TransitionInput<{ answer: string; }>, ctx: RunContext, ): Promise; showSuccess(state: ConnectGitHubState, ctx: RunContext): Promise; } ``` ### GitHubIntegrationModule NestJS module that provides `ConnectGitHubWorkflow` — a guided end-to-end workflow that authenticates via OAuth, creates or links a GitHub repo, configures git remotes, resolves branch divergence via HITL, and pushes. Registration: - `GitHubIntegrationModule` — bare import; it internally imports `GitModule`, `GitHubModule`, `HitlModule`, and `OAuthModule`, so you do not import those yourself. No static configuration methods exist. Requires: the peer packages `@loopstack/git`, `@loopstack/github`, `@loopstack/hitl`, `@loopstack/oauth`, and `@loopstack/remote-client` must be installed, plus a configured GitHub OAuth app (client ID/secret via `GitHubModule`'s env vars) and the `RemoteClient` infrastructure required by `GitModule`. ```ts import { GitHubIntegrationModule } from '@loopstack/github-integration'; ``` ```ts export class GitHubIntegrationModule {} ``` --- > Source: https://loopstack.ai/llms/reference/api/github.md --- title: 'API: @loopstack/github' description: 'Public API reference for @loopstack/github' includeInLlmsFullTxt: false --- # API: @loopstack/github ## Classes ### GitHubCreateIssueCommentTool Tool that adds a comment to a GitHub issue or pull request. ```ts import { GitHubCreateIssueCommentTool } from '@loopstack/github'; ``` **Provided by:** `GitHubModule` ```ts export class GitHubCreateIssueCommentTool extends BaseTool< GitHubCreateIssueCommentArgs, object, GitHubCreateIssueCommentResult > { protected handle( args: GitHubCreateIssueCommentArgs, ctx: RunContext, ): Promise>; } ``` ### GitHubCreateIssueTool Tool that creates a new issue in a GitHub repository. ```ts import { GitHubCreateIssueTool } from '@loopstack/github'; ``` **Provided by:** `GitHubModule` ```ts export class GitHubCreateIssueTool extends BaseTool { protected handle(args: GitHubCreateIssueArgs, ctx: RunContext): Promise>; } ``` ### GitHubCreateOrUpdateFileTool Tool that creates or updates a file in a GitHub repository, base64-encoding the provided text and committing it. Pass the existing file `sha` to update in place. ```ts import { GitHubCreateOrUpdateFileTool } from '@loopstack/github'; ``` **Provided by:** `GitHubModule` ```ts export class GitHubCreateOrUpdateFileTool extends BaseTool< GitHubCreateOrUpdateFileArgs, object, GitHubCreateOrUpdateFileResult > { protected handle( args: GitHubCreateOrUpdateFileArgs, ctx: RunContext, ): Promise>; } ``` ### GitHubCreatePullRequestTool Tool that opens a new pull request in a GitHub repository from a head branch into a base branch. ```ts import { GitHubCreatePullRequestTool } from '@loopstack/github'; ``` **Provided by:** `GitHubModule` ```ts export class GitHubCreatePullRequestTool extends BaseTool< GitHubCreatePullRequestArgs, object, GitHubCreatePullRequestResult > { protected handle( args: GitHubCreatePullRequestArgs, ctx: RunContext, ): Promise>; } ``` ### GitHubCreateRepoTool Tool that creates a new GitHub repository for the authenticated user. ```ts import { GitHubCreateRepoTool } from '@loopstack/github'; ``` **Provided by:** `GitHubModule` ```ts export class GitHubCreateRepoTool extends BaseTool { protected handle(args: GitHubCreateRepoArgs, ctx: RunContext): Promise>; } ``` ### GitHubGetAuthenticatedUserTool Tool that fetches the profile of the currently authenticated GitHub user. ```ts import { GitHubGetAuthenticatedUserTool } from '@loopstack/github'; ``` **Provided by:** `GitHubModule` ```ts export class GitHubGetAuthenticatedUserTool extends BaseTool< GitHubGetAuthenticatedUserArgs, object, GitHubGetAuthenticatedUserResult > { protected handle( _args: GitHubGetAuthenticatedUserArgs, ctx: RunContext, ): Promise>; } ``` ### GitHubGetCommitTool Tool that fetches detailed information about a single commit in a GitHub repository, including diff stats and changed files. ```ts import { GitHubGetCommitTool } from '@loopstack/github'; ``` **Provided by:** `GitHubModule` ```ts export class GitHubGetCommitTool extends BaseTool { protected handle(args: GitHubGetCommitArgs, ctx: RunContext): Promise>; } ``` ### GitHubGetFileContentTool Tool that reads the content of a file from a GitHub repository, decoding the base64 payload returned by the API into plain text. ```ts import { GitHubGetFileContentTool } from '@loopstack/github'; ``` **Provided by:** `GitHubModule` ```ts export class GitHubGetFileContentTool extends BaseTool { protected handle(args: GitHubGetFileContentArgs, ctx: RunContext): Promise>; } ``` ### GitHubGetIssueTool Tool that fetches detailed information about a single GitHub issue. ```ts import { GitHubGetIssueTool } from '@loopstack/github'; ``` **Provided by:** `GitHubModule` ```ts export class GitHubGetIssueTool extends BaseTool { protected handle(args: GitHubGetIssueArgs, ctx: RunContext): Promise>; } ``` ### GitHubGetPullRequestTool Tool that fetches detailed information about a single GitHub pull request. ```ts import { GitHubGetPullRequestTool } from '@loopstack/github'; ``` **Provided by:** `GitHubModule` ```ts export class GitHubGetPullRequestTool extends BaseTool { protected handle(args: GitHubGetPullRequestArgs, ctx: RunContext): Promise>; } ``` ### GitHubGetRepoTool Tool that fetches detailed information about a single GitHub repository. Takes an `owner` and `repo` and returns full repository metadata. ```ts import { GitHubGetRepoTool } from '@loopstack/github'; ``` **Provided by:** `GitHubModule` ```ts export class GitHubGetRepoTool extends BaseTool { protected handle(args: GitHubGetRepoArgs, ctx: RunContext): Promise>; } ``` ### GitHubGetWorkflowRunTool Tool that fetches detailed information about a single GitHub Actions workflow run. ```ts import { GitHubGetWorkflowRunTool } from '@loopstack/github'; ``` **Provided by:** `GitHubModule` ```ts export class GitHubGetWorkflowRunTool extends BaseTool { protected handle(args: GitHubGetWorkflowRunArgs, ctx: RunContext): Promise>; } ``` ### GitHubListBranchesTool Tool that lists branches for a GitHub repository. ```ts import { GitHubListBranchesTool } from '@loopstack/github'; ``` **Provided by:** `GitHubModule` ```ts export class GitHubListBranchesTool extends BaseTool { protected handle(args: GitHubListBranchesArgs, ctx: RunContext): Promise>; } ``` ### GitHubListDirectoryTool Tool that lists the contents of a directory in a GitHub repository. ```ts import { GitHubListDirectoryTool } from '@loopstack/github'; ``` **Provided by:** `GitHubModule` ```ts export class GitHubListDirectoryTool extends BaseTool { protected handle(args: GitHubListDirectoryArgs, ctx: RunContext): Promise>; } ``` ### GitHubListIssuesTool Tool that lists issues for a GitHub repository, with state, label and assignee filters. Note that the GitHub API also returns pull requests, marked via `isPullRequest`. ```ts import { GitHubListIssuesTool } from '@loopstack/github'; ``` **Provided by:** `GitHubModule` ```ts export class GitHubListIssuesTool extends BaseTool { protected handle(args: GitHubListIssuesArgs, ctx: RunContext): Promise>; } ``` ### GitHubListPrReviewsTool Tool that lists reviews submitted on a GitHub pull request. ```ts import { GitHubListPrReviewsTool } from '@loopstack/github'; ``` **Provided by:** `GitHubModule` ```ts export class GitHubListPrReviewsTool extends BaseTool { protected handle(args: GitHubListPrReviewsArgs, ctx: RunContext): Promise>; } ``` ### GitHubListPullRequestsTool Tool that lists pull requests for a GitHub repository, with state and base-branch filters. ```ts import { GitHubListPullRequestsTool } from '@loopstack/github'; ``` **Provided by:** `GitHubModule` ```ts export class GitHubListPullRequestsTool extends BaseTool< GitHubListPullRequestsArgs, object, GitHubListPullRequestsResult > { protected handle( args: GitHubListPullRequestsArgs, ctx: RunContext, ): Promise>; } ``` ### GitHubListReposTool Tool that lists repositories for the authenticated GitHub user, with visibility, sort and paging options. ```ts import { GitHubListReposTool } from '@loopstack/github'; ``` **Provided by:** `GitHubModule` ```ts export class GitHubListReposTool extends BaseTool { protected handle(args: GitHubListReposArgs, ctx: RunContext): Promise>; } ``` ### GitHubListUserOrgsTool Tool that lists the organizations the authenticated GitHub user belongs to. ```ts import { GitHubListUserOrgsTool } from '@loopstack/github'; ``` **Provided by:** `GitHubModule` ```ts export class GitHubListUserOrgsTool extends BaseTool { protected handle(args: GitHubListUserOrgsArgs, ctx: RunContext): Promise>; } ``` ### GitHubListWorkflowRunsTool Tool that lists GitHub Actions workflow runs for a repository, with branch and status filters. ```ts import { GitHubListWorkflowRunsTool } from '@loopstack/github'; ``` **Provided by:** `GitHubModule` ```ts export class GitHubListWorkflowRunsTool extends BaseTool< GitHubListWorkflowRunsArgs, object, GitHubListWorkflowRunsResult > { protected handle( args: GitHubListWorkflowRunsArgs, ctx: RunContext, ): Promise>; } ``` ### GitHubMergePullRequestTool Tool that merges a GitHub pull request using the chosen merge method. ```ts import { GitHubMergePullRequestTool } from '@loopstack/github'; ``` **Provided by:** `GitHubModule` ```ts export class GitHubMergePullRequestTool extends BaseTool< GitHubMergePullRequestArgs, object, GitHubMergePullRequestResult > { protected handle( args: GitHubMergePullRequestArgs, ctx: RunContext, ): Promise>; } ``` ### GitHubModule NestJS module that provides the GitHub OAuth provider (`GitHubOAuthProvider`) and 25 GitHub API tools for repositories, issues, pull requests, file content/git ops, actions/workflow runs, search, and users/orgs. Registration: - `GitHubModule` — bare import; it internally imports `OAuthModule` and registers `GitHubOAuthProvider` plus all tools. No static configuration methods exist. Requires: a configured GitHub OAuth app via the environment variables `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, and `GITHUB_OAUTH_REDIRECT_URI`; without valid OAuth credentials the tools return `{ error: 'unauthorized' }`. ```ts import { GitHubModule } from '@loopstack/github'; ``` ```ts export class GitHubModule {} ``` ### GitHubSearchCodeTool Tool that searches for code across GitHub repositories using the GitHub search syntax. ```ts import { GitHubSearchCodeTool } from '@loopstack/github'; ``` **Provided by:** `GitHubModule` ```ts export class GitHubSearchCodeTool extends BaseTool { protected handle(args: GitHubSearchCodeArgs, ctx: RunContext): Promise>; } ``` ### GitHubSearchIssuesTool Tool that searches for issues and pull requests across GitHub using the GitHub search syntax. ```ts import { GitHubSearchIssuesTool } from '@loopstack/github'; ``` **Provided by:** `GitHubModule` ```ts export class GitHubSearchIssuesTool extends BaseTool { protected handle(args: GitHubSearchIssuesArgs, ctx: RunContext): Promise>; } ``` ### GitHubSearchReposTool Tool that searches for repositories on GitHub using the GitHub search syntax. ```ts import { GitHubSearchReposTool } from '@loopstack/github'; ``` **Provided by:** `GitHubModule` ```ts export class GitHubSearchReposTool extends BaseTool { protected handle(args: GitHubSearchReposArgs, ctx: RunContext): Promise>; } ``` ### GitHubTriggerWorkflowTool Tool that triggers a GitHub Actions workflow dispatch event on a given ref. ```ts import { GitHubTriggerWorkflowTool } from '@loopstack/github'; ``` **Provided by:** `GitHubModule` ```ts export class GitHubTriggerWorkflowTool extends BaseTool< GitHubTriggerWorkflowArgs, object, GitHubTriggerWorkflowResult > { protected handle( args: GitHubTriggerWorkflowArgs, ctx: RunContext, ): Promise>; } ``` ## Type Aliases ### GitHubCreateIssueArgs Args for `GitHubCreateIssueTool`: the repository `owner`, `repo`, issue `title` and optional `body`, `labels` and `assignees`. ```ts import { GitHubCreateIssueArgs } from '@loopstack/github'; ``` ```ts export type GitHubCreateIssueArgs = z.infer; ``` ### GitHubCreateIssueCommentArgs Args for `GitHubCreateIssueCommentTool`: the repository `owner`, `repo`, `issueNumber` (issue or pull request) and comment `body`. ```ts import { GitHubCreateIssueCommentArgs } from '@loopstack/github'; ``` ```ts export type GitHubCreateIssueCommentArgs = z.infer; ``` ### GitHubCreateIssueCommentResult Result for `GitHubCreateIssueCommentTool`: the created `comment` summary, or an `error`. ```ts import { GitHubCreateIssueCommentResult } from '@loopstack/github'; ``` ```ts export type GitHubCreateIssueCommentResult = | { comment: { id: number; htmlUrl: string; createdAt: string; user: string; }; } | { error: string; message: string; }; ``` ### GitHubCreateIssueResult Result for `GitHubCreateIssueTool`: the created `issue` summary, or an `error`. ```ts import { GitHubCreateIssueResult } from '@loopstack/github'; ``` ```ts export type GitHubCreateIssueResult = | { issue: { id: number; number: number; title: string; htmlUrl: string; state: string; }; } | { error: string; message: string; }; ``` ### GitHubCreateOrUpdateFileArgs Args for `GitHubCreateOrUpdateFileTool`: the repository `owner`, `repo`, file `path`, plain-text `content`, commit `message`, optional `branch` and `sha` of the file being replaced. ```ts import { GitHubCreateOrUpdateFileArgs } from '@loopstack/github'; ``` ```ts export type GitHubCreateOrUpdateFileArgs = z.infer; ``` ### GitHubCreateOrUpdateFileResult Result for `GitHubCreateOrUpdateFileTool`: the written `file` and resulting `commit`, or an `error`. ```ts import { GitHubCreateOrUpdateFileResult } from '@loopstack/github'; ``` ```ts export type GitHubCreateOrUpdateFileResult = | { file: { name: string; path: string; sha: string; htmlUrl: string; }; commit: { sha: string; message: string; }; } | { error: string; message: string; }; ``` ### GitHubCreatePullRequestArgs Args for `GitHubCreatePullRequestTool`: the repository `owner`, `repo`, `title`, `head` and `base` branches, optional `body` and `draft` flag. ```ts import { GitHubCreatePullRequestArgs } from '@loopstack/github'; ``` ```ts export type GitHubCreatePullRequestArgs = z.input; ``` ### GitHubCreatePullRequestResult Result for `GitHubCreatePullRequestTool`: the created `pullRequest` summary, or an `error`. ```ts import { GitHubCreatePullRequestResult } from '@loopstack/github'; ``` ```ts export type GitHubCreatePullRequestResult = | { pullRequest: { id: number; number: number; title: string; htmlUrl: string; state: string; draft: boolean; }; } | { error: string; message: string; }; ``` ### GitHubCreateRepoArgs Args for `GitHubCreateRepoTool`: repository `name`, optional `description`, `private` visibility and `autoInit` to seed an initial commit. ```ts import { GitHubCreateRepoArgs } from '@loopstack/github'; ``` ```ts export type GitHubCreateRepoArgs = z.input; ``` ### GitHubCreateRepoResult Result for `GitHubCreateRepoTool`: the created `repo` summary, or an `error`. ```ts import { GitHubCreateRepoResult } from '@loopstack/github'; ``` ```ts export type GitHubCreateRepoResult = { repo?: { id: number; fullName: string; name: string; htmlUrl: string; private: boolean; defaultBranch: string; }; error?: string; message?: string; }; ``` ### GitHubGetAuthenticatedUserArgs Args for `GitHubGetAuthenticatedUserTool`: an empty object; the user is resolved from the token. ```ts import { GitHubGetAuthenticatedUserArgs } from '@loopstack/github'; ``` ```ts export type GitHubGetAuthenticatedUserArgs = z.infer; ``` ### GitHubGetAuthenticatedUserResult Result for `GitHubGetAuthenticatedUserTool`: a `user` profile with login, name, email, avatar and counts, or an `error`. ```ts import { GitHubGetAuthenticatedUserResult } from '@loopstack/github'; ``` ```ts export type GitHubGetAuthenticatedUserResult = { user?: { id: number; login: string; name: string | null; email: string | null; avatarUrl: string; htmlUrl: string; bio: string | null; publicRepos: number; followers: number; following: number; createdAt: string; }; error?: string; message?: string; }; ``` ### GitHubGetCommitArgs Args for `GitHubGetCommitTool`: the repository `owner`, `repo` and `ref` (commit SHA, branch or tag). ```ts import { GitHubGetCommitArgs } from '@loopstack/github'; ``` ```ts export type GitHubGetCommitArgs = z.infer; ``` ### GitHubGetCommitResult Result for `GitHubGetCommitTool`: a `commit` object with author, committer, diff `stats` and changed `files`, or an `error`. ```ts import { GitHubGetCommitResult } from '@loopstack/github'; ``` ```ts export type GitHubGetCommitResult = | { commit: { sha: string; message: string; author: { name: string; email: string; date: string; login: string | null; }; committer: { name: string; date: string; }; htmlUrl: string; stats: { additions: number; deletions: number; total: number; }; files: Array<{ filename: string; status: string; additions: number; deletions: number; changes: number; }>; }; } | { error: string; message: string; }; ``` ### GitHubGetFileContentArgs Args for `GitHubGetFileContentTool`: the repository `owner`, `repo`, file `path` and optional `ref` (branch, tag or commit SHA). ```ts import { GitHubGetFileContentArgs } from '@loopstack/github'; ``` ```ts export type GitHubGetFileContentArgs = z.infer; ``` ### GitHubGetFileContentResult Result for `GitHubGetFileContentTool`: a `file` object with decoded text `content` plus path, sha and size, or an `error`. ```ts import { GitHubGetFileContentResult } from '@loopstack/github'; ``` ```ts export type GitHubGetFileContentResult = | { file: { name: string; path: string; sha: string; size: number; type: string; content: string | null; htmlUrl: string; }; } | { error: string; message: string; }; ``` ### GitHubGetIssueArgs Args for `GitHubGetIssueTool`: the repository `owner`, `repo` and `issueNumber`. ```ts import { GitHubGetIssueArgs } from '@loopstack/github'; ``` ```ts export type GitHubGetIssueArgs = z.infer; ``` ### GitHubGetIssueResult Result for `GitHubGetIssueTool`: an `issue` object with title, body, state, labels, assignees and timestamps, or an `error`. ```ts import { GitHubGetIssueResult } from '@loopstack/github'; ``` ```ts export type GitHubGetIssueResult = | { issue: { id: number; number: number; title: string; body: string | null; state: string; user: string; labels: string[]; assignees: string[]; milestone: string | null; createdAt: string; updatedAt: string; closedAt: string | null; htmlUrl: string; comments: number; }; } | { error: string; message: string; }; ``` ### GitHubGetPullRequestArgs Args for `GitHubGetPullRequestTool`: the repository `owner`, `repo` and `pullNumber`. ```ts import { GitHubGetPullRequestArgs } from '@loopstack/github'; ``` ```ts export type GitHubGetPullRequestArgs = z.infer; ``` ### GitHubGetPullRequestResult Result for `GitHubGetPullRequestTool`: a `pullRequest` object with branches, merge state, diff stats and timestamps, or an `error`. ```ts import { GitHubGetPullRequestResult } from '@loopstack/github'; ``` ```ts export type GitHubGetPullRequestResult = | { pullRequest: { id: number; number: number; title: string; body: string | null; state: string; user: string; head: string; headSha: string; base: string; merged: boolean; mergeable: boolean | null; draft: boolean; additions: number; deletions: number; changedFiles: number; createdAt: string; updatedAt: string; mergedAt: string | null; htmlUrl: string; comments: number; reviewComments: number; }; } | { error: string; message: string; }; ``` ### GitHubGetRepoArgs Args for `GitHubGetRepoTool`: the repository `owner` and `repo` name. ```ts import { GitHubGetRepoArgs } from '@loopstack/github'; ``` ```ts export type GitHubGetRepoArgs = z.infer; ``` ### GitHubGetRepoResult Result for `GitHubGetRepoTool`: a `repo` object with id, full name, visibility, description, language, default branch, stars, forks, topics and license, or an `error`. ```ts import { GitHubGetRepoResult } from '@loopstack/github'; ``` ```ts export type GitHubGetRepoResult = { repo?: { id: number; fullName: string; name: string; owner: string; ownerAvatar: string; private: boolean; htmlUrl: string; description: string | null; language: string | null; defaultBranch: string; stars: number; forks: number; openIssues: number; createdAt: string; updatedAt: string; topics: string[]; license: string | null; }; error?: string; message?: string; }; ``` ### GitHubGetWorkflowRunArgs Args for `GitHubGetWorkflowRunTool`: the repository `owner`, `repo` and `runId`. ```ts import { GitHubGetWorkflowRunArgs } from '@loopstack/github'; ``` ```ts export type GitHubGetWorkflowRunArgs = z.infer; ``` ### GitHubGetWorkflowRunResult Result for `GitHubGetWorkflowRunTool`: a `run` object with status, conclusion, branch and run metadata, or an `error`. ```ts import { GitHubGetWorkflowRunResult } from '@loopstack/github'; ``` ```ts export type GitHubGetWorkflowRunResult = | { run: { id: number; name: string; status: string; conclusion: string | null; headBranch: string; headSha: string; event: string; workflowId: number; runNumber: number; runAttempt: number; createdAt: string; updatedAt: string; runStartedAt: string; htmlUrl: string; }; } | { error: string; message: string; }; ``` ### GitHubListBranchesArgs Args for `GitHubListBranchesTool`: the repository `owner`, `repo` and `perPage` page size. ```ts import { GitHubListBranchesArgs } from '@loopstack/github'; ``` ```ts export type GitHubListBranchesArgs = z.input; ``` ### GitHubListBranchesResult Result for `GitHubListBranchesTool`: a `branches` array with name, commit SHA and protection flag, or an `error`. ```ts import { GitHubListBranchesResult } from '@loopstack/github'; ``` ```ts export type GitHubListBranchesResult = { branches?: Array<{ name: string; commitSha: string; protected: boolean; }>; error?: string; message?: string; }; ``` ### GitHubListDirectoryArgs Args for `GitHubListDirectoryTool`: the repository `owner`, `repo`, directory `path` (defaults to the repo root) and optional `ref`. ```ts import { GitHubListDirectoryArgs } from '@loopstack/github'; ``` ```ts export type GitHubListDirectoryArgs = z.input; ``` ### GitHubListDirectoryResult Result for `GitHubListDirectoryTool`: an `entries` array of files and subdirectories, or an `error`. ```ts import { GitHubListDirectoryResult } from '@loopstack/github'; ``` ```ts export type GitHubListDirectoryResult = { entries?: Array<{ name: string; path: string; sha: string; size: number; type: string; htmlUrl: string; }>; error?: string; message?: string; }; ``` ### GitHubListIssuesArgs Args for `GitHubListIssuesTool`: the repository `owner`, `repo`, issue `state`, optional `labels`/`assignee` filters and `perPage`/`page` paging. ```ts import { GitHubListIssuesArgs } from '@loopstack/github'; ``` ```ts export type GitHubListIssuesArgs = z.input; ``` ### GitHubListIssuesResult Result for `GitHubListIssuesTool`: an `issues` array (each flagged with `isPullRequest` since the GitHub API mixes in pull requests), or an `error`. ```ts import { GitHubListIssuesResult } from '@loopstack/github'; ``` ```ts export type GitHubListIssuesResult = { issues?: Array<{ id: number; number: number; title: string; state: string; user: string; labels: string[]; assignees: string[]; createdAt: string; updatedAt: string; htmlUrl: string; isPullRequest: boolean; }>; error?: string; message?: string; }; ``` ### GitHubListPrReviewsArgs Args for `GitHubListPrReviewsTool`: the repository `owner`, `repo` and `pullNumber`. ```ts import { GitHubListPrReviewsArgs } from '@loopstack/github'; ``` ```ts export type GitHubListPrReviewsArgs = z.infer; ``` ### GitHubListPrReviewsResult Result for `GitHubListPrReviewsTool`: a `reviews` array with reviewer, body, state and submission time (absent for a pending review), or an `error`. ```ts import { GitHubListPrReviewsResult } from '@loopstack/github'; ``` ```ts export type GitHubListPrReviewsResult = | { reviews: Array<{ id: number; user: string; body: string; state: string; submittedAt?: string; htmlUrl: string; }>; } | { error: string; message: string; }; ``` ### GitHubListPullRequestsArgs Args for `GitHubListPullRequestsTool`: the repository `owner`, `repo`, PR `state`, optional `base` branch filter and `perPage`/`page` paging. ```ts import { GitHubListPullRequestsArgs } from '@loopstack/github'; ``` ```ts export type GitHubListPullRequestsArgs = z.input; ``` ### GitHubListPullRequestsResult Result for `GitHubListPullRequestsTool`: a `pullRequests` array of PR summaries, or an `error`. ```ts import { GitHubListPullRequestsResult } from '@loopstack/github'; ``` ```ts export type GitHubListPullRequestsResult = { pullRequests?: Array<{ id: number; number: number; title: string; state: string; user: string; head: string; headSha: string; base: string; createdAt: string; updatedAt: string; htmlUrl: string; draft: boolean; }>; error?: string; message?: string; }; ``` ### GitHubListReposArgs Args for `GitHubListReposTool`: `visibility`, `sort`, `perPage` and `page` paging controls. ```ts import { GitHubListReposArgs } from '@loopstack/github'; ``` ```ts export type GitHubListReposArgs = z.input; ``` ### GitHubListReposResult Result for `GitHubListReposTool`: a `repos` array of repository summaries, or an `error`. ```ts import { GitHubListReposResult } from '@loopstack/github'; ``` ```ts export type GitHubListReposResult = { repos?: Array<{ id: number; fullName: string; name: string; owner: string; private: boolean; htmlUrl: string; description: string | null; language: string | null; defaultBranch: string; updatedAt: string; }>; error?: string; message?: string; }; ``` ### GitHubListUserOrgsArgs Args for `GitHubListUserOrgsTool`: the `perPage` page size. ```ts import { GitHubListUserOrgsArgs } from '@loopstack/github'; ``` ```ts export type GitHubListUserOrgsArgs = z.input; ``` ### GitHubListUserOrgsResult Result for `GitHubListUserOrgsTool`: an `orgs` array with login, description and avatar, or an `error`. ```ts import { GitHubListUserOrgsResult } from '@loopstack/github'; ``` ```ts export type GitHubListUserOrgsResult = { orgs?: Array<{ id: number; login: string; description: string | null; avatarUrl: string; }>; error?: string; message?: string; }; ``` ### GitHubListWorkflowRunsArgs Args for `GitHubListWorkflowRunsTool`: the repository `owner`, `repo`, optional `branch` and `status` filters and `perPage`/`page` paging. ```ts import { GitHubListWorkflowRunsArgs } from '@loopstack/github'; ``` ```ts export type GitHubListWorkflowRunsArgs = z.input; ``` ### GitHubListWorkflowRunsResult Result for `GitHubListWorkflowRunsTool`: `totalCount` and a `runs` array of workflow-run summaries with status and conclusion, or an `error`. ```ts import { GitHubListWorkflowRunsResult } from '@loopstack/github'; ``` ```ts export type GitHubListWorkflowRunsResult = { totalCount?: number; runs?: Array<{ id: number; name: string; status: string; conclusion: string | null; headBranch: string; headSha: string; event: string; createdAt: string; updatedAt: string; htmlUrl: string; }>; error?: string; message?: string; }; ``` ### GitHubMergePullRequestArgs Args for `GitHubMergePullRequestTool`: the repository `owner`, `repo`, `pullNumber`, `mergeMethod` and optional `commitTitle`/`commitMessage`. ```ts import { GitHubMergePullRequestArgs } from '@loopstack/github'; ``` ```ts export type GitHubMergePullRequestArgs = z.input; ``` ### GitHubMergePullRequestResult Result for `GitHubMergePullRequestTool`: a `merge` object with the merge commit `sha` and `merged` flag, or an `error`. ```ts import { GitHubMergePullRequestResult } from '@loopstack/github'; ``` ```ts export type GitHubMergePullRequestResult = | { merge: { sha: string; merged: boolean; message: string; }; } | { error: string; message: string; }; ``` ### GitHubSearchCodeArgs Args for `GitHubSearchCodeTool`: the GitHub code-search `query` and `perPage`/`page` paging. ```ts import { GitHubSearchCodeArgs } from '@loopstack/github'; ``` ```ts export type GitHubSearchCodeArgs = z.input; ``` ### GitHubSearchCodeResult Result for `GitHubSearchCodeTool`: `totalCount` and a `results` array of matching files with their repository, or an `error`. ```ts import { GitHubSearchCodeResult } from '@loopstack/github'; ``` ```ts export type GitHubSearchCodeResult = { totalCount?: number; results?: Array<{ name: string; path: string; sha: string; htmlUrl: string; repository: string; }>; error?: string; message?: string; }; ``` ### GitHubSearchIssuesArgs Args for `GitHubSearchIssuesTool`: the GitHub search `query`, optional `sort` and `perPage`/`page` paging. ```ts import { GitHubSearchIssuesArgs } from '@loopstack/github'; ``` ```ts export type GitHubSearchIssuesArgs = z.input; ``` ### GitHubSearchIssuesResult Result for `GitHubSearchIssuesTool`: `totalCount` and a `results` array of matching issues and pull requests (each flagged with `isPullRequest`), or an `error`. ```ts import { GitHubSearchIssuesResult } from '@loopstack/github'; ``` ```ts export type GitHubSearchIssuesResult = | { totalCount: number; results: Array<{ id: number; number: number; title: string; state: string; user: string; htmlUrl: string; createdAt: string; updatedAt: string; isPullRequest: boolean; }>; } | { error: string; message: string; }; ``` ### GitHubSearchReposArgs Args for `GitHubSearchReposTool`: the GitHub search `query`, optional `sort` and `perPage`/`page` paging. ```ts import { GitHubSearchReposArgs } from '@loopstack/github'; ``` ```ts export type GitHubSearchReposArgs = z.input; ``` ### GitHubSearchReposResult Result for `GitHubSearchReposTool`: `totalCount` and a `results` array of matching repositories, or an `error`. ```ts import { GitHubSearchReposResult } from '@loopstack/github'; ``` ```ts export type GitHubSearchReposResult = | { totalCount: number; results: Array<{ id: number; fullName: string; description: string | null; htmlUrl: string; language: string | null; stars: number; forks: number; updatedAt: string; }>; } | { error: string; message: string; }; ``` ### GitHubTriggerWorkflowArgs Args for `GitHubTriggerWorkflowTool`: the repository `owner`, `repo`, `workflowId`, `ref` to run against and optional `inputs` for the dispatch event. ```ts import { GitHubTriggerWorkflowArgs } from '@loopstack/github'; ``` ```ts export type GitHubTriggerWorkflowArgs = z.infer; ``` ### GitHubTriggerWorkflowResult Result for `GitHubTriggerWorkflowTool`: a `triggered` flag with a message, or an `error`. ```ts import { GitHubTriggerWorkflowResult } from '@loopstack/github'; ``` ```ts export type GitHubTriggerWorkflowResult = | { triggered: boolean; message: string; } | { error: string; message: string; }; ``` ## Variables ### GitHubCreateIssueCommentResultSchema Zod schema for the success shape of `GitHubCreateIssueCommentResult`. ```ts import { GitHubCreateIssueCommentResultSchema } from '@loopstack/github'; ``` ```ts GitHubCreateIssueCommentResultSchema: z.ZodObject< { comment: z.ZodObject< { id: z.ZodNumber; htmlUrl: z.ZodString; createdAt: z.ZodString; user: z.ZodString; }, z.core.$strict >; }, z.core.$strict >; ``` ### GitHubCreateIssueResultSchema Zod schema for the success shape of `GitHubCreateIssueResult`. ```ts import { GitHubCreateIssueResultSchema } from '@loopstack/github'; ``` ```ts GitHubCreateIssueResultSchema: z.ZodObject< { issue: z.ZodObject< { id: z.ZodNumber; number: z.ZodNumber; title: z.ZodString; htmlUrl: z.ZodString; state: z.ZodString; }, z.core.$strict >; }, z.core.$strict >; ``` ### GitHubCreateOrUpdateFileResultSchema Zod schema for the success shape of `GitHubCreateOrUpdateFileResult`. ```ts import { GitHubCreateOrUpdateFileResultSchema } from '@loopstack/github'; ``` ```ts GitHubCreateOrUpdateFileResultSchema: z.ZodObject< { file: z.ZodObject< { name: z.ZodString; path: z.ZodString; sha: z.ZodString; htmlUrl: z.ZodString; }, z.core.$strict >; commit: z.ZodObject< { sha: z.ZodString; message: z.ZodString; }, z.core.$strict >; }, z.core.$strict >; ``` ### GitHubCreatePullRequestResultSchema Zod schema for the success shape of `GitHubCreatePullRequestResult`. ```ts import { GitHubCreatePullRequestResultSchema } from '@loopstack/github'; ``` ```ts GitHubCreatePullRequestResultSchema: z.ZodObject< { pullRequest: z.ZodObject< { id: z.ZodNumber; number: z.ZodNumber; title: z.ZodString; htmlUrl: z.ZodString; state: z.ZodString; draft: z.ZodBoolean; }, z.core.$strict >; }, z.core.$strict >; ``` ### GitHubCreateRepoResultSchema Zod schema for the success shape of `GitHubCreateRepoResult`. ```ts import { GitHubCreateRepoResultSchema } from '@loopstack/github'; ``` ```ts GitHubCreateRepoResultSchema: z.ZodObject< { repo: z.ZodObject< { id: z.ZodNumber; fullName: z.ZodString; name: z.ZodString; htmlUrl: z.ZodString; private: z.ZodBoolean; defaultBranch: z.ZodString; }, z.core.$strict >; }, z.core.$strict >; ``` ### GitHubGetAuthenticatedUserResultSchema Zod schema for the success shape of `GitHubGetAuthenticatedUserResult`. ```ts import { GitHubGetAuthenticatedUserResultSchema } from '@loopstack/github'; ``` ```ts GitHubGetAuthenticatedUserResultSchema: z.ZodObject< { user: z.ZodObject< { id: z.ZodNumber; login: z.ZodString; name: z.ZodNullable; email: z.ZodNullable; avatarUrl: z.ZodString; htmlUrl: z.ZodString; bio: z.ZodNullable; publicRepos: z.ZodNumber; followers: z.ZodNumber; following: z.ZodNumber; createdAt: z.ZodString; }, z.core.$strict >; }, z.core.$strict >; ``` ### GitHubGetCommitResultSchema Zod schema for the success shape of `GitHubGetCommitResult`. ```ts import { GitHubGetCommitResultSchema } from '@loopstack/github'; ``` ```ts GitHubGetCommitResultSchema: z.ZodObject< { commit: z.ZodObject< { sha: z.ZodString; message: z.ZodString; author: z.ZodObject< { name: z.ZodString; email: z.ZodString; date: z.ZodString; login: z.ZodNullable; }, z.core.$strict >; committer: z.ZodObject< { name: z.ZodString; date: z.ZodString; }, z.core.$strict >; htmlUrl: z.ZodString; stats: z.ZodObject< { additions: z.ZodNumber; deletions: z.ZodNumber; total: z.ZodNumber; }, z.core.$strict >; files: z.ZodArray< z.ZodObject< { filename: z.ZodString; status: z.ZodString; additions: z.ZodNumber; deletions: z.ZodNumber; changes: z.ZodNumber; }, z.core.$strict > >; }, z.core.$strict >; }, z.core.$strict >; ``` ### GitHubGetFileContentResultSchema Zod schema for the success shape of `GitHubGetFileContentResult`. ```ts import { GitHubGetFileContentResultSchema } from '@loopstack/github'; ``` ```ts GitHubGetFileContentResultSchema: z.ZodObject< { file: z.ZodObject< { name: z.ZodString; path: z.ZodString; sha: z.ZodString; size: z.ZodNumber; type: z.ZodString; content: z.ZodNullable; htmlUrl: z.ZodString; }, z.core.$strict >; }, z.core.$strict >; ``` ### GitHubGetIssueResultSchema Zod schema for the success shape of `GitHubGetIssueResult`. ```ts import { GitHubGetIssueResultSchema } from '@loopstack/github'; ``` ```ts GitHubGetIssueResultSchema: z.ZodObject< { issue: z.ZodObject< { id: z.ZodNumber; number: z.ZodNumber; title: z.ZodString; body: z.ZodNullable; state: z.ZodString; user: z.ZodString; labels: z.ZodArray; assignees: z.ZodArray; milestone: z.ZodNullable; createdAt: z.ZodString; updatedAt: z.ZodString; closedAt: z.ZodNullable; htmlUrl: z.ZodString; comments: z.ZodNumber; }, z.core.$strict >; }, z.core.$strict >; ``` ### GitHubGetPullRequestResultSchema Zod schema for the success shape of `GitHubGetPullRequestResult`. ```ts import { GitHubGetPullRequestResultSchema } from '@loopstack/github'; ``` ```ts GitHubGetPullRequestResultSchema: z.ZodObject< { pullRequest: z.ZodObject< { id: z.ZodNumber; number: z.ZodNumber; title: z.ZodString; body: z.ZodNullable; state: z.ZodString; user: z.ZodString; head: z.ZodString; headSha: z.ZodString; base: z.ZodString; merged: z.ZodBoolean; mergeable: z.ZodNullable; draft: z.ZodBoolean; additions: z.ZodNumber; deletions: z.ZodNumber; changedFiles: z.ZodNumber; createdAt: z.ZodString; updatedAt: z.ZodString; mergedAt: z.ZodNullable; htmlUrl: z.ZodString; comments: z.ZodNumber; reviewComments: z.ZodNumber; }, z.core.$strict >; }, z.core.$strict >; ``` ### GitHubGetRepoResultSchema Zod schema for the success shape of `GitHubGetRepoResult`. ```ts import { GitHubGetRepoResultSchema } from '@loopstack/github'; ``` ```ts GitHubGetRepoResultSchema: z.ZodObject< { repo: z.ZodObject< { id: z.ZodNumber; fullName: z.ZodString; name: z.ZodString; owner: z.ZodString; ownerAvatar: z.ZodString; private: z.ZodBoolean; htmlUrl: z.ZodString; description: z.ZodNullable; language: z.ZodNullable; defaultBranch: z.ZodString; stars: z.ZodNumber; forks: z.ZodNumber; openIssues: z.ZodNumber; createdAt: z.ZodString; updatedAt: z.ZodString; topics: z.ZodArray; license: z.ZodNullable; }, z.core.$strict >; }, z.core.$strict >; ``` ### GitHubGetWorkflowRunResultSchema Zod schema for the success shape of `GitHubGetWorkflowRunResult`. ```ts import { GitHubGetWorkflowRunResultSchema } from '@loopstack/github'; ``` ```ts GitHubGetWorkflowRunResultSchema: z.ZodObject< { run: z.ZodObject< { id: z.ZodNumber; name: z.ZodString; status: z.ZodString; conclusion: z.ZodNullable; headBranch: z.ZodString; headSha: z.ZodString; event: z.ZodString; workflowId: z.ZodNumber; runNumber: z.ZodNumber; runAttempt: z.ZodNumber; createdAt: z.ZodString; updatedAt: z.ZodString; runStartedAt: z.ZodString; htmlUrl: z.ZodString; }, z.core.$strict >; }, z.core.$strict >; ``` ### GitHubListBranchesResultSchema Zod schema for the success shape of `GitHubListBranchesResult`. ```ts import { GitHubListBranchesResultSchema } from '@loopstack/github'; ``` ```ts GitHubListBranchesResultSchema: z.ZodObject< { branches: z.ZodArray< z.ZodObject< { name: z.ZodString; commitSha: z.ZodString; protected: z.ZodBoolean; }, z.core.$strict > >; }, z.core.$strict >; ``` ### GitHubListDirectoryResultSchema Zod schema for the success shape of `GitHubListDirectoryResult`. ```ts import { GitHubListDirectoryResultSchema } from '@loopstack/github'; ``` ```ts GitHubListDirectoryResultSchema: z.ZodObject< { entries: z.ZodArray< z.ZodObject< { name: z.ZodString; path: z.ZodString; sha: z.ZodString; size: z.ZodNumber; type: z.ZodString; htmlUrl: z.ZodString; }, z.core.$strict > >; }, z.core.$strict >; ``` ### GitHubListIssuesResultSchema Zod schema for the success shape of `GitHubListIssuesResult`. ```ts import { GitHubListIssuesResultSchema } from '@loopstack/github'; ``` ```ts GitHubListIssuesResultSchema: z.ZodObject< { issues: z.ZodArray< z.ZodObject< { id: z.ZodNumber; number: z.ZodNumber; title: z.ZodString; state: z.ZodString; user: z.ZodString; labels: z.ZodArray; assignees: z.ZodArray; createdAt: z.ZodString; updatedAt: z.ZodString; htmlUrl: z.ZodString; isPullRequest: z.ZodBoolean; }, z.core.$strict > >; }, z.core.$strict >; ``` ### GitHubListPrReviewsResultSchema Zod schema for the success shape of `GitHubListPrReviewsResult`. ```ts import { GitHubListPrReviewsResultSchema } from '@loopstack/github'; ``` ```ts GitHubListPrReviewsResultSchema: z.ZodObject< { reviews: z.ZodArray< z.ZodObject< { id: z.ZodNumber; user: z.ZodString; body: z.ZodString; state: z.ZodString; submittedAt: z.ZodOptional; htmlUrl: z.ZodString; }, z.core.$strict > >; }, z.core.$strict >; ``` ### GitHubListPullRequestsResultSchema Zod schema for the success shape of `GitHubListPullRequestsResult`. ```ts import { GitHubListPullRequestsResultSchema } from '@loopstack/github'; ``` ```ts GitHubListPullRequestsResultSchema: z.ZodObject< { pullRequests: z.ZodArray< z.ZodObject< { id: z.ZodNumber; number: z.ZodNumber; title: z.ZodString; state: z.ZodString; user: z.ZodString; head: z.ZodString; headSha: z.ZodString; base: z.ZodString; createdAt: z.ZodString; updatedAt: z.ZodString; htmlUrl: z.ZodString; draft: z.ZodBoolean; }, z.core.$strict > >; }, z.core.$strict >; ``` ### GitHubListReposResultSchema Zod schema for the success shape of `GitHubListReposResult`. ```ts import { GitHubListReposResultSchema } from '@loopstack/github'; ``` ```ts GitHubListReposResultSchema: z.ZodObject< { repos: z.ZodArray< z.ZodObject< { id: z.ZodNumber; fullName: z.ZodString; name: z.ZodString; owner: z.ZodString; private: z.ZodBoolean; htmlUrl: z.ZodString; description: z.ZodNullable; language: z.ZodNullable; defaultBranch: z.ZodString; updatedAt: z.ZodString; }, z.core.$strict > >; }, z.core.$strict >; ``` ### GitHubListUserOrgsResultSchema Zod schema for the success shape of `GitHubListUserOrgsResult`. ```ts import { GitHubListUserOrgsResultSchema } from '@loopstack/github'; ``` ```ts GitHubListUserOrgsResultSchema: z.ZodObject< { orgs: z.ZodArray< z.ZodObject< { id: z.ZodNumber; login: z.ZodString; description: z.ZodNullable; avatarUrl: z.ZodString; }, z.core.$strict > >; }, z.core.$strict >; ``` ### GitHubListWorkflowRunsResultSchema Zod schema for the success shape of `GitHubListWorkflowRunsResult`. ```ts import { GitHubListWorkflowRunsResultSchema } from '@loopstack/github'; ``` ```ts GitHubListWorkflowRunsResultSchema: z.ZodObject< { totalCount: z.ZodNumber; runs: z.ZodArray< z.ZodObject< { id: z.ZodNumber; name: z.ZodString; status: z.ZodString; conclusion: z.ZodNullable; headBranch: z.ZodString; headSha: z.ZodString; event: z.ZodString; createdAt: z.ZodString; updatedAt: z.ZodString; htmlUrl: z.ZodString; }, z.core.$strict > >; }, z.core.$strict >; ``` ### GitHubMergePullRequestResultSchema Zod schema for the success shape of `GitHubMergePullRequestResult`. ```ts import { GitHubMergePullRequestResultSchema } from '@loopstack/github'; ``` ```ts GitHubMergePullRequestResultSchema: z.ZodObject< { merge: z.ZodObject< { sha: z.ZodString; merged: z.ZodBoolean; message: z.ZodString; }, z.core.$strict >; }, z.core.$strict >; ``` ### GitHubSearchCodeResultSchema Zod schema for the success shape of `GitHubSearchCodeResult`. ```ts import { GitHubSearchCodeResultSchema } from '@loopstack/github'; ``` ```ts GitHubSearchCodeResultSchema: z.ZodObject< { totalCount: z.ZodNumber; results: z.ZodArray< z.ZodObject< { name: z.ZodString; path: z.ZodString; sha: z.ZodString; htmlUrl: z.ZodString; repository: z.ZodString; }, z.core.$strict > >; }, z.core.$strict >; ``` ### GitHubSearchIssuesResultSchema Zod schema for the success shape of `GitHubSearchIssuesResult`. ```ts import { GitHubSearchIssuesResultSchema } from '@loopstack/github'; ``` ```ts GitHubSearchIssuesResultSchema: z.ZodObject< { totalCount: z.ZodNumber; results: z.ZodArray< z.ZodObject< { id: z.ZodNumber; number: z.ZodNumber; title: z.ZodString; state: z.ZodString; user: z.ZodString; htmlUrl: z.ZodString; createdAt: z.ZodString; updatedAt: z.ZodString; isPullRequest: z.ZodBoolean; }, z.core.$strict > >; }, z.core.$strict >; ``` ### GitHubSearchReposResultSchema Zod schema for the success shape of `GitHubSearchReposResult`. ```ts import { GitHubSearchReposResultSchema } from '@loopstack/github'; ``` ```ts GitHubSearchReposResultSchema: z.ZodObject< { totalCount: z.ZodNumber; results: z.ZodArray< z.ZodObject< { id: z.ZodNumber; fullName: z.ZodString; description: z.ZodNullable; htmlUrl: z.ZodString; language: z.ZodNullable; stars: z.ZodNumber; forks: z.ZodNumber; updatedAt: z.ZodString; }, z.core.$strict > >; }, z.core.$strict >; ``` ### GitHubTriggerWorkflowResultSchema Zod schema for the success shape of `GitHubTriggerWorkflowResult`. ```ts import { GitHubTriggerWorkflowResultSchema } from '@loopstack/github'; ``` ```ts GitHubTriggerWorkflowResultSchema: z.ZodObject< { triggered: z.ZodBoolean; message: z.ZodString; }, z.core.$strict >; ``` --- > Source: https://loopstack.ai/llms/reference/api/google-workspace.md --- title: 'API: @loopstack/google-workspace' description: 'Public API reference for @loopstack/google-workspace' includeInLlmsFullTxt: false --- # API: @loopstack/google-workspace ## Classes ### GmailGetMessageTool Tool that gets the full content of a single Gmail message. Takes a `messageId` and `format`, and returns headers, decoded body text, snippet, label ids, and attachment metadata, or `{ error: 'unauthorized' }` when no valid Google token is available. ```ts import { GmailGetMessageTool } from '@loopstack/google-workspace'; ``` **Provided by:** `GoogleWorkspaceModule` ```ts export class GmailGetMessageTool extends BaseTool { protected handle(args: GmailGetMessageArgs, ctx: RunContext): Promise>; } ``` ### GmailReplyToMessageTool Tool that replies to an existing Gmail message in-thread. Fetches the original message to set proper reply headers, supports `replyAll`, and returns the sent reply's id, thread id, and label ids, or `{ error: 'unauthorized' }` when no valid Google token is available. ```ts import { GmailReplyToMessageTool } from '@loopstack/google-workspace'; ``` **Provided by:** `GoogleWorkspaceModule` ```ts export class GmailReplyToMessageTool extends BaseTool { protected handle(args: GmailReplyToMessageArgs, ctx: RunContext): Promise>; } ``` ### GmailSearchMessagesTool Tool that searches Gmail messages using Gmail query syntax. Takes a `query`, optional `labelIds`, and pagination, and returns message summaries with headers and snippets plus a `nextPageToken`, or `{ error: 'unauthorized' }` when no valid Google token is available. ```ts import { GmailSearchMessagesTool } from '@loopstack/google-workspace'; ``` **Provided by:** `GoogleWorkspaceModule` ```ts export class GmailSearchMessagesTool extends BaseTool { protected handle(args: GmailSearchMessagesArgs, ctx: RunContext): Promise>; } ``` ### GmailSendMessageTool Tool that sends a new email via Gmail. Takes `to`/`cc`/`bcc` recipients, a subject, and plain-text (and optional HTML) body, and returns the sent message's id, thread id, and label ids, or `{ error: 'unauthorized' }` when no valid Google token is available. ```ts import { GmailSendMessageTool } from '@loopstack/google-workspace'; ``` **Provided by:** `GoogleWorkspaceModule` ```ts export class GmailSendMessageTool extends BaseTool { protected handle(args: GmailSendMessageArgs, ctx: RunContext): Promise>; } ``` ### GoogleCalendarCreateEventTool Tool that creates a new event on a Google Calendar. Takes a summary, start/end times, and optional description, location, attendees, and reminders, and returns the created event's id and link, or `{ error: 'unauthorized' }` when no valid Google token is available. ```ts import { GoogleCalendarCreateEventTool } from '@loopstack/google-workspace'; ``` **Provided by:** `GoogleWorkspaceModule` ```ts export class GoogleCalendarCreateEventTool extends BaseTool< GoogleCalendarCreateEventArgs, object, GoogleCalendarCreateEventResult > { protected handle( args: GoogleCalendarCreateEventArgs, ctx: RunContext, ): Promise>; } ``` ### GoogleCalendarFetchEventsTool Tool that fetches events from a Google Calendar within a time range. Takes a `timeMin`/`timeMax` window (and optional `calendarId`, `query`, `maxResults`) and returns matching events with start/end, attendees, and links, or `{ error: 'unauthorized' }` when no valid Google token is available. ```ts import { GoogleCalendarFetchEventsTool } from '@loopstack/google-workspace'; ``` **Provided by:** `GoogleWorkspaceModule` ```ts export class GoogleCalendarFetchEventsTool extends BaseTool< GoogleCalendarFetchEventsArgs, object, GoogleCalendarFetchEventsResult > { protected handle( args: GoogleCalendarFetchEventsArgs, ctx: RunContext, ): Promise>; } ``` ### GoogleCalendarListCalendarsTool Tool that lists all Google Calendars the authenticated user has access to. Returns each calendar's id, summary, time zone, and primary flag, or `{ error: 'unauthorized' }` when no valid Google token is available. ```ts import { GoogleCalendarListCalendarsTool } from '@loopstack/google-workspace'; ``` **Provided by:** `GoogleWorkspaceModule` ```ts export class GoogleCalendarListCalendarsTool extends BaseTool< GoogleCalendarListCalendarsArgs, object, GoogleCalendarListCalendarsResult > { protected handle( args: GoogleCalendarListCalendarsArgs, ctx: RunContext, ): Promise>; } ``` ### GoogleDriveDownloadFileTool Tool that downloads or exports a file from Google Drive. Takes a `fileId` and optional `exportMimeType`, automatically handles Google Docs/Sheets/Slides export, and returns text or base64-encoded content with its mime type, or `{ error: 'unauthorized' }` when no valid Google token is available. `exportMimeType` applies to Google Docs/Sheets/Slides only; other files are returned as stored, with their own mime type. ```ts import { GoogleDriveDownloadFileTool } from '@loopstack/google-workspace'; ``` **Provided by:** `GoogleWorkspaceModule` ```ts export class GoogleDriveDownloadFileTool extends BaseTool< GoogleDriveDownloadFileArgs, object, GoogleDriveDownloadFileResult > { protected handle( args: GoogleDriveDownloadFileArgs, ctx: RunContext, ): Promise>; } ``` ### GoogleDriveGetFileMetadataTool Tool that gets detailed metadata for a single Google Drive file. Takes a `fileId` and returns name, mime type, size, timestamps, owners, parents, and sharing state, or `{ error: 'unauthorized' }` when no valid Google token is available. ```ts import { GoogleDriveGetFileMetadataTool } from '@loopstack/google-workspace'; ``` **Provided by:** `GoogleWorkspaceModule` ```ts export class GoogleDriveGetFileMetadataTool extends BaseTool< GoogleDriveGetFileMetadataArgs, object, GoogleDriveGetFileMetadataResult > { protected handle( args: GoogleDriveGetFileMetadataArgs, ctx: RunContext, ): Promise>; } ``` ### GoogleDriveListFilesTool Tool that lists and searches files in Google Drive. Supports Drive query syntax, folder browsing, ordering, and pagination, and returns file metadata plus a `nextPageToken`, or `{ error: 'unauthorized' }` when no valid Google token is available. ```ts import { GoogleDriveListFilesTool } from '@loopstack/google-workspace'; ``` **Provided by:** `GoogleWorkspaceModule` ```ts export class GoogleDriveListFilesTool extends BaseTool { protected handle(args: GoogleDriveListFilesArgs, ctx: RunContext): Promise>; } ``` ### GoogleDriveUploadFileTool Tool that uploads a new file to Google Drive using multipart upload. Takes a name, content, mime type, and optional folder and description, and returns the created file's id, name, and link, or `{ error: 'unauthorized' }` when no valid Google token is available. ```ts import { GoogleDriveUploadFileTool } from '@loopstack/google-workspace'; ``` **Provided by:** `GoogleWorkspaceModule` ```ts export class GoogleDriveUploadFileTool extends BaseTool< GoogleDriveUploadFileArgs, object, GoogleDriveUploadFileResult > { protected handle( args: GoogleDriveUploadFileArgs, ctx: RunContext, ): Promise>; } ``` ### GoogleWorkspaceModule NestJS module that provides the Google OAuth 2.0 provider and 11 Google Workspace tools (Calendar, Gmail, and Drive) for use in workflows and agents. Registration: - `GoogleWorkspaceModule` — a bare import is enough. It imports `OAuthModule` internally and registers `GoogleWorkspaceOAuthProvider` (provider id `'google'`) plus all Calendar, Gmail, and Drive tools as providers, so they are resolvable by DI with no static configuration method. Requires: Google OAuth client credentials in the environment — `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are mandatory (optionally `GOOGLE_OAUTH_REDIRECT_URI`, defaults to `/oauth/callback`). Without them the OAuth flow cannot authenticate and tools return `{ error: 'unauthorized' }`. ```ts import { GoogleWorkspaceModule } from '@loopstack/google-workspace'; ``` ```ts export class GoogleWorkspaceModule {} ``` ## Type Aliases ### GmailGetMessageArgs Args for `GmailGetMessageTool`. ```ts import { GmailGetMessageArgs } from '@loopstack/google-workspace'; ``` ```ts export type GmailGetMessageArgs = z.infer; ``` ### GmailGetMessageResult Result for `GmailGetMessageTool`. ```ts import { GmailGetMessageResult } from '@loopstack/google-workspace'; ``` ```ts export type GmailGetMessageResult = | { id: string; threadId: string; from: string; to: string; cc: string; subject: string; date: string; body: string; snippet: string; labelIds: string[]; attachments: Array<{ attachmentId: string; filename: string; mimeType: string; size: number; }>; } | { error: 'unauthorized'; message: string; } | { error: 'api_error'; message: string; }; ``` ### GmailReplyToMessageArgs Args for `GmailReplyToMessageTool`. ```ts import { GmailReplyToMessageArgs } from '@loopstack/google-workspace'; ``` ```ts export type GmailReplyToMessageArgs = z.infer; ``` ### GmailReplyToMessageResult Result for `GmailReplyToMessageTool`. ```ts import { GmailReplyToMessageResult } from '@loopstack/google-workspace'; ``` ```ts export type GmailReplyToMessageResult = | { id: string; threadId: string; labelIds: string[]; } | { error: 'unauthorized'; message: string; } | { error: 'api_error'; message: string; }; ``` ### GmailSearchMessagesArgs Args for `GmailSearchMessagesTool`. ```ts import { GmailSearchMessagesArgs } from '@loopstack/google-workspace'; ``` ```ts export type GmailSearchMessagesArgs = z.infer; ``` ### GmailSearchMessagesResult Result for `GmailSearchMessagesTool`. ```ts import { GmailSearchMessagesResult } from '@loopstack/google-workspace'; ``` ```ts export type GmailSearchMessagesResult = | { messages: Array<{ id: string; threadId: string; snippet: string; from: string; to: string; subject: string; date: string; }>; nextPageToken?: string; } | { error: 'unauthorized'; message: string; } | { error: 'api_error'; message: string; }; ``` ### GmailSendMessageArgs Args for `GmailSendMessageTool`. ```ts import { GmailSendMessageArgs } from '@loopstack/google-workspace'; ``` ```ts export type GmailSendMessageArgs = z.infer; ``` ### GmailSendMessageResult Result for `GmailSendMessageTool`. ```ts import { GmailSendMessageResult } from '@loopstack/google-workspace'; ``` ```ts export type GmailSendMessageResult = | { id: string; threadId: string; labelIds: string[]; } | { error: 'unauthorized'; message: string; } | { error: 'api_error'; message: string; }; ``` ### GoogleCalendarCreateEventArgs Args for `GoogleCalendarCreateEventTool`. ```ts import { GoogleCalendarCreateEventArgs } from '@loopstack/google-workspace'; ``` ```ts export type GoogleCalendarCreateEventArgs = z.infer; ``` ### GoogleCalendarCreateEventResult Result for `GoogleCalendarCreateEventTool`. ```ts import { GoogleCalendarCreateEventResult } from '@loopstack/google-workspace'; ``` ```ts export type GoogleCalendarCreateEventResult = | { event: { id: string; summary: string; start: string | undefined; end: string | undefined; htmlLink: string; }; } | { error: 'unauthorized'; message: string; } | { error: 'api_error'; message: string; }; ``` ### GoogleCalendarFetchEventsArgs Args for `GoogleCalendarFetchEventsTool`. ```ts import { GoogleCalendarFetchEventsArgs } from '@loopstack/google-workspace'; ``` ```ts export type GoogleCalendarFetchEventsArgs = z.infer; ``` ### GoogleCalendarFetchEventsResult Result for `GoogleCalendarFetchEventsTool`. ```ts import { GoogleCalendarFetchEventsResult } from '@loopstack/google-workspace'; ``` ```ts export type GoogleCalendarFetchEventsResult = { events?: Array<{ id: string; summary?: string; description?: string; start: string | undefined; end: string | undefined; location?: string; attendees?: Array<{ email: string; responseStatus?: string; }>; htmlLink?: string; }>; error?: string; message?: string; }; ``` ### GoogleCalendarListCalendarsArgs Args for `GoogleCalendarListCalendarsTool`. ```ts import { GoogleCalendarListCalendarsArgs } from '@loopstack/google-workspace'; ``` ```ts export type GoogleCalendarListCalendarsArgs = z.infer; ``` ### GoogleCalendarListCalendarsResult Result for `GoogleCalendarListCalendarsTool`. ```ts import { GoogleCalendarListCalendarsResult } from '@loopstack/google-workspace'; ``` ```ts export type GoogleCalendarListCalendarsResult = | { calendars: Array<{ id: string; summary: string; description?: string; primary: boolean; timeZone?: string; }>; } | { error: 'unauthorized'; message: string; } | { error: 'api_error'; message: string; }; ``` ### GoogleDriveDownloadFileArgs Args for `GoogleDriveDownloadFileTool`. ```ts import { GoogleDriveDownloadFileArgs } from '@loopstack/google-workspace'; ``` ```ts export type GoogleDriveDownloadFileArgs = z.infer; ``` ### GoogleDriveDownloadFileResult Result for `GoogleDriveDownloadFileTool`. ```ts import { GoogleDriveDownloadFileResult } from '@loopstack/google-workspace'; ``` ```ts export type GoogleDriveDownloadFileResult = | { content: string; mimeType: string; } | { content: string; mimeType: string; encoding: 'base64'; } | { error: 'unauthorized'; message: string; } | { error: 'api_error'; message: string; }; ``` ### GoogleDriveGetFileMetadataArgs Args for `GoogleDriveGetFileMetadataTool`. ```ts import { GoogleDriveGetFileMetadataArgs } from '@loopstack/google-workspace'; ``` ```ts export type GoogleDriveGetFileMetadataArgs = z.infer; ``` ### GoogleDriveGetFileMetadataResult Result for `GoogleDriveGetFileMetadataTool`. ```ts import { GoogleDriveGetFileMetadataResult } from '@loopstack/google-workspace'; ``` ```ts export type GoogleDriveGetFileMetadataResult = | { id: string; name: string; mimeType: string; size?: string; modifiedTime: string; createdTime: string; owners?: Array<{ displayName: string; email: string; }>; webViewLink?: string; parents?: string[]; description?: string; shared?: boolean; } | { error: 'unauthorized'; message: string; } | { error: 'api_error'; message: string; }; ``` ### GoogleDriveListFilesArgs Args for `GoogleDriveListFilesTool`. ```ts import { GoogleDriveListFilesArgs } from '@loopstack/google-workspace'; ``` ```ts export type GoogleDriveListFilesArgs = z.infer; ``` ### GoogleDriveListFilesResult Result for `GoogleDriveListFilesTool`. ```ts import { GoogleDriveListFilesResult } from '@loopstack/google-workspace'; ``` ```ts export type GoogleDriveListFilesResult = | { files: Array<{ id: string; name: string; mimeType: string; size?: string; modifiedTime: string; createdTime: string; owners?: Array<{ displayName: string; email: string; }>; webViewLink?: string; }>; nextPageToken?: string; } | { error: 'unauthorized'; message: string; } | { error: 'api_error'; message: string; }; ``` ### GoogleDriveUploadFileArgs Args for `GoogleDriveUploadFileTool`. ```ts import { GoogleDriveUploadFileArgs } from '@loopstack/google-workspace'; ``` ```ts export type GoogleDriveUploadFileArgs = z.infer; ``` ### GoogleDriveUploadFileResult Result for `GoogleDriveUploadFileTool`. ```ts import { GoogleDriveUploadFileResult } from '@loopstack/google-workspace'; ``` ```ts export type GoogleDriveUploadFileResult = | { id: string; name: string; mimeType: string; webViewLink?: string; } | { error: 'unauthorized'; message: string; } | { error: 'api_error'; message: string; }; ``` ## Variables ### GmailGetMessageResultSchema Zod schema for the success shape of `GmailGetMessageResult` — the message content and attachment metadata. ```ts import { GmailGetMessageResultSchema } from '@loopstack/google-workspace'; ``` ```ts GmailGetMessageResultSchema: z.ZodObject< { id: z.ZodString; threadId: z.ZodString; from: z.ZodString; to: z.ZodString; cc: z.ZodString; subject: z.ZodString; date: z.ZodString; body: z.ZodString; snippet: z.ZodString; labelIds: z.ZodArray; attachments: z.ZodArray< z.ZodObject< { attachmentId: z.ZodString; filename: z.ZodString; mimeType: z.ZodString; size: z.ZodNumber; }, z.core.$strict > >; }, z.core.$strict >; ``` ### GmailReplyToMessageResultSchema Zod schema for the success shape of `GmailReplyToMessageResult` — the sent reply. ```ts import { GmailReplyToMessageResultSchema } from '@loopstack/google-workspace'; ``` ```ts GmailReplyToMessageResultSchema: z.ZodObject< { id: z.ZodString; threadId: z.ZodString; labelIds: z.ZodArray; }, z.core.$strict >; ``` ### GmailSearchMessagesResultSchema Zod schema for the success shape of `GmailSearchMessagesResult` — the message summaries and pagination token. ```ts import { GmailSearchMessagesResultSchema } from '@loopstack/google-workspace'; ``` ```ts GmailSearchMessagesResultSchema: z.ZodObject< { messages: z.ZodArray< z.ZodObject< { id: z.ZodString; threadId: z.ZodString; snippet: z.ZodString; from: z.ZodString; to: z.ZodString; subject: z.ZodString; date: z.ZodString; }, z.core.$strict > >; nextPageToken: z.ZodOptional; }, z.core.$strict >; ``` ### GmailSendMessageResultSchema Zod schema for the success shape of `GmailSendMessageResult` — the sent message. ```ts import { GmailSendMessageResultSchema } from '@loopstack/google-workspace'; ``` ```ts GmailSendMessageResultSchema: z.ZodObject< { id: z.ZodString; threadId: z.ZodString; labelIds: z.ZodArray; }, z.core.$strict >; ``` ### GoogleCalendarCreateEventResultSchema Zod schema for the success shape of `GoogleCalendarCreateEventResult` — the created event. ```ts import { GoogleCalendarCreateEventResultSchema } from '@loopstack/google-workspace'; ``` ```ts GoogleCalendarCreateEventResultSchema: z.ZodObject< { event: z.ZodObject< { id: z.ZodString; summary: z.ZodString; start: z.ZodOptional; end: z.ZodOptional; htmlLink: z.ZodString; }, z.core.$strict >; }, z.core.$strict >; ``` ### GoogleCalendarFetchEventsResultSchema Zod schema for the success shape of `GoogleCalendarFetchEventsResult` — the fetched events. ```ts import { GoogleCalendarFetchEventsResultSchema } from '@loopstack/google-workspace'; ``` ```ts GoogleCalendarFetchEventsResultSchema: z.ZodObject< { events: z.ZodArray< z.ZodObject< { id: z.ZodString; summary: z.ZodOptional; description: z.ZodOptional; start: z.ZodOptional; end: z.ZodOptional; location: z.ZodOptional; attendees: z.ZodOptional< z.ZodArray< z.ZodObject< { email: z.ZodString; responseStatus: z.ZodOptional; }, z.core.$strict > > >; htmlLink: z.ZodOptional; }, z.core.$strict > >; }, z.core.$strict >; ``` ### GoogleCalendarListCalendarsResultSchema Zod schema for the success shape of `GoogleCalendarListCalendarsResult` — the calendar list. ```ts import { GoogleCalendarListCalendarsResultSchema } from '@loopstack/google-workspace'; ``` ```ts GoogleCalendarListCalendarsResultSchema: z.ZodObject< { calendars: z.ZodArray< z.ZodObject< { id: z.ZodString; summary: z.ZodString; description: z.ZodOptional; primary: z.ZodBoolean; timeZone: z.ZodOptional; }, z.core.$strict > >; }, z.core.$strict >; ``` ### GoogleDriveDownloadFileResultSchema Zod schema for the success shape of `GoogleDriveDownloadFileResult` — the file content, base64-encoded when binary. ```ts import { GoogleDriveDownloadFileResultSchema } from '@loopstack/google-workspace'; ``` ```ts GoogleDriveDownloadFileResultSchema: z.ZodObject< { content: z.ZodString; mimeType: z.ZodString; encoding: z.ZodOptional>; }, z.core.$strict >; ``` ### GoogleDriveGetFileMetadataResultSchema Zod schema for the success shape of `GoogleDriveGetFileMetadataResult` — the file metadata. ```ts import { GoogleDriveGetFileMetadataResultSchema } from '@loopstack/google-workspace'; ``` ```ts GoogleDriveGetFileMetadataResultSchema: z.ZodObject< { id: z.ZodString; name: z.ZodString; mimeType: z.ZodString; size: z.ZodOptional; modifiedTime: z.ZodString; createdTime: z.ZodString; owners: z.ZodOptional< z.ZodArray< z.ZodObject< { displayName: z.ZodString; email: z.ZodString; }, z.core.$strict > > >; webViewLink: z.ZodOptional; parents: z.ZodOptional>; description: z.ZodOptional; shared: z.ZodOptional; }, z.core.$strict >; ``` ### GoogleDriveListFilesResultSchema Zod schema for the success shape of `GoogleDriveListFilesResult` — the file list and pagination token. ```ts import { GoogleDriveListFilesResultSchema } from '@loopstack/google-workspace'; ``` ```ts GoogleDriveListFilesResultSchema: z.ZodObject< { files: z.ZodArray< z.ZodObject< { id: z.ZodString; name: z.ZodString; mimeType: z.ZodString; size: z.ZodOptional; modifiedTime: z.ZodString; createdTime: z.ZodString; owners: z.ZodOptional< z.ZodArray< z.ZodObject< { displayName: z.ZodString; email: z.ZodString; }, z.core.$strict > > >; webViewLink: z.ZodOptional; }, z.core.$strict > >; nextPageToken: z.ZodOptional; }, z.core.$strict >; ``` ### GoogleDriveUploadFileResultSchema Zod schema for the success shape of `GoogleDriveUploadFileResult` — the created file. ```ts import { GoogleDriveUploadFileResultSchema } from '@loopstack/google-workspace'; ``` ```ts GoogleDriveUploadFileResultSchema: z.ZodObject< { id: z.ZodString; name: z.ZodString; mimeType: z.ZodString; webViewLink: z.ZodOptional; }, z.core.$strict >; ``` --- > Source: https://loopstack.ai/llms/reference/api/hitl.md --- title: 'API: @loopstack/hitl' description: 'Public API reference for @loopstack/hitl' includeInLlmsFullTxt: false --- # API: @loopstack/hitl ## Classes ### AskClarificationTool Tool that asks the user a clarification question and waits for their answer. Runs the `AskUserWorkflow` as an inline sub-workflow in `text`, `options`, or `confirm` mode, pausing the agent loop until the user responds. Returns an `AskClarificationResult`. ```ts import { AskClarificationTool } from '@loopstack/hitl'; ``` **Provided by:** `HitlModule` ```ts export class AskClarificationTool extends BaseTool { constructor(askUserWorkflow: AskUserWorkflow); protected handle( args: AskClarificationInput, ctx: RunContext, options?: ToolCallOptions, ): Promise>; complete(result: Record): Promise>; } ``` ### AskForApprovalTool Tool that presents a concept to the user for approval and waits for their decision. Runs the `ConfirmUserWorkflow` as an inline sub-workflow, rendering the `concept` markdown with a confirm button and pausing the agent loop until the user approves or denies. Returns an `AskForApprovalResult`. ```ts import { AskForApprovalTool } from '@loopstack/hitl'; ``` **Provided by:** `HitlModule` ```ts export class AskForApprovalTool extends BaseTool { constructor(confirmUserWorkflow: ConfirmUserWorkflow); protected handle( args: AskForApprovalInput, ctx: RunContext, options?: ToolCallOptions, ): Promise>; complete(result: Record): Promise>; } ``` ### AskUserConfirmDocument Document that presents a yes/no question to the user and captures their answer. ```ts import { AskUserConfirmDocument } from '@loopstack/hitl'; ``` ```ts export class AskUserConfirmDocument { question: string; answer?: string; } ``` ### AskUserDocument Document that presents a free-text question to the user and captures their answer. ```ts import { AskUserDocument } from '@loopstack/hitl'; ``` ```ts export class AskUserDocument { question: string; answer?: string; } ``` ### AskUserOptionsDocument Document that presents a question with a list of options for the user to pick from, optionally allowing a custom answer. ```ts import { AskUserOptionsDocument } from '@loopstack/hitl'; ``` ```ts export class AskUserOptionsDocument { question: string; options: string[]; allowCustomAnswer?: boolean; answer?: string; } ``` ### AskUserWorkflow Workflow that presents a question to the user and waits for their answer. Takes a `question` plus an optional `mode` of `text` (free-text, the default), `options` (pick from the supplied `options`, optionally allowing a custom answer), or `confirm` (yes/no). Renders the matching document, blocks on the user's input, and publishes the result as `{ answer }`. ```ts import { AskUserWorkflow } from '@loopstack/hitl'; ``` **Provided by:** `HitlModule` ```ts export class AskUserWorkflow extends BaseWorkflow { start(state: AskUserState, ctx: RunContext): void; showQuestionOptions(state: AskUserState): Promise; showQuestionConfirm(state: AskUserState): Promise; showQuestionText(state: AskUserState): Promise; userAnswered( state: AskUserState, input: TransitionInput<{ answer: string; }>, ): Promise; } ``` ### ConfirmUserDocument Document that presents markdown content to the user for an approve/deny decision. ```ts import { ConfirmUserDocument } from '@loopstack/hitl'; ``` ```ts export class ConfirmUserDocument { markdown: string; } ``` ### ConfirmUserWorkflow Workflow that presents markdown content to the user and waits for an approve/deny decision. Renders the `markdown` argument as a confirmation document, then blocks until the user responds. Publishes the result as `{ confirmed, markdown }`, where `confirmed` is `true` when approved and `false` when denied. ```ts import { ConfirmUserWorkflow } from '@loopstack/hitl'; ``` **Provided by:** `HitlModule` ```ts export class ConfirmUserWorkflow extends BaseWorkflow { showContent(state: ConfirmUserState, ctx: RunContext): Promise; userConfirmed(state: ConfirmUserState): void; userDenied(state: ConfirmUserState): void; } ``` ### HitlModule NestJS module that provides human-in-the-loop workflows and tools — the `AskUserWorkflow` and `ConfirmUserWorkflow` sub-workflows plus the `AskClarificationTool` and `AskForApprovalTool` — letting agents pause to gather user input or approval. Registration: - `HitlModule` (bare import) — registers and exports the workflows and tools. There is no `forRoot` / `forFeature`; a plain import is all that is needed. Requires: nothing beyond importing the module. ```ts import { HitlModule } from '@loopstack/hitl'; ``` ```ts export class HitlModule {} ``` ## Type Aliases ### AskUserArgs Args for `AskUserWorkflow` (passed to `run()`). Holds `question`, optional `mode`, `options`, and `allowCustomAnswer`. ```ts import { AskUserArgs } from '@loopstack/hitl'; ``` ```ts export type AskUserArgs = z.infer; ``` ### ConfirmUserArgs Args for `ConfirmUserWorkflow` (passed to `run()`). Holds the `markdown` content presented for approval. ```ts import { ConfirmUserArgs } from '@loopstack/hitl'; ``` ```ts export type ConfirmUserArgs = z.infer; ``` ## Variables ### AskUserAnswerSchema Zod schema for the answer `AskUserWorkflow` waits on (the user's reply). ```ts import { AskUserAnswerSchema } from '@loopstack/hitl'; ``` ```ts AskUserAnswerSchema: z.ZodObject< { answer: z.ZodString; }, z.core.$strip >; ``` ### AskUserArgsSchema Zod schema for `AskUserWorkflow` args (what callers pass to `run()`). ```ts import { AskUserArgsSchema } from '@loopstack/hitl'; ``` ```ts AskUserArgsSchema: z.ZodObject< { question: z.ZodString; mode: z.ZodOptional< z.ZodEnum<{ options: 'options'; text: 'text'; confirm: 'confirm'; }> >; options: z.ZodOptional>; allowCustomAnswer: z.ZodOptional; }, z.core.$strip >; ``` ### ConfirmUserArgsSchema Zod schema for `ConfirmUserWorkflow` args (what callers pass to `run()`). ```ts import { ConfirmUserArgsSchema } from '@loopstack/hitl'; ``` ```ts ConfirmUserArgsSchema: z.ZodObject< { markdown: z.ZodString; }, z.core.$strip >; ``` --- > Source: https://loopstack.ai/llms/reference/api/llm-provider.md --- title: 'API: @loopstack/llm-provider' description: 'Public API reference for @loopstack/llm-provider' includeInLlmsFullTxt: false --- # API: @loopstack/llm-provider ## Classes ### LlmContextDocument Document that represents hidden LLM conversation context (never shown in Studio). Persisted server-side and included by LLM providers when building conversation history (tagged `'message'`), but marked `internal: true` so it is excluded from Studio's document responses and never renders as a chat bubble. Its `role` is narrowed to `'user' | 'assistant'`. Use it to seed the model with system context, prior steps, or workflow background the end user should not see. ```ts import { LlmContextDocument } from '@loopstack/llm-provider'; ``` ```ts export class LlmContextDocument extends MessageDocument { role: 'user' | 'assistant'; } ``` ### LlmDelegateToolCallsTool Tool that executes the tool calls contained in an LLM response. Extracts tool-use blocks from the normalized `message`, resolves them via the ToolRegistry, and runs them through `LlmDelegateService `, scheduling async completions against the provided `callback.transition`. Only names listed in `tools` — the tools the LLM was offered — are executed; any other call becomes an error tool result. Returns an `LlmDelegateResult` summarizing completed, pending, and errored tool calls, and saves the results as an `LlmMessageDocument ` unless `config.save` is `false`. ```ts import { LlmDelegateToolCallsTool } from '@loopstack/llm-provider'; ``` **Provided by:** `LlmProviderModule` ```ts export class LlmDelegateToolCallsTool extends BaseTool< LlmDelegateToolCallsToolArgs, LlmDelegateToolCallsConfig, LlmDelegateResult > { protected handle( args: LlmDelegateToolCallsToolArgs, _ctx: RunContext, options?: ToolCallOptions, ): Promise>; } ``` ### LlmGenerateObjectTool Tool that generates a structured object conforming to a Zod/JSON schema via the configured LLM provider. Takes a `prompt` or `messages` plus an `outputSchema` (a Zod schema converted to JSON Schema) and resolves provider, model, and system prompt from `options.config`. Returns an `LlmGenerateObjectResult` whose `data` matches the schema, with usage in `LlmResultMeta`. ```ts import { LlmGenerateObjectTool } from '@loopstack/llm-provider'; ``` **Provided by:** `LlmProviderModule` ```ts export class LlmGenerateObjectTool extends BaseTool< LlmGenerateObjectArgs, LlmGenerateObjectConfig, LlmGenerateObjectResult, LlmResultMeta > { protected handle( args: LlmGenerateObjectArgs, ctx: RunContext, options?: ToolCallOptions, ): Promise>; } ``` ### LlmGenerateTextTool Tool that generates text with the configured LLM provider. Accepts a `prompt` or a `messages` array and resolves provider, model, system prompt, and tool names from `options.config`. Resolved tool names are turned into provider tool definitions, and output is streamed to the client when streaming is available. Returns an `LlmGenerateTextResult` with provider/model usage in `LlmResultMeta`. ```ts import { LlmGenerateTextTool } from '@loopstack/llm-provider'; ``` **Provided by:** `LlmProviderModule` ```ts export class LlmGenerateTextTool extends BaseTool< LlmGenerateTextArgs, LlmGenerateTextConfig, LlmGenerateTextResult, LlmResultMeta > { protected handle( args: LlmGenerateTextArgs, ctx: RunContext, options?: ToolCallOptions, ): Promise>; } ``` ### LlmMessageDocument Document that renders an LLM chat message in Studio. Extends `MessageDocument` with a narrowed `role` of `'user' | 'assistant'`, an optional message `id`, structured `blocks` (LLM content blocks), and a `stopReason`. Tagged `'message'` so it participates in conversation history, and rendered via the `llm-message.document.yaml` widget. ```ts import { LlmMessageDocument } from '@loopstack/llm-provider'; ``` ```ts export class LlmMessageDocument extends MessageDocument { role: 'user' | 'assistant'; id?: string; blocks?: LlmContentBlock[]; stopReason?: LlmStopReason; meta?: UIMessageMeta; } ``` ### LlmProviderModule NestJS module that provides the LLM tools (`LlmGenerateTextTool`, `LlmGenerateObjectTool`, `LlmDelegateToolCallsTool`, `LlmUpdateToolResultTool`) and the provider registry, configured with provider/model defaults. Registration: - `LlmProviderModule` (bare import) — registers the global root with the default (empty) config; pair it with a provider module and set provider/model per call. - `LlmProviderModule.forRoot(config)` — sets the app-wide default `LlmModuleConfig` (default provider/model). Import once at the root. - `LlmProviderModule.forFeature(config)` — overrides the config for one module's tools without re-registering the global root. Use for a feature-scoped default. Requires: a registered provider module (e.g. `ClaudeModule` / `OpenAiModule`) imported alongside it — this module holds the registry, the provider modules populate it. ```ts import { LlmProviderModule } from '@loopstack/llm-provider'; ``` ```ts export class LlmProviderModule { static forRoot(config: LlmModuleConfig): DynamicModule; static forFeature(config: LlmModuleConfig): DynamicModule; } ``` ### LlmUpdateToolResultTool Tool that records an async tool completion and updates a pending delegate result. Handles the callback fired when a delegated tool finishes: it merges `completedTool` into the supplied `delegateResult` via `LlmDelegateService ` and returns the updated `LlmDelegateResult`. Once all tool calls complete, results are saved as an `LlmMessageDocument ` unless `config.save` is `false`. ```ts import { LlmUpdateToolResultTool } from '@loopstack/llm-provider'; ``` **Provided by:** `LlmProviderModule` ```ts export class LlmUpdateToolResultTool extends BaseTool< LlmUpdateToolResultToolArgs, LlmUpdateToolResultConfig, LlmDelegateResult > { protected handle( args: LlmUpdateToolResultToolArgs, _ctx: RunContext, options?: ToolCallOptions, ): Promise>; } ``` ## Interfaces ### LlmDelegateResult Result returned by tool-call delegation (`LlmDelegateToolCallsTool` and `LlmUpdateToolResultTool`). - `allCompleted` — whether every delegated tool call has finished. - `toolResults` — the collected `LlmToolResultEntry` items. - `pendingCount` — number of tool calls still awaiting completion. - `errorCount` / `hasErrors` / `errors` — error count, flag, and the `LlmToolErrorEntry` details. ```ts import { LlmDelegateResult } from '@loopstack/llm-provider'; ``` ```ts export interface LlmDelegateResult { allCompleted: boolean; toolResults: LlmToolResultEntry[]; pendingCount: number; errorCount: number; hasErrors: boolean; errors: LlmToolErrorEntry[]; } ``` ### LlmGenerateObjectResult Result returned by the `generateObject` provider operation (and `LlmGenerateObjectTool`) — the structured `data` matching the output schema plus the native `response`. ```ts import { LlmGenerateObjectResult } from '@loopstack/llm-provider'; ``` ```ts export interface LlmGenerateObjectResult { data: unknown; response: unknown; } ``` ### LlmGenerateTextResult Result returned by the `generateText` provider operation (and `LlmGenerateTextTool`). - `message` — the normalized assistant message produced by the provider. - `response` — the unmodified native API response (Anthropic.Message, OpenAI.ChatCompletion, etc.). ```ts import { LlmGenerateTextResult } from '@loopstack/llm-provider'; ``` ```ts export interface LlmGenerateTextResult { message: LlmNormalizedMessage; response: unknown; } ``` ### LlmMessage An inline message authors pass as prompt args — a `role` plus `text` and/or structured `blocks`. ```ts import { LlmMessage } from '@loopstack/llm-provider'; ``` ```ts export interface LlmMessage { role: 'user' | 'assistant'; text?: string; blocks?: LlmContentBlock[]; } ``` ### LlmModuleConfig Config for `LlmProviderModule` — the default `provider` and `model` passed to `forRoot()` / `forFeature()`. ```ts import { LlmModuleConfig } from '@loopstack/llm-provider'; ``` ```ts export interface LlmModuleConfig { provider?: string; model?: string; } ``` ### LlmToolErrorEntry A single tool-call error collected during delegation (part of `LlmDelegateResult`). ```ts import { LlmToolErrorEntry } from '@loopstack/llm-provider'; ``` ```ts export interface LlmToolErrorEntry { toolName: string; toolCallId: string; message: string; } ``` ### LlmToolResultEntry A single tool-call result collected during delegation (part of `LlmDelegateResult`). ```ts import { LlmToolResultEntry } from '@loopstack/llm-provider'; ``` ```ts export interface LlmToolResultEntry { type: 'tool_result'; toolCallId: string; content?: string; isError?: boolean; } ``` ### LlmUsage Token usage stats reported by a provider for one LLM call. ```ts import { LlmUsage } from '@loopstack/llm-provider'; ``` ```ts export interface LlmUsage { inputTokens: number; outputTokens: number; cacheCreationInputTokens?: number; cacheReadInputTokens?: number; reasoningTokens?: number; } ``` ## Type Aliases ### LlmConfig Config for shared LLM passthrough, inferred from `LlmConfigSchema`. ```ts import { LlmConfig } from '@loopstack/llm-provider'; ``` ```ts export type LlmConfig = z.infer; ``` ### LlmContentBlock A single block of LLM message content (text, tool call, tool result, etc.). ```ts import { LlmContentBlock } from '@loopstack/llm-provider'; ``` ```ts export type LlmContentBlock = UIContentBlock; ``` ### LlmResultMeta Metadata returned by the LLM tools (`LlmResultMeta` carries the resolved `provider`, `model`, and `LlmUsage`). ```ts import { LlmResultMeta } from '@loopstack/llm-provider'; ``` ```ts export type LlmResultMeta = { provider: string; model: string; usage?: LlmUsage; }; ``` ### LlmStopReason The reason an LLM turn stopped (`end_turn`, `tool_use`, `max_tokens`, `stop_sequence`). ```ts import { LlmStopReason } from '@loopstack/llm-provider'; ``` ```ts export type LlmStopReason = NonNullable; ``` ## Variables ### LlmConfigSchema Zod schema for the shared LLM config — import in parent workflows/tools to pass `model` through as args. ```ts import { LlmConfigSchema } from '@loopstack/llm-provider'; ``` ```ts LlmConfigSchema: z.ZodObject< { model: z.ZodOptional; }, z.core.$strip >; ``` ### LlmContentBlockSchema Zod schema for a single LLM content block (text, tool call, tool result, etc.). ```ts import { LlmContentBlockSchema } from '@loopstack/llm-provider'; ``` ```ts LlmContentBlockSchema: z.ZodDiscriminatedUnion< [ z.ZodObject< { type: z.ZodLiteral<'text'>; text: z.ZodString; }, z.core.$strip >, z.ZodObject< { type: z.ZodLiteral<'thinking'>; text: z.ZodString; }, z.core.$strip >, z.ZodObject< { type: z.ZodLiteral<'tool_call'>; id: z.ZodString; name: z.ZodString; args: z.ZodRecord; }, z.core.$strip >, z.ZodObject< { type: z.ZodLiteral<'server_tool_use'>; id: z.ZodString; name: z.ZodString; input: z.ZodRecord; }, z.core.$strip >, z.ZodObject< { type: z.ZodLiteral<'server_tool_result'>; toolUseId: z.ZodString; content: z.ZodUnknown; }, z.core.$strip >, z.ZodObject< { type: z.ZodLiteral<'tool_result'>; toolCallId: z.ZodString; content: z.ZodString; isError: z.ZodBoolean; }, z.core.$strip >, ], 'type' >; ``` ### LlmDelegateResultSchema Zod schema for `LlmDelegateResult` — the `resultSchema` of `llm_delegate_tool_calls` and `llm_update_tool_result`. ```ts import { LlmDelegateResultSchema } from '@loopstack/llm-provider'; ``` ```ts LlmDelegateResultSchema: z.ZodObject< { allCompleted: z.ZodBoolean; toolResults: z.ZodArray< z.ZodObject< { type: z.ZodLiteral<'tool_result'>; toolCallId: z.ZodString; content: z.ZodOptional; isError: z.ZodOptional; }, z.core.$strict > >; pendingCount: z.ZodNumber; errorCount: z.ZodNumber; hasErrors: z.ZodBoolean; errors: z.ZodArray< z.ZodObject< { toolName: z.ZodString; toolCallId: z.ZodString; message: z.ZodString; }, z.core.$strict > >; }, z.core.$strict >; ``` ### LlmDelegateToolCallsConfigSchema Zod schema for `llm_delegate_tool_calls` tool config (result persistence options). ```ts import { LlmDelegateToolCallsConfigSchema } from '@loopstack/llm-provider'; ``` ```ts LlmDelegateToolCallsConfigSchema: z.ZodObject< { save: z.ZodOptional; meta: z.ZodOptional>; }, z.core.$strip >; ``` ### LlmDelegateToolCallsToolSchema Zod schema for `llm_delegate_tool_calls` tool args (the LLM `message`, the `tools` the LLM was offered, and the `callback.transition` to fire on completion). ```ts import { LlmDelegateToolCallsToolSchema } from '@loopstack/llm-provider'; ``` ```ts LlmDelegateToolCallsToolSchema: z.ZodObject< { message: z.ZodObject< { role: z.ZodEnum<{ user: 'user'; assistant: 'assistant'; }>; blocks: z.ZodOptional< z.ZodArray< z.ZodDiscriminatedUnion< [ z.ZodObject< { type: z.ZodLiteral<'text'>; text: z.ZodString; }, z.core.$strip >, z.ZodObject< { type: z.ZodLiteral<'thinking'>; text: z.ZodString; }, z.core.$strip >, z.ZodObject< { type: z.ZodLiteral<'tool_call'>; id: z.ZodString; name: z.ZodString; args: z.ZodRecord; }, z.core.$strip >, z.ZodObject< { type: z.ZodLiteral<'server_tool_use'>; id: z.ZodString; name: z.ZodString; input: z.ZodRecord; }, z.core.$strip >, z.ZodObject< { type: z.ZodLiteral<'server_tool_result'>; toolUseId: z.ZodString; content: z.ZodUnknown; }, z.core.$strip >, z.ZodObject< { type: z.ZodLiteral<'tool_result'>; toolCallId: z.ZodString; content: z.ZodString; isError: z.ZodBoolean; }, z.core.$strip >, ], 'type' > > >; meta: z.ZodOptional< z.ZodObject< { model: z.ZodOptional; usage: z.ZodOptional< z.ZodObject< { inputTokens: z.ZodNumber; outputTokens: z.ZodNumber; cacheCreationInputTokens: z.ZodOptional; cacheReadInputTokens: z.ZodOptional; reasoningTokens: z.ZodOptional; }, z.core.$strip > >; costUsd: z.ZodOptional; numTurns: z.ZodOptional; durationMs: z.ZodOptional; }, z.core.$strip > >; id: z.ZodOptional; text: z.ZodString; stopReason: z.ZodOptional< z.ZodEnum<{ end_turn: 'end_turn'; tool_use: 'tool_use'; max_tokens: 'max_tokens'; stop_sequence: 'stop_sequence'; }> >; }, z.core.$strip >; tools: z.ZodArray; callback: z.ZodObject< { transition: z.ZodString; }, z.core.$strip >; }, z.core.$strip >; ``` ### LlmGenerateObjectArgsSchema Zod schema for `llm_generate_object` tool args (`prompt`/`messages` plus the `outputSchema` the result must conform to). ```ts import { LlmGenerateObjectArgsSchema } from '@loopstack/llm-provider'; ``` ```ts LlmGenerateObjectArgsSchema: z.ZodObject< { prompt: z.ZodOptional; messages: z.ZodOptional< z.ZodArray< z.ZodObject< { role: z.ZodEnum<{ user: 'user'; assistant: 'assistant'; }>; content: z.ZodUnion]>; }, z.core.$strip > > >; outputSchema: z.ZodCustom< z.ZodType>, z.ZodType> >; }, z.core.$strip >; ``` ### LlmGenerateObjectConfigSchema Zod schema for `llm_generate_object` tool config (`provider`, `model`, `system`, `providerConfig`). ```ts import { LlmGenerateObjectConfigSchema } from '@loopstack/llm-provider'; ``` ```ts LlmGenerateObjectConfigSchema: z.ZodObject< { provider: z.ZodOptional; system: z.ZodOptional; model: z.ZodOptional; messagesSearchTag: z.ZodOptional; providerConfig: z.ZodOptional>; }, z.core.$strip >; ``` ### LlmGenerateObjectResultSchema Zod schema for `LlmGenerateObjectResult` — the `resultSchema` of `llm_generate_object`. `data` is validated against the caller's `outputSchema` inside the tool; here it is intentionally uncontracted, as is the provider-raw `response`. ```ts import { LlmGenerateObjectResultSchema } from '@loopstack/llm-provider'; ``` ```ts LlmGenerateObjectResultSchema: z.ZodObject< { data: z.ZodUnknown; response: z.ZodUnknown; }, z.core.$strict >; ``` ### LlmGenerateTextArgsSchema Zod schema for `llm_generate_text` tool args (`prompt` and/or `messages`). ```ts import { LlmGenerateTextArgsSchema } from '@loopstack/llm-provider'; ``` ```ts LlmGenerateTextArgsSchema: z.ZodObject< { prompt: z.ZodOptional; messages: z.ZodOptional< z.ZodArray< z.ZodObject< { role: z.ZodEnum<{ user: 'user'; assistant: 'assistant'; }>; content: z.ZodUnion]>; }, z.core.$strip > > >; }, z.core.$strip >; ``` ### LlmGenerateTextConfigSchema Zod schema for `llm_generate_text` tool config (`provider`, `model`, `system`, `tools`, `providerConfig`, and persistence options). ```ts import { LlmGenerateTextConfigSchema } from '@loopstack/llm-provider'; ``` ```ts LlmGenerateTextConfigSchema: z.ZodObject< { provider: z.ZodOptional; system: z.ZodOptional; model: z.ZodOptional; messagesSearchTag: z.ZodOptional; providerConfig: z.ZodOptional>; tools: z.ZodOptional>; save: z.ZodOptional; meta: z.ZodOptional>; }, z.core.$strip >; ``` ### LlmGenerateTextResultSchema Zod schema for `LlmGenerateTextResult` — the `resultSchema` of `llm_generate_text`. The native `response` is provider-raw and intentionally uncontracted. ```ts import { LlmGenerateTextResultSchema } from '@loopstack/llm-provider'; ``` ```ts LlmGenerateTextResultSchema: z.ZodObject< { message: z.ZodObject< { role: z.ZodEnum<{ user: 'user'; assistant: 'assistant'; }>; blocks: z.ZodOptional< z.ZodArray< z.ZodDiscriminatedUnion< [ z.ZodObject< { type: z.ZodLiteral<'text'>; text: z.ZodString; }, z.core.$strip >, z.ZodObject< { type: z.ZodLiteral<'thinking'>; text: z.ZodString; }, z.core.$strip >, z.ZodObject< { type: z.ZodLiteral<'tool_call'>; id: z.ZodString; name: z.ZodString; args: z.ZodRecord; }, z.core.$strip >, z.ZodObject< { type: z.ZodLiteral<'server_tool_use'>; id: z.ZodString; name: z.ZodString; input: z.ZodRecord; }, z.core.$strip >, z.ZodObject< { type: z.ZodLiteral<'server_tool_result'>; toolUseId: z.ZodString; content: z.ZodUnknown; }, z.core.$strip >, z.ZodObject< { type: z.ZodLiteral<'tool_result'>; toolCallId: z.ZodString; content: z.ZodString; isError: z.ZodBoolean; }, z.core.$strip >, ], 'type' > > >; meta: z.ZodOptional< z.ZodObject< { model: z.ZodOptional; usage: z.ZodOptional< z.ZodObject< { inputTokens: z.ZodNumber; outputTokens: z.ZodNumber; cacheCreationInputTokens: z.ZodOptional; cacheReadInputTokens: z.ZodOptional; reasoningTokens: z.ZodOptional; }, z.core.$strip > >; costUsd: z.ZodOptional; numTurns: z.ZodOptional; durationMs: z.ZodOptional; }, z.core.$strip > >; id: z.ZodOptional; text: z.ZodString; stopReason: z.ZodOptional< z.ZodEnum<{ end_turn: 'end_turn'; tool_use: 'tool_use'; max_tokens: 'max_tokens'; stop_sequence: 'stop_sequence'; }> >; }, z.core.$strip >; response: z.ZodUnknown; }, z.core.$strict >; ``` ### LlmToolErrorEntrySchema Zod schema for `LlmToolErrorEntry`. ```ts import { LlmToolErrorEntrySchema } from '@loopstack/llm-provider'; ``` ```ts LlmToolErrorEntrySchema: z.ZodObject< { toolName: z.ZodString; toolCallId: z.ZodString; message: z.ZodString; }, z.core.$strict >; ``` ### LlmToolResultEntrySchema Zod schema for `LlmToolResultEntry`. ```ts import { LlmToolResultEntrySchema } from '@loopstack/llm-provider'; ``` ```ts LlmToolResultEntrySchema: z.ZodObject< { type: z.ZodLiteral<'tool_result'>; toolCallId: z.ZodString; content: z.ZodOptional; isError: z.ZodOptional; }, z.core.$strict >; ``` ### LlmUpdateToolResultConfigSchema Zod schema for `llm_update_tool_result` tool config (result persistence options). ```ts import { LlmUpdateToolResultConfigSchema } from '@loopstack/llm-provider'; ``` ```ts LlmUpdateToolResultConfigSchema: z.ZodObject< { save: z.ZodOptional; meta: z.ZodOptional>; }, z.core.$strip >; ``` ### LlmUpdateToolResultToolSchema Zod schema for `llm_update_tool_result` tool args (the pending `delegateResult` and the `completedTool` to merge in). ```ts import { LlmUpdateToolResultToolSchema } from '@loopstack/llm-provider'; ``` ```ts LlmUpdateToolResultToolSchema: z.ZodObject< { delegateResult: z.ZodObject< { allCompleted: z.ZodBoolean; toolResults: z.ZodArray; pendingCount: z.ZodNumber; errorCount: z.ZodOptional; hasErrors: z.ZodOptional; errors: z.ZodOptional>; }, z.core.$strip >; completedTool: z.ZodAny; }, z.core.$strip >; ``` --- > Source: https://loopstack.ai/llms/reference/api/local-file-explorer.md --- title: 'API: @loopstack/local-file-explorer' description: 'Public API reference for @loopstack/local-file-explorer' includeInLlmsFullTxt: false --- # API: @loopstack/local-file-explorer ## Classes ### FileApiService Service that exposes workspace-scoped file tree and file content reads, parsing workflow YAML into `workflowConfig` where present; inject it for higher-level local file access. ```ts import { FileApiService } from '@loopstack/local-file-explorer'; ``` **Provided by:** `LocalFileExplorerModule` ```ts export class FileApiService { constructor(fileSystemService: FileSystemService); getFileTree(_workspaceClassName: string): Promise; getFileContent(_workspaceClassName: string, filePath: string): Promise; } ``` ### FileContentDto Result for a local file read — the file `path`, its `content`, and an optional parsed `workflowConfig` for workflow YAML files. ```ts import { FileContentDto } from '@loopstack/local-file-explorer'; ``` ```ts export class FileContentDto { path: string; content: string; workflowConfig?: Record; } ``` ### FileExplorerNodeDto Result representing a node in the local file tree — a file or folder with id, name, path, type, and optional children. ```ts import { FileExplorerNodeDto } from '@loopstack/local-file-explorer'; ``` ```ts export class FileExplorerNodeDto { id: string; name: string; path: string; type: 'file' | 'folder'; children?: FileExplorerNodeDto[]; } ``` ### FileSystemService Service that performs path-safe local filesystem access — resolves the workspace root, builds the file tree, reads file contents, and guards against directory traversal; inject it for programmatic file access. ```ts import { FileSystemService } from '@loopstack/local-file-explorer'; ``` **Provided by:** `LocalFileExplorerModule` ```ts export class FileSystemService { constructor(configService: ConfigService); getWorkspaceRootPath(): string; validatePath(basePath: string, targetPath: string): boolean; resolveContainedPath(basePath: string, relativePath: string): Promise; buildFileTree(rootPath: string, relativePath?: string): Promise; readFileContent(filePath: string, maxSize?: number): Promise; exists(filePath: string): Promise; } ``` ### LocalFileExplorerModule NestJS module that provides workspace-scoped REST endpoints for browsing and reading the local filesystem (`LocalFileExplorerController`), plus the `FileApiService` and `FileSystemService` for programmatic file access. Registration: - `LocalFileExplorerModule` — bare import. Enough for most apps: the controller and services are wired up automatically and the endpoints go live. - `LocalFileExplorerModule.forFeature(config?: { enabled?: boolean; environments?: string[] })` — use to register it as a Studio feature flag (lights up the file-explorer panel) and optionally scope it to specific environment names. Requires: nothing beyond importing the module. ```ts import { LocalFileExplorerModule } from '@loopstack/local-file-explorer'; ``` ```ts export class LocalFileExplorerModule { static forFeature(config?: { enabled?: boolean; environments?: string[] }): DynamicModule; } ``` --- > Source: https://loopstack.ai/llms/reference/api/mcp.md --- title: 'API: @loopstack/mcp' description: 'Public API reference for @loopstack/mcp' includeInLlmsFullTxt: false --- # API: @loopstack/mcp ## Classes ### McpAuthError Error thrown when the remote MCP server responds with 401 or 403. Catch this to handle missing or invalid authentication credentials. ```ts import { McpAuthError } from '@loopstack/mcp'; ``` ```ts export class McpAuthError extends McpError {} ``` ### McpCallTool Tool that calls a tool on a remote MCP server over HTTPS (Streamable HTTP or legacy SSE). ```ts import { McpCallTool } from '@loopstack/mcp'; ``` **Provided by:** `McpModule` ```ts export class McpCallTool extends McpToolBase { protected handle( args: McpCallToolArgs, ctx: RunContext, options?: ToolCallOptions, ): Promise; } ``` ### McpClientService Service that connects to remote MCP servers; inject it to list and call tools on an MCP endpoint. ```ts import { McpClientService } from '@loopstack/mcp'; ``` **Provided by:** `McpModule` ```ts export class McpClientService { constructor(env?: EnvReader, metrics?: McpMetricsPort); listTools( rawUrl: string, config: McpToolConfig, options?: McpClientCallOptions, ): Promise<{ tools: unknown; }>; callTool( rawUrl: string, config: McpToolConfig, toolName: string, toolArgs: Record, options?: McpClientCallOptions, ): Promise; mergeHeaders(config: McpToolConfig, url: URL): Record; } ``` ### McpError Base class for all MCP failures. Catch this to handle any error raised while connecting to or calling a remote MCP server. ```ts import { McpError } from '@loopstack/mcp'; ``` ```ts export abstract class McpError extends Error { constructor(message: string); } ``` ### McpListToolsTool Tool that lists the tool definitions exposed by a remote MCP server. ```ts import { McpListToolsTool } from '@loopstack/mcp'; ``` **Provided by:** `McpModule` ```ts export class McpListToolsTool extends McpToolBase { protected handle( args: McpListToolsArgs, ctx: RunContext, options?: ToolCallOptions, ): Promise; } ``` ### McpModule NestJS module that provides remote MCP client tools — `mcp_list_tools` (`McpListToolsTool`), `mcp_call` (`McpCallTool`), and the `McpClientService` that connects to remote Model Context Protocol servers. Registration: - `McpModule.forRoot(McpToolConfigInput)` — the only entry point; registers the module globally and co-imports `LoopCoreModule`. Pass config (allowlist, auth header mappings) to apply it to every tool call; config is optional here, in which case each call must supply config via `options.config`. Requires: an `allowedHosts` allowlist supplied either at the module level (via `forRoot`) or per call via `options.config` — a tool call with no config at either level throws (the SSRF allowlist is mandatory). For authenticated servers, the env vars referenced by `hostHeaderEnv` / `headerEnv` must also be set, since header values are read from `process.env` at call time. ```ts import { McpModule } from '@loopstack/mcp'; ``` ```ts export class McpModule { static forRoot(config?: McpToolConfigInput): DynamicModule; } ``` ### McpProtocolError Error thrown when the MCP server returns a malformed response (JSON-RPC parse or invalid message). Catch this to handle protocol-level violations from the remote server. ```ts import { McpProtocolError } from '@loopstack/mcp'; ``` ```ts export class McpProtocolError extends McpError {} ``` ### McpTimeoutError Error thrown when an MCP call exceeds its configured `timeoutMs`. Catch this to handle slow or unresponsive remote servers. ```ts import { McpTimeoutError } from '@loopstack/mcp'; ``` ```ts export class McpTimeoutError extends McpError {} ``` ### McpToolBase Abstract base for tools that call a remote MCP server; extend it to add custom MCP-backed tools. Concrete subclasses must repeat the `@Tool({ schema, configSchema })` decorator — decorator metadata is not inherited. ```ts import { McpToolBase } from '@loopstack/mcp'; ``` ```ts export abstract class McpToolBase extends BaseTool { protected readonly mcp: McpClientService; protected requireConfig(config: McpToolConfig | undefined): McpToolConfig; } ``` ### McpTransportError Error thrown on transport-level failures (DNS, TCP, TLS, abort, or transport fallback). Catch this to handle network or connection problems reaching the remote server. ```ts import { McpTransportError } from '@loopstack/mcp'; ``` ```ts export class McpTransportError extends McpError {} ``` ### McpUrlSecurityError Error thrown when an MCP URL fails the security checks (SSRF, allowlist, scheme, or userinfo violations). Catch this to react to a rejected or unsafe target URL. ```ts import { McpUrlSecurityError } from '@loopstack/mcp'; ``` ```ts export class McpUrlSecurityError extends McpError {} ``` ## Interfaces ### McpClientCallOptions Options for an `McpClientService` call (per-request timeout, transport, DNS-resolution skip). ```ts import { McpClientCallOptions } from '@loopstack/mcp'; ``` ```ts export interface McpClientCallOptions { timeoutMs?: number; skipDnsResolution?: boolean; transport?: McpTransportKind; } ``` ## Type Aliases ### McpCallToolArgs Args for `McpCallTool` (`mcp_call`). ```ts import { McpCallToolArgs } from '@loopstack/mcp'; ``` ```ts export type McpCallToolArgs = z.infer; ``` ### McpCallToolResult Result of an `McpClientService.callTool()` invocation — a modern call-tool result or a legacy tool result. ```ts import { McpCallToolResult } from '@loopstack/mcp'; ``` ```ts export type McpCallToolResult = | { kind: 'legacyToolResult'; toolResult: unknown; meta?: unknown; } | { kind: 'callToolResult'; content: unknown; structuredContent?: unknown; isError?: unknown; meta?: unknown; }; ``` ### McpConnectionArgs Args for connecting to a remote MCP server, shared by the MCP tools. ```ts import { McpConnectionArgs } from '@loopstack/mcp'; ``` ```ts export type McpConnectionArgs = z.infer; ``` ### McpListToolsArgs Args for `McpListToolsTool` (`mcp_list_tools`). ```ts import { McpListToolsArgs } from '@loopstack/mcp'; ``` ```ts export type McpListToolsArgs = z.infer; ``` ### McpToolConfig Config for the MCP tools (`McpCallTool`, `McpListToolsTool`). ```ts import { McpToolConfig } from '@loopstack/mcp'; ``` ```ts export type McpToolConfig = z.infer; ``` ### McpToolConfigInput Input config for `McpModule.forRoot()` (the pre-parse shape of `McpToolConfig`). ```ts import { McpToolConfigInput } from '@loopstack/mcp'; ``` ```ts export type McpToolConfigInput = z.input; ``` ### McpTransportKind Transport used to reach a remote MCP server — Streamable HTTP or legacy SSE. ```ts import { McpTransportKind } from '@loopstack/mcp'; ``` ```ts export type McpTransportKind = 'streamableHttp' | 'sse'; ``` ## Variables ### McpCallToolArgsSchema Zod schema for `mcp_call` tool arguments. ```ts import { McpCallToolArgsSchema } from '@loopstack/mcp'; ``` ```ts McpCallToolArgsSchema: z.ZodObject< { serverUrl: z.ZodURL; timeoutMs: z.ZodOptional; transport: z.ZodDefault< z.ZodOptional< z.ZodEnum<{ streamableHttp: 'streamableHttp'; sse: 'sse'; }> > >; toolName: z.ZodString; arguments: z.ZodDefault>>; }, z.core.$strict >; ``` ### McpCallToolResultSchema Zod schema for `McpCallToolResult` — the `resultSchema` of `mcp_call`. The proxied tool payloads (`toolResult`, `content`, `structuredContent`, `meta`) are intentionally uncontracted. ```ts import { McpCallToolResultSchema } from '@loopstack/mcp'; ``` ```ts McpCallToolResultSchema: z.ZodUnion< readonly [ z.ZodObject< { kind: z.ZodLiteral<'legacyToolResult'>; toolResult: z.ZodUnknown; meta: z.ZodOptional; }, z.core.$strict >, z.ZodObject< { kind: z.ZodLiteral<'callToolResult'>; content: z.ZodUnknown; structuredContent: z.ZodOptional; isError: z.ZodOptional; meta: z.ZodOptional; }, z.core.$strict >, ] >; ``` ### McpConnectionArgsSchema Zod schema for the connection arguments shared by the MCP tools (`serverUrl`, `timeoutMs`, `transport`). ```ts import { McpConnectionArgsSchema } from '@loopstack/mcp'; ``` ```ts McpConnectionArgsSchema: z.ZodObject< { serverUrl: z.ZodURL; timeoutMs: z.ZodOptional; transport: z.ZodDefault< z.ZodOptional< z.ZodEnum<{ streamableHttp: 'streamableHttp'; sse: 'sse'; }> > >; }, z.core.$strict >; ``` ### McpListToolsArgsSchema Zod schema for `mcp_list_tools` tool arguments. ```ts import { McpListToolsArgsSchema } from '@loopstack/mcp'; ``` ```ts McpListToolsArgsSchema: z.ZodObject< { serverUrl: z.ZodURL; timeoutMs: z.ZodOptional; transport: z.ZodDefault< z.ZodOptional< z.ZodEnum<{ streamableHttp: 'streamableHttp'; sse: 'sse'; }> > >; }, z.core.$strict >; ``` ### McpListToolsResultSchema Zod schema for the `mcp_list_tools` result — the remote server's tool definitions are passed through verbatim and intentionally uncontracted. ```ts import { McpListToolsResultSchema } from '@loopstack/mcp'; ``` ```ts McpListToolsResultSchema: z.ZodObject< { tools: z.ZodUnknown; }, z.core.$strict >; ``` ### McpToolConfigSchema Zod schema for MCP tool configuration — host allowlist and auth header mappings. ```ts import { McpToolConfigSchema } from '@loopstack/mcp'; ``` ```ts McpToolConfigSchema: z.ZodObject< { allowedHosts: z.ZodArray; allowInsecureHttp: z.ZodDefault>; allowPrivateHosts: z.ZodDefault>; defaultHeaders: z.ZodOptional>; headerEnv: z.ZodOptional>; hostHeaderEnv: z.ZodOptional>>; }, z.core.$strict >; ``` --- > Source: https://loopstack.ai/llms/reference/api/oauth.md --- title: 'API: @loopstack/oauth' description: 'Public API reference for @loopstack/oauth' includeInLlmsFullTxt: false --- # API: @loopstack/oauth ## Classes ### BuildOAuthUrlTool Tool that builds an OAuth 2.0 authorization URL for a provider, including a CSRF state parameter. ```ts import { BuildOAuthUrlTool } from '@loopstack/oauth'; ``` **Provided by:** `OAuthModule` ```ts export class BuildOAuthUrlTool extends BaseTool { protected handle(args: BuildOAuthUrlArgs): Promise>; } ``` ### ExchangeOAuthTokenTool Tool that exchanges an OAuth 2.0 authorization code for access and refresh tokens and stores them for the user. ```ts import { ExchangeOAuthTokenTool } from '@loopstack/oauth'; ``` **Provided by:** `OAuthModule` ```ts export class ExchangeOAuthTokenTool extends BaseTool { protected handle(args: ExchangeOAuthTokenArgs, ctx: RunContext): Promise>; } ``` ### OAuthCallbackController Public OAuth callback endpoints that complete the authorization-code flow from `code` + `state` alone: the state token (unguessable, single-use, 10 minute TTL, re-validated by the workflow's own `expectedState` check) resolves the pending `OAuthWorkflow`, whose `exchangeToken` transition is fired server-side as the user who started the flow. Two entry points, same completion: - `GET /api/v1/oauth/callback` — a provider redirect target (`*_OAUTH_REDIRECT_URI=/api/v1/oauth/callback`); renders a minimal "connected" page. Works without the Studio frontend — CLI-printed auth URLs and headless deployments complete here. - `POST /api/v1/oauth/complete` — JSON variant used by Studio's callback page when it was opened without a popup opener (e.g. from a CLI link while the redirect URI still points at Studio). ```ts import { OAuthCallbackController } from '@loopstack/oauth'; ``` **Provided by:** `OAuthModule` ```ts export class OAuthCallbackController { constructor(sessions: OAuthSessionService, workflowRunner: WorkflowRunner); complete(payload: CompleteOAuthPayload): Promise<{ ok: true; provider: string; }>; callback(res: Response, code?: string, state?: string, error?: string, errorDescription?: string): Promise; } ``` ### OAuthModule NestJS module that provides the provider-agnostic OAuth 2.0 framework — the `OAuthProviderRegistry` and `OAuthTokenStore` services, the `build_oauth_url` and `exchange_oauth_token` tools, and the generic `OAuthWorkflow` for the authorization code flow. Registration: - `OAuthModule` — a bare import is enough. The module is `@Global()`, so a single import anywhere makes its services, tools, and workflow available application-wide via DI; no static configuration method exists. Requires: at least one OAuth provider implementing `OAuthProviderInterface` must be registered for authentication to do anything useful — provider modules (e.g. `@loopstack/google-workspace` or `@loopstack/github`) self-register on init via `OAuthProviderRegistry`. Token persistence uses Redis (`REDIS_HOST`/`REDIS_PORT`/`REDIS_PASSWORD`) but is optional, falling back to in-memory storage when Redis is unavailable. ```ts import { OAuthModule } from '@loopstack/oauth'; ``` ```ts export class OAuthModule {} ``` ### OAuthPromptDocument Document that renders the OAuth authorization prompt (provider, auth URL, and connection status) in Studio. ```ts import { OAuthPromptDocument } from '@loopstack/oauth'; ``` ```ts export class OAuthPromptDocument { provider: string; authUrl: string; state: string; status: 'pending' | 'success' | 'error'; message?: string; } ``` ### OAuthSessionService Service that registers pending OAuth flows by their CSRF `state` and hands them out exactly once (Redis-backed with in-memory fallback, 10 minute TTL) — the server-side `state → workflow` lookup behind the public OAuth callback. ```ts import { OAuthSessionService } from '@loopstack/oauth'; ``` **Provided by:** `OAuthModule` ```ts export class OAuthSessionService implements OnModuleDestroy { constructor(); onModuleDestroy(): void; register(state: string, session: OAuthSession): Promise; consume(state: string): Promise; } ``` ### OAuthTokenStore Service that stores and retrieves per-user OAuth tokens (Redis-backed, with in-memory fallback) and transparently refreshes expired access tokens; inject it to read a valid access token for a provider. ```ts import { OAuthTokenStore } from '@loopstack/oauth'; ``` **Provided by:** `OAuthModule` ```ts export class OAuthTokenStore implements OnModuleDestroy { constructor(); onModuleDestroy(): void; storeTokens(userId: string, providerId: string, tokens: StoredTokens): Promise; storeFromTokenSet(userId: string, providerId: string, tokenSet: OAuthTokenSet): Promise; getTokens(userId: string, providerId: string): Promise; getValidAccessToken(userId: string, providerId: string): Promise; } ``` ### OAuthWorkflow Workflow that runs the OAuth 2.0 authorization code flow for a provider: it builds the auth URL, prompts the user via an `OAuthPromptDocument`, and exchanges the returned code for stored tokens. Run it standalone to pre-authenticate or invoke it from another workflow when authentication is required. ```ts import { OAuthWorkflow } from '@loopstack/oauth'; ``` **Provided by:** `OAuthModule` ```ts export class OAuthWorkflow extends BaseWorkflow { constructor( buildOAuthUrl: BuildOAuthUrlTool, exchangeOAuthToken: ExchangeOAuthTokenTool, sessions: OAuthSessionService, ); initiateOAuth(state: OAuthState, ctx: RunContext): Promise; exchangeToken( state: OAuthState, input: TransitionInput<{ code: string; state: string; }>, ): Promise; } ``` ## Interfaces ### BuildOAuthUrlResult Result for `BuildOAuthUrlTool`. ```ts import { BuildOAuthUrlResult } from '@loopstack/oauth'; ``` ```ts export interface BuildOAuthUrlResult { authUrl: string; state: string; } ``` ### OAuthProviderInterface Contract that an OAuth 2.0 provider implements to plug into the OAuth framework; implement it to add a new provider. ```ts import { OAuthProviderInterface } from '@loopstack/oauth'; ``` ```ts export interface OAuthProviderInterface { readonly providerId: string; readonly defaultScopes: string[]; buildAuthUrl(scopes: string[], state: string): string; exchangeCode(code: string): Promise; refreshToken(refreshToken: string): Promise; } ``` ### OAuthSession Pending OAuth flow registered when the authorization URL is built — the lookup that lets the public callback complete the exchange from `code` + `state` alone, regardless of who opened the URL (Studio popup, CLI-printed link, plain browser). ```ts import { OAuthSession } from '@loopstack/oauth'; ``` ```ts export interface OAuthSession { workflowId: string; userId: string; provider: string; } ``` ### OAuthTokenSet Token set returned by an OAuth provider after a code exchange or refresh. ```ts import { OAuthTokenSet } from '@loopstack/oauth'; ``` ```ts export interface OAuthTokenSet { accessToken: string; refreshToken?: string; expiresIn?: number; scope: string; } ``` ### StoredTokens Persisted OAuth token record held by `OAuthTokenStore`. ```ts import { StoredTokens } from '@loopstack/oauth'; ``` ```ts export interface StoredTokens { accessToken: string; refreshToken?: string; expiresAt?: number; scope: string; } ``` ## Type Aliases ### BuildOAuthUrlArgs Args for `BuildOAuthUrlTool`. ```ts import { BuildOAuthUrlArgs } from '@loopstack/oauth'; ``` ```ts export type BuildOAuthUrlArgs = z.infer; ``` ### ExchangeOAuthTokenArgs Args for `ExchangeOAuthTokenTool`. ```ts import { ExchangeOAuthTokenArgs } from '@loopstack/oauth'; ``` ```ts export type ExchangeOAuthTokenArgs = z.infer; ``` ### ExchangeOAuthTokenResult Result for `ExchangeOAuthTokenTool`. ```ts import { ExchangeOAuthTokenResult } from '@loopstack/oauth'; ``` ```ts export type ExchangeOAuthTokenResult = { accessToken: string; refreshToken: string | undefined; expiresIn: number | undefined; scope: string | undefined; }; ``` ## Variables ### BuildOAuthUrlResultSchema Zod schema for `BuildOAuthUrlResult` — the `resultSchema` of `build_oauth_url`. ```ts import { BuildOAuthUrlResultSchema } from '@loopstack/oauth'; ``` ```ts BuildOAuthUrlResultSchema: z.ZodObject< { authUrl: z.ZodString; state: z.ZodString; }, z.core.$strict >; ``` ### BuildOAuthUrlSchema Zod schema for `BuildOAuthUrlTool` args. ```ts import { BuildOAuthUrlSchema } from '@loopstack/oauth'; ``` ```ts BuildOAuthUrlSchema: z.ZodObject< { provider: z.ZodString; scopes: z.ZodArray; }, z.core.$strict >; ``` ### ExchangeOAuthTokenResultSchema Zod schema for `ExchangeOAuthTokenResult` — the `resultSchema` of `exchange_oauth_token`. ```ts import { ExchangeOAuthTokenResultSchema } from '@loopstack/oauth'; ``` ```ts ExchangeOAuthTokenResultSchema: z.ZodObject< { accessToken: z.ZodString; refreshToken: z.ZodOptional; expiresIn: z.ZodOptional; scope: z.ZodOptional; }, z.core.$strict >; ``` ### ExchangeOAuthTokenSchema Zod schema for `ExchangeOAuthTokenTool` args. ```ts import { ExchangeOAuthTokenSchema } from '@loopstack/oauth'; ``` ```ts ExchangeOAuthTokenSchema: z.ZodObject< { provider: z.ZodString; code: z.ZodString; state: z.ZodString; expectedState: z.ZodString; }, z.core.$strict >; ``` ### OAuthPromptDocumentSchema Zod schema for `OAuthPromptDocument`. ```ts import { OAuthPromptDocumentSchema } from '@loopstack/oauth'; ``` ```ts OAuthPromptDocumentSchema: z.ZodObject< { provider: z.ZodString; authUrl: z.ZodString; state: z.ZodString; status: z.ZodDefault< z.ZodEnum<{ error: 'error'; success: 'success'; pending: 'pending'; }> >; message: z.ZodOptional; }, z.core.$strict >; ``` --- > Source: https://loopstack.ai/llms/reference/api/openai.md --- title: 'API: @loopstack/openai' description: 'Public API reference for @loopstack/openai' includeInLlmsFullTxt: false --- # API: @loopstack/openai ## Classes ### OpenAiModule NestJS module that provides the OpenAI LLM provider (`OpenAiLlmProvider`, registered under provider id `openai`) and the `OpenAiClientService`. Registration: - `OpenAiModule` — bare import is all that is needed; there are no static methods. On startup the provider registers itself into the LLM provider registry, after which `openai` can be selected as a provider in LLM tools and workflows. Requires: must be co-imported with `LlmProviderModule`, which supplies the `LlmProviderRegistry` the provider registers into; and an OpenAI API key, read from the `OPENAI_API_KEY` env var by default (override the env var name per call via `envApiKey`). ```ts import { OpenAiModule } from '@loopstack/openai'; ``` ```ts export class OpenAiModule {} ``` ## Interfaces ### OpenAiProviderConfig Provider-specific configuration for the OpenAI LLM provider. Passed via `providerConfig` in LlmGenerateTextArgs / LlmGenerateObjectArgs. ```ts import { OpenAiProviderConfig } from '@loopstack/openai'; ``` ```ts export interface OpenAiProviderConfig { maxTokens?: number; temperature?: number; stopSequences?: string[]; frequencyPenalty?: number; presencePenalty?: number; envApiKey?: string; } ``` --- > Source: https://loopstack.ai/llms/reference/api/quota.md --- title: 'API: @loopstack/quota' description: 'Public API reference for @loopstack/quota' includeInLlmsFullTxt: false --- # API: @loopstack/quota ## Classes ### QuotaClientService Service that reads and reports Redis-backed quota counters; inject it to check usage or report consumption. ```ts import { QuotaClientService } from '@loopstack/quota'; ``` **Provided by:** `QuotaModule` ```ts export class QuotaClientService implements QuotaClientServiceInterface { constructor(redis: Redis | null); checkQuota(userId: string, quotaType: string): Promise; report(userId: string, quotaType: string, amount: number): Promise; } ``` ### QuotaModule NestJS module that provides opt-in quota tracking and enforcement for tool calls — the `QuotaInterceptor`, `QuotaClientService`, `QuotaCalculatorRegistry`, and built-in AI-cost and processing-time calculators. Registration: - `QuotaModule.forRoot(QuotaModuleOptions)` — use when you configure the module in code; sets the `enabled` flag and the Redis connection (`redisHost`/`redisPort`/`redisPassword`/`redisDb`) and registers the module globally. - `QuotaModule.forRootAsync()` — use when configuration comes from the environment at runtime; reads `QUOTA_ENABLED`, `QUOTA_REDIS_HOST`, `QUOTA_REDIS_PORT`, `QUOTA_REDIS_PASSWORD` and `QUOTA_REDIS_DB`, then delegates to `forRoot`. Anything left unset falls back to the deployment's own Redis connection (`REDIS_URL`, or `REDIS_HOST` / `REDIS_PORT` / `REDIS_PASSWORD` / `REDIS_DB`). Requires: a reachable Redis instance when `enabled: true` (usage counters are Redis-backed). When `enabled` is `false` (the default), the Redis connection is skipped and the interceptor is a no-op. ```ts import { QuotaModule } from '@loopstack/quota'; ``` ```ts export class QuotaModule implements OnModuleInit { constructor(calculatorRegistry: QuotaCalculatorRegistry); onModuleInit(): void; static forRoot(options?: QuotaModuleOptions): DynamicModule; static forRootAsync(): DynamicModule; } ``` ## Interfaces ### QuotaModuleOptions Options for `QuotaModule.forRoot()` — toggles quota tracking and configures the Redis connection. ```ts import { QuotaModuleOptions } from '@loopstack/quota'; ``` ```ts export interface QuotaModuleOptions { enabled: boolean; redisHost?: string; redisPort?: number; redisPassword?: string; redisDb?: number; } ``` ## Type Aliases ### QuotaCheckResult Result of `QuotaClientService.checkQuota()` — whether the limit is exceeded plus current used and limit values. ```ts import { QuotaCheckResult } from '@loopstack/quota'; ``` ```ts export type QuotaCheckResult = { exceeded: boolean; used: number; limit: number; }; ``` --- > Source: https://loopstack.ai/llms/reference/api/remote-client.md --- title: 'API: @loopstack/remote-client' description: 'Public API reference for @loopstack/remote-client' includeInLlmsFullTxt: false --- # API: @loopstack/remote-client ## Classes ### BashTool Tool that executes a shell command on the remote instance, streaming its output live into a document as it runs, and returns the merged output plus the exit code. ```ts import { BashTool } from '@loopstack/remote-client'; ``` **Provided by:** `RemoteClientModule` ```ts export class BashTool extends BaseTool { constructor(env: EnvironmentService, remote: RemoteClient); protected handle(args: BashArgs, ctx: RunContext): Promise>; } ``` ### EditTool Tool that performs an exact string replacement in a file on the remote instance. ```ts import { EditTool } from '@loopstack/remote-client'; ``` **Provided by:** `RemoteClientModule` ```ts export class EditTool extends BaseTool { constructor(env: EnvironmentService, remote: RemoteClient); protected handle(args: EditArgs): Promise>; } ``` ### EnvironmentService Service that resolves the remote agent URL for the current execution scope (preferring the `sandbox` slot) and manages a workspace's environment records; inject it in tools and transitions to reach the right remote server, or to read, replace, and delete a workspace's environments. ```ts import { EnvironmentService } from '@loopstack/remote-client'; ``` **Provided by:** `RemoteClientModule` ```ts export class EnvironmentService { constructor( scope: ScopeAccessor, repo: Repository, remote: RemoteClient, clientMessages: ClientMessageService, ); getEnvironments(): Promise; getAgentUrl(slotId?: string): Promise; assertReachable(slotId?: string): Promise; getEnvironmentsByWorkspace(workspaceId: string): Promise; getAgentUrlForWorkspace(workspaceId: string, slotId?: string): Promise; findByWorkspace(workspaceId: string): Promise; replaceAll( workspaceId: string, environments: Partial[], ): Promise; deleteByWorkspace(workspaceId: string): Promise; markRunning( workspaceId: string, slotId: string, data: { agentUrl: string; remoteEnvironmentId: string; type?: string; connectionUrl?: string; local?: boolean; }, ): Promise; markStopped(workspaceId: string, slotId: string): Promise; } ``` ### GlobTool Tool that finds files on the remote instance by glob pattern. ```ts import { GlobTool } from '@loopstack/remote-client'; ``` **Provided by:** `RemoteClientModule` ```ts export class GlobTool extends BaseTool { constructor(env: EnvironmentService, remote: RemoteClient); protected handle(args: GlobArgs): Promise>; } ``` ### GrepTool Tool that searches file contents on the remote instance by regex pattern. ```ts import { GrepTool } from '@loopstack/remote-client'; ``` **Provided by:** `RemoteClientModule` ```ts export class GrepTool extends BaseTool { constructor(env: EnvironmentService, remote: RemoteClient); protected handle(args: GrepArgs): Promise>; } ``` ### LogsTool Tool that retrieves application logs from the remote instance. ```ts import { LogsTool } from '@loopstack/remote-client'; ``` **Provided by:** `RemoteClientModule` ```ts export class LogsTool extends BaseTool { constructor(env: EnvironmentService, remote: RemoteClient); protected handle(args: LogsArgs): Promise>; } ``` ### ReadTool Tool that reads a file from the remote instance, optionally limited to a line range. ```ts import { ReadTool } from '@loopstack/remote-client'; ``` **Provided by:** `RemoteClientModule` ```ts export class ReadTool extends BaseTool { constructor(env: EnvironmentService, remote: RemoteClient); protected handle(args: ReadArgs): Promise>; } ``` ### RebuildAppTool Tool that rebuilds and restarts the app on the remote instance. ```ts import { RebuildAppTool } from '@loopstack/remote-client'; ``` **Provided by:** `RemoteClientModule` ```ts export class RebuildAppTool extends BaseTool, object, RebuildAppResult> { constructor(env: EnvironmentService, remote: RemoteClient); protected handle(): Promise>; } ``` ### RemoteClient Service that wraps the remote server's HTTP API — file operations, shell execution, app lifecycle, and git commands; inject it for low-level remote access when the higher-level tools are not enough. ```ts import { RemoteClient } from '@loopstack/remote-client'; ``` **Provided by:** `RemoteClientModule` ```ts export class RemoteClient { ping(connectionUrl: string): Promise<{ status: string; timestamp: string; }>; writeFile(connectionUrl: string, path: string, content: string): Promise; readFile(connectionUrl: string, path: string, offset?: number, limit?: number): Promise; editFile( connectionUrl: string, path: string, oldString: string, newString: string, replaceAll?: boolean, ): Promise; executeCommand(connectionUrl: string, command: string, cwd?: string, timeout?: number): Promise; startExec( connectionUrl: string, options: { command: string; cwd?: string; timeout?: number; }, ): Promise; execStatus(connectionUrl: string, id: string): Promise; readExecLog(connectionUrl: string, id: string, offset: number): Promise; killExec( connectionUrl: string, id: string, ): Promise<{ ok: boolean; }>; streamCommand(connectionUrl: string, options: StreamCommandOptions): Promise; glob(connectionUrl: string, pattern: string, path?: string): Promise; grep( connectionUrl: string, pattern: string, path?: string, options?: { glob?: string; type?: string; caseInsensitive?: boolean; }, ): Promise; rebuildApp(connectionUrl: string): Promise<{ success: boolean; message: string; }>; getLogs(connectionUrl: string, lines?: number, type?: 'out' | 'error' | 'all'): Promise; setEnvVars( connectionUrl: string, variables: { key: string; value: string; }[], ): Promise<{ success: boolean; count: number; restarted: boolean; }>; resetWorkspace(connectionUrl: string): Promise<{ success: boolean; message: string; }>; purgeWorkspace( connectionUrl: string, workspaceRoot?: string, ): Promise<{ success: boolean; message: string; }>; getFileTree(connectionUrl: string, basePath?: string): Promise; gitStatus(connectionUrl: string): Promise; gitLog(connectionUrl: string, limit?: number): Promise; gitDiff(connectionUrl: string, staged?: boolean): Promise; gitBranches(connectionUrl: string): Promise; gitRemote(connectionUrl: string): Promise; gitAdd( connectionUrl: string, files: string[], ): Promise<{ success: boolean; }>; gitCommit( connectionUrl: string, message: string, ): Promise<{ hash: string; message: string; }>; gitPush( connectionUrl: string, options?: { remote?: string; branch?: string; force?: boolean; token?: string; }, ): Promise; gitFetch(connectionUrl: string, remote?: string, token?: string): Promise; gitPull( connectionUrl: string, options?: { remote?: string; branch?: string; token?: string; }, ): Promise; gitCheckout( connectionUrl: string, branch: string, create?: boolean, ): Promise<{ branch: string; }>; gitBranch( connectionUrl: string, name: string, ): Promise<{ branch: string; }>; gitRemoveRemote( connectionUrl: string, name?: string, ): Promise<{ success: boolean; }>; gitConfigureRemote( connectionUrl: string, url: string, ): Promise<{ success: boolean; }>; gitConfigUser( connectionUrl: string, name: string, email: string, ): Promise<{ success: boolean; }>; gitWorktreeList(connectionUrl: string): Promise; gitWorktreeAdd( connectionUrl: string, options: { path: string; branch?: string; newBranch?: boolean; force?: boolean; }, ): Promise; gitWorktreeRemove( connectionUrl: string, options: { path: string; force?: boolean; }, ): Promise<{ success: boolean; }>; gitWorktreePrune(connectionUrl: string): Promise; } ``` ### RemoteClientModule NestJS module that provides the `RemoteClient` HTTP client, environment services (`EnvironmentService`, `EnvironmentConfigService`), the `EnvironmentController`, and the remote workflow tools (`ReadTool`, `WriteTool`, `EditTool`, `BashTool`, `GlobTool`, `GrepTool`, `RebuildAppTool`, `ResetWorkspaceTool`, `LogsTool`, `SyncSecretsTool`) for operating on a remote workspace's filesystem and shell. Registration: - `RemoteClientModule` — bare import. Registers the global root with default (empty) config; enough when you don't need to declare available environment types. - `RemoteClientModule.forRoot(options?: RemoteClientModuleOptions)` — use once at the app root to set the global config, notably the list of available environment types (`options.environments.available`) users can provision. - `RemoteClientModule.forFeature(options: RemoteClientFeatureOptions)` — use in a feature module to register environment slot configurations (`options.slots`) scoped to that module; does not re-import the global root. Requires: a configured TypeORM database connection — the module registers the `WorkspaceEntity` and `WorkspaceEnvironmentEntity` and co-imports `SecretsModule`. `forFeature` additionally requires a non-empty `slots` array. ```ts import { RemoteClientModule } from '@loopstack/remote-client'; ``` ```ts export class RemoteClientModule { static forRoot(options?: RemoteClientModuleOptions): DynamicModule; static forFeature(options: RemoteClientFeatureOptions): DynamicModule; } ``` ### ResetWorkspaceTool Tool that resets the remote workspace to its initial state, clearing changes, temp files, database, and Redis. ```ts import { ResetWorkspaceTool } from '@loopstack/remote-client'; ``` **Provided by:** `RemoteClientModule` ```ts export class ResetWorkspaceTool extends BaseTool, object, ResetWorkspaceResult> { constructor(env: EnvironmentService, remote: RemoteClient); protected handle(): Promise>; } ``` ### SyncSecretsTool Tool that syncs all workspace secrets to the remote environment as `.env` variables and restarts the app. ```ts import { SyncSecretsTool } from '@loopstack/remote-client'; ``` **Provided by:** `RemoteClientModule` ```ts export class SyncSecretsTool extends BaseTool { constructor(env: EnvironmentService, remote: RemoteClient, secretService: SecretService); protected handle(_args: SyncSecretsInput, ctx: RunContext): Promise>; } ``` ### WorkspaceEnvironmentContextDto Result describing a workspace environment in execution context — slot, type, and the resolved connection and agent URLs returned by `EnvironmentService`. ```ts import { WorkspaceEnvironmentContextDto } from '@loopstack/remote-client'; ``` ```ts export class WorkspaceEnvironmentContextDto { slotId: string; type: string; envName?: string; connectionUrl?: string; agentUrl?: string; status?: 'running' | 'stopped'; workerId?: string; workerUrl?: string; static fromEntities(entities: WorkspaceEnvironmentEntity[]): WorkspaceEnvironmentContextDto[]; } ``` ### WorkspaceEnvironmentDto Result representing a persisted workspace environment — slot, type, remote environment id, and the connection and agent URLs used to reach it. ```ts import { WorkspaceEnvironmentDto } from '@loopstack/remote-client'; ``` ```ts export class WorkspaceEnvironmentDto implements WorkspaceEnvironmentInterface { slotId: string; type: string; remoteEnvironmentId: string; envName?: string; connectionUrl?: string; agentUrl?: string; workerId?: string; workerUrl?: string; local?: boolean; status?: EnvironmentStatus; static create(entity: WorkspaceEnvironmentEntity): WorkspaceEnvironmentDto; } ``` ### WriteTool Tool that writes a file on the remote instance, creating parent directories and overwriting existing files. ```ts import { WriteTool } from '@loopstack/remote-client'; ``` **Provided by:** `RemoteClientModule` ```ts export class WriteTool extends BaseTool { constructor(env: EnvironmentService, remote: RemoteClient); protected handle(args: WriteArgs): Promise>; } ``` ## Interfaces ### ExecLogChunk One incremental slice of a streamed command's merged output from `RemoteClient.readExecLog`. ```ts import { ExecLogChunk } from '@loopstack/remote-client'; ``` ```ts export interface ExecLogChunk { chunk: string; nextOffset: number; } ``` ### ExecResponse Response from `RemoteClient.executeCommand` — stdout, stderr, and the process exit code. ```ts import { ExecResponse } from '@loopstack/remote-client'; ``` ```ts export interface ExecResponse { stdout: string; stderr: string; exitCode: number; } ``` ### ExecStartResponse Response from `RemoteClient.startExec` — the id of the started streamed command. ```ts import { ExecStartResponse } from '@loopstack/remote-client'; ``` ```ts export interface ExecStartResponse { id: string; } ``` ### ExecStatusResponse Status of a streamed command from `RemoteClient.execStatus`. ```ts import { ExecStatusResponse } from '@loopstack/remote-client'; ``` ```ts export interface ExecStatusResponse { id: string; status: 'running' | 'exited' | 'killed'; exitCode: number | null; killedBySignal: string | null; timedOut: boolean; bytesWritten: number; startedAt: string; endedAt: string | null; } ``` ### FileEditResponse Response from `RemoteClient.editFile` — success flag, path, and the number of replacements made. ```ts import { FileEditResponse } from '@loopstack/remote-client'; ``` ```ts export interface FileEditResponse { success: boolean; path: string; replacements: number; } ``` ### FileReadResponse Response from `RemoteClient.readFile` — the file `content`. ```ts import { FileReadResponse } from '@loopstack/remote-client'; ``` ```ts export interface FileReadResponse { content: string; } ``` ### GlobResponse Response from `RemoteClient.glob` — the matched file paths. ```ts import { GlobResponse } from '@loopstack/remote-client'; ``` ```ts export interface GlobResponse { files: string[]; } ``` ### GrepMatch A single `RemoteClient.grep` match — the file, line number, and matching line content. ```ts import { GrepMatch } from '@loopstack/remote-client'; ``` ```ts export interface GrepMatch { file: string; line: number; content: string; } ``` ### GrepResponse Response from `RemoteClient.grep` — the list of matches. ```ts import { GrepResponse } from '@loopstack/remote-client'; ``` ```ts export interface GrepResponse { matches: GrepMatch[]; } ``` ### RemoteClientFeatureOptions Options for `RemoteClientModule.forFeature` — the environment `slots` a feature module contributes. ```ts import { RemoteClientFeatureOptions } from '@loopstack/remote-client'; ``` ```ts export interface RemoteClientFeatureOptions { slots: EnvironmentConfigInterface[]; } ``` ### RemoteClientModuleOptions Options for `RemoteClientModule.forRoot` — the list of environment types users can provision via `environments.available`. ```ts import { RemoteClientModuleOptions } from '@loopstack/remote-client'; ``` ```ts export interface RemoteClientModuleOptions { environments?: { available?: AvailableEnvironmentInterface[]; }; } ``` ### StreamCommandOptions Options for `RemoteClient.streamCommand` — how to run the command and where to deliver live output. ```ts import { StreamCommandOptions } from '@loopstack/remote-client'; ``` ```ts export interface StreamCommandOptions { command: string; cwd?: string; timeout?: number; pollMs?: number; signal?: AbortSignal; onChunk?: (chunk: string) => void | Promise; } ``` ### StreamCommandResult Terminal outcome of `RemoteClient.streamCommand` — the exit code and the full captured output. ```ts import { StreamCommandResult } from '@loopstack/remote-client'; ``` ```ts export interface StreamCommandResult { exitCode: number; output: string; } ``` --- > Source: https://loopstack.ai/llms/reference/api/remote-file-explorer.md --- title: 'API: @loopstack/remote-file-explorer' description: 'Public API reference for @loopstack/remote-file-explorer' includeInLlmsFullTxt: false --- # API: @loopstack/remote-file-explorer ## Classes ### RemoteFileExplorerModule NestJS module that provides REST endpoints for browsing the file tree and reading file contents of a remote workspace (`RemoteFileExplorerController`), proxying requests to the remote agent via `RemoteClient`. Registration: - `RemoteFileExplorerModule` — bare import. Enough when no feature-flag scoping is needed: the controller is wired up and the endpoints go live. - `RemoteFileExplorerModule.forFeature(config?: { enabled?: boolean; environments?: string[] })` — use to register it as a Studio feature flag and optionally restrict it to specific environment names. Requires: `RemoteClient` and `EnvironmentService` from `@loopstack/remote-client` must be available in the DI container — import `RemoteClientModule` in a parent module. The remote agent URL is resolved at runtime; no environment variables are required by this module itself. ```ts import { RemoteFileExplorerModule } from '@loopstack/remote-file-explorer'; ``` ```ts export class RemoteFileExplorerModule { static forFeature(config?: { enabled?: boolean; environments?: string[] }): DynamicModule; } ``` --- > Source: https://loopstack.ai/llms/reference/api/secrets.md --- title: 'API: @loopstack/secrets' description: 'Public API reference for @loopstack/secrets' includeInLlmsFullTxt: false --- # API: @loopstack/secrets ## Classes ### GetSecretKeysTool Tool that returns the secret keys available in the current workspace without exposing their values. ```ts import { GetSecretKeysTool } from '@loopstack/secrets'; ``` **Provided by:** `SecretsModule` ```ts export class GetSecretKeysTool extends BaseTool { protected handle(_args: object | undefined, ctx: RunContext): Promise>; } ``` ### RequestSecretsTask Tool that requests secrets from the user by launching `SecretsRequestWorkflow` as a callback-driven sub-workflow; it completes once the user has submitted the form. ```ts import { RequestSecretsTask } from '@loopstack/secrets'; ``` **Provided by:** `SecretsModule` ```ts export class RequestSecretsTask extends BaseTool { constructor(secretsRequestWorkflow: SecretsRequestWorkflow); protected handle( args: RequestSecretsTaskInput, ctx: RunContext, options?: ToolCallOptions, ): Promise>; complete(_result: Record): Promise>; } ``` ### SecretRequestDocument Document that renders the secrets request form in Studio, listing the secret keys the user is asked to provide values for. ```ts import { SecretRequestDocument } from '@loopstack/secrets'; ``` ```ts export class SecretRequestDocument { variables?: { key: string; value?: string; }[]; } ``` ### SecretService Service that performs workspace-scoped CRUD on secrets — find, create, update, upsert, and delete; inject it to read or write secret values programmatically from backend code. It also resolves the effective env for a workspace, overlaying the module's configured global fallback keys (from `process.env`) with the workspace's own secrets — see `SecretsModuleConfig`. ```ts import { SecretService } from '@loopstack/secrets'; ``` **Provided by:** `SecretsModule` ```ts export class SecretService { constructor(secretRepository: Repository, config: SecretsModuleConfig); findAllByWorkspace(workspaceId: string): Promise; resolveEnv(workspaceId: string): Promise; resolveEnvMap(workspaceId: string): Promise>; resolveKeys(workspaceId: string): Promise; create( workspaceId: string, data: { key: string; value: string; }, ): Promise; update( id: string, workspaceId: string, data: { value?: string; }, ): Promise; upsert( workspaceId: string, data: { key: string; value: string; }, ): Promise; delete(id: string, workspaceId: string): Promise; } ``` ### SecretsModule NestJS module that provides workspace-scoped secrets storage — the `SecretEntity`, `SecretService`, `SecretController` REST API, the `get_secret_keys` / `request_secrets_task` tools, `SecretsRequestWorkflow`, and `SecretRequestDocument`. Registration: - `SecretsModule` — bare import registers the global root with the default (empty) config; use when you don't need the feature toggle or a global-secret allowlist. - `SecretsModule.forRoot(config)` — sets the app-wide default `SecretsModuleConfig` (e.g. the global-secret allowlist read by `SecretService`). Import once at the root. - `SecretsModule.forFeature(config)` — registers the `secrets` Studio feature and overrides the config for this module's `SecretService` / `get_secret_keys` — so different modules can declare different global-secret allowlists. Requires: a configured database — your root `TypeOrmModule.forRoot()` must include `SecretEntity` (the module registers it via `TypeOrmModule.forFeature` internally, but the connection and schema must exist). ```ts import { SecretsModule } from '@loopstack/secrets'; ``` ```ts export class SecretsModule { static forRoot(config?: SecretsModuleConfig): DynamicModule; static forFeature(config?: SecretsModuleConfig): DynamicModule; } ``` ### SecretsRequestWorkflow Workflow that presents a secrets request form to the user and waits for submission, completing once the user has entered and stored the requested secret values. ```ts import { SecretsRequestWorkflow } from '@loopstack/secrets'; ``` **Provided by:** `SecretsModule` ```ts export class SecretsRequestWorkflow extends BaseWorkflow { showForm(state: SecretsRequestState, ctx: RunContext): Promise; secretsSubmitted(_state: SecretsRequestState): void; } ``` ## Interfaces ### SecretsModuleConfig Configuration for `SecretsModule.forRoot` / `SecretsModule.forFeature`. ```ts import { SecretsModuleConfig } from '@loopstack/secrets'; ``` ```ts export interface SecretsModuleConfig { enabled?: boolean; globalSecretKeys?: string[]; } ``` ## Type Aliases ### GetSecretKeysResult Result for `get_secret_keys` — one entry per available key with a `hasValue` flag (never the value) and a `global` flag marking keys that resolve from the global fallback rather than a workspace secret. ```ts import { GetSecretKeysResult } from '@loopstack/secrets'; ``` ```ts export type GetSecretKeysResult = { key: string; hasValue: boolean; global: boolean; }[]; ``` ### RequestSecretsTaskResult Result for `request_secrets_task` — the launched sub-workflow's id while pending, or a confirmation string once the user has stored the secrets. ```ts import { RequestSecretsTaskResult } from '@loopstack/secrets'; ``` ```ts export type RequestSecretsTaskResult = | { workflowId: string; } | string; ``` ## Functions ### formatResolvedSecretsMessage A one-line, user-facing summary of a `ResolvedWorkspaceEnv` — which injected secret keys came from the workspace vs the global fallback — for surfacing the secret sources to the user in a workflow message. Returns null when nothing was injected. ```ts import { formatResolvedSecretsMessage } from '@loopstack/secrets'; ``` ```ts export function formatResolvedSecretsMessage({ workspaceKeys, globalKeys }: ResolvedWorkspaceEnv): string | null; ``` ## Variables ### GetSecretKeysResultSchema Zod schema for `GetSecretKeysResult` — the `resultSchema` of `get_secret_keys`. ```ts import { GetSecretKeysResultSchema } from '@loopstack/secrets'; ``` ```ts GetSecretKeysResultSchema: z.ZodArray< z.ZodObject< { key: z.ZodString; hasValue: z.ZodBoolean; global: z.ZodBoolean; }, z.core.$strict > >; ``` ### RequestSecretsTaskResultSchema Zod schema for `RequestSecretsTaskResult` — the confirmation string returned once the user has stored the secrets. ```ts import { RequestSecretsTaskResultSchema } from '@loopstack/secrets'; ``` ```ts RequestSecretsTaskResultSchema: z.ZodString; ``` ### SecretRequestDocumentSchema Zod schema for the secrets request form document — a list of variables, each with a `key` and an optional `value`. ```ts import { SecretRequestDocumentSchema } from '@loopstack/secrets'; ``` ```ts SecretRequestDocumentSchema: z.ZodObject< { variables: z.ZodOptional< z.ZodArray< z.ZodObject< { key: z.ZodString; value: z.ZodOptional; }, z.core.$strip > > >; }, z.core.$strict >; ``` --- > Source: https://loopstack.ai/llms/reference/api/web.md --- title: 'API: @loopstack/web' description: 'Public API reference for @loopstack/web' includeInLlmsFullTxt: false --- # API: @loopstack/web ## Classes ### WebFetchTool Tool that fetches a URL, converts HTML to Markdown, and optionally summarizes the content through the configured LLM provider (model `claude-haiku-4-5-20251001` by default). A summarized result carries the provider, model and token usage as `LlmResultMeta`. ```ts import { WebFetchTool } from '@loopstack/web'; ``` **Provided by:** `WebModule` ```ts export class WebFetchTool extends BaseTool> { protected handle(args: WebFetchArgs, ctx: RunContext): Promise>>; } ``` ### WebModule NestJS module that provides the `web_fetch` tool (`WebFetchTool`) and its supporting services — fetches a URL, converts HTML to Markdown, and optionally summarizes the content with the configured LLM provider. Registration: - `WebModule` — bare import; registers the `WebFetchTool` and the fetcher, Markdown, and summarizer services. There are no static configuration methods. Requires: `LlmProviderModule` imported alongside it (the summarizer resolves its provider from the global `LlmProviderRegistry`). The optional summarization step (triggered when a `prompt` arg is passed) also needs a provider module such as `ClaudeModule` or `OpenAiModule` and its API key. It uses the tool's `provider` arg, else the `LlmProviderModule` default provider, else `claude`, and 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`. ```ts import { WebModule } from '@loopstack/web'; ``` ```ts export class WebModule {} ``` ## Interfaces ### WebFetchResult Result for `WebFetchTool` — the fetched URL, response metadata, the Markdown or summarized content, and optional redirect details. ```ts import { WebFetchResult } from '@loopstack/web'; ``` ```ts export interface WebFetchResult { url: string; bytes: number; code: number; codeText: string; contentType: string; result: string; truncated: boolean; cached: boolean; durationMs: number; redirect?: { originalUrl: string; redirectUrl: string; statusCode: number; }; } ``` ## Type Aliases ### WebFetchArgs Args for `WebFetchTool`. ```ts import { WebFetchArgs } from '@loopstack/web'; ``` ```ts export type WebFetchArgs = z.infer; ``` ## Variables ### WebFetchResultSchema Zod schema for `WebFetchResult`. ```ts import { WebFetchResultSchema } from '@loopstack/web'; ``` ```ts WebFetchResultSchema: z.ZodObject< { url: z.ZodString; bytes: z.ZodNumber; code: z.ZodNumber; codeText: z.ZodString; contentType: z.ZodString; result: z.ZodString; truncated: z.ZodBoolean; cached: z.ZodBoolean; durationMs: z.ZodNumber; redirect: z.ZodOptional< z.ZodObject< { originalUrl: z.ZodString; redirectUrl: z.ZodString; statusCode: z.ZodNumber; }, z.core.$strict > >; }, z.core.$strict >; ``` ### WebFetchSchema Zod schema for `WebFetchTool` arguments. ```ts import { WebFetchSchema } from '@loopstack/web'; ``` ```ts WebFetchSchema: z.ZodObject< { url: z.ZodURL; prompt: z.ZodOptional; provider: z.ZodOptional; model: z.ZodOptional; envApiKey: z.ZodOptional; maxTokens: z.ZodOptional; }, z.core.$strict >; ``` ---