### Quick Start: Define and Run an Agent Source: https://github.com/infinityi-mc/engine-lib/blob/main/README.md A basic example demonstrating how to define an agent with a mock provider and run it. This is useful for getting started quickly. ```typescript import { defineAgent, runAgent } from "@infinityi/engine-lib"; import { mockProvider, textResult } from "@infinityi/engine-lib/testing"; const agent = defineAgent({ name: "assistant", provider: mockProvider({ result: () => textResult("hello") }), }); const result = await runAgent(agent, { input: "Say hello." }); console.log(result.output); ``` -------------------------------- ### Full Configuration Example Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/configuration.md Demonstrates a comprehensive setup for an agent, including provider configuration with resilience (circuit breaker, retries), tool setup, agent definition, session creation, and run configuration with rate limiting and context window management. ```typescript import { defineAgent, createOpenAI, runAgent, createSession, tokenBucketRateLimiter, circuitBreaker, withProviderRetry, } from '@infinityi/engine-lib'; import { shellTools } from '@infinityi/engine-lib/tools-shell'; // Provider config const provider = createOpenAI({ apiKey: process.env.OPENAI_API_KEY!, model: 'gpt-4', timeout: 30000, }); // Provider resilience const resilientProvider = circuitBreaker( withProviderRetry(provider, { maxRetries: 3, backoffMs: (attempt) => Math.pow(2, attempt) * 100, }), { failureThreshold: 5, timeout: 60000, } ); // Tools config const { runCommand } = shellTools({ allowedCwds: [process.cwd()], policy: { deny: [/rm/, /sudo/] }, env: { allow: ['PATH', 'HOME'] }, }); // Agent config const agent = defineAgent({ name: 'terminal_assistant', provider: resilientProvider, instructions: 'You are a helpful terminal assistant.', tools: [runCommand], generationSettings: { temperature: 0.7, maxOutputTokens: 2048, }, }); // Session config const session = createSession({ id: 'user-session-123', metadata: { userId: 'user-123', title: 'Terminal session' }, }); // Rate limiter config const rateLimiter = tokenBucketRateLimiter({ capacity: 500000, refillRate: 100000, refillIntervalMs: 1000, }); // Run config const result = await runAgent(agent, { input: 'What files are in the current directory?', session, maxSteps: 10, maxHandoffs: 2, contextWindow: { strategy: 'truncate', maxTokens: 4096, reserve: 512, }, budget: { totalTokens: 10000, outputTokens: 5000, }, rateLimiter, signal: timeoutSignal, // AbortSignal for 5min timeout }); console.log(result.output); ``` -------------------------------- ### Complete Multi-Tool Agent Example Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/tools-packages.md Demonstrates the setup and execution of an agent equipped with shell, filesystem, HTTP, and web tools. Ensure your OPENAI_API_KEY environment variable is set. ```typescript import { defineAgent, createOpenAI, runAgent, s, defineTool, } from '@infinityi/engine-lib'; import { shellTools } from '@infinityi/engine-lib/tools-shell'; import { filesystemTools } from '@infinityi/engine-lib/tools-fs'; import { httpTools } from '@infinityi/engine-lib/tools-http'; import { webTools } from '@infinityi/engine-lib/tools-web'; // Create all tool packages const shell = shellTools({ allowedCwds: [process.cwd()], policy: { deny: [/sudo\b/, /\brm\b/] }, env: { allow: ['PATH', 'HOME', 'NODE_ENV'] }, }); const fs = filesystemTools({ allowedRoots: [process.cwd()], }); const http = httpTools({ allowedHosts: ['api.github.com', 'api.openai.com'], }); const web = webTools({ allowPublicInternet: true, robots: 'enforce', }); // Create agent with all tools const agent = defineAgent({ name: 'full_featured_agent', provider: createOpenAI({ apiKey: process.env.OPENAI_API_KEY, model: 'gpt-4', }), instructions: `You are a capable agent with access to: - Terminal/shell execution (run_command) - File operations (read_file, write_file, find_files) - HTTP requests (http_get, http_post) - Web search and fetching (web_search, fetch_url) Use these tools to solve problems and answer questions.`, tools: [ shell.runCommand, fs.readFile, fs.writeFile, fs.findFiles, http.httpGet, http.httpPost, web.webSearch, web.fetchUrl, ], }); // Run the agent const result = await runAgent(agent, { input: `Find the latest GitHub commits for infinityi-mc/engine-lib, read the CHANGELOG, and summarize recent changes.`, maxSteps: 10, }); console.log(result.output); ``` -------------------------------- ### Complete Agent Example Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/providers.md A full example demonstrating how to set up a custom provider, define tools, create an agent, and run it. This example includes creating an OpenAI provider, defining a calculator tool with an unsafe eval function, and running an agent to solve a math problem. ```typescript import { createOpenAI, defineAgent, runAgent, s, defineTool, } from '@infinityi/engine-lib'; // Create provider const provider = createOpenAI({ apiKey: process.env.OPENAI_API_KEY, model: 'gpt-4', }); // Define tool const calculator = defineTool({ name: 'calculate', description: 'Perform a calculation', parameters: s.object({ expression: s.string(), }), execute: async (args) => { try { const result = eval(args.expression); // Unsafe! Use expression parser in production return { ok: true, content: result }; } catch (e) { return { ok: false, error: String(e) }; } }, }); // Define agent const agent = defineAgent({ name: 'math_assistant', provider, instructions: 'Help solve math problems. Use the calculator tool.', tools: [calculator], }); // Run const result = await runAgent(agent, { input: 'What is 25 * 4?', }); console.log(result.output); ``` -------------------------------- ### Install and Build Engine-lib Project Source: https://github.com/infinityi-mc/engine-lib/blob/main/README.md Commands to install dependencies, run checks, tests, build the project, and generate documentation. ```bash bun install bun run check bun test bun run build bun run docs ``` -------------------------------- ### Complete Example: Event Hub and Subscribers Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/events.md This example demonstrates setting up an event hub, subscribing to various event types with custom logic for metrics, and integrating with a message bus. It shows how to use `runAgent` with an `onEvent` handler to dispatch events. ```typescript import { runAgent, createEventHub, loggingSubscriber, messageBusSubscriber, } from '@infinityi/engine-lib'; // Create event hub const hub = createEventHub(); // Add logging subscriber hub.subscribe(loggingSubscriber({ logger: ctx.forge?.logger, level: 'info', })); // Add custom metrics subscriber hub.subscribe((event) => { if (event.type === 'run.start') { metrics.increment('runs.started', { agent: event.agent }); } else if (event.type === 'run.finish') { metrics.histogram('run.output_length', event.output.length); metrics.histogram('run.token_usage', event.usage?.totalTokens ?? 0); } else if (event.type === 'tool.call') { metrics.increment('tool_calls', { tool: event.name }); } else if (event.type === 'error') { metrics.increment('run_errors', { error: event.error.name }); } }); // Add message bus subscriber hub.subscribe(messageBusSubscriber({ bus: ctx.forge?.messageBus, topic: 'agent-events', })); // Run with event dispatch const onEvent = (event: RunEvent) => { hub.dispatch(event); }; const result = await runAgent(agent, { input: 'hello', onEvent, }); ``` -------------------------------- ### Create Google Provider Example Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/providers.md Example of how to instantiate a Google provider using the `createGoogle` factory function. Ensure the `GOOGLE_API_KEY` environment variable is set. ```typescript const provider = createGoogle({ apiKey: process.env.GOOGLE_API_KEY, model: 'gemini-1.5-pro', }); ``` -------------------------------- ### Complete Example: Agent with Static and Dynamic Context Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/context.md This example shows how to define an agent that utilizes both static documentation and a dynamic retriever for context. The static context provides fixed API documentation, while the dynamic context fetches relevant information based on user queries. Ensure you have your OpenAI API key set in the environment variables. ```typescript import { runAgent, defineAgent, createOpenAI, staticContext, dynamicContext, } from '@infinityi/engine-lib'; // Static context: always include documentation const docContext = staticContext([ { type: 'system', text: `# API Documentation ## GET /api/users Returns a list of users...`, }, ]); // Dynamic context: retrieve relevant docs based on conversation const retrieverContext = dynamicContext(async (ctx) => { const query = ctx.messages .filter((m) => m.role === 'user') .map((m) => m.content.filter((p) => p.type === 'text').map((p) => (p as any).text).join(' ')) .join(' '); if (!query) return []; const relevant = await documentRetriever.search(query, { limit: 3 }); return [ user(`Relevant documentation:\n${relevant.map((d) => d.content).join('\n\n')}`), ]; }); const agent = defineAgent({ name: 'api_assistant', provider: createOpenAI({ apiKey: process.env.OPENAI_API_KEY, model: 'gpt-4', }), instructions: 'Use the provided documentation to answer API questions.', }); // Run with context injection and window management const result = await runAgent(agent, { input: 'How do I list all users?', context: retrieverContext, // Inject dynamic context contextWindow: { strategy: 'truncate', maxTokens: 4096, reserve: 512, // Reserve tokens for output }, }); console.log(result.output); ``` -------------------------------- ### Create OpenAI Compatible Provider Example Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/providers.md Example of how to instantiate an OpenAI-compatible provider using the `createOpenAICompatible` factory function. This is useful for services like Ollama or vLLM. ```typescript const provider = createOpenAICompatible({ baseUrl: 'http://localhost:11434/v1', model: 'llama2', }); ``` -------------------------------- ### Create OpenAI Provider Example Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/providers.md Example of how to instantiate an OpenAI provider using the `createOpenAI` factory function. Ensure the `OPENAI_API_KEY` environment variable is set. ```typescript const provider = createOpenAI({ apiKey: process.env.OPENAI_API_KEY, model: 'gpt-4', }); ``` -------------------------------- ### Complete Agent Example with Authorization and Approval Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/approval-authorization.md This example shows a full implementation of an agent that requires both role-based authorization and human approval before executing tools. It sets up roles, an authorizer, an approval policy, and a human input gateway. ```typescript import { runAgent, defineAgent, createOpenAI, trustApprovalPolicy, deferredHumanInputGateway, } from '@infinityi/engine-lib'; import { roleToolAuthorizer } from '@infinityi/engine-lib/authorization'; // Define roles and permissions const roles = new Map([ ['admin', new Set(['write_file', 'delete_file', 'system_command'])], ['editor', new Set(['write_file', 'read_file'])], ['viewer', new Set(['read_file'])], ]); // Create authorizer const authorizer = roleToolAuthorizer(roles); // Create approval gate const approval = trustApprovalPolicy({ defaultTrust: 'low', }); // Create human gateway const gateway = deferredHumanInputGateway(async (req) => { // In real app: send notification, wait for response console.log('Human input requested:', req.question); return 'approved'; // Simulated response }); // Create agent const agent = defineAgent({ name: 'document_manager', provider: createOpenAI({ apiKey: process.env.OPENAI_API_KEY, model: 'gpt-4', }), instructions: 'You help manage documents. Use tools to read, write, and delete files.', tools: [readTool, writeTool, deleteTool], }); // Run with authorization and approval const result = await runAgent(agent, { input: 'Delete the old backup files', // Authorization: check if user has role to delete toolAuthorizer: authorizer, // Approval: ask for human confirmation approval, humanInput: gateway, // Track the principal (user making the request) // Passed via EngineContext to authorizer }); console.log(result.output); ``` -------------------------------- ### Complete Agent Execution Example Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/execution.md Demonstrates defining a tool, an agent, and running it with both buffered and streaming outputs. Requires API key and model configuration. ```typescript import { defineAgent, runAgent, createOpenAI, defineTool, s, } from '@infinityi/engine-lib'; // Set up tools const getTempTool = defineTool({ name: 'get_temperature', description: 'Get current temperature for a city', parameters: s.object({ city: s.string() }), execute: async ({ city }) => { return { ok: true, content: `${city}: 72°F` }; }, }); // Define agent const weatherAgent = defineAgent({ name: 'weather_assistant', provider: createOpenAI({ apiKey: process.env.OPENAI_API_KEY, model: 'gpt-4', }), instructions: 'You are a helpful weather assistant. Use the temperature tool when asked about weather.', tools: [getTempTool], }); // Run buffered const result = await runAgent(weatherAgent, { input: 'What is the temperature in Boston?', maxSteps: 5, }); console.log(result.output); console.log('Tokens used:', result.usage?.totalTokens); // Run streaming const handle = runAgent(weatherAgent, { input: 'Compare temperatures in Boston and NYC', stream: true, }); for await (const event of handle) { if (event.type === 'token') { process.stdout.write(event.delta); } else if (event.type === 'tool.call') { console.log(`\n[Tool] ${event.name}`); } } const finalResult = await handle.completed; console.log('\nFinal output:', finalResult.output); ``` -------------------------------- ### Local Development Commands Source: https://github.com/infinityi-mc/engine-lib/blob/main/README.md Commands for local development, including installation, checking, testing, and building the project with Bun. ```bash bun install bun run check bun test bun run build ``` -------------------------------- ### Create Anthropic Provider Example Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/providers.md Example of how to instantiate an Anthropic provider using the `createAnthropic` factory function. Ensure the `ANTHROPIC_API_KEY` environment variable is set. ```typescript const provider = createAnthropic({ apiKey: process.env.ANTHROPIC_API_KEY, model: 'claude-3-sonnet-20240229', }); ``` -------------------------------- ### Install engine-lib with Bun Source: https://github.com/infinityi-mc/engine-lib/blob/main/README.md Use this command to add the engine-lib package to your project using the Bun package manager. ```bash bun add @infinityi/engine-lib ``` -------------------------------- ### Complete Session Lifecycle Example Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/sessions.md Demonstrates the full lifecycle of a session, including creation, running an agent for multiple turns, checking resume metadata, forking the session for alternative paths, and comparing message history between parent and child sessions. ```typescript import { createSession, forkSession, readResumeInfo, InMemorySessionStore, runAgent, } from '@infinityi/engine-lib'; // Create a durable session const session = createSession({ id: 'conversation-123', store: new InMemorySessionStore(), metadata: { userId: 'user-456', title: 'Debug session' }, }); // First turn const result1 = await runAgent(agent, { input: 'Explain how this code works', session, }); console.log(result1.output); // Second turn (continues history) const result2 = await runAgent(agent, { input: 'Now optimize it', session, }); console.log(result2.output); // Check resume metadata const resume = await readResumeInfo(session); console.log('Tools used:', resume?.toolNames); // Fork to explore an alternate path const exploration = await forkSession(session, { id: 'alt-path' }); const result3 = await runAgent(agent, { input: 'Refactor it instead', session: exploration, }); // Original session is unchanged const parentMessages = await session.messages(); console.log('Parent history:', parentMessages.length); const childMessages = await exploration.messages(); console.log('Child history:', childMessages.length); ``` -------------------------------- ### Reference Guides Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/INDEX.md This section contains reference guides for types, errors, and configuration options within the library. ```APIDOC ## Reference Guides This section contains reference guides for types, errors, and configuration options within the library. ### Type Reference - **Description**: Complete type taxonomy (all exported types listed by module). - **Link**: types.md ### Error Reference - **Description**: Error hierarchy, triggers, and handling patterns. - **Link**: errors.md ### Configuration Reference - **Description**: All constructor options and run parameters. - **Link**: configuration.md ``` -------------------------------- ### Create and Use EventHub Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/events.md Example of creating an EventHub with an error handler and subscribing to events for logging and metrics. ```typescript const hub = createEventHub({ onError: (error, event, subscriber) => { console.error(`Subscriber failed on event ${event.type}:`, error); }, }); // Subscribe logging hub.subscribe((event) => { console.log(`[${event.type}]`); }); // Subscribe metrics hub.subscribe((event) => { if (event.type === 'run.finish') { metrics.increment('runs.completed', { output_length: event.output.length }); } }); ``` -------------------------------- ### Initialize Web Tools Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/tools-packages.md Initializes web tools with specific configurations for public internet access, robots.txt enforcement, and a custom search provider. This setup is then used to define an agent with web search and fetch URL capabilities. ```typescript import { webTools } from '@infinityi/engine-lib/tools-web'; const web = webTools({ allowPublicInternet: true, robots: 'enforce', // Respect robots.txt searchProvider: { search: async (query) => { // Integration with your search API return [...results]; }, }, }); const agent = defineAgent({ name: 'research_agent', tools: [web.webSearch, web.fetchUrl], ... }); ``` -------------------------------- ### Complete Conversation Example Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/messages.md Demonstrates how to build a conversation using various message types provided by the library, including system, user, assistant, and tool messages. ```APIDOC ## Complete Example ### Description Build a conversation using various message types. ### Usage ```typescript import { user, assistant, system, text, image, toolResult } from '@infinityi/engine-lib/messages'; // Build a conversation const messages = [ system('You are a helpful assistant.'), user([ text('Analyze this image:'), image('image/png', 'base64encodeddata...') ]), assistant('This image shows a cat.'), user('Call the identify_animal tool'), assistant([ { type: 'tool_call', id: '1', name: 'identify_animal', arguments: { image: 'cat' } } ]), { role: 'tool', name: 'identify_animal', content: [toolResult({ species: 'Felis catus', confidence: 0.95 })] } ]; ``` ``` -------------------------------- ### Implementing Resilience with Engine-Lib Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/resilience.md This example shows how to chain multiple resilience patterns: retries for transient errors, a circuit breaker to halt requests during outages, and a rate limiter to control request frequency. It also demonstrates budget enforcement for token usage during agent execution. ```typescript import { runAgent, createOpenAI, withProviderRetry, circuitBreaker, tokenBucketRateLimiter, evaluateBudget, BudgetExceededError, } from '@infinityi/engine-lib'; // Set up resilient provider const baseProvider = createOpenAI({ apiKey: process.env.OPENAI_API_KEY, model: 'gpt-4', }); // Add retry const retryProvider = withProviderRetry(baseProvider, { maxRetries: 3, backoffMs: (attempt) => Math.pow(2, attempt) * 100, retryableStatus: (status) => status >= 500, }); // Add circuit breaker const resilientProvider = circuitBreaker(retryProvider, { failureThreshold: 5, timeout: 60000, onStateChange: (from, to) => { console.log(`Provider circuit: ${from} -> ${to}`); }, }); // Create agent with resilient provider const agent = defineAgent({ name: 'resilient_assistant', provider: resilientProvider, instructions: 'You are helpful.', }); // Set up rate limiter const rateLimiter = tokenBucketRateLimiter({ capacity: 500000, // 500K token capacity refillRate: 100000, // Refill 100K tokens refillIntervalMs: 1000, // Every second }); // Run with budget enforcement try { const handle = runAgent(agent, { input: 'Explain quantum mechanics', maxSteps: 10, budget: { totalTokens: 2000, outputTokens: 1500, }, rateLimiter, onEvent: (event) => { if (event.type === 'budget.warning') { console.warn( `Budget warning: ${event.field} ${event.used}/${event.limit}`, ); } }, stream: true, }); for await (const event of handle) { if (event.type === 'token') { process.stdout.write(event.delta); } } const result = await handle.completed; // Record actual token usage for rate limiter if (result.usage && isTokenRateLimiter(rateLimiter)) { rateLimiter.recordTokens(result.usage.inputTokens, result.usage.outputTokens); } } catch (e) { if (e instanceof BudgetExceededError) { console.error(`Budget exceeded on ${e.field}: ${e.limit}`); } else { throw e; } } ``` -------------------------------- ### Define Agent with Static and Dynamic Instructions Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/agents.md Examples of using `defineAgent` with both static string instructions and dynamic instructions resolved via a function. ```typescript // Static const agent = defineAgent({ instructions: 'You are a helpful assistant.', ... }); // Dynamic const agent = defineAgent({ instructions: async (ctx) => { const timezone = await getTimezone(ctx.forge); return `You are a helpful assistant in timezone ${timezone}.`; }, ... }); ``` -------------------------------- ### emptyUsage() Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/execution.md Creates a `Usage` object initialized with zero values for all token counts. This is a convenient starting point for accumulating usage metrics. ```APIDOC ## emptyUsage() ### Description Create a zero-valued `Usage` object. ### Returns - `Usage`: An object with `inputTokens`, `outputTokens`, and `totalTokens` set to 0. ``` -------------------------------- ### Create Shell Tools with Configuration Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/tools-packages.md Demonstrates how to create shell execution tools using the `shellTools` factory, configuring allowed commands, environment variables, and integrating with an agent. ```typescript import { shellTools } from '@infinityi/engine-lib/tools-shell'; const { runCommand, spawnCommand } = shellTools({ allowedCwds: [process.cwd()], policy: { allow: [/^npm\s/, /^node\s/], deny: [/rm\b/, /sudo\b/], }, env: { allow: ['PATH', 'HOME', 'NODE_ENV'], }, }); const agent = defineAgent({ name: 'terminal', tools: [runCommand], ... }); ``` -------------------------------- ### Define and Run an Agent with Tools Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/agents.md Demonstrates how to define a provider, define custom tools, create agents, and run an agent with a defined tool. Ensure your OPENAI_API_KEY environment variable is set. ```typescript import { defineAgent, createOpenAI, runAgent, asTool, defineTool, s, } from '@infinityi/engine-lib'; // Create provider const provider = createOpenAI({ apiKey: process.env.OPENAI_API_KEY, model: 'gpt-4', }); // Define tools const writeTool = defineTool({ name: 'write_file', description: 'Write a file', parameters: s.object({ path: s.string(), content: s.string() }), execute: async (args) => ({ ok: true, content: `Wrote ${args.path}` }), }); // Define agents const coder = defineAgent({ name: 'coder', provider, tools: [writeTool], }); const reviewer = defineAgent({ name: 'reviewer', provider, instructions: 'Review code carefully', tools: [asTool(coder)], }); // Run const result = await runAgent(reviewer, { input: 'Write and review a function', }); console.log(result.output); ``` -------------------------------- ### Handling Provider Errors Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/errors.md Example of how to catch and handle ProviderError exceptions, checking for retryable conditions. ```typescript try { const result = await runAgent(agent, { input: 'hello' }); } catch (e) { if (e instanceof ProviderError) { console.error(`Provider error (${e.provider}): ${e.message}`); if (e.retryable) { console.log('Retrying...'); } } } ``` -------------------------------- ### Catch and Inspect SchemaValidationError Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/errors.md Example of how to catch a SchemaValidationError and iterate through its 'issues' to log detailed validation failures. ```typescript try { const data = schema.parse(unknownData); } catch (e) { if (e instanceof SchemaValidationError) { for (const issue of e.issues) { console.log(`${issue.path.join('.')}: ${issue.message}`); } } } ``` -------------------------------- ### Create Filesystem Tools Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/tools-packages.md Configure and create filesystem tools with specified allowed roots and optional file size/count limits. These tools are then used to define agent capabilities. ```typescript interface FilesystemToolsConfig { readonly allowedRoots: string[]; readonly maxFileSize?: number; readonly maxFileCount?: number; } ``` ```typescript import { filesystemTools } from '@infinityi/engine-lib/tools-fs'; const fs = filesystemTools({ allowedRoots: [process.cwd(), '/tmp/shared'], maxFileSize: 100 * 1024 * 1024, // 100MB }); const agent = defineAgent({ name: 'document_agent', tools: [fs.readFile, fs.writeFile, fs.findFiles], ... }); ``` -------------------------------- ### Create Built-in Providers Source: https://github.com/infinityi-mc/engine-lib/blob/main/docs/guide/02-providers.md Demonstrates how to create instances of built-in providers like OpenAI, Anthropic, Google, and OpenAI-compatible services using their respective factory functions. Ensure API keys and model names are correctly configured. ```typescript import { createAnthropic, createGoogle, createOpenAI, createOpenAICompatible, } from "@infinityi/engine-lib/providers"; const openai = createOpenAI({ apiKey: process.env.OPENAI_API_KEY!, model: "gpt-5", }); const anthropic = createAnthropic({ apiKey: process.env.ANTHROPIC_API_KEY!, model: "claude-opus-4-7", }); const google = createGoogle({ apiKey: process.env.GOOGLE_API_KEY!, model: "gemini-2.5-pro", }); const local = createOpenAICompatible({ baseUrl: "http://localhost:1234/v1", model: "local-model", }); ``` -------------------------------- ### Recover from SessionAgentMismatchError Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/errors.md Implement recovery logic for session-agent mismatches. This example demonstrates checking for compatibility and creating a new session if a mismatch is detected. ```typescript const session = createSession({ id: 'user-123' }); const resume = await readResumeInfo(session); if (resume && !compareAgentResume(newAgent, resume)) { // Create a new session or ask for permission to overwrite const session2 = createSession({ id: `${session.id}-v2` }); await runAgent(newAgent, { input, session: session2 }); } ``` -------------------------------- ### Define and Run an Agent Source: https://github.com/infinityi-mc/engine-lib/blob/main/README.md Set up an OpenAI provider and define a basic agent. Use this for simple agent execution without complex tools or state management. ```typescript import { createOpenAI, defineAgent, runAgent } from "@infinityi/engine-lib"; const provider = createOpenAI({ apiKey: process.env.OPENAI_API_KEY!, model: "gpt-5", }); const agent = defineAgent({ name: "assistant", provider, instructions: "Answer clearly and use tools when needed.", }); const result = await runAgent(agent, { input: "Summarize the latest deployment status.", }); ``` -------------------------------- ### Import Testing Utilities Source: https://github.com/infinityi-mc/engine-lib/blob/main/docs/guide/10-testing-and-lifecycle.md Import necessary utilities for testing agents. Use `mockProvider` for simple tests, `scriptedProvider` for multi-turn flows, and `textResult`/`toolCallResult` to script provider behavior. ```ts import { mockProvider, scriptedProvider, textResult, toolCallResult, } from "@infinityi/engine-lib/testing"; ``` -------------------------------- ### Handle BudgetExceededError Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/errors.md Catch and log specific budget exceeded errors. This example shows how to check the error type and access its properties to provide informative messages. ```typescript try { await runAgent(agent, { input: 'explain quantum mechanics in detail', budget: { totalTokens: 500 }, // Very tight }); } catch (e) { if (e instanceof BudgetExceededError) { console.log(`Budget exceeded: ${e.field} at ${e.usage[e.field]}`); } } ``` -------------------------------- ### Add Filesystem Tools Source: https://github.com/infinityi-mc/engine-lib/blob/main/docs/guide/07-optional-tool-packs.md Initialize filesystem tools, restricting access to specified root directories. This pack provides tools for repository mapping, file searching, text operations, and more. ```typescript import { filesystemTools } from "@infinityi/engine-lib/tools-fs"; const fsTools = filesystemTools({ allowedRoots: [process.cwd()], }); ``` -------------------------------- ### Run the Agent Source: https://github.com/infinityi-mc/engine-lib/blob/main/docs/guide/01-getting-started.md Execute the defined agent with a specific input and log the output. This demonstrates the basic agent execution flow. ```typescript const result = await runAgent(agent, { input: "Say hello." }); console.log(result.output); ``` -------------------------------- ### Extract JSON Schema from Schema Object Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/schema.md Use toJsonSchema() to get the raw JSON Schema representation from a Schema object. This is useful when you need to serialize or share the schema. ```typescript const paramSchema = s.object({ query: s.string(), limit: s.optional(s.integer()), }); const jsonSchema = toJsonSchema(paramSchema); // { type: 'object', properties: { query: {...}, limit: {...} }, required: ['query'], ... } ``` -------------------------------- ### Integrate Authorization, Policy, and Approval in Run Loop Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/approval-authorization.md Demonstrates the integration of authorization, policy, and approval mechanisms within the run loop of an agent. Authorization runs first, followed by policy, and finally approval. ```typescript const result = await runAgent(agent, { input: 'some task', // Authorization: role-based access control toolAuthorizer: roleToolAuthorizer(roles), // Policy: governance rules policy: policyEngine, // Approval: human-in-the-loop approval: trustApprovalPolicy({ defaultTrust: 'low' }), humanInput: myGateway, }); ``` -------------------------------- ### Compose Multiple Policies Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/governance-retrieval.md Combines multiple policy engines using AND logic, ensuring all policies must allow an action for it to be permitted. Example demonstrates checking a shell execution. ```typescript const combined = composePolicies( shellPolicy, fsPolicy, httpPolicy ); const decision = await combined.check({ operation: 'execute_shell', target: 'ls -la' }, ctx); ``` -------------------------------- ### Define and Run an Agent with Tools Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/README.md This snippet demonstrates how to define a tool, an agent that uses the tool with an OpenAI provider, and then run the agent with an input. Ensure you have the necessary API key and model configured. ```typescript import { defineAgent, runAgent, createOpenAI, s, defineTool } from '@infinityi/engine-lib'; const tool = defineTool({ name: 'example', parameters: s.object({ input: s.string() }), execute: async ({ input }) => ({ ok: true, content: `Got: ${input}` }), }); const agent = defineAgent({ name: 'assistant', provider: createOpenAI({ apiKey: '...', model: 'gpt-4' }), tools: [tool], }); const result = await runAgent(agent, { input: 'hello' }); console.log(result.output); ``` -------------------------------- ### StreamEvent Type Definition Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/providers.md Defines the possible events emitted during a streaming response. Covers message start, text deltas, tool call events, and the final finish event with usage details. ```typescript type StreamEvent = | { type: 'message_start'; model: string } | { type: 'text_delta'; text: string } | { type: 'tool_call_start'; index: number; id: string; name: string } | { type: 'tool_call_delta'; index: number; argumentsTextDelta: string } | { type: 'tool_call_end'; index: number } | { type: 'finish'; finishReason: FinishReason; usage?: Usage }; ``` -------------------------------- ### Estimate Message Tokens Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/context.md Use `estimateTokens` to get a rough count of tokens for a given message. This function is used by the default token counter and provides a quick way to assess message size. ```typescript const msg = user('Hello, world!'); const tokens = estimateTokens(msg); // Rough estimate ``` -------------------------------- ### Handle Schema Validation Errors Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/schema.md Catch `SchemaValidationError` when validation fails using `parse`, or use `safeParse` to get a result object indicating success or failure with detailed issues. This allows for robust error handling in your application. ```typescript const schema = s.object({ id: s.integer(), name: s.string(), }); try { schema.parse({ id: 'not-a-number', name: 'test' }); } catch (e) { // e is SchemaValidationError console.log(e.issues); // [{ path: ['id'], message: 'expected number' }] } // Or use safeParse to avoid throwing const result = schema.safeParse({ id: 'not-a-number', name: 'test' }); if (!result.success) { console.log(result.error.issues); } ``` -------------------------------- ### Web Tools (`@infinityi/engine-lib/tools-web`) Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/tools-packages.md Provides static web search, fetching, and HTML parsing capabilities without JavaScript execution or browser emulation. It allows configuration for allowed hosts, public internet access, search providers, robots.txt policies, and default headers. ```APIDOC ## Web Tools (`@infinityi/engine-lib/tools-web`) Static web search, fetching, and HTML parsing (no JavaScript execution, no browser). ### Factory **webTools(config: WebToolsConfig): WebTools** Create web tools. ```typescript interface WebToolsConfig { readonly allowedHosts?: string[]; readonly allowPublicInternet?: boolean; readonly searchProvider?: SearchProvider; readonly robots?: RobotsPolicy; readonly defaultHeaders?: HeaderEntry[]; } ``` | Option | Type | Required | Description | |--------|------|----------|-------------| | allowedHosts | string[] | no | Hosts where requests are permitted | | allowPublicInternet | boolean | no | Allow any host | | searchProvider | SearchProvider | no | Search API provider (e.g., Google, Bing) | | robots | RobotsPolicy | no | How to handle robots.txt ('enforce', 'warn', 'ignore') | | defaultHeaders | HeaderEntry[] | no | Default headers for requests | **Returns:** `WebTools` — Tools: `web_search`, `fetch_url`, `extract_text`, `crawl_links` **Source:** `src/tools-web/define.ts` ```typescript import { webTools } from '@infinityi/engine-lib/tools-web'; const web = webTools({ allowPublicInternet: true, robots: 'enforce', // Respect robots.txt searchProvider: { search: async (query) => { // Integration with your search API return [...results]; }, }, }); const agent = defineAgent({ name: 'research_agent', tools: [web.webSearch, web.fetchUrl], ... }); ``` ``` -------------------------------- ### Build a Conversation with Messages API Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/messages.md Illustrates how to construct a full conversation history using various message types like system, user, assistant, image, and tool results. This example shows the typical flow of a multi-turn interaction. ```typescript import { user, assistant, system, text, image, toolResult } from '@infinityi/engine-lib/messages'; // Build a conversation const messages = [ system('You are a helpful assistant.'), user([ text('Analyze this image:'), image('image/png', 'base64encodeddata...') ]), assistant('This image shows a cat.'), user('Call the identify_animal tool'), assistant([ { type: 'tool_call', id: '1', name: 'identify_animal', arguments: { image: 'cat' } } ]), { role: 'tool', name: 'identify_animal', content: [toolResult({ species: 'Felis catus', confidence: 0.95 })] } ]; ``` -------------------------------- ### createGoogle Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/providers.md Creates a Google provider instance (Gemini). Requires an API key and model ID, with an optional timeout parameter. ```APIDOC ## createGoogle(options: GoogleOptions): Provider ### Description Create a Google provider (Gemini). ### Method createGoogle ### Parameters #### Options - **apiKey** (string) - yes - Google API key - **model** (string) - yes - Model id (e.g., 'gemini-1.5-pro') - **timeout** (number) - no - Request timeout in ms (Default: 30000) ### Returns `Provider` ### Example ```typescript const provider = createGoogle({ apiKey: process.env.GOOGLE_API_KEY, model: 'gemini-1.5-pro', }); ``` ``` -------------------------------- ### Define RunEvent Type Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/execution.md Defines the structure for various events that can occur during an agent run, including start, message, token, tool calls/results, policy decisions, human input requests, budget warnings, child agent events, handoffs, and errors. ```typescript type RunEvent = | { type: 'run.start'; agent: string } | { type: 'message'; message: Message } | { type: 'token'; delta: string } | { type: 'tool.call'; id: string; name: string; arguments: unknown } | { type: 'tool.result'; id: string; name: string; result: ToolResult } | { type: 'tool.approval_requested'; id: string; name: string; argumentsDigest: string } | { type: 'tool.authorization_decided'; id: string; name: string; allowed: boolean; reason?: string; argumentsDigest: string } | { type: 'policy.decision'; id: string; name: string; allowed: boolean; reason?: string; requiresApproval?: boolean; transformed?: boolean; argumentsDigest: string } | { type: 'tool.approval_decided'; id: string; name: string; approved: boolean; reason?: string; argumentsDigest: string } | { type: 'human.input_requested'; requestId: string; question: string; context?: string } | { type: 'human.input_provided'; requestId: string; cancelled: boolean } | { type: 'budget.warning'; field: 'totalTokens' | 'inputTokens' | 'outputTokens'; used: number; limit: number } | { type: 'agent.child'; agent: string; event: RunEvent } | { type: 'agent.handoff'; from: string; to: string } | { type: 'run.finish'; output: string; usage?: Usage } | { type: 'error'; error: AgentError }; ``` -------------------------------- ### ContextWindowOptions Interface Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/context.md Configuration options for managing the context window, including strategy, size, and token counting. ```APIDOC ## Interface: ContextWindowOptions ### Description Options for context-window management. ### Definition ```typescript interface ContextWindowOptions { readonly strategy?: ContextStrategy; readonly maxTokens?: number; readonly reserve?: number; readonly counter?: TokenCounter; } ``` ### Options - **strategy** (`ContextStrategy`) - Optional - How to handle budget overflow - **maxTokens** (`number`) - Optional - Total context window size - **reserve** (`number`) - Optional - Tokens reserved for output - **counter** (`TokenCounter`) - Optional - Custom token counter (defaults to rough estimator) ``` -------------------------------- ### Filesystem Tools Configuration Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/configuration.md Sets up filesystem tools with restrictions on accessible root directories and limits on file size and count. ```typescript interface FilesystemToolsConfig { readonly allowedRoots: string[]; readonly maxFileSize?: number; readonly maxFileCount?: number; } ``` -------------------------------- ### Session Creation Options Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/configuration.md Defines the structure for creating a new session, including optional identifiers, tenant association, storage backend, and initial metadata. ```typescript interface CreateSessionOptions { readonly id?: string; readonly tenantId?: string; readonly store?: SessionStore; readonly metadata?: Record; } ``` -------------------------------- ### Create a New Session Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/sessions.md Use `createSession` to initialize a new session. You can provide an ID, tenant ID, a custom session store, or initial metadata. If no ID is provided, one will be generated. ```typescript interface CreateSessionOptions { readonly id?: string; readonly tenantId?: string; readonly store?: SessionStore; readonly metadata?: Record; } ``` ```typescript const session = createSession({ id: 'user-123' }); await runAgent(agent, { input: 'hello', session }); await runAgent(agent, { input: 'follow-up', session }); const allMessages = await session.messages(); console.log(allMessages.length); ``` -------------------------------- ### Configure Local Sandbox Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/tools-packages.md Sets up shell tools using the local sandbox implementation. This is suitable for in-process execution without actual isolation, sharing the same environment as direct execution. ```typescript import { localSandbox } from '@infinityi/engine-lib/tools-sandbox'; const { runCommand } = shellTools({ allowedCwds: ['/workspace'], sandbox: localSandbox(), }); ``` -------------------------------- ### askHumanTool Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/approval-authorization.md Creates a tool that prompts a human for input, useful for agent interactions requiring clarification or confirmation. ```APIDOC ## askHumanTool(config: AskHumanConfig): ToolDefinition ### Description Create a tool that asks a human for input (used within agent). ### Parameters #### Request Body - **gateway** (HumanInputGateway) - Required - The gateway to use for human input. - **context** (string) - Optional - Additional context for the human input prompt. ### Source `src/approval/human-input.ts` ### Example ```typescript const askHuman = askHumanTool({ gateway: myHumanInputGateway, context: 'Use this tool to ask the user for clarification', }); const agent = defineAgent({ name: 'assistant', tools: [askHuman, ...otherTools], ... }); ``` ``` -------------------------------- ### createOpenAICompatible Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/providers.md Creates a provider for OpenAI-compatible APIs (e.g., Ollama, vLLM, LM Studio). Requires a base URL and model ID, with optional API key and timeout. ```APIDOC ## createOpenAICompatible(options: OpenAICompatibleOptions): Provider ### Description Create a provider for OpenAI-compatible APIs (e.g., Ollama, vLLM, LM Studio). ### Method createOpenAICompatible ### Parameters #### Options - **baseUrl** (string) - yes - API endpoint base URL - **model** (string) - yes - Model id - **apiKey** (string) - no - Optional API key if the endpoint requires auth - **timeout** (number) - no - Request timeout in ms (Default: 30000) ### Returns `Provider` ### Example ```typescript const provider = createOpenAICompatible({ baseUrl: 'http://localhost:11434/v1', model: 'llama2', }); ``` ``` -------------------------------- ### Create Static Context Provider Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/context.md Use `staticContext` to create a provider that returns a fixed set of context items. This is useful for providing consistent information like system prompts or predefined data. ```typescript const context = staticContext([ { type: 'system', text: 'You are in debug mode.' }, user('Here is the documentation:\n...'), ]); ``` -------------------------------- ### staticContext Source: https://github.com/infinityi-mc/engine-lib/blob/main/_autodocs/api-reference/context.md Creates a context provider that returns a fixed set of context items on every call. This is useful for providing consistent information or instructions. ```APIDOC ## staticContext(items: ContextItem[]): ContextProvider ### Description Create a provider that returns fixed context items on every call. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **items** (ContextItem[]) - Required - An array of context items to be provided. ### Request Example ```typescript const context = staticContext([ { type: 'system', text: 'You are in debug mode.' }, user('Here is the documentation:\n...'), ]); ``` ### Response #### Success Response (200) * **ContextProvider** - A provider that returns the fixed context items. #### Response Example None provided. ```