### Quick Start: OpenCode Agent Session Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/README.md Shows how to establish a session with the OpenCode provider. This example includes configuring connection options like `baseUrl` for a local server or omitting it to start an embedded server. It follows the standard pattern of creating an agent, session, prompting, and disposing. ```typescript import { createAgent } from "@omni-agent-sdk/provider-opencode"; const agent = createAgent({ model: "anthropic/claude-opus-4-6", providerOptions: { baseUrl: "http://localhost:4096", // connect to a running OpenCode server }, }); const session = await agent.createSession({ cwd: process.cwd() }); const result = await session.prompt({ message: "What is a monorepo?" }); console.log(result.text); await session.dispose(); await agent.dispose(); ``` -------------------------------- ### Install Workspace Dependencies Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/examples/README.md Installs all necessary dependencies for the project. This command should be run from the repository's root directory. ```bash pnpm install ``` -------------------------------- ### Run Basic Prompt Example with Codex Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/examples/README.md Executes the `basic-prompt.ts` example using the Codex provider. Requires the `OPENAI_API_KEY` environment variable to be set. ```bash OPENAI_API_KEY=sk-... npx tsx examples/basic-prompt.ts codex ``` -------------------------------- ### Run Basic Prompt Example with Provider Env Var Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/examples/README.md Executes the `basic-prompt.ts` example, setting the provider dynamically via the `PROVIDER` environment variable. Requires the corresponding API key environment variable to be set. ```bash PROVIDER=codex OPENAI_API_KEY=sk-... npx tsx examples/basic-prompt.ts ``` -------------------------------- ### Type-Check Examples Only Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/examples/README.md Checks only the TypeScript files within the `examples` directory. This is faster if the providers have already been built. ```bash cd examples && npx tsc --noEmit ``` -------------------------------- ### Run Basic Prompt Example with Claude Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/examples/README.md Executes the `basic-prompt.ts` example using the Claude provider. Requires the `ANTHROPIC_API_KEY` environment variable to be set. ```bash ANTHROPIC_API_KEY=sk-ant-... npx tsx examples/basic-prompt.ts ``` -------------------------------- ### Type-Check Project and Examples Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/examples/README.md Performs type-checking for the entire project, including building providers first. This ensures code quality and adherence to TypeScript standards. ```bash pnpm check ``` -------------------------------- ### Basic Agent and Prompting in TypeScript Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/examples/README.md Demonstrates the fundamental workflow of creating an agent, initiating a session, sending a prompt, and printing the response using the omni-agent-sdk. ```typescript import { requireEnv, resolveProvider, createProviderAgent, printEvent, } from "./_helpers.ts"; const provider = resolveProvider(); const agent = await createProviderAgent({ provider }); const session = agent.newSession(); const response = await session.prompt("Create agent → session → prompt → print"); printEvent(response); ``` -------------------------------- ### Install Omni-Agent SDK Providers Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/README.md Installs the necessary packages for the Omni-Agent SDK, including core types and specific provider adapters for Claude, Codex, and OpenCode. Each provider requires its own SDK package and the corresponding adapter. ```bash # Claude provider npm install @omni-agent-sdk/provider-claude @anthropic-ai/claude-agent-sdk # Codex provider npm install @omni-agent-sdk/provider-codex @openai/codex-sdk # OpenCode provider npm install @omni-agent-sdk/provider-opencode @opencode-ai/sdk # Core types and AgentManager only (no provider required) npm install @omni-agent-sdk/core ``` -------------------------------- ### Aborting Prompts and Sessions in TypeScript Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/examples/README.md Demonstrates how to use `AbortController` to cancel ongoing prompts or entire sessions using `prompt()` and `session.abort()`. ```typescript import { AbortController, requireEnv, resolveProvider, createProviderAgent, printEvent, } from "./_helpers.ts"; const provider = resolveProvider(); const agent = await createProviderAgent({ provider }); const session = agent.newSession(); const controller = new AbortController(); // Abort a prompt session.prompt("Long running task", { signal: controller.signal }); setTimeout(() => controller.abort(), 1000); // Abort the entire session setTimeout(() => session.abort(), 2000); ``` -------------------------------- ### Session Management: Resume by ID and List Sessions in TypeScript Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/examples/README.md Demonstrates how to manage agent sessions, including resuming a session using its unique ID and listing all available sessions. ```typescript import { requireEnv, resolveProvider, createProviderAgent, printEvent, } from "./_helpers.ts"; const provider = resolveProvider(); const agent = await createProviderAgent({ provider }); // Create a new session const initialSession = agent.newSession(); const sessionId = initialSession.id; await initialSession.prompt("Initial prompt"); // Resume session by ID const resumedSession = await agent.resumeSession(sessionId); await resumedSession.prompt("Continuing the conversation"); // List all sessions const sessions = await agent.listSessions(); console.log("Available sessions:", sessions); ``` -------------------------------- ### MCP Server Configuration (stdio + URL) in TypeScript Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/examples/README.md Configures and interacts with an MCP (Multi-Channel Protocol) server, supporting both standard input/output (stdio) and URL-based communication. ```typescript import { requireEnv, resolveProvider, createProviderAgent, printEvent, } from "./_helpers.ts"; const provider = resolveProvider(); const agent = await createProviderAgent({ provider }); // MCP server config (stdio + URL) const mcpConfig = { stdio: true, // Use stdio for communication url: "http://localhost:8080", // Optional URL }; const session = agent.newSession({ mcpConfig }); const response = await session.prompt("Communicate via MCP server"); printEvent(response); ``` -------------------------------- ### Real-time Event Streaming in TypeScript Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/examples/README.md Shows how to process `OmniEvent` objects in real-time as they are generated by the agent using the `promptStreaming()` method. ```typescript import { requireEnv, resolveProvider, createProviderAgent, printEvent, } from "./_helpers.ts"; const provider = resolveProvider(); const agent = await createProviderAgent({ provider }); const session = agent.newSession(); for await (const event of session.promptStreaming("Real-time `OmniEvent` iteration via `promptStreaming()`")) { printEvent(event); } ``` -------------------------------- ### Multi-Turn Conversation Memory in TypeScript Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/examples/README.md Illustrates how to maintain conversation history across multiple prompts within a single session, enabling multi-turn interactions. ```typescript import { requireEnv, resolveProvider, createProviderAgent, printEvent, } from "./_helpers.ts"; const provider = resolveProvider(); const agent = await createProviderAgent({ provider }); const session = agent.newSession(); await session.prompt("First prompt"); await session.prompt("Second prompt"); const response = await session.prompt("Third prompt"); printEvent(response); ``` -------------------------------- ### Provider-Specific Options in TypeScript Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/examples/README.md Utilizes `providerOptions` to pass configuration specific to individual providers like Claude and Codex, enabling access to their unique features. ```typescript import { requireEnv, resolveProvider, createProviderAgent, printEvent, } from "./_helpers.ts"; const provider = resolveProvider(); let agent; if (provider === "claude") { agent = await createProviderAgent({ provider, providerOptions: { claude: { model: "claude-3-opus-20240229", // Other Claude-specific options }, }, }); } else if (provider === "codex") { agent = await createProviderAgent({ provider, providerOptions: { codex: { model: "davinci-002", // Other Codex-specific options }, }, }); } else { throw new Error("Unsupported provider"); } const session = agent.newSession(); const response = await session.prompt("Provider-specific prompt"); printEvent(response); ``` -------------------------------- ### Configure OpenCode Agent (Embedded Mode) (TypeScript) Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/docs/provider-options.md Demonstrates configuring an OpenCode agent in embedded mode using `OpenCodeAgentConfig`. This setup starts a local OpenCode server automatically and allows customization of `hostname`, `port`, and `timeout`. ```typescript import { createAgent } from "@omni-agent-sdk/provider-opencode"; import type { OpenCodeAgentConfig } from "@omni-agent-sdk/provider-opencode"; // Embedded mode: start a local OpenCode server automatically (omit baseUrl) const embeddedConfig: OpenCodeAgentConfig = { model: "anthropic/claude-opus-4-6", providerOptions: { hostname: "127.0.0.1", port: 4096, timeout: 10_000, }, }; const agent = createAgent(embeddedConfig); ``` -------------------------------- ### Quick Start: Claude Agent Session Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/README.md Demonstrates how to create and use an agent session with the Claude provider. It initializes an agent, creates a session, sends a prompt, and then disposes of the session and agent. Requires ANTHROPIC_API_KEY to be set. ```typescript import { createAgent } from "@omni-agent-sdk/provider-claude"; const agent = createAgent({ model: "claude-opus-4-6", permissions: "auto-approve", }); const session = await agent.createSession({ cwd: process.cwd() }); const result = await session.prompt({ message: "What is a monorepo?" }); console.log(result.text); await session.dispose(); await agent.dispose(); ``` -------------------------------- ### Quick Start: Codex Agent Session Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/README.md Illustrates how to create and interact with a session using the Codex provider. This involves agent creation, session initiation, sending a prompt, and cleaning up resources. Requires OPENAI_API_KEY to be set. ```typescript import { createAgent } from "@omni-agent-sdk/provider-codex"; const agent = createAgent({ model: "o3", permissions: "auto-approve", }); const session = await agent.createSession({ cwd: process.cwd() }); const result = await session.prompt({ message: "What is a monorepo?" }); console.log(result.text); await session.dispose(); await agent.dispose(); ``` -------------------------------- ### Provider-Agnostic Agent and Session Handling in TypeScript Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/examples/README.md Demonstrates using `OmniAgent` and `OmniSession` types, allowing providers to be swapped at runtime without changing the core logic. ```typescript import { requireEnv, resolveProvider, createProviderAgent, printEvent, } from "./_helpers.ts"; const provider = resolveProvider(); // Type as OmniAgent/OmniSession, swap providers at runtime const agent = await createProviderAgent({ provider }); const session = agent.newSession(); const response = await session.prompt("Provider-agnostic example"); printEvent(response); ``` -------------------------------- ### Structured Output with JSON Schema in TypeScript Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/examples/README.md Defines a JSON schema for the expected output and uses `outputSchema` to ensure the agent returns a typed, structured response. ```typescript import { requireEnv, resolveProvider, createProviderAgent, printEvent, } from "./_helpers.ts"; const provider = resolveProvider(); const agent = await createProviderAgent({ provider }); const session = agent.newSession(); const response = await session.prompt("Generate structured output", { outputSchema: { type: "object", properties: { name: { type: "string" }, age: { type: "number" }, }, required: ["name", "age"], }, }); // The response will be typed according to the schema const data = response.data as { name: string; age: number; }; console.log(`Name: ${data.name}, Age: ${data.age}`); ``` -------------------------------- ### Budget and Turn Limits in TypeScript Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/examples/README.md Configures and enforces limits on agent and prompt execution, including maximum budget in USD (`maxBudgetUsd`) and maximum number of turns (`maxTurns`). ```typescript import { requireEnv, resolveProvider, createProviderAgent, printEvent, } from "./_helpers.ts"; const provider = resolveProvider(); const agent = await createProviderAgent({ provider, maxBudgetUsd: 0.1, // Limit agent budget }); const session = agent.newSession({ maxTurns: 5, // Limit session turns }); try { await session.prompt("This prompt respects budget and turn limits", { maxBudgetUsd: 0.05, // Limit prompt budget maxTurns: 2, // Limit prompt turns }); } catch (err) { console.error("Error during limited execution:", err); } ``` -------------------------------- ### Configure Stdio MCP Server for Filesystem Access (TypeScript) Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/docs/configuration.md Shows how to configure a Model Context Protocol (MCP) server for filesystem operations using a stdio-based executable. This example sets up an MCP server named 'filesystem' using `npx` to run the `@modelcontextprotocol/server-filesystem` package. ```typescript const agent = createAgent({ mcpServers: { filesystem: { command: "npx", args: ["-y", "@modelcontextprotocol/server-filesystem", "/my/project"], env: { MCP_LOG_LEVEL: "error" }, }, }, }); ``` -------------------------------- ### Setup Agent Manager and Register Agents Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/docs/agent-manager.md Initializes the AgentManager and registers multiple agents (e.g., Claude, Codex) with specific configurations. The first registered agent becomes the default. ```typescript import { AgentManager } from "@omni-agent-sdk/core"; import { createAgent as createClaudeAgent } from "@omni-agent-sdk/provider-claude"; import { createAgent as createCodexAgent } from "@omni-agent-sdk/provider-codex"; const manager = new AgentManager(); manager.register("claude", createClaudeAgent({ model: "claude-opus-4-6", permissions: "auto-approve", })); manager.register("codex", createCodexAgent({ model: "o3", permissions: "auto-approve", })); ``` -------------------------------- ### Error Handling with OmniAgentError in TypeScript Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/examples/README.md Shows how to catch and handle various errors like `OmniAgentError`, `AbortError`, and `BudgetExceededError`, inspecting the `err.code` for specific error types. ```typescript import { OmniAgentError, AbortError, BudgetExceededError, requireEnv, resolveProvider, createProviderAgent, printEvent, } from "./_helpers.ts"; const provider = resolveProvider(); const agent = await createProviderAgent({ provider }); const session = agent.newSession(); try { await session.prompt("This might cause an error"); } catch (err) { if (err instanceof OmniAgentError) { console.error(`OmniAgentError: ${err.message}, Code: ${err.code}`); } else if (err instanceof AbortError) { console.error("Request aborted."); } else if (err instanceof BudgetExceededError) { console.error("Budget exceeded."); } else { console.error("An unexpected error occurred:", err); } } ``` -------------------------------- ### Custom Tool Permissions in TypeScript Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/examples/README.md Implements custom permission logic for tools using `OmniPermissionPolicy` and the `canUseTool` callback, allowing fine-grained control over tool usage. ```typescript import { OmniPermissionPolicy, requireEnv, resolveProvider, createProviderAgent, printEvent, } from "./_helpers.ts"; const provider = resolveProvider(); const agent = await createProviderAgent({ provider }); const customPolicy: OmniPermissionPolicy = { canUseTool: async (tool, session) => { // Custom logic to determine if a tool can be used console.log(`Checking permission for tool: ${tool.name}`); return true; // Allow usage }, }; const session = agent.newSession({ permissionPolicy: customPolicy }); await session.prompt("Use a tool with custom permissions", { tools: [ { name: "myTool", description: "A sample tool", parameters: { type: "object", properties: {} }, func: async () => "Tool result", }, ], }); ``` -------------------------------- ### session.prompt - Send Prompt and Get Response Source: https://context7.com/thegoateddev/omni-agent-sdk/llms.txt Sends a prompt message to the AI agent and returns a complete response, including text, messages, token usage, and optional structured output. ```APIDOC ## session.prompt - Send Prompt and Get Response ### Description Sends a prompt message to the AI agent and returns a complete response. The `PromptResult` includes the final text, all conversation messages, token usage statistics, and optional structured output. ### Method `session.prompt(options: PromptOptions): Promise` ### Parameters #### PromptOptions - **message** (string) - Required - The user's message or prompt. - **model** (string) - Optional - Override the default model for this prompt. - **systemPrompt** (string) - Optional - Override the system prompt for this prompt. - **maxTurns** (number) - Optional - Override the maximum turns for this prompt. - **maxBudgetUsd** (number) - Optional - Override the maximum budget for this prompt. - **signal** (AbortSignal) - Optional - An AbortSignal to cancel the request. ### Request Example ```typescript import { createAgent } from "@omni-agent-sdk/provider-claude"; const agent = createAgent({ model: "claude-opus-4-6", permissions: "auto-approve", }); const session = await agent.createSession({ cwd: process.cwd() }); // Basic prompt const result = await session.prompt({ message: "Explain what a monorepo is in two sentences.", }); console.log(result.text); console.log(`Session: ${result.sessionId}`); console.log(`Tokens: ${result.usage.tokens?.total}`); console.log(`Cost: $${result.usage.totalCostUsd?.toFixed(4)}`); console.log(`Is Error: ${result.isError}`); // Prompt with options const controller = new AbortController(); setTimeout(() => controller.abort(), 30_000); const resultWithOptions = await session.prompt({ message: "Summarize the file at src/index.ts.", model: "claude-sonnet-4-20250514", // override model systemPrompt: "Be concise.", maxTurns: 3, maxBudgetUsd: 0.50, signal: controller.signal, }); await session.dispose(); await agent.dispose(); ``` ### Response #### Success Response (200) - **PromptResult** (object) - **text** (string) - The AI's response text. - **sessionId** (string) - The ID of the session. - **usage** (object) - Token and cost usage statistics. - **tokens** (object) - Token usage details. - **total** (number) - Total tokens used. - **totalCostUsd** (number) - Total cost in USD. - **isError** (boolean) - Indicates if an error occurred during the prompt. - **messages** (array) - Array of all messages in the conversation. - **structuredOutput** (any) - Optional structured output from the AI. ``` -------------------------------- ### Configure HTTP/SSE MCP Server (TypeScript) Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/docs/configuration.md Demonstrates configuring a remote MCP server using its URL. This example sets up an MCP server named 'remote' that connects to a specified HTTP/SSE endpoint. ```typescript const agent = createAgent({ mcpServers: { remote: { url: "https://my-mcp-host.example.com/sse", }, }, }); ``` -------------------------------- ### Streaming API - Getting the Final Result Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/docs/streaming.md Explains how to retrieve the complete prompt result after iterating through the stream or by calling result() directly. ```APIDOC ## Streaming API - Getting the Final Result ### Description After processing the stream of events, you can obtain the final `PromptResult` which contains the complete text and usage information. This can be done by calling `stream.result()` after the iteration or by calling it directly on the stream object, which will consume the stream internally. ### Method (N/A - This is a method on the `OmniStream` object) ### Endpoint (N/A - This is a method on the `OmniStream` object) ### Parameters (N/A - This is a method on the `OmniStream` object) ### Request Example ```typescript await using stream = session.promptStreaming({ message: "Hello" }); for await (const event of stream) { // process events } const result = await stream.result(); console.log(result.text); console.log(`Tokens: ${result.usage.tokens?.total}`); ``` ### Response #### Success Response (200) Returns a `PromptResult` object containing: - **text** (string): The complete generated text. - **usage** (OmniUsage): Information about token usage. #### Response Example ```json { "text": "Hello!", "usage": { "tokens": { "prompt": 10, "completion": 5, "total": 15 } } } ``` ``` -------------------------------- ### Configure Prompt Input with PromptInput in TypeScript Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/docs/configuration.md The `PromptInput` interface allows overriding agent-level configurations for a single prompt. It accepts parameters like `message`, `model`, `systemPrompt`, `outputSchema`, `maxTurns`, `maxBudgetUsd`, `signal`, and `providerOptions`. The example demonstrates setting a user message, a maximum number of turns, and an abort signal for a prompt. ```typescript const controller = new AbortController(); setTimeout(() => controller.abort(), 30_000); const result = await session.prompt({ message: "Summarize the file at src/index.ts.", maxTurns: 3, signal: controller.signal, }); ``` -------------------------------- ### Configure Codex Agent with Provider Options (TypeScript) Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/docs/provider-options.md Illustrates configuring a Codex agent using `CodexAgentConfig` from `@omni-agent-sdk/provider-codex`. This example includes setting `approvalPolicy`, `modelReasoningEffort`, and `skipGitRepoCheck` for tailored Codex behavior. ```typescript import { createAgent } from "@omni-agent-sdk/provider-codex"; import type { CodexAgentConfig } from "@omni-agent-sdk/provider-codex"; const config: CodexAgentConfig = { model: "o3", permissions: "auto-approve", providerOptions: { approvalPolicy: "never", modelReasoningEffort: "medium", skipGitRepoCheck: true, }, }; const agent = createAgent(config); ``` -------------------------------- ### Send Prompt and Get Response with session.prompt (TypeScript) Source: https://context7.com/thegoateddev/omni-agent-sdk/llms.txt The `prompt` method on a session instance sends a message to the AI agent and returns a complete response. The response includes the final text, conversation history, token usage statistics, and optional structured output. This method can also accept options to override default agent settings for a specific prompt. ```typescript import { createAgent } from "@omni-agent-sdk/provider-claude"; const agent = createAgent({ model: "claude-opus-4-6", permissions: "auto-approve", }); const session = await agent.createSession({ cwd: process.cwd() }); // Basic prompt const result = await session.prompt({ message: "Explain what a monorepo is in two sentences.", }); console.log(result.text); console.log(`Session: ${result.sessionId}`); console.log(`Tokens: ${result.usage.tokens?.total}`); console.log(`Cost: $${result.usage.totalCostUsd?.toFixed(4)}`); console.log(`Is Error: ${result.isError}`); // Prompt with options const controller = new AbortController(); setTimeout(() => controller.abort(), 30_000); const resultWithOptions = await session.prompt({ message: "Summarize the file at src/index.ts.", model: "claude-sonnet-4-20250514", // override model systemPrompt: "Be concise.", maxTurns: 3, maxBudgetUsd: 0.50, signal: controller.signal, }); await session.dispose(); await agent.dispose(); ``` -------------------------------- ### Configure Session Creation with CreateSessionOptions in TypeScript Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/docs/configuration.md The `CreateSessionOptions` interface is used when creating a new agent session via `agent.createSession()`. It allows overriding agent-level settings such as the working directory (`cwd`) and provider-specific options. The example shows how to specify a custom working directory for a new session. ```typescript const session = await agent.createSession({ cwd: "/my/project", }); ``` -------------------------------- ### Create Omni Agent with Basic Configuration (TypeScript) Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/docs/configuration.md Demonstrates how to create an agent instance using `createAgent` with essential configuration options like model, permissions, working directory, system prompt, budget, and tool restrictions. ```typescript import { createAgent } from "@omni-agent-sdk/provider-claude"; const agent = createAgent({ model: "claude-opus-4-6", permissions: "auto-approve", cwd: "/my/project", systemPrompt: "You are a senior TypeScript engineer.", maxBudgetUsd: 2.00, maxTurns: 10, tools: { disallowed: ["bash"] }, }); ``` -------------------------------- ### Streaming API - Basic Usage Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/docs/streaming.md Demonstrates the basic usage of promptStreaming() to iterate over events and process text deltas as they arrive. ```APIDOC ## POST /api/prompt/stream ### Description Initiates a streaming session to receive real-time events from the agent as a response is generated. This allows for processing text chunks, tool calls, and other events as they occur. ### Method POST ### Endpoint `/api/prompt/stream` ### Parameters #### Request Body - **message** (string) - Required - The user's message or prompt to send to the agent. - **signal** (AbortSignal) - Optional - An AbortSignal to cancel the stream. ### Request Example ```json { "message": "Count from 1 to 5." } ``` ### Response #### Success Response (200) Returns an `OmniStream` object, which is an async iterable of `OmniEvent` objects. **Event Types:** - `text_delta`: A chunk of generated text. - `tool_start`: The agent is about to call a tool. - `tool_end`: A tool call completed (or failed). - `message_start`: A new message has started. - `message_end`: A message completed. - `turn_start`: An agentic turn has started. - `turn_end`: A turn finished. - `error`: The provider reported an error mid-stream. #### Response Example (This is an example of how to consume the stream, not a direct response body) ```typescript await using stream = session.promptStreaming({ message: "Count from 1 to 5." }); for await (const event of stream) { if (event.type === "text_delta") { process.stdout.write(event.text); } } ``` ``` -------------------------------- ### Configure MCP Servers for Omni Agent SDK (TypeScript) Source: https://context7.com/thegoateddev/omni-agent-sdk/llms.txt Demonstrates how to configure Model Context Protocol (MCP) servers for the Omni Agent SDK. This includes setting up both stdio-based local servers using child processes and remote servers via HTTP/SSE endpoints. The configuration is then applied when creating an agent, allowing it to utilize tools provided by these MCP servers. ```typescript import type { OmniMcpServerConfig } from "@omni-agent-sdk/core"; import { createAgent } from "@omni-agent-sdk/provider-claude"; // stdio-based MCP server (spawned as child process) const filesystemServer: OmniMcpServerConfig = { command: "npx", args: ["-y", "@modelcontextprotocol/server-filesystem", process.cwd()], env: { MCP_LOG_LEVEL: "error", }, }; // URL-based MCP server (remote HTTP/SSE) const remoteServer: OmniMcpServerConfig = { url: "https://my-mcp-host.example.com/sse", }; const agent = createAgent({ model: "claude-opus-4-6", permissions: "auto-approve", mcpServers: { filesystem: filesystemServer, // remote: remoteServer, }, }); const session = await agent.createSession({ cwd: process.cwd() }); // Agent can now use tools from MCP servers const result = await session.prompt({ message: "Using filesystem tools, list files and count TypeScript files.", }); console.log(result.text); await session.dispose(); await agent.dispose(); ``` -------------------------------- ### Configure Provider-Specific Options for AI Agents (TypeScript) Source: https://context7.com/thegoateddev/omni-agent-sdk/llms.txt Illustrates how to pass provider-specific settings to different AI agents using the `providerOptions` object in the Omni Agent SDK. This allows for fine-tuning agent behavior beyond standard configurations, such as adjusting permission modes, enabling experimental features, or tuning reasoning effort. ```typescript import { createAgent as createClaudeAgent } from "@omni-agent-sdk/provider-claude"; import { createAgent as createCodexAgent } from "@omni-agent-sdk/provider-codex"; import { createAgent as createOpenCodeAgent } from "@omni-agent-sdk/provider-opencode"; // Claude with extended thinking and checkpointing const claudeAgent = createClaudeAgent({ model: "claude-opus-4-6", permissions: "auto-approve", providerOptions: { permissionMode: "acceptEdits", enableFileCheckpointing: true, betas: ["interleaved-thinking-2025-05-14"], }, }); // Codex with reasoning effort tuning const codexAgent = createCodexAgent({ model: "o3", permissions: "auto-approve", providerOptions: { approvalPolicy: "never", modelReasoningEffort: "high", skipGitRepoCheck: true, }, }); // OpenCode with embedded server const openCodeAgent = createOpenCodeAgent({ model: "anthropic/claude-opus-4-6", providerOptions: { hostname: "127.0.0.1", port: 4096, timeout: 10_000, agent: "coder", }, }); // Or connect to existing OpenCode server const openCodeClientAgent = createOpenCodeAgent({ model: "openai/gpt-4o", providerOptions: { baseUrl: "http://localhost:4096", }, }); ``` -------------------------------- ### Define OmniStream Interface Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/docs/api-reference.md Defines the `OmniStream` interface for handling streaming responses from the agent. It is an `AsyncDisposable` and provides an asynchronous iterator for events, a method to get the final result, and an abort function. ```typescript interface OmniStream extends AsyncDisposable { [Symbol.asyncIterator](): AsyncIterator; result(): Promise; abort(): Promise; } ``` -------------------------------- ### Register and Route Agents with AgentManager (TypeScript) Source: https://context7.com/thegoateddev/omni-agent-sdk/llms.txt Demonstrates how to register multiple AI agents with AgentManager, set a default agent, and route prompts either to the default or a specific agent. It requires the '@omni-agent-sdk/core' and provider-specific packages. ```typescript import { AgentManager } from "@omni-agent-sdk/core"; import { createAgent as createClaudeAgent } from "@omni-agent-sdk/provider-claude"; import { createAgent as createCodexAgent } from "@omni-agent-sdk/provider-codex"; const manager = new AgentManager(); // Register agents - first becomes default manager.register("claude", createClaudeAgent({ model: "claude-opus-4-6", permissions: "auto-approve", })); manager.register("codex", createCodexAgent({ model: "o3", permissions: "auto-approve", })); console.log(`Registered: ${manager.agentNames().join(", ")}`); // claude, codex console.log(`Default: ${manager.defaultAgentName}`); // claude // Default routing - uses current default agent const session1 = await manager.createSession({ cwd: process.cwd() }); const result1 = await session1.prompt({ message: "Hello from default!" }); console.log(result1.text); await session1.dispose(); // Explicit routing - specify agent by name const session2 = await manager.createSessionOn("codex", { cwd: process.cwd() }); const result2 = await session2.prompt({ message: "Hello from Codex!" }); console.log(result2.text); await session2.dispose(); // Change default at runtime manager.defaultAgentName = "codex"; // Iterate over all agents for (const [name, agent] of manager) { console.log(`${name}: provider=${agent.provider}`); } await manager.dispose(); // disposes all agents ``` -------------------------------- ### Stream Response Events with session.promptStreaming Source: https://context7.com/thegoateddev/omni-agent-sdk/llms.txt Demonstrates how to use `session.promptStreaming` to receive real-time event iteration for streaming output. It handles different event types like text deltas, tool usage, and errors, and retrieves the final result after streaming. ```typescript import { createAgent } from "@omni-agent-sdk/provider-claude"; const agent = createAgent({ model: "claude-opus-4-6", permissions: "auto-approve", }); const session = await agent.createSession({ cwd: process.cwd() }); // Stream with async iteration (ES2022 explicit resource management) await using stream = session.promptStreaming({ message: "Count from 1 to 5, pausing briefly between each number.", }); for await (const event of stream) { switch (event.type) { case "text_delta": process.stdout.write(event.text); break; case "tool_start": console.log(`\n[Tool Start] ${event.toolName}`); break; case "tool_end": console.log(`[Tool End] ${event.toolId} (error: ${event.isError})`); break; case "turn_end": console.log(`\n[Turn End] Tokens: ${event.usage?.tokens?.total}`); break; case "error": console.error(`[Error] ${event.error.message}`); break; } } // Get final result after streaming const result = await stream.result(); console.log(`\nFinal text: ${result.text}`); console.log(`Total tokens: ${result.usage.tokens?.total}`); await session.dispose(); await agent.dispose(); ``` -------------------------------- ### Get Final Prompt Result After Streaming in TypeScript Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/docs/streaming.md Shows how to iterate through a streaming response and then retrieve the complete `PromptResult` using `stream.result()`. This is useful for accessing final text and usage statistics after processing all events. ```typescript await using stream = session.promptStreaming({ message: "Hello" }); for await (const event of stream) { // process events } const result = await stream.result(); console.log(result.text); console.log(`Tokens: ${result.usage.tokens?.total}`); ``` -------------------------------- ### PromptInput Options Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/docs/configuration.md Options that can be passed to `session.prompt()` or `session.promptStreaming()` to override agent-level configurations for a single call. ```APIDOC ## PromptInput Options Per-prompt options passed to `session.prompt()` or `session.promptStreaming()`. These override the agent-level config for that single call. ### Parameters #### Request Body - **message** (string) - Required - The user message. - **model** (string) - Optional - Override the model for this prompt only. - **systemPrompt** (string) - Optional - Override the system prompt for this prompt only. - **outputSchema** (JsonSchema) - Optional - JSON schema for structured output. Parsed result available in `PromptResult.structuredOutput`. - **maxTurns** (number) - Optional - Override the turn limit for this prompt. - **maxBudgetUsd** (number) - Optional - Override the budget cap for this prompt. - **signal** (AbortSignal) - Optional - Standard Web API signal. Cancel the prompt by calling `controller.abort()`. - **providerOptions** (Record) - Optional - Provider-specific overrides for this prompt. ### Request Example ```typescript const controller = new AbortController(); setTimeout(() => controller.abort(), 30_000); const result = await session.prompt({ message: "Summarize the file at src/index.ts.", maxTurns: 3, signal: controller.signal, }); ``` ``` -------------------------------- ### session.prompt with outputSchema - Structured Output Source: https://context7.com/thegoateddev/omni-agent-sdk/llms.txt Request structured JSON responses by passing a JSON Schema to `outputSchema`. The parsed result is available in `result.structuredOutput`. ```APIDOC ## POST /session/prompt (with outputSchema) ### Description Sends a message to the agent and requests the response to be structured according to a provided JSON Schema. The parsed structured output is returned. ### Method POST ### Endpoint /session/prompt ### Parameters #### Query Parameters - **message** (string) - Required - The user's message or prompt. - **outputSchema** (JsonSchema) - Required - A JSON schema defining the desired output structure. ### Request Body ```json { "message": "string", "outputSchema": { ... } // Required JSON Schema } ``` ### Response #### Success Response (200) - **PromptResponse** - An object containing the agent's text response and the structured output. - **text** (string) - The text content of the agent's response. - **structuredOutput** (any) - The parsed structured output conforming to the `outputSchema`. - **usage** (object) - Token usage information. #### Response Example ```typescript import type { JsonSchema } from "@omni-agent-sdk/core"; interface LanguageList { languages: Array<{ name: string; year: number; paradigm: string }>; } const schema: JsonSchema = { type: "object", required: ["languages"], properties: { languages: { type: "array", description: "List of programming languages", items: { type: "object", required: ["name", "year", "paradigm"], properties: { name: { type: "string", description: "Language name" }, year: { type: "number", description: "Year created" }, paradigm: { type: "string", description: "Primary paradigm" }, }, }, }, }, }; const result = await session.prompt({ message: "Return exactly 3 well-known programming languages as JSON.", outputSchema: schema, }); const typed = result.structuredOutput as LanguageList; for (const lang of typed.languages) { console.log(`${lang.name} (${lang.year}) - ${lang.paradigm}`); } // Output: // JavaScript (1995) - multi-paradigm // Python (1991) - object-oriented // Rust (2010) - systems ``` ``` -------------------------------- ### Generic Fallback Execution Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/docs/agent-manager.md Demonstrates the `withFallback` method, which allows applying fallback logic to any asynchronous function, not just session creation. An optional order override can be provided. ```typescript const result = await manager.withFallback( (agent) => agent.createSession({ cwd: process.cwd() }), ["claude", "codex"] // optional order override ); ``` -------------------------------- ### Configure Claude Agent with Provider Options (TypeScript) Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/docs/provider-options.md Demonstrates how to configure a Claude agent using `ClaudeAgentConfig` from `@omni-agent-sdk/provider-claude`. It shows setting provider-specific options like `permissionMode`, `enableFileCheckpointing`, and `betas` for advanced features. ```typescript import { createAgent } from "@omni-agent-sdk/provider-claude"; import type { ClaudeAgentConfig } from "@omni-agent-sdk/provider-claude"; const config: ClaudeAgentConfig = { model: "claude-opus-4-6", permissions: "auto-approve", providerOptions: { permissionMode: "acceptEdits", enableFileCheckpointing: true, betas: ["interleaved-thinking-2025-05-14"], }, }; const agent = createAgent(config); ``` -------------------------------- ### session.prompt - Multi-Turn Conversations Source: https://context7.com/thegoateddev/omni-agent-sdk/llms.txt Sessions maintain conversation context across multiple `prompt()` calls, allowing the model to remember previous exchanges within the same session. ```APIDOC ## POST /session/prompt ### Description Sends a message to the agent and receives a response, maintaining conversation context for multi-turn dialogues. ### Method POST ### Endpoint /session/prompt ### Parameters #### Query Parameters - **message** (string) - Required - The user's message or prompt. - **outputSchema** (JsonSchema) - Optional - A JSON schema to structure the output. ### Request Body ```json { "message": "string", "outputSchema": { ... } // Optional JSON Schema } ``` ### Response #### Success Response (200) - **PromptResponse** - An object containing the agent's text response and potentially structured output. - **text** (string) - The text content of the agent's response. - **structuredOutput** (any) - The parsed structured output if `outputSchema` was provided. - **usage** (object) - Token usage information. #### Response Example ```typescript // Turn 1 - establish context const turn1 = await session.prompt({ message: "My name is Alice and I am learning TypeScript." }); console.log("Turn 1:", turn1.text); // Turn 2 - model recalls context const turn2 = await session.prompt({ message: "What is my name and what am I learning?" }); console.log("Turn 2:", turn2.text); // Output: "Your name is Alice and you are learning TypeScript." ``` ``` -------------------------------- ### Request Structured JSON Output with JSON Schema Source: https://context7.com/thegoateddev/omni-agent-sdk/llms.txt Shows how to request structured JSON responses by providing a JSON Schema to the `outputSchema` parameter. The parsed JSON output is accessible via `result.structuredOutput` and can be type-casted for easier use. ```typescript import type { JsonSchema } from "@omni-agent-sdk/core"; import { createAgent } from "@omni-agent-sdk/provider-claude"; interface LanguageList { languages: Array<{ name: string; year: number; paradigm: string; }>; } const schema: JsonSchema = { type: "object", required: ["languages"], properties: { languages: { type: "array", description: "List of programming languages", items: { type: "object", required: ["name", "year", "paradigm"], properties: { name: { type: "string", description: "Language name" }, year: { type: "number", description: "Year created" }, paradigm: { type: "string", description: "Primary paradigm" }, }, }, }, }, }; const agent = createAgent({ model: "claude-opus-4-6", permissions: "auto-approve", }); const session = await agent.createSession({ cwd: process.cwd() }); const result = await session.prompt({ message: "Return exactly 3 well-known programming languages as JSON.", outputSchema: schema, }); const typed = result.structuredOutput as LanguageList; for (const lang of typed.languages) { console.log(`${lang.name} (${lang.year}) - ${lang.paradigm}`); } // Output: // JavaScript (1995) - multi-paradigm // Python (1991) - object-oriented // Rust (2010) - systems await session.dispose(); await agent.dispose(); ``` -------------------------------- ### Configure OpenCode Agent (Client-Only Mode) (TypeScript) Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/docs/provider-options.md Shows how to configure an OpenCode agent in client-only mode using `OpenCodeAgentConfig` from `@omni-agent-sdk/provider-opencode`. This requires specifying the `baseUrl` of a running OpenCode server. ```typescript import { createAgent } from "@omni-agent-sdk/provider-opencode"; import type { OpenCodeAgentConfig } from "@omni-agent-sdk/provider-opencode"; // Client-only mode: connect to a running OpenCode server const config: OpenCodeAgentConfig = { model: "anthropic/claude-opus-4-6", providerOptions: { baseUrl: "http://localhost:4096", }, }; const agent = createAgent(config); ``` -------------------------------- ### Stream Prompt Response with TypeScript Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/docs/streaming.md Demonstrates basic usage of `promptStreaming()` to receive and process text delta events from an asynchronous stream. It utilizes ES2022 explicit resource management (`await using`) for automatic stream cleanup. ```typescript await using stream = session.promptStreaming({ message: "Count from 1 to 5." }); for await (const event of stream) { if (event.type === "text_delta") { process.stdout.write(event.text); } } ``` -------------------------------- ### OpenCode Model Format Specification (TypeScript) Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/docs/provider-options.md Explains the `"providerID/modelID -------------------------------- ### Define PromptInput Interface Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/docs/api-reference.md Defines the `PromptInput` interface for structuring input to the agent's prompt method. It includes the user's message, optional model, system prompt, output schema, turn limits, budget, and an abort signal. ```typescript interface PromptInput { message: string; model?: string; systemPrompt?: string; outputSchema?: JsonSchema; maxTurns?: number; maxBudgetUsd?: number; signal?: AbortSignal; providerOptions?: Record; } ``` -------------------------------- ### CreateSessionOptions Source: https://github.com/thegoateddev/omni-agent-sdk/blob/main/docs/configuration.md Options passed to `agent.createSession()` to override agent-level settings for a specific session. ```APIDOC ## CreateSessionOptions Passed to `agent.createSession()`. Overrides agent-level settings for this session only. ### Parameters #### Request Body - **cwd** (string) - Optional - Working directory. Overrides the agent-level `cwd`. - **providerOptions** (Record) - Optional - Provider-specific options for session creation. ### Request Example ```typescript const session = await agent.createSession({ cwd: "/my/project", }); ``` ```