### Install @tinyclaw/matcher Source: https://github.com/warengonzaga/tinyclaw/blob/main/packages/matcher/README.md Install the @tinyclaw/matcher package using Bun. ```bash bun add @tinyclaw/matcher ``` -------------------------------- ### Start Development Server Source: https://github.com/warengonzaga/tinyclaw/blob/main/src/landing/README.md Use this command to start the development server. It runs on port 5174. ```bash bun run dev ``` -------------------------------- ### Install @tinyclaw/logger Source: https://github.com/warengonzaga/tinyclaw/blob/main/packages/logger/README.md Install the logger package using bun. ```bash bun add @tinyclaw/logger ``` -------------------------------- ### Clean Commit Examples Source: https://github.com/warengonzaga/tinyclaw/blob/main/CONTRIBUTING.md Examples demonstrating the Clean Commit convention used for commit messages, including prefixes for new features, updates, removals, security fixes, setup, chores, tests, docs, and releases. ```text ๐Ÿ“ฆ new (core): add conversation memory system ๐Ÿ”ง update (api): improve error handling ๐Ÿงช test (memory): add unit tests for temporal decay ๐Ÿ“– docs: update installation instructions ``` -------------------------------- ### Basic tinyclaw CLI Commands Source: https://github.com/warengonzaga/tinyclaw/blob/main/src/cli/README.md Provides a list of essential commands for interacting with the tinyclaw CLI. Use these for initial setup, starting the agent, managing configuration, backing up data, and resetting the agent. ```bash tinyclaw setup # First-time setup tinyclaw start # Start the agent tinyclaw config # Manage configuration tinyclaw backup # Backup agent data tinyclaw purge # Reset agent data ``` -------------------------------- ### Run Development Server Source: https://github.com/warengonzaga/tinyclaw/blob/main/src/web/README.md Use this command to start the development server with hot-reloading. Requires Bun or npm. ```bash bun run dev ``` ```bash npm run dev ``` -------------------------------- ### Install @tinyclaw/shield Source: https://github.com/warengonzaga/tinyclaw/blob/main/packages/shield/README.md Install the @tinyclaw/shield package using bun. ```bash bun add @tinyclaw/shield ``` -------------------------------- ### Install tinyclaw CLI Source: https://github.com/warengonzaga/tinyclaw/blob/main/src/cli/README.md Installs the tinyclaw CLI globally using Bun. Ensure Bun is installed on your system. ```bash bun add -g tinyclaw ``` -------------------------------- ### Install @tinyclaw/secrets Source: https://github.com/warengonzaga/tinyclaw/blob/main/packages/secrets/README.md Install the @tinyclaw/secrets package using Bun. ```bash bun add @tinyclaw/secrets ``` -------------------------------- ### Install @tinyclaw/intercom Source: https://github.com/warengonzaga/tinyclaw/blob/main/packages/intercom/README.md Install the @tinyclaw/intercom package using bun. ```bash bun add @tinyclaw/intercom ``` -------------------------------- ### Install Dependencies with Bun Source: https://github.com/warengonzaga/tinyclaw/blob/main/README.md Installs project dependencies using the Bun package manager. Ensure Bun is installed before running. ```bash bun install ``` -------------------------------- ### Fork and Clone Tiny Claw Repository Source: https://github.com/warengonzaga/tinyclaw/blob/main/CONTRIBUTING.md Instructions for setting up your local development environment by forking the repository, cloning it, adding the upstream remote, and installing dependencies using Bun. ```bash # Fork the repo on GitHub first, then: git clone https://github.com/YOUR_USERNAME/tinyclaw.git cd tinyclaw git remote add upstream https://github.com/warengonzaga/tinyclaw.git bun install ``` -------------------------------- ### Install @tinyclaw/sandbox Source: https://github.com/warengonzaga/tinyclaw/blob/main/packages/sandbox/README.md Add the @tinyclaw/sandbox package to your project dependencies using Bun. ```bash bun add @tinyclaw/sandbox ``` -------------------------------- ### Run Tiny Claw in Development Source: https://github.com/warengonzaga/tinyclaw/blob/main/CONTRIBUTING.md Commands to start the CLI and web UI in development mode, build the project, and run the test suite using Bun. ```bash bun dev # Start the CLI in development mode bun dev:ui # Start the web UI in development mode bun build # Build all packages bun test # Run the full test suite ``` -------------------------------- ### Install @tinyclaw/shell Source: https://github.com/warengonzaga/tinyclaw/blob/main/packages/shell/README.md Install the @tinyclaw/shell package using Bun. This is the primary method for adding the package to your project. ```bash bun add @tinyclaw/shell ``` -------------------------------- ### Develop a Telegram Channel Plugin Source: https://context7.com/warengonzaga/tinyclaw/llms.txt Illustrates creating a Telegram channel plugin for TinyClaw. It includes defining pairing tools for conversational setup, implementing the `ChannelPlugin` interface with `start` and `stop` methods, and handling message routing between Telegram and the agent loop. ```typescript import type { ChannelPlugin, PluginRuntimeContext, Tool, SecretsManagerInterface, ConfigManagerInterface, } from '@tinyclaw/types'; // Create pairing tools for conversational setup function createPairingTools( secrets: SecretsManagerInterface, configManager: ConfigManagerInterface, ): Tool[] { return [ { name: 'telegram_pair', description: 'Connect your Telegram bot to Tiny Claw', parameters: { type: 'object', properties: { bot_token: { type: 'string', description: 'Telegram bot token from @BotFather' }, }, required: ['bot_token'], }, async execute(args) { const token = String(args.bot_token); // Validate token format if (!token.match(/^\d+:[A-Za-z0-9_-]+$/)) { return 'Invalid bot token format'; } // Store token securely await secrets.store('channel.telegram.token', token); // Enable the channel configManager.set('channels.telegram.enabled', true); // Add plugin to enabled list const plugins = configManager.get('plugins.enabled', []) as string[]; if (!plugins.includes('@tinyclaw/plugin-channel-telegram')) { plugins.push('@tinyclaw/plugin-channel-telegram'); configManager.set('plugins.enabled', plugins); } return 'Telegram bot connected! Please restart Tiny Claw to activate.'; }, }, ]; } // Define the channel plugin const plugin: ChannelPlugin = { id: '@tinyclaw/plugin-channel-telegram', name: 'Telegram', description: 'Telegram channel plugin for Tiny Claw', type: 'channel', version: '0.1.0', getPairingTools(secrets, configManager) { return createPairingTools(secrets, configManager); }, async start(context: PluginRuntimeContext) { // Resolve bot token from secrets const token = await context.secrets.get('channel.telegram.token'); if (!token) throw new Error('Telegram bot token not configured'); // Initialize Telegram bot client // ... bot setup code ... // Handle incoming messages bot.on('message', async (msg) => { // Skip bot's own messages if (msg.from?.is_bot) return; // Namespace user ID to prevent collisions const userId = `telegram:${msg.from?.id}`; const text = msg.text || ''; // Send to agent loop via context.enqueue const response = await context.enqueue(userId, text); // Send response back to Telegram await bot.sendMessage(msg.chat.id, response); }); console.log('Telegram channel started'); }, async stop() { // Disconnect and cleanup // ... cleanup code ... console.log('Telegram channel stopped'); }, }; export default plugin; ``` -------------------------------- ### Run Tiny Claw Application Source: https://github.com/warengonzaga/tinyclaw/blob/main/README.md Starts the Tiny Claw application. Access the web interface at http://localhost:3000 after running. ```bash bun start ``` -------------------------------- ### Install @tinyclaw/config Source: https://github.com/warengonzaga/tinyclaw/blob/main/packages/config/README.md Install the @tinyclaw/config package using Bun. This command adds the package as a dependency to your project. ```bash bun add @tinyclaw/config ``` -------------------------------- ### Install @tinyclaw/delegation Source: https://github.com/warengonzaga/tinyclaw/blob/main/packages/delegation/README.md Install the delegation package using bun. This command adds the necessary dependencies for sub-agent delegation and lifecycle management. ```bash bun add @tinyclaw/delegation ``` -------------------------------- ### Install @tinyclaw/plugins Source: https://github.com/warengonzaga/tinyclaw/blob/main/packages/plugins/README.md Install the @tinyclaw/plugins package using Bun. This command adds the package to your project's dependencies. ```bash bun add @tinyclaw/plugins ``` -------------------------------- ### Install @tinyclaw/heartware with Bun Source: https://github.com/warengonzaga/tinyclaw/blob/main/packages/heartware/README.md Use this command to add the @tinyclaw/heartware package to your project dependencies when using Bun. ```bash bun add @tinyclaw/heartware ``` -------------------------------- ### Install @tinyclaw/core with Bun Source: https://github.com/warengonzaga/tinyclaw/blob/main/packages/core/README.md Use this command to add the @tinyclaw/core package to your project when using the Bun package manager. ```bash bun add @tinyclaw/core ``` -------------------------------- ### Install @tinyclaw/pulse Source: https://github.com/warengonzaga/tinyclaw/blob/main/packages/pulse/README.md Use this command to add the @tinyclaw/pulse package to your project dependencies. ```bash bun add @tinyclaw/pulse ``` -------------------------------- ### Create and Use Nudge Engine Source: https://github.com/warengonzaga/tinyclaw/blob/main/packages/nudge/README.md Initialize the nudge engine with a gateway, schedule nudges with various parameters, and flush pending notifications. This setup is typically part of the agent's core functionality. ```typescript import { createNudgeEngine, wireNudgeToIntercom, createNudgeTools } from '@tinyclaw/nudge'; // Create the engine with an outbound gateway const nudgeEngine = createNudgeEngine({ gateway }); // Schedule a nudge nudgeEngine.schedule({ userId: 'web:owner', category: 'reminder', content: 'Don\'t forget to review the pull request!', priority: 'normal', deliverAfter: Date.now() + 30 * 60_000, // 30 minutes from now }); // Flush pending nudges (called by Pulse on a 1-minute interval) await nudgeEngine.flush(); // Wire intercom events to auto-generate nudges const unwire = wireNudgeToIntercom(nudgeEngine, intercom); // Create agent tools (send_nudge, check_pending_nudges, cancel_nudge) const tools = createNudgeTools(nudgeEngine); ``` -------------------------------- ### Install @tinyclaw/queue with Bun Source: https://github.com/warengonzaga/tinyclaw/blob/main/packages/queue/README.md Use this command to add the @tinyclaw/queue package to your project dependencies when using Bun as your package manager. ```bash bun add @tinyclaw/queue ``` -------------------------------- ### Install @tinyclaw/memory with Bun Source: https://github.com/warengonzaga/tinyclaw/blob/main/packages/memory/README.md Use this command to add the @tinyclaw/memory package to your project when using the Bun package manager. ```bash bun add @tinyclaw/memory ``` -------------------------------- ### Install @tinyclaw/router Source: https://github.com/warengonzaga/tinyclaw/blob/main/packages/router/README.md Use this command to add the @tinyclaw/router package to your project dependencies. ```bash bun add @tinyclaw/router ``` -------------------------------- ### Install @tinyclaw/compactor with Bun Source: https://github.com/warengonzaga/tinyclaw/blob/main/packages/compactor/README.md Use this command to add the @tinyclaw/compactor package to your project dependencies when using the Bun package manager. ```bash bun add @tinyclaw/compactor ``` -------------------------------- ### Create Delegation Tools Source: https://context7.com/warengonzaga/tinyclaw/llms.txt Initialize delegation tools using `createDelegationTools` for managing sub-agents. This setup requires various configurations like an orchestrator, database, and message queue. The tools enable task delegation, lifecycle management, and template operations. ```typescript import { createDelegationTools } from '@tinyclaw/delegation'; // Create delegation tools with configuration const { tools, lifecycle, templates, background } = createDelegationTools({ orchestrator: providerOrchestrator, allTools: registeredTools, db: database, heartwareContext, learning: learningEngine, queue: messageQueue, defaultSubAgentTools: ['heartware_read', 'memory_recall', 'execute_code'], timeoutEstimator, intercom: intercomBus, }); ``` -------------------------------- ### Minimal Channel Plugin Template Source: https://github.com/warengonzaga/tinyclaw/blob/main/plugins/channel/README.md A basic template for a Tiny Claw channel plugin, including necessary imports, interface implementation, and placeholder methods for pairing, starting, and stopping. ```typescript import type { ChannelPlugin, PluginRuntimeContext, Tool, SecretsManagerInterface, ConfigManagerInterface, } from '@tinyclaw/types'; function createPairingTools( secrets: SecretsManagerInterface, configManager: ConfigManagerInterface, ): Tool[] { return []; } const plugin: ChannelPlugin = { id: '@tinyclaw/plugin-channel-', name: '', description: ' channel plugin for Tiny Claw', type: 'channel', version: '0.1.0', getPairingTools( secrets: SecretsManagerInterface, configManager: ConfigManagerInterface, ): Tool[] { return createPairingTools(secrets, configManager); }, async start(context: PluginRuntimeContext): Promise { // 1. Resolve token/settings from context.secrets + context.configManager // 2. Connect to platform SDK // 3. On inbound message: // const response = await context.enqueue(userId, text); // 4. Send response back to the channel }, async stop(): Promise { // Disconnect SDK clients and clean up }, }; export default plugin; ``` -------------------------------- ### Build Production Application Source: https://github.com/warengonzaga/tinyclaw/blob/main/src/web/README.md Use this command to create a production-ready build of the application. Requires Bun or npm. ```bash bun run build ``` ```bash npm run build ``` -------------------------------- ### Preview Production Build Source: https://github.com/warengonzaga/tinyclaw/blob/main/src/web/README.md Use this command to preview the production build locally. Requires Bun or npm. ```bash bun run preview ``` ```bash npm run preview ``` -------------------------------- ### Build for Production Source: https://github.com/warengonzaga/tinyclaw/blob/main/src/landing/README.md Execute this command to build the project for production deployment. ```bash bun run build ``` -------------------------------- ### Initialize and Run Tiny Claw Agent Loop Source: https://context7.com/warengonzaga/tinyclaw/llms.txt Demonstrates how to set up the AgentContext with necessary dependencies and initiate the agent loop for processing user messages with streaming responses. Ensure all context dependencies like database, LLM provider, and memory engine are properly initialized before use. ```typescript import { agentLoop } from '@tinyclaw/core'; import type { AgentContext, StreamEvent } from '@tinyclaw/types'; // Define the agent context with all required dependencies const context: AgentContext = { db: database, // SQLite database instance provider: ollamaProvider, // LLM provider (Ollama, OpenAI, etc.) learning: learningEngine, // Behavioral pattern detection tools: registeredTools, // Array of available tools heartwareContext: heartwareCtx, // Personality and configuration context shield: shieldEngine, // Security policy engine modelName: 'kimi-k2.5:cloud', // Current model name providerName: 'Ollama Cloud', // Provider display name ownerId: 'user-123', // Owner's user ID for authority checks memory: memoryEngine, // Adaptive memory engine compactor: compactorEngine, // Context compaction engine delegation: delegationContext, // Sub-agent delegation system }; // Process a message with streaming response const response = await agentLoop( 'Help me analyze this codebase', // User message 'user-123', // User ID context, (event: StreamEvent) => { // Handle streaming events switch (event.type) { case 'text': process.stdout.write(event.content); break; case 'tool_start': console.log(`Running tool: ${event.tool}`); break; case 'tool_result': console.log(`Tool result: ${event.result}`); break; case 'delegation_start': console.log(`Delegating to: ${event.delegation.role}`); break; case 'done': console.log('\nResponse complete'); break; } } ); ``` -------------------------------- ### Preview Production Build Source: https://github.com/warengonzaga/tinyclaw/blob/main/src/landing/README.md Use this command to preview the production build locally before deploying. ```bash bun run preview ``` -------------------------------- ### Create and Use Adaptive Memory Engine Source: https://context7.com/warengonzaga/tinyclaw/llms.txt Initializes the memory engine with a database and demonstrates recording various event types with optional importance overrides. It also shows how to search memories using a query and retrieve context for an agent. ```typescript import { createMemoryEngine } from '@tinyclaw/memory'; // Create memory engine with database const memory = createMemoryEngine(db); // Record different types of events const correctionId = memory.recordEvent('user-123', { type: 'correction', content: 'User corrected: prefer TypeScript over JavaScript', outcome: 'Updated coding preferences', importance: 0.95, }); memory.recordEvent('user-123', { type: 'preference_learned', content: 'User likes concise responses without emojis', }); memory.recordEvent('user-123', { type: 'fact_stored', content: 'User lives in Philippines, timezone UTC+08:00', }); memory.recordEvent('user-123', { type: 'task_completed', content: 'Helped debug authentication issue', outcome: 'Fixed JWT token validation', }); // Search memories with relevance scoring const results = memory.search('user-123', 'coding preferences', 10); results.forEach(result => { console.log(`[${result.source}] Score: ${result.relevanceScore.toFixed(2)}`); console.log(` ${result.content}`); }); // Get context for agent system prompt const context = memory.getContextForAgent('user-123', 'help with code'); console.log(context); ``` -------------------------------- ### Build Project Packages Source: https://github.com/warengonzaga/tinyclaw/blob/main/README.md Compiles and bundles all project packages. This command is typically used before deployment. ```bash bun build ``` -------------------------------- ### Initialize and Use Heartware Manager Source: https://context7.com/warengonzaga/tinyclaw/llms.txt Sets up the Heartware Manager for secure file-based configuration, including initialization, reading, writing, searching, and listing configuration files. Demonstrates loading context and creating agent tools. ```typescript import { HeartwareManager, createHeartwareTools, loadHeartwareContext } from '@tinyclaw/heartware'; // Create heartware manager const heartware = new HeartwareManager({ baseDir: '/path/to/.tinyclaw/data/heartware', userId: 'user-123', auditDir: '/path/to/.tinyclaw/data/audit', backupDir: '/path/to/.tinyclaw/data/heartware/.backups', }); // Initialize (creates default files if needed) await heartware.initialize(); // Read a configuration file const soulContent = await heartware.read('SOUL.md'); const friendContent = await heartware.read('FRIEND.md'); // Write to a configuration file (with audit logging) await heartware.write('FRIEND.md', ` # Owner Profile Name: John Location: Philippines Timezone: UTC+08:00 ## Preferences - Prefers concise responses - Likes code examples `); // Search across all files const results = await heartware.search('timezone'); results.forEach(r => console.log(`Found in ${r.file}: ${r.match}`)); // List all heartware files const files = await heartware.list(); // Returns: ['SOUL.md', 'IDENTITY.md', 'FRIEND.md', 'FRIENDS.md', 'SHIELD.md', 'memory/'] // Load heartware context for agent system prompt const context = await loadHeartwareContext(heartware); // Returns formatted markdown with identity, soul traits, preferences, etc. // Create agent tools for heartware manipulation const tools = createHeartwareTools(heartware); // Tools: heartware_read, heartware_write, heartware_list, heartware_search ``` -------------------------------- ### ChannelPlugin Interface Definition Source: https://github.com/warengonzaga/tinyclaw/blob/main/plugins/channel/README.md Defines the contract for channel plugins, including metadata and methods for starting, stopping, and optionally providing pairing tools. ```typescript export interface ChannelPlugin extends PluginMeta { readonly type: 'channel'; start(context: PluginRuntimeContext): Promise; stop(): Promise; getPairingTools?( secrets: SecretsManagerInterface, configManager: ConfigManagerInterface, ): Tool[]; } ``` -------------------------------- ### ProviderPlugin Interface Definition Source: https://github.com/warengonzaga/tinyclaw/blob/main/plugins/provider/README.md Defines the contract for a Tiny Claw provider plugin, including methods for creating a provider and optionally getting pairing tools. ```typescript export interface ProviderPlugin extends PluginMeta { readonly type: 'provider'; createProvider(secrets: SecretsManagerInterface): Promise; getPairingTools?( secrets: SecretsManagerInterface, configManager: ConfigManagerInterface, ): Tool[]; } ``` -------------------------------- ### Create a Learning Engine for Pattern Detection Source: https://context7.com/warengonzaga/tinyclaw/llms.txt Initialize a learning engine with a storage path and minimum confidence level. Analyze conversations to detect user preferences and patterns, then retrieve learned context for prompt injection. ```typescript import { createLearningEngine } from '@tinyclaw/learning'; // Create learning engine with storage path const learning = createLearningEngine({ storagePath: '/path/to/.tinyclaw/data/learning', minConfidence: 0.7, // Minimum confidence to store patterns }); // Analyze a conversation exchange learning.analyze( 'Can you make the response shorter?', // User message 'Of course! I\'ll be more concise. Here\'s...', // Assistant response conversationHistory // Message history ); // Detected signals are automatically stored as patterns // Signal types: correction, positive, preference, negative // Get learned context for prompt injection const context = learning.getContext(); console.log('Preferences:', context.preferences); console.log('What works:', context.patterns); console.log('Recent corrections:', context.recentCorrections); // Output: // Preferences: // - User prefers concise responses // What works: // - Works well: Direct answers without preamble // Recent corrections: // - User corrected: responses were too verbose // Inject learned context into system prompt const enhancedPrompt = learning.injectIntoPrompt(baseSystemPrompt, context); // Appends: // ## Learned About This User // ### Preferences // - User prefers concise responses // ### What Works // - Works well: Direct answers without preamble // ### Recent Corrections // - User corrected: responses were too verbose // Get learning statistics const stats = learning.getStats(); console.log(`Total patterns: ${stats.totalPatterns}`); console.log(`High confidence: ${stats.highConfidencePatterns}`); ``` -------------------------------- ### Initialize State and DOM References Source: https://github.com/warengonzaga/tinyclaw/blob/main/plugins/channel/plugin-channel-friends/src/chat.html Sets up initial application state variables and obtains references to various DOM elements used throughout the chat interface. This is essential for managing the application's dynamic behavior. ```javascript // โ”€โ”€ State โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ let authenticated = false; let username = ''; let nickname = ''; let messages = []; let isStreaming = false; let agentStatus = 'checking'; // โ”€โ”€ DOM refs โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ const $inviteView = document.getElementById('inviteView'); const $chatView = document.getElementById('chatView'); const $inviteInput = document.getElementById('inviteInput'); const $inviteBtn = document.getElementById('inviteBtn'); const $inviteError = document.getElementById('inviteError'); const $messages = document.getElementById('messages'); const $emptyState = document.getElementById('emptyState'); const $greetingTitle = document.getElementById('greetingTitle'); const $chatInput = document.getElementById('chatInput'); const $sendBtn = document.getElementById('sendBtn'); const $errorBanner = document.getElementById('errorBanner'); const $thinkingHint = document.getElementById('thinkingHint'); const $statusDot = document.getElementById('statusDot'); const $statusText = document.getElementById('statusText'); ``` -------------------------------- ### Create and Configure Context Compactor Source: https://context7.com/warengonzaga/tinyclaw/llms.txt Initializes the context compactor with custom configurations for compaction thresholds, message retention, token budgets for different summary tiers, and settings for deduplication and pre-compression rules like stripping emojis and collapsing whitespace. ```typescript import { createCompactor } from '@tinyclaw/compactor'; // Create compactor with custom configuration const compactor = createCompactor(db, { threshold: 50, keepRecent: 10, tierBudgets: { l0: 200, l1: 500, l2: 1000, }, dedup: { enabled: true, similarityThreshold: 0.7, }, preCompression: { stripEmoji: true, collapseWhitespace: true, dedupLines: true, }, }); ``` -------------------------------- ### Create and Use Tinyclaw Gateway Source: https://github.com/warengonzaga/tinyclaw/blob/main/packages/gateway/README.md Demonstrates how to create a gateway instance, register a channel sender (e.g., 'web'), and send proactive messages to specific users or broadcast messages to all channels. Ensure the channel sender implementation correctly handles message delivery. ```typescript import { createGateway } from '@tinyclaw/gateway'; const gateway = createGateway(); // Register a channel sender gateway.register('web', { name: 'Web UI', async send(userId, message) { // Push via SSE to the browser }, }); // Send a proactive message await gateway.send('web:owner', { content: 'Your background task is complete!', priority: 'normal', source: 'background_task', }); // Broadcast to all channels await gateway.broadcast({ content: 'System update available', priority: 'low', source: 'system', }); ``` -------------------------------- ### Configure and Run Shell Engine Source: https://context7.com/warengonzaga/tinyclaw/llms.txt Sets up a controlled shell environment with custom configurations like working directory, timeouts, and output limits. Use this for safe command execution. ```typescript import { createShellEngine, createShellTools } from '@tinyclaw/shell'; // Create shell engine with configuration const shell = createShellEngine({ workingDirectory: '/project', defaultTimeout: 30_000, // 30 second default timeout maxTimeout: 120_000, // 2 minute max timeout maxOutputSize: 10_240, // 10KB output limit allowPatterns: ['make *', 'npm *', 'bun *'], // Custom allowlist }); // Execute a safe command (auto-approved) const lsResult = await shell.run('ls -la'); console.log(lsResult); // Output: (file listing) // Execute with custom timeout const buildResult = await shell.run('npm run build', 60_000); // Commands not in allowlist require approval const curlResult = await shell.run('curl https://api.example.com'); console.log(curlResult); // Output: This command requires owner approval before it can run. // Command: curl https://api.example.com // Reason: Command not in allowlist // Dangerous commands are always blocked const dangerousResult = await shell.run('rm -rf /'); console.log(dangerousResult); // Output: Shell command denied: Dangerous command pattern detected // Create agent tools for shell interaction const shellTools = createShellTools(shell); // Tools: run_shell, shell_approve, shell_allow // Approve a command (persistent across sessions) await shell.permissions.approve('curl https://api.example.com', true); // Add pattern to allowlist shell.permissions.addAllowPattern('docker *'); // List current permissions const patterns = shell.permissions.listAllowPatterns(); const approvals = shell.permissions.listApprovals(); // Cleanup on shutdown shell.shutdown(); ``` -------------------------------- ### Run Compaction and Access Summaries Source: https://context7.com/warengonzaga/tinyclaw/llms.txt Checks if compaction is needed and executes it if so, logging detailed metrics about the process including token savings and compression ratio. It also shows how to access the generated tiered summaries (L0, L1, L2) and retrieve the latest summary for context injection. ```typescript // Check and run compaction if needed const result = await compactor.compactIfNeeded('user-123', provider); if (result) { console.log('Compaction complete:'); console.log(` Messages before: ${result.metrics.messagesBefore}`); console.log(` Messages summarized: ${result.metrics.messagesSummarized}`); console.log(` Tokens before: ${result.metrics.tokensBefore}`); console.log(` Tokens after: ${result.metrics.tokensAfter}`); console.log(` Compression ratio: ${(result.metrics.compressionRatio * 100).toFixed(1)}%`); console.log(` Dedup groups removed: ${result.metrics.dedupGroupsRemoved}`); // Access tiered summaries console.log(' L0 (micro):', result.summary.l0); console.log(' L1 (short):', result.summary.l1); console.log(' L2 (full):', result.summary.l2); } // Get latest summary for context injection const summary = compactor.getLatestSummary('user-123'); if (summary) { console.log('Previous conversation summary:', summary); } ``` -------------------------------- ### Initialize Application Source: https://github.com/warengonzaga/tinyclaw/blob/main/plugins/channel/plugin-channel-friends/src/chat.html Initializes the application by performing an initial health check, setting up periodic health checks, and checking authentication. This is an immediately invoked async function expression (IIAFE). ```javascript // โ”€โ”€ Init โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ (async function init() { checkHealth(); setInterval(checkHealth, 12000); await checkAuth(); })(); ``` -------------------------------- ### Create and Use OpenAI Provider Source: https://context7.com/warengonzaga/tinyclaw/llms.txt Initializes the OpenAI provider with API configuration and demonstrates checking availability and performing chat completions with tool calling support. Handles response types for text and tool calls. ```typescript import { createOpenAIProvider } from '@tinyclaw/plugin-provider-openai'; import { SecretsManager } from '@tinyclaw/secrets'; // Create provider with configuration const provider = createOpenAIProvider({ secrets: await SecretsManager.create({ cwd: dataDir }), model: 'gpt-4.1', baseUrl: 'https://api.openai.com', }); // Check availability (validates API key) const available = await provider.isAvailable(); // Chat completion with tools const response = await provider.chat([ { role: 'system', content: 'You are a helpful coding assistant.' }, { role: 'user', content: 'Write a function to calculate fibonacci numbers' }, ], [ { name: 'execute_code', description: 'Execute JavaScript code in a sandbox', parameters: { type: 'object', properties: { code: { type: 'string', description: 'Code to execute' }, }, required: ['code'], }, execute: async (args) => sandbox.execute(String(args.code)), }, ]); // Handle response types if (response.type === 'text') { console.log(response.content); } else if (response.type === 'tool_calls') { for (const call of response.toolCalls) { console.log(`Tool: ${call.name}`); console.log(`Args: ${JSON.stringify(call.arguments)}`); } } ``` -------------------------------- ### Run Tiny Claw Tests Source: https://github.com/warengonzaga/tinyclaw/blob/main/CONTRIBUTING.md Commands to execute tests using Bun's built-in test runner, including running all tests, tests for a specific package, or running tests in watch mode. ```bash bun test # Run all tests bun test packages/memory # Run tests for a specific package bun test --watch # Run in watch mode ``` -------------------------------- ### Create and Use Intercom for Pub/Sub Source: https://context7.com/warengonzaga/tinyclaw/llms.txt Demonstrates creating an Intercom instance with a history limit, subscribing to specific topics and all events, emitting events, retrieving recent events, and managing subscriptions. Unsubscribe or clear all subscriptions when no longer needed. ```typescript import { createIntercom } from '@tinyclaw/intercom'; // Create intercom with history limit const intercom = createIntercom(100); // Keep last 100 events per topic // Subscribe to specific topics const unsubTaskComplete = intercom.on('task:completed', (event) => { console.log(`Task completed for ${event.userId}:`, event.data); }); const unsubAgentCreated = intercom.on('agent:created', (event) => { console.log(`New agent created: ${event.data.agentId}`); }); // Subscribe to all events (wildcard) const unsubAll = intercom.onAny((event) => { console.log(`[${event.topic}] ${JSON.stringify(event.data)}`); }); // Emit events intercom.emit('task:queued', 'user-123', { taskId: 'task-uuid', agentId: 'agent-uuid', description: 'Research WebAssembly', }); intercom.emit('task:completed', 'user-123', { taskId: 'task-uuid', result: 'Research complete', durationMs: 45000, }); intercom.emit('agent:created', 'user-123', { agentId: 'agent-uuid', role: 'Technical Research Analyst', }); intercom.emit('memory:consolidated', 'user-123', { merged: 5, pruned: 12, decayed: 30, }); // Get recent events for a topic const recentTasks = intercom.recent('task:completed', 5); console.log(`Last 5 completed tasks:`, recentTasks); // Get all recent events across topics const allRecent = intercom.recentAll(10); console.log(`Last 10 events:`, allRecent); // Unsubscribe when done unsubTaskComplete(); unsubAgentCreated(); unsubAll(); // Clear all subscriptions and history intercom.clear(); ``` -------------------------------- ### Create and Use Shield Security Engine Source: https://context7.com/warengonzaga/tinyclaw/llms.txt Initializes the Shield engine with SHIELD.md content and evaluates events against defined threat policies. Use this to enforce anti-malware protection. ```typescript import { createShieldEngine } from '@tinyclaw/shield'; // SHIELD.md content defining security policies const shieldContent = ` # SHIELD.md ## Threat: Credential Theft - id: CRED-001 - severity: critical - confidence: 0.95 - fingerprint: sha256:abc123... ### Indicators - tool.call: store_secret - tool.args.key: /password|token|api.?key/i - tool.args.value: /.+/ ### Directives - action: require_approval - scope: tool.call ## Threat: File System Attack - id: FS-001 - severity: critical - confidence: 0.90 ### Indicators - tool.call: heartware_write - tool.args.filename: /\\\\.\\.|^\\\/etc|^\\\/root/ ### Directives - action: block - scope: tool.call `; // Create Shield engine const shield = createShieldEngine(shieldContent); // Check if Shield is active console.log(`Shield active: ${shield.isActive()}`); console.log(`Active threats: ${shield.getThreats().length}`); // Evaluate a tool call event const decision = shield.evaluate({ scope: 'tool.call', toolName: 'heartware_write', toolArgs: { filename: '../../../etc/passwd', content: 'malicious' }, userId: 'user-123', }); console.log(`Action: ${decision.action}`); // 'block' console.log(`Threat ID: ${decision.threatId}`); // 'FS-001' console.log(`Matched on: ${decision.matchedOn}`); // 'tool.args.filename' console.log(`Reason: ${decision.reason}`); // 'File System Attack (critical, confidence: 0.90)' // Safe operations return 'log' action const safeDecision = shield.evaluate({ scope: 'tool.call', toolName: 'heartware_read', toolArgs: { filename: 'FRIEND.md' }, userId: 'user-123', }); console.log(`Safe action: ${safeDecision.action}`); // 'log' ``` -------------------------------- ### Minimal Provider Plugin Template Source: https://github.com/warengonzaga/tinyclaw/blob/main/plugins/provider/README.md A basic template for a Tiny Claw provider plugin, demonstrating the required `ProviderPlugin` export and implementation of `createProvider` and `getPairingTools`. ```typescript // src/index.ts import type { ProviderPlugin, SecretsManagerInterface, ConfigManagerInterface, Tool, } from '@tinyclaw/types'; import { createMyProvider } from './provider.js'; import { createMyPairingTools } from './pairing.js'; const plugin: ProviderPlugin = { id: '@tinyclaw/plugin-provider-', name: '', description: ' provider plugin for Tiny Claw', type: 'provider', version: '0.1.0', async createProvider(secrets: SecretsManagerInterface) { return createMyProvider({ secrets }); }, getPairingTools( secrets: SecretsManagerInterface, configManager: ConfigManagerInterface, ): Tool[] { return createMyPairingTools(secrets, configManager); }, }; export default plugin; ``` -------------------------------- ### Reinforce and Consolidate Memories Source: https://context7.com/warengonzaga/tinyclaw/llms.txt Demonstrates how to reinforce a specific memory using its ID to increase its access count and update its last accessed time. It also shows how to trigger memory consolidation, which includes decay, pruning, and merging of similar memories, returning statistics on the process. ```typescript // Reinforce a memory (increases access count and updates last_accessed) memory.reinforce(correctionId); // Consolidate memories (decay, prune, merge duplicates) const stats = memory.consolidate('user-123'); console.log(`Decayed: ${stats.decayed}, Pruned: ${stats.pruned}, Merged: ${stats.merged}`); ``` -------------------------------- ### Run Test Suite Source: https://github.com/warengonzaga/tinyclaw/blob/main/README.md Executes the project's test suite to ensure code quality and functionality. Essential for verifying changes. ```bash bun test ``` -------------------------------- ### Development Mode with Hot Reload Source: https://github.com/warengonzaga/tinyclaw/blob/main/README.md Launches the application in development mode, enabling hot reloading for faster iteration. Use this during active development. ```bash bun dev ``` -------------------------------- ### Minimal package.json for a Channel Plugin Source: https://github.com/warengonzaga/tinyclaw/blob/main/plugins/channel/README.md Specifies the essential fields for a Tiny Claw channel plugin's package.json, including name, version, entry point, and dependencies. ```json { "name": "@tinyclaw/plugin-channel-", "version": "0.1.0", "type": "module", "main": "./src/index.ts", "exports": { ".": "./src/index.ts" }, "dependencies": { "@tinyclaw/logger": "workspace:*", "@tinyclaw/types": "workspace:*" } } ``` -------------------------------- ### Create and Use SQLite Database Source: https://context7.com/warengonzaga/tinyclaw/llms.txt Initializes an SQLite database for storing conversation history, memory, and agent data. Use this to manage persistent data for your TinyClaw application. ```typescript import { createDatabase } from '@tinyclaw/core'; // Create database at specified path const db = createDatabase('/path/to/.tinyclaw/data/tinyclaw.db'); // Save a conversation message db.saveMessage('user-123', 'user', 'Hello, Tiny Claw!'); db.saveMessage('user-123', 'assistant', 'Hello! How can I help you today?'); // Retrieve conversation history (most recent 20 messages) const history = db.getHistory('user-123', 20); // Returns: [{ role: 'user', content: '...' }, { role: 'assistant', content: '...' }] // Save and retrieve memory db.saveMemory('user-123', 'timezone', 'UTC+08:00'); const memory = db.getMemory('user-123'); // Returns: { timezone: 'UTC+08:00' } // Manage sub-agents db.saveSubAgent({ id: 'agent-uuid', userId: 'user-123', role: 'Technical Research Analyst', systemPrompt: 'You are a research specialist...', toolsGranted: ['heartware_read', 'memory_recall'], status: 'active', performanceScore: 0.85, totalTasks: 10, successfulTasks: 8, createdAt: Date.now(), lastActiveAt: Date.now(), }); // Save episodic memory event (with FTS5 indexing) db.saveEpisodicEvent({ id: crypto.randomUUID(), userId: 'user-123', eventType: 'preference_learned', content: 'User prefers concise responses', outcome: null, importance: 0.8, accessCount: 0, createdAt: Date.now(), lastAccessedAt: Date.now(), }); // Search episodic memory using full-text search const searchResults = db.searchEpisodicFTS('concise responses', 'user-123', 10); // Returns: [{ id: '...', rank: -2.5 }] // Close database when done db.close(); ``` -------------------------------- ### Minimal package.json for Provider Plugin Source: https://github.com/warengonzaga/tinyclaw/blob/main/plugins/provider/README.md Specifies the essential fields for a Tiny Claw provider plugin's package.json, including name, version, type, main entry point, exports, and dependencies. ```json { "name": "@tinyclaw/plugin-provider-", "version": "0.1.0", "type": "module", "main": "./src/index.ts", "exports": { ".": "./src/index.ts" }, "dependencies": { "@tinyclaw/logger": "workspace:*", "@tinyclaw/types": "workspace:*" } } ``` -------------------------------- ### Show Chat View Source: https://github.com/warengonzaga/tinyclaw/blob/main/plugins/channel/plugin-channel-friends/src/chat.html Switches the UI from the invite view to the chat view. It updates the greeting title with the user's nickname or username and sets focus to the chat input field. ```javascript function showChat() { $inviteView.classList.remove('active'); $chatView.classList.add('active'); $greetingTitle.textContent = 'Hey, ' + (nickname || username) + '!'; $chatInput.focus(); } ```