{"_id":"@ahmedelsharkawycs/forge-ai-sdk","_rev":"3-70a8ddb05b3380ccdf9d038063370b7c","name":"@ahmedelsharkawycs/forge-ai-sdk","dist-tags":{"latest":"1.1.0"},"versions":{"1.0.0":{"name":"@ahmedelsharkawycs/forge-ai-sdk","version":"1.0.0","keywords":["ai","agent","sdk","llm","code-generation","openai","anthropic","orchestration","typescript"],"author":{"name":"Ahmed Sharkawy"},"license":"MIT","_id":"@ahmedelsharkawycs/forge-ai-sdk@1.0.0","maintainers":[{"name":"ahmedelsharkawycs","email":"ahmed.sharkawy.sde@gmail.com"}],"homepage":"https://github.com/AhmedElsharkawyCS/ForgeAI#readme","bugs":{"url":"https://github.com/AhmedElsharkawyCS/ForgeAI/issues"},"dist":{"shasum":"4c57900d0d893178bb006335c1534d21b3ad2451","tarball":"https://registry.npmjs.org/@ahmedelsharkawycs/forge-ai-sdk/-/forge-ai-sdk-1.0.0.tgz","fileCount":7,"integrity":"sha512-l98Whd7yH0GfQ4bwChWXNVazjJJ8xQllwwPFVA/fpt6Lxr9vJKXZpxYMLB3NL7OK7hB6RIP8y3HlEHi6aH56rA==","signatures":[{"sig":"MEQCIAcxHxn4VahOmJfCCRqkwl+leQAxSKaXZvDdB6tH+07kAiAFsBpMvX+3BIXE1BOtZgiQD0NHz80UolQorKoy0eQvmQ==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":257192},"main":"./dist/index.js","types":"./dist/index.d.ts","module":"./dist/index.mjs","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.mjs","require":"./dist/index.js"}},"gitHead":"f69fcdf63a8fbd15d3fa2376963df319775290c5","scripts":{"dev":"tsup src/index.ts --format cjs,esm --dts --watch","lint":"eslint src/**/*.ts","build":"tsup src/index.ts --format cjs,esm --dts --clean","type-check":"tsc --noEmit","prepublishOnly":"npm run build"},"_npmUser":{"name":"ahmedelsharkawycs","email":"ahmed.sharkawy.sde@gmail.com"},"repository":{"url":"git+https://github.com/AhmedElsharkawyCS/ForgeAI.git","type":"git"},"_npmVersion":"10.9.2","description":"A powerful multi-phase AI agent SDK for building code generation systems with support for multiple LLM providers","directories":{},"_nodeVersion":"22.17.1","dependencies":{"zod":"^3.23.8","diff":"^5.2.0"},"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"_hasShrinkwrap":false,"devDependencies":{"tsup":"^8.0.0","eslint":"^9.13.0","openai":"^6.17.0","typescript":"^5.6.2","@types/diff":"^5.2.2","@types/node":"^20.0.0","@anthropic-ai/sdk":"^0.72.1","@typescript-eslint/parser":"^8.0.0","@typescript-eslint/eslint-plugin":"^8.0.0"},"peerDependencies":{"openai":"^4.0.0","@anthropic-ai/sdk":"^0.30.0"},"peerDependenciesMeta":{"openai":{"optional":true},"@anthropic-ai/sdk":{"optional":true}},"_npmOperationalInternal":{"tmp":"tmp/forge-ai-sdk_1.0.0_1770258397827_0.4683224701110944","host":"s3://npm-registry-packages-npm-production"}},"1.0.1":{"name":"@ahmedelsharkawycs/forge-ai-sdk","version":"1.0.1","keywords":["ai","agent","sdk","llm","code-generation","openai","anthropic","orchestration","typescript"],"author":{"name":"Ahmed Sharkawy"},"license":"MIT","_id":"@ahmedelsharkawycs/forge-ai-sdk@1.0.1","maintainers":[{"name":"ahmedelsharkawycs","email":"ahmed.sharkawy.sde@gmail.com"}],"homepage":"https://github.com/AhmedElsharkawyCS/ForgeAI#readme","bugs":{"url":"https://github.com/AhmedElsharkawyCS/ForgeAI/issues"},"dist":{"shasum":"6bb7ec6f47e6fb7779b55ec8a9e2c4deaeec4e6f","tarball":"https://registry.npmjs.org/@ahmedelsharkawycs/forge-ai-sdk/-/forge-ai-sdk-1.0.1.tgz","fileCount":7,"integrity":"sha512-zO28VsAtQoPSgUN1RjLi66P2Gaalsp5+eR/04ZERMy6RZ9MACIpMSy5gJgK9/b5G+TcPW3spNEJ+47rToq7AlQ==","signatures":[{"sig":"MEUCIDkOf2JMjr9jFkygzE9OtFQAy5EOAgBMZOYN1iYSjRIXAiEAnLEpk6CMdDk5MG7s+5jl93nhk3iUUexChp8sxpvAJWo=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":257192},"main":"./dist/index.js","types":"./dist/index.d.ts","module":"./dist/index.mjs","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.mjs","require":"./dist/index.js"}},"gitHead":"9fe6f038b3c0fe4d121857d87fa5b2cbb891615c","scripts":{"dev":"tsup src/index.ts --format cjs,esm --dts --watch","lint":"eslint src/**/*.ts","build":"tsup src/index.ts --format cjs,esm --dts --clean","type-check":"tsc --noEmit","prepublishOnly":"npm run build"},"_npmUser":{"name":"ahmedelsharkawycs","email":"ahmed.sharkawy.sde@gmail.com"},"repository":{"url":"git+https://github.com/AhmedElsharkawyCS/ForgeAI.git","type":"git"},"_npmVersion":"10.9.2","description":"A powerful multi-phase AI agent SDK for building code generation systems with support for multiple LLM providers","directories":{},"_nodeVersion":"22.17.1","dependencies":{"zod":"^3.23.8","diff":"^5.2.0"},"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"_hasShrinkwrap":false,"devDependencies":{"tsup":"^8.0.0","eslint":"^9.13.0","openai":"^6.17.0","typescript":"^5.6.2","@types/diff":"^5.2.2","@types/node":"^20.0.0","@anthropic-ai/sdk":"^0.72.1","@typescript-eslint/parser":"^8.0.0","@typescript-eslint/eslint-plugin":"^8.0.0"},"peerDependencies":{"openai":"^4.0.0","@anthropic-ai/sdk":"^0.30.0"},"peerDependenciesMeta":{"openai":{"optional":true},"@anthropic-ai/sdk":{"optional":true}},"_npmOperationalInternal":{"tmp":"tmp/forge-ai-sdk_1.0.1_1770259376500_0.3693279975689261","host":"s3://npm-registry-packages-npm-production"}},"1.1.0":{"name":"@ahmedelsharkawycs/forge-ai-sdk","version":"1.1.0","description":"A powerful multi-phase AI agent SDK for building code generation systems with support for multiple LLM providers","main":"./dist/index.js","module":"./dist/index.mjs","types":"./dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.mjs","require":"./dist/index.js"}},"scripts":{"build":"tsup src/index.ts --format cjs,esm --dts --clean","dev":"tsup src/index.ts --format cjs,esm --dts --watch","prepublishOnly":"npm run build","lint":"eslint src/**/*.ts","type-check":"tsc --noEmit"},"keywords":["ai","agent","sdk","llm","code-generation","openai","anthropic","orchestration","typescript"],"author":{"name":"Ahmed Sharkawy"},"license":"MIT","repository":{"type":"git","url":"git+https://github.com/AhmedElsharkawyCS/ForgeAI.git"},"bugs":{"url":"https://github.com/AhmedElsharkawyCS/ForgeAI/issues"},"homepage":"https://github.com/AhmedElsharkawyCS/ForgeAI#readme","peerDependencies":{"@anthropic-ai/sdk":"^0.30.0","openai":"^4.0.0"},"peerDependenciesMeta":{"openai":{"optional":true},"@anthropic-ai/sdk":{"optional":true}},"dependencies":{"diff":"^5.2.0","zod":"^3.23.8"},"devDependencies":{"@anthropic-ai/sdk":"^0.72.1","@types/diff":"^5.2.2","@types/node":"^20.0.0","@typescript-eslint/eslint-plugin":"^8.0.0","@typescript-eslint/parser":"^8.0.0","eslint":"^9.13.0","openai":"^6.17.0","tsup":"^8.0.0","typescript":"^5.6.2"},"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"_id":"@ahmedelsharkawycs/forge-ai-sdk@1.1.0","gitHead":"1e3c0620b9dd697b08fe6018568f28fa5e466d62","_nodeVersion":"22.17.1","_npmVersion":"10.9.2","dist":{"integrity":"sha512-fCITFL/zKt5lITKaUDjS1oPqVhCVRU4TntFbG/Uy/o3G3aEk1z7F89ujea4xvusWHsi3lpeHqGS9T4gM6Qz6zQ==","shasum":"8cf8c271f8766430b1671e056e4cc32a73523b9c","tarball":"https://registry.npmjs.org/@ahmedelsharkawycs/forge-ai-sdk/-/forge-ai-sdk-1.1.0.tgz","fileCount":7,"unpackedSize":314734,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIGFGO5KFt1RyCJPWBTtjpgu7bSNcAYqPluDnN8IrRu0aAiEA/Ld2yFKxUo850fFFEr2CMnU/X/F+oX358rLMZ+Zg8pM="}]},"_npmUser":{"name":"ahmedelsharkawycs","email":"ahmed.sharkawy.sde@gmail.com"},"directories":{},"maintainers":[{"name":"ahmedelsharkawycs","email":"ahmed.sharkawy.sde@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/forge-ai-sdk_1.1.0_1770586473728_0.8679534242859503"},"_hasShrinkwrap":false}},"time":{"created":"2026-02-05T02:26:37.644Z","modified":"2026-02-08T21:34:34.036Z","1.0.0":"2026-02-05T02:26:38.032Z","1.0.1":"2026-02-05T02:42:56.663Z","1.1.0":"2026-02-08T21:34:33.919Z"},"bugs":{"url":"https://github.com/AhmedElsharkawyCS/ForgeAI/issues"},"author":{"name":"Ahmed Sharkawy"},"license":"MIT","homepage":"https://github.com/AhmedElsharkawyCS/ForgeAI#readme","keywords":["ai","agent","sdk","llm","code-generation","openai","anthropic","orchestration","typescript"],"repository":{"type":"git","url":"git+https://github.com/AhmedElsharkawyCS/ForgeAI.git"},"description":"A powerful multi-phase AI agent SDK for building code generation systems with support for multiple LLM providers","maintainers":[{"name":"ahmedelsharkawycs","email":"ahmed.sharkawy.sde@gmail.com"}],"readme":"# ForgeAI SDK\n\nA powerful, state-based AI agent SDK that works seamlessly in both Node.js and browser environments. The agent operates through phases (Intent → Plan → Execute → Validate) and manages virtual files as state, supporting multiple LLM providers and pluggable storage adapters.\n\n## Features\n\n- 🔄 **Phase-Based Orchestration**: Intent analysis → Planning → Execution → Validation\n- 💾 **Pluggable Storage**: Memory, LocalStorage, or Node.js File System adapters\n- 🤖 **Multi-Provider Support**: OpenAI and Anthropic (Claude) out of the box\n- 🌐 **Cross-Platform**: Works in both Node.js and browser environments\n- 📦 **Virtual File System**: All operations work on virtual state, not real files\n- 🔒 **Policy Gates**: Built-in safety validation and restrictions\n- 📡 **Event System**: React to phase transitions, file changes, and LLM streaming\n- 🔄 **Transactional State**: Rollback support with snapshot history\n- ✅ **Type-Safe**: Full TypeScript support with Zod runtime validation\n- 🌊 **Streaming Support**: Real-time LLM response streaming\n- 🧩 **Dependency Graph**: Automatic import/export parsing for context-aware code generation\n- 📋 **Project Templates**: Pre-built React + Vite + MUI starter templates\n- 🏗️ **Modular Prompt System**: Tiered, composable prompts for each agent phase\n\n## Installation\n\n```bash\nnpm install @ahmedelsharkawycs/forge-ai-sdk openai\n# or\nyarn add @ahmedelsharkawycs/forge-ai-sdk openai\n# For Anthropic Claude:\nnpm install @ahmedelsharkawycs/forge-ai-sdk @anthropic-ai/sdk\n```\n\n## Quick Start\n\n### Basic Usage\n\n```typescript\nimport { \n  Agent, \n  InMemoryAdapter, \n  OpenAIProvider \n} from '@ahmedelsharkawycs/forge-ai-sdk';\n\n// Create an agent\nconst agent = new Agent({\n  adapter: new InMemoryAdapter(),\n  provider: new OpenAIProvider({ \n    apiKey: process.env.OPENAI_API_KEY \n  }),\n  initialFiles: [\n    {\n      path: '/src/index.ts',\n      content: '// Entry point',\n      version: 1,\n      lastModified: Date.now()\n    }\n  ]\n});\n\n// Or use a pre-built template for quick bootstrapping\nimport { getReactMUIViteTemplate } from '@ahmedelsharkawycs/forge-ai-sdk';\n\nconst agentWithTemplate = new Agent({\n  adapter: new InMemoryAdapter(),\n  provider: new OpenAIProvider({ apiKey: process.env.OPENAI_API_KEY }),\n  initialFiles: getReactMUIViteTemplate() // React + Vite + MUI + TypeScript\n});\n\n// Initialize\nawait agent.initialize();\n\n// Listen to events\nagent.on('file:update', (file) => {\n  console.log(`File updated: ${file.path}`);\n});\n\nagent.on('intent:start', () => {\n  console.log('Analyzing intent...');\n});\n\nagent.on('stream:chunk', ({ content }) => {\n  process.stdout.write(content); // Real-time streaming\n});\n\n// Send a message\nconst response = await agent.sendMessage(\n  'Add a hello world function to /src/index.ts'\n);\n\nconsole.log(response.content);\nconsole.log('Files changed:', response.filesChanged);\n\n// Get current files\nconst files = agent.getFiles();\nconsole.log(files);\n```\n\n### Using Different Storage Adapters\n\n#### Browser (LocalStorage)\n\n```typescript\nimport { Agent, LocalStorageAdapter, OpenAIProvider } from '@ahmedelsharkawycs/forge-ai-sdk';\n\nconst agent = new Agent({\n  adapter: new LocalStorageAdapter('my-agent-state'), // Custom storage key\n  provider: new OpenAIProvider({ apiKey: 'sk-...' })\n});\n```\n\n#### Node.js (File System)\n\n```typescript\nimport { Agent, NodeFSAdapter, AnthropicProvider } from '@ahmedelsharkawycs/forge-ai-sdk';\n\nconst agent = new Agent({\n  adapter: new NodeFSAdapter('./.ai-agent-state.json'), // Atomic writes, file watching\n  provider: new AnthropicProvider({ apiKey: 'sk-ant-...' })\n});\n```\n\n### Using Anthropic (Claude)\n\n```typescript\nimport { Agent, InMemoryAdapter, AnthropicProvider } from '@ahmedelsharkawycs/forge-ai-sdk';\n\nconst agent = new Agent({\n  adapter: new InMemoryAdapter(),\n  provider: new AnthropicProvider({\n    apiKey: process.env.ANTHROPIC_API_KEY,\n    model: 'claude-sonnet-4-5' // Default model\n  })\n});\n```\n\n### Using Project Templates\n\nThe SDK ships with a pre-built React + Vite + MUI + TypeScript template that includes all essential project files (`App.tsx`, `main.tsx`, `theme.ts`, `package.json`, `vite.config.ts`, `tsconfig.json`, `index.html`):\n\n```typescript\nimport { Agent, InMemoryAdapter, OpenAIProvider, getReactMUIViteTemplate } from '@ahmedelsharkawycs/forge-ai-sdk';\n\nconst agent = new Agent({\n  adapter: new InMemoryAdapter(),\n  provider: new OpenAIProvider({ apiKey: process.env.OPENAI_API_KEY }),\n  initialFiles: getReactMUIViteTemplate()\n});\n\nawait agent.initialize();\n\n// The agent now has full project context and can generate components,\n// update the theme, add dependencies to package.json, etc.\nawait agent.sendMessage('Add a login page with email and password fields');\n```\n\n## Architecture\n\nThe agent follows a phase-based orchestration pattern:\n\n```\nUser Message\n    ↓\nIntent Phase (Classify intent, identify target files)\n    ↓\nPlanning Phase (Create action plan, validate against policies)\n    ↓\nExecution Phase (Execute actions, generate content, update virtual files)\n    ↓\nValidation Phase (Verify changes, generate markdown summary)\n    ↓\nResponse\n```\n\n### Intent Types\n\nThe agent classifies user requests into these intent types:\n- `create` - Create new files\n- `edit` - Modify existing files\n- `delete` - Remove files\n- `query` - Answer questions about code\n- `refactor` - Restructure code\n- `analyze` - Analyze code patterns\n\n### Action Types\n\nThe planning phase generates these action types:\n- `create_file` - Create a new file\n- `update_file` - Update existing file content\n- `delete_file` - Delete a file\n- `read_file` - Read file for context\n\nEach action can include a `relatedFiles` array populated by the planning phase using the dependency graph, which provides the execution phase with the right context for code generation.\n\n### Core Components\n\n#### 1. State Manager\n\nManages the agent's state with transactional updates, version tracking, and rollback support:\n\n```typescript\nimport { StateManager, InMemoryAdapter } from '@ahmedelsharkawycs/forge-ai-sdk';\n\nconst stateManager = new StateManager(new InMemoryAdapter());\nawait stateManager.initialize();\n\n// Transactional update with automatic rollback on error\nawait stateManager.transaction(async (state) => {\n  await stateManager.updateFiles([\n    { type: 'update', path: '/file.ts', content: 'new content' }\n  ]);\n});\n\n// Rollback to previous version (keeps last 10 snapshots)\nawait stateManager.rollback(previousVersion);\n```\n\n#### 2. Virtual File System\n\nOperates on virtual files without touching the real filesystem:\n\n```typescript\nimport { VirtualFileSystem } from '@ahmedelsharkawycs/forge-ai-sdk';\n\nconst vfs = new VirtualFileSystem([\n  { path: '/src/app.ts', content: 'code', version: 1, lastModified: Date.now() }\n]);\n\n// Write file (auto-detects language from extension)\nvfs.writeFile('/src/utils.ts', 'export const add = (a, b) => a + b;');\n\n// Read file\nconst file = vfs.getFile('/src/utils.ts');\n\n// Find files by pattern\nconst tsFiles = vfs.findFiles(/\\.ts$/);\n\n// Apply batch changes\nvfs.applyChanges([\n  { type: 'create', path: '/new.ts', content: 'content' },\n  { type: 'update', path: '/src/app.ts', content: 'updated' },\n  { type: 'delete', path: '/old.ts' }\n]);\n```\n\n**Supported Languages** (auto-detected from file extension):\n- TypeScript (`.ts`, `.tsx`)\n- JavaScript (`.js`, `.jsx`)\n- JSON (`.json`)\n- HTML (`.html`)\n- Markdown (`.md`)\n\n#### 3. Policy Gate\n\nEnforce safety policies and restrictions:\n\n```typescript\nimport { PolicyGate } from '@ahmedelsharkawycs/forge-ai-sdk';\n\nconst policyGate = new PolicyGate({\n  maxFileSize: 1024 * 1024, // 1MB (default)\n  allowedFileTypes: ['ts', 'tsx', 'js', 'jsx', 'json'],\n  maxConcurrentActions: 20, // default\n  requireConfirmation: true\n});\n\n// Validate a plan\nconst result = policyGate.validatePlan(plan);\nif (!result.allowed) {\n  console.error(`Policy violation: ${result.reason}`);\n}\n\n// Validate path safety (prevents directory traversal, unsafe patterns)\nconst pathResult = policyGate.validateAction(action);\n```\n\n## API Reference\n\n### Agent\n\nMain agent class for orchestrating AI operations.\n\n#### Constructor\n\n```typescript\nnew Agent(options: AgentOptions)\n```\n\n**Options:**\n- `adapter`: Storage adapter (InMemoryAdapter, LocalStorageAdapter, NodeFSAdapter)\n- `provider`: LLM provider (OpenAIProvider, AnthropicProvider)\n- `initialFiles?`: Array of initial virtual files\n- `policies?`: Policy configuration\n- `autoSave?`: Auto-save state after changes (default: true)\n\n#### Methods\n\n- `initialize()`: Initialize the agent and load state\n- `sendMessage(content: string)`: Send a message and get a response\n- `getFiles()`: Get all virtual files\n- `getFile(path: string)`: Get a specific file\n- `getMessages()`: Get message history\n- `getState()`: Get current agent state\n- `on(event, handler)`: Register event listener\n- `once(event, handler)`: Register one-time event listener\n- `off(event, handler)`: Remove event listener\n- `clear()`: Clear all state\n- `destroy()`: Cleanup resources\n\n#### Events\n\n**Phase Events:**\n- `intent:start` - Intent phase starting\n- `intent:complete` - Intent phase completed\n- `plan:start` - Planning phase starting\n- `plan:complete` - Planning phase completed\n- `execute:start` - Execution phase starting\n- `execute:complete` - Execution phase completed\n- `validate:start` - Validation phase starting\n- `validate:complete` - Validation phase completed\n\n**File Events:**\n- `file:create` - File created\n- `file:update` - File updated\n- `file:delete` - File deleted\n\n**Action Events:**\n- `action:start` - Individual action starting\n- `action:complete` - Individual action completed\n- `action:failed` - Individual action failed\n\n**LLM Events (Non-Streaming):**\n- `llm:start` - LLM request starting\n- `llm:complete` - LLM request completed\n\n**Streaming Events:**\n- `stream:start` - Streaming started\n- `stream:chunk` - Received chunk `{ content: string }`\n- `stream:complete` - Streaming completed\n\n**Other Events:**\n- `message:add` - Message added to history\n- `error` - Error occurred\n\n### Storage Adapters\n\n#### InMemoryAdapter\n\nEphemeral in-memory storage (useful for testing).\n\n```typescript\nconst adapter = new InMemoryAdapter();\n// Deep clones state to prevent external mutations\n```\n\n#### LocalStorageAdapter\n\nBrowser localStorage persistence with cross-tab sync.\n\n```typescript\nconst adapter = new LocalStorageAdapter('storage-key'); // default: 'ai-agent-state'\n\n// Watch for external changes (cross-tab sync)\nconst unsubscribe = adapter.watch((state) => {\n  console.log('State changed in another tab');\n});\n```\n\n#### NodeFSAdapter\n\nNode.js filesystem persistence with atomic writes.\n\n```typescript\nconst adapter = new NodeFSAdapter('./path/to/state.json');\n\n// Atomic writes (temp file + rename)\n// Auto-creates directories\n// Optional file watching\nconst unsubscribe = adapter.watch((state) => {\n  console.log('State file changed');\n});\n```\n\n### LLM Providers\n\n#### OpenAIProvider\n\n```typescript\nconst provider = new OpenAIProvider({\n  apiKey: 'sk-...',\n  model: 'gpt-5.2', // default\n  organization: 'org-...', // optional\n  baseURL: 'https://api.openai.com/v1', // optional\n  streaming: true // Enable/disable streaming (default: true)\n});\n\n// Supports tool calling and streaming\n```\n\n#### AnthropicProvider\n\n```typescript\nconst provider = new AnthropicProvider({\n  apiKey: 'sk-ant-...',\n  model: 'claude-sonnet-4-5', // default\n  baseURL: 'https://api.anthropic.com', // optional\n  streaming: true // Enable/disable streaming (default: true)\n});\n\n// Supports tool calling and streaming\n```\n\n### Provider Interface\n\nCreate custom providers by implementing:\n\n```typescript\ninterface ILLMProvider {\n  name: string;\n  complete(request: LLMRequest): Promise<LLMResponse>;\n  stream?(request: LLMRequest): AsyncIterable<LLMChunk>;\n}\n```\n\n## Advanced Usage\n\n### Custom Policy Configuration\n\n```typescript\nconst agent = new Agent({\n  adapter: new InMemoryAdapter(),\n  provider: new OpenAIProvider({ apiKey: 'sk-...' }),\n  policies: {\n    maxFileSize: 500 * 1024, // 500KB\n    allowedFileTypes: ['ts', 'tsx'],\n    maxConcurrentActions: 20, // default is 20\n    requireConfirmation: false\n  }\n});\n```\n\n### State Snapshots and Rollback\n\n```typescript\n// State manager keeps last 10 snapshots automatically\nconst state = agent.getState();\nconsole.log('Current version:', state.version);\n\n// Make changes\nawait agent.sendMessage('Refactor the code');\n\n// Access the state manager for rollback\n// Note: StateManager is internal, access via agent internals if needed\n```\n\n### Real-Time Streaming\n\n```typescript\n// Listen for streaming chunks\nagent.on('stream:start', () => {\n  console.log('LLM started generating...');\n});\n\nagent.on('stream:chunk', ({ content }) => {\n  process.stdout.write(content); // Real-time output\n});\n\nagent.on('stream:complete', () => {\n  console.log('\\nGeneration complete');\n});\n\n// Send message - streaming happens automatically if provider supports it\nawait agent.sendMessage('Generate a complex component');\n```\n\n### Event-Driven Workflows\n\n```typescript\n// Track all phases\nagent.on('intent:start', () => console.log('Analyzing intent...'));\nagent.on('intent:complete', (result) => console.log('Intent:', result.type));\n\nagent.on('plan:start', () => console.log('Creating plan...'));\nagent.on('plan:complete', (plan) => console.log('Actions:', plan.actions.length));\n\nagent.on('execute:start', () => console.log('Executing...'));\nagent.on('action:start', (action) => console.log('Action:', action.type, action.path));\nagent.on('action:complete', (action) => console.log('Completed:', action.path));\nagent.on('execute:complete', (result) => console.log('Success:', result.success));\n\nagent.on('validate:start', () => console.log('Validating...'));\nagent.on('validate:complete', (result) => console.log('Valid:', result.isValid));\n\nagent.on('file:create', (file) => console.log('Created:', file.path));\nagent.on('file:update', (file) => console.log('Updated:', file.path));\nagent.on('file:delete', (path) => console.log('Deleted:', path));\n\nagent.on('error', (error) => console.error('Error:', error));\n```\n\n### Working with Virtual Files\n\n```typescript\n// Get all files\nconst files = agent.getFiles();\n\n// Filter files by pattern\nconst tsFiles = files.filter(f => f.path.endsWith('.ts'));\n\n// Get file content\nconst file = agent.getFile('/src/index.ts');\nconsole.log(file?.content);\n\n// Access file metadata\nconsole.log({\n  path: file?.path,\n  version: file?.version,\n  language: file?.language, // Auto-detected\n  lastModified: new Date(file?.lastModified)\n});\n```\n\n### Path Convention\n\nAll file paths must start with `/`:\n\n```typescript\n// Correct\n'/src/components/Button.tsx'\n'/utils/helpers.ts'\n'/package.json'\n\n// Incorrect (will be normalized)\n'src/components/Button.tsx'\n'./utils/helpers.ts'\n```\n\n## Examples\n\n### Example 1: Code Generation\n\n```typescript\nconst agent = new Agent({\n  adapter: new InMemoryAdapter(),\n  provider: new OpenAIProvider({ apiKey: process.env.OPENAI_API_KEY }),\n  initialFiles: []\n});\n\nawait agent.initialize();\n\nawait agent.sendMessage(\n  'Create a TypeScript utility file with functions for string manipulation'\n);\n\nconst utils = agent.getFile('/src/utils.ts');\nconsole.log(utils?.content);\n```\n\n### Example 2: Code Refactoring\n\n```typescript\nconst agent = new Agent({\n  adapter: new LocalStorageAdapter('refactor-session'),\n  provider: new AnthropicProvider({ apiKey: process.env.ANTHROPIC_API_KEY }),\n  initialFiles: [\n    {\n      path: '/src/legacy.js',\n      content: oldCode,\n      version: 1,\n      lastModified: Date.now()\n    }\n  ]\n});\n\nawait agent.initialize();\nawait agent.sendMessage('Convert /src/legacy.js to TypeScript with proper types');\n\nconst modernCode = agent.getFile('/src/legacy.ts');\n```\n\n### Example 3: Multi-File Project Setup\n\n```typescript\nconst agent = new Agent({\n  adapter: new NodeFSAdapter('./project-state.json'),\n  provider: new OpenAIProvider({ apiKey: process.env.OPENAI_API_KEY })\n});\n\nawait agent.initialize();\n\nawait agent.sendMessage(`\n  Create a React component library with:\n  - Button component\n  - Input component\n  - Card component\n  - TypeScript types\n  - Index file exporting all components\n`);\n\nconst files = agent.getFiles();\nfiles.forEach(f => console.log(f.path));\n```\n\n### Example 4: Streaming Response\n\n```typescript\nconst agent = new Agent({\n  adapter: new InMemoryAdapter(),\n  provider: new OpenAIProvider({ apiKey: process.env.OPENAI_API_KEY })\n});\n\nawait agent.initialize();\n\n// Set up streaming before sending message\nlet fullContent = '';\nagent.on('stream:chunk', ({ content }) => {\n  fullContent += content;\n  process.stdout.write(content);\n});\n\nagent.on('stream:complete', () => {\n  console.log('\\n--- Streaming complete ---');\n  console.log('Total length:', fullContent.length);\n});\n\nawait agent.sendMessage('Explain this codebase structure');\n```\n\n## Type Safety\n\nThe SDK is fully typed with TypeScript and uses Zod for runtime validation:\n\n```typescript\nimport { \n  validateSchema, \n  IntentResultSchema,\n  ActionPlanSchema,\n  type IntentResult,\n  type ActionPlan,\n  type ValidationResult\n} from '@ahmedelsharkawycs/forge-ai-sdk';\n\n// Validate unknown data\nconst data: unknown = getLLMResponse();\nconst result = validateSchema(IntentResultSchema, data);\n\nif (result.success) {\n  const intent: IntentResult = result.data;\n  console.log(intent.type, intent.confidence);\n} else {\n  console.error('Validation error:', result.error);\n}\n\n// Safe parsing with fallback\nimport { parseOrDefault } from '@ahmedelsharkawycs/forge-ai-sdk';\nconst plan = parseOrDefault(ActionPlanSchema, data, defaultPlan);\n\n// ValidationResult uses simple string errors\nconst validation: ValidationResult = {\n  isValid: true,\n  summary: '## Changes Summary\\n...',\n  errors: [] // Simple string array (no more ValidationError objects)\n};\n```\n\n## Logging\n\nThe SDK includes a configurable logger:\n\n```typescript\nimport { Logger } from '@ahmedelsharkawycs/forge-ai-sdk';\n\n// Create logger with log level\nconst logger = new Logger('info'); // 'info' | 'debug' | 'error' | 'all' | 'none'\n\nlogger.info('Information message');\nlogger.debug('Debug details');\nlogger.error('Error occurred', error);\n\n// Create child logger with prefix\nconst childLogger = logger.createChildLogger('[MyComponent]');\nchildLogger.info('Prefixed message');\n\n// Access log history\nconst history = logger.getHistory();\n```\n\n## Best Practices\n\n1. **Initialize Before Use**: Always call `agent.initialize()` before sending messages\n2. **Use Policies**: Configure appropriate policies for your use case\n3. **Handle Events**: Listen to events for better observability\n4. **Error Handling**: Wrap agent calls in try-catch blocks\n5. **State Persistence**: Choose the right adapter for your environment\n6. **Clean Up**: Call `agent.destroy()` when done to free resources\n7. **Path Convention**: Always use paths starting with `/`\n8. **Streaming**: Use streaming events for better UX in interactive applications\n\n## Security\n\nThe SDK includes multiple security features:\n\n- **Path Validation**: Prevents directory traversal attacks (`..`, `//`)\n- **File Size Limits**: Prevents memory exhaustion (default 1MB)\n- **Type Validation**: Runtime checks with Zod schemas\n- **Policy Gates**: Configurable restrictions on actions\n- **Virtual State**: No direct filesystem access\n- **Unsafe Path Detection**: Blocks system paths, null bytes, invalid characters\n\n## Contributing\n\nContributions are welcome! Please read our contributing guidelines before submitting PRs.\n\n## License\n\nMIT\n\n## Support\n\nFor issues and questions, please open a GitHub issue.\n","readmeFilename":"README.md"}