### AgentFS Python SDK: Development Setup and Commands Source: https://github.com/tursodatabase/agentfs/blob/main/sdk/python/README.md Details the development setup for the AgentFS Python SDK, including installing dependencies with `uv`, running tests with `pytest`, and formatting/checking code with `ruff`. ```bash # Install dependencies uv sync --group dev # Run tests uv run pytest # Format code uv run ruff format agentfs_sdk tests # Check code uv run ruff check agentfs_sdk tests ``` -------------------------------- ### Install AgentFS CLI Source: https://github.com/tursodatabase/agentfs/blob/main/MANUAL.md Installs the AgentFS CLI using a script from GitHub releases. This command downloads and executes an installation script to set up the AgentFS command-line tool. ```bash curl -fsSL https://github.com/tursodatabase/agentfs/releases/latest/download/agentfs-installer.sh | sh ``` -------------------------------- ### Install AgentFS SDK Source: https://github.com/tursodatabase/agentfs/blob/main/README.md Installs the agentfs-sdk package using npm. This is the first step to integrate AgentFS into your project. ```bash npm install agentfs-sdk ``` -------------------------------- ### Serve MCP Protocol Source: https://github.com/tursodatabase/agentfs/blob/main/MANUAL.md Starts an MCP (Model Context Protocol) server to expose AgentFS functionalities. It allows specifying which tools (e.g., filesystem operations, key-value operations) to expose. ```bash agentfs serve mcp [OPTIONS] ``` -------------------------------- ### Install AgentFS CLI Source: https://context7.com/tursodatabase/agentfs/llms.txt Installs the AgentFS Command Line Interface using a provided installation script. This is the primary method for interacting with AgentFS from the terminal. ```bash curl -fsSL https://agentfs.ai/install | bash ``` -------------------------------- ### Start MCP Server Source: https://context7.com/tursodatabase/agentfs/llms.txt Starts a Model Context Protocol (MCP) server to expose AgentFS tools to AI agents. Allows specifying which tools to expose, including filesystem and key-value operations. ```bash # Start MCP server for an agent agentfs serve mcp my-agent # Expose specific tools only agentfs serve mcp my-agent --tools read_file,write_file,kv_get,kv_set # Available tools: # Filesystem: read_file, write_file, readdir, mkdir, remove, rename, stat, access # Key-Value: kv_get, kv_set, kv_delete, kv_list ``` -------------------------------- ### Create BusyBox Root Filesystem Source: https://github.com/tursodatabase/agentfs/blob/main/examples/firecracker/README.md Constructs a minimal ext4 root filesystem image utilizing BusyBox. This provides a compact and efficient operating system environment for the Firecracker VM, suitable for running AgentFS. ```bash ./build-rootfs.sh ``` -------------------------------- ### Run Firecracker VM Source: https://github.com/tursodatabase/agentfs/blob/main/examples/firecracker/README.md Launches the Firecracker virtual machine using the previously built kernel and root filesystem. This script initiates the VM environment where AgentFS can be utilized. Press Ctrl+C to terminate the VM. ```bash ./run.sh ``` -------------------------------- ### Run Encrypted AgentFS Sandbox Session (Bash) Source: https://github.com/tursodatabase/agentfs/blob/main/MANUAL.md Shows how to start an encrypted AgentFS sandbox session using bash. This command assumes that the `AGENTFS_KEY` and `AGENTFS_CIPHER` environment variables are already set or are provided as arguments. ```bash agentfs run --key $KEY --cipher aes256gcm -- bash ``` -------------------------------- ### Install AgentFS Python SDK Source: https://github.com/tursodatabase/agentfs/blob/main/sdk/python/README.md Installs the AgentFS Python SDK using pip. This is the first step to using the library in your Python projects. ```bash pip install agentfs-sdk ``` -------------------------------- ### Start NFS Server Source: https://context7.com/tursodatabase/agentfs/llms.txt Starts an NFS server to export AgentFS over the network, enabling remote access to the agent's filesystem. ```bash # Start NFS server for an agent agentfs serve nfs my-agent ``` -------------------------------- ### Start Development Server with npm Source: https://github.com/tursodatabase/agentfs/blob/main/examples/cloudflare/README.md Starts the local development server for the AI agent. This allows for testing and iteration during development. ```bash npm run dev ``` -------------------------------- ### Quick Start: AgentFS Python SDK Usage Source: https://github.com/tursodatabase/agentfs/blob/main/sdk/python/README.md Demonstrates the basic usage of the AgentFS Python SDK, including opening an agent filesystem, using the key-value store, performing filesystem operations, and tracking tool calls. It requires the asyncio library for asynchronous operations. ```python import asyncio from agentfs_sdk import AgentFS, AgentFSOptions async def main(): # Open an agent filesystem agent = await AgentFS.open(AgentFSOptions(id='my-agent')) # Use key-value store await agent.kv.set('config', {'debug': True, 'version': '1.0'}) config = await agent.kv.get('config') print(f"Config: {config}") # Use filesystem await agent.fs.write_file('/data/notes.txt', 'Hello, AgentFS!') content = await agent.fs.read_file('/data/notes.txt') print(f"Content: {content}") # Track tool calls call_id = await agent.tools.start('search', {'query': 'Python'}) await agent.tools.success(call_id, {'results': ['result1', 'result2']}) # Get statistics stats = await agent.tools.get_stats() for stat in stats: print(f"{stat.name}: {stat.total_calls} calls, {stat.avg_duration_ms:.2f}ms avg") # Close the database await agent.close() if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### AgentFS Python SDK: Key-Value Store Operations Source: https://github.com/tursodatabase/agentfs/blob/main/sdk/python/README.md Provides examples of interacting with the key-value store in the AgentFS Python SDK. It covers setting, getting, listing, and deleting key-value pairs, with automatic JSON serialization. ```python # Set a value await agent.kv.set('user:123', {'name': 'Alice', 'age': 30}) # Get a value user = await agent.kv.get('user:123') # List by prefix users = await agent.kv.list('user:') # Delete a value await agent.kv.delete('user:123') ``` -------------------------------- ### Initialize Encrypted AgentFS Filesystem (Bash) Source: https://github.com/tursodatabase/agentfs/blob/main/MANUAL.md Demonstrates how to initialize a new AgentFS filesystem with local encryption. It includes generating a key, initializing the filesystem with a specified cipher, and accessing it. Requires `openssl` for key generation. ```bash # Generate a 256-bit key (64 hex characters) KEY=$(openssl rand -hex 32) # Initialize with encryption agentfs init --key $KEY --cipher aes256gcm my-secure-agent # Access the filesystem agentfs fs my-secure-agent --key $KEY --cipher aes256gcm ls / ``` -------------------------------- ### Manage Shell Completions Source: https://github.com/tursodatabase/agentfs/blob/main/MANUAL.md Manages shell completions for the AgentFS CLI. Supports installing, uninstalling, and showing completions for various shells like bash, zsh, fish, and powershell. ```bash agentfs completions install [SHELL] agentfs completions uninstall [SHELL] agentfs completions show ``` -------------------------------- ### Serve NFS Protocol Source: https://github.com/tursodatabase/agentfs/blob/main/MANUAL.md Starts an NFS server to export AgentFS over the network. It allows configuring the bind IP address and port. Clients can mount the exported filesystem using standard NFS mount commands. ```bash agentfs serve nfs [OPTIONS] ``` ```bash # Mounting from client: mount -t nfs -o vers=3,tcp,port=11111,mountport=11111,nolock :/ ``` -------------------------------- ### Install Dependencies with npm Source: https://github.com/tursodatabase/agentfs/blob/main/examples/cloudflare/README.md Installs the necessary project dependencies using npm. This is a prerequisite for running the agent. ```bash npm install ``` -------------------------------- ### just-bash Integration with AgentFS Source: https://context7.com/tursodatabase/agentfs/llms.txt Integrates AgentFS with the just-bash library to enable AI agent command execution with a persistent filesystem. This example demonstrates creating an AgentFS-backed filesystem and using it with the `createBashTool` function. It requires `just-bash` and `agentfs-sdk/just-bash`. ```typescript import { createBashTool } from 'just-bash'; import { agentfs } from 'agentfs-sdk/just-bash'; // Create filesystem backed by AgentFS const fs = await agentfs({ id: 'bash-agent' }); // Create bash tool with AgentFS filesystem const bashTool = createBashTool({ fs, cwd: '/', timeout: 30000 }); // Execute commands with persistent storage await bashTool.execute('echo "Hello" > /output/greeting.txt'); await bashTool.execute('cat /output/greeting.txt'); // Use with custom mount point const fsWithMount = await agentfs({ id: 'agent' }, '/workspace'); ``` -------------------------------- ### Rust SDK: Perform Filesystem Operations Source: https://context7.com/tursodatabase/agentfs/llms.txt Demonstrates how to perform common filesystem operations like creating directories, writing and reading files, getting file statistics, and listing directory contents using the AgentFS Rust SDK's async interface. It requires the `agentfs_sdk` and `tokio` crates. ```rust use agentfs_sdk::{AgentFS, AgentFSOptions}; #[tokio::main] async fn main() -> Result<(), Box> { let agent = AgentFS::open(AgentFSOptions::with_id("fs-demo")).await?; // Create directory agent.fs.mkdir("/documents", 0, 0).await?; // Write file agent.fs.write_file("/documents/readme.txt", b"Hello, world!", 0, 0).await?; // Read file let content = agent.fs.read_file("/documents/readme.txt").await?; if let Some(data) = content { println!("{}", String::from_utf8_lossy(&data)); } // Get file stats let stats = agent.fs.stat("/documents/readme.txt").await?; if let Some(s) = stats { println!("Size: {} bytes", s.size); println!("Is file: {}", s.is_file()); println!("Is directory: {}", s.is_directory()); } // List directory let entries = agent.fs.readdir("/documents").await?; if let Some(files) = entries { for file in files { println!(" {}", file); } } Ok(()) } ``` -------------------------------- ### AgentFS SDK Usage in TypeScript Source: https://github.com/tursodatabase/agentfs/blob/main/README.md Demonstrates how to use the AgentFS SDK in TypeScript for persistent and ephemeral storage. It covers opening databases, performing key-value operations (set, get), filesystem operations (writeFile, readdir), and tracking tool calls. ```typescript import { AgentFS } from 'agentfs-sdk'; // Persistent storage with identifier const agent = await AgentFS.open({ id: 'my-agent' }); // Creates: .agentfs/my-agent.db // Or use ephemeral in-memory database const ephemeralAgent = await AgentFS.open(); // Key-value operations await agent.kv.set('user:preferences', { theme: 'dark' }); const prefs = await agent.kv.get('user:preferences'); // Filesystem operations await agent.fs.writeFile('/output/report.pdf', pdfBuffer); const files = await agent.fs.readdir('/output'); // Tool call tracking await agent.tools.record( 'web_search', Date.now() / 1000, Date.now() / 1000 + 1.5, { query: 'AI' }, { results: [...] } ); ``` -------------------------------- ### AgentFS Synchronization with TypeScript SDK Source: https://context7.com/tursodatabase/agentfs/llms.txt This TypeScript code example shows how to use the AgentFS SDK to open a synced agent, perform pull and push operations for remote synchronization, and retrieve sync statistics. It assumes the agent has been previously initialized with sync configurations. ```typescript // TypeScript SDK with sync import { AgentFS } from 'agentfs-sdk'; const agent = await AgentFS.open({ id: 'synced-agent', // Sync options would be configured during init }); // Check if sync is enabled if (agent.is_synced()) { await agent.pull(); // Pull remote changes await agent.push(); // Push local changes const stats = await agent.sync_stats(); console.log(stats); } ``` -------------------------------- ### Initialize Agent Filesystem Source: https://github.com/tursodatabase/agentfs/blob/main/MANUAL.md Initializes a new agent filesystem. It supports specifying an agent ID, overwriting existing filesystems, setting a base directory for copy-on-write, and configuring local encryption or remote synchronization. ```bash agentfs init [OPTIONS] [ID] ``` -------------------------------- ### Initialize and Access Encrypted AgentFS using Environment Variables (Bash) Source: https://github.com/tursodatabase/agentfs/blob/main/MANUAL.md Illustrates initializing and accessing an AgentFS filesystem using environment variables for encryption. This method avoids passing the key and cipher directly in commands. ```bash export AGENTFS_KEY=$(openssl rand -hex 32) export AGENTFS_CIPHER=aes256gcm agentfs init my-secure-agent agentfs fs my-secure-agent ls / ``` -------------------------------- ### Start NFS Server with AgentFS Source: https://context7.com/tursodatabase/agentfs/llms.txt Starts the AgentFS NFS server, which can be configured to bind to a specific address and port. Default is 127.0.0.1:11111. Clients can mount this server using standard NFS client tools. ```bash # Start NFS server (default: 127.0.0.1:11111) agentfs serve nfs my-agent # Bind to specific address and port agentfs serve nfs my-agent --bind 0.0.0.0 --port 2049 # Mount from client mount -t nfs -o vers=3,tcp,port=11111,mountport=11111,nolock localhost:/ /mnt/agent ``` -------------------------------- ### Build Linux Kernel with NFSv3 Support Source: https://github.com/tursodatabase/agentfs/blob/main/examples/firecracker/README.md Downloads and compiles the Linux kernel version 6.1.x, ensuring NFSv3 support is enabled for network file system operations within the Firecracker VM. This script is essential for AgentFS functionality that relies on NFS. ```bash ./build-kernel.sh ``` -------------------------------- ### Create Tool Calls Table and Indexes (SQL) Source: https://github.com/tursodatabase/agentfs/blob/main/SPEC.md Defines the 'tool_calls' table for logging tool invocations, including parameters, results, errors, and timing. It also includes indexes for efficient querying by tool name and start time. ```sql CREATE TABLE tool_calls ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, parameters TEXT, result TEXT, error TEXT, started_at INTEGER NOT NULL, completed_at INTEGER NOT NULL, duration_ms INTEGER NOT NULL ) CREATE INDEX idx_tool_calls_name ON tool_calls(name) CREATE INDEX idx_tool_calls_started_at ON tool_calls(started_at) ``` -------------------------------- ### Rust SDK: Track Tool Calls Source: https://context7.com/tursodatabase/agentfs/llms.txt Illustrates how to track tool invocations and analyze their performance within Rust applications using the AgentFS SDK. It covers starting a tool call, marking it as successful or failed, retrieving call details, and obtaining performance statistics. Requires `agentfs_sdk`, `tokio`, and `serde_json`. ```rust use agentfs_sdk::{AgentFS, AgentFSOptions, ToolCallStatus}; use std::time::{SystemTime, UNIX_EPOCH}; #[tokio::main] async fn main() -> Result<(), Box> { let agent = AgentFS::open(AgentFSOptions::with_id("tools-demo")).await?; // Start a tool call let call_id = agent.tools.start( "web_search", Some(serde_json::json!({"query": "Rust async"})) ).await?; // Mark as successful agent.tools.success( call_id, Some(serde_json::json!({"results": []})) ).await?; // Or mark as failed // agent.tools.error(call_id, "Connection failed").await?; // Get the tool call let call = agent.tools.get(call_id).await?; if let Some(c) = call { println!("Tool: {}, Status: {:?}", c.name, c.status); } // Get statistics for a specific tool let stats = agent.tools.stats_for("web_search").await?; if let Some(s) = stats { println!("Total calls: {}", s.total_calls); println!("Successful: {}", s.successful); println!("Avg duration: {}ms", s.avg_duration_ms); } Ok(()) } ``` -------------------------------- ### Show Filesystem Diffs Source: https://github.com/tursodatabase/agentfs/blob/main/MANUAL.md Displays filesystem changes in overlay mode for a given agent filesystem. This command helps visualize modifications made within the agentfs environment. ```bash agentfs diff ``` -------------------------------- ### Query Recent Tool Calls (SQL) Source: https://github.com/tursodatabase/agentfs/blob/main/SPEC.md Fetches tool call records that occurred after a specified timestamp, ordered by start time. This is useful for retrieving recent activity. ```sql SELECT * FROM tool_calls WHERE started_at > ? ORDER BY started_at DESC ``` -------------------------------- ### AgentFS Python SDK: Filesystem Operations Source: https://github.com/tursodatabase/agentfs/blob/main/sdk/python/README.md Illustrates common filesystem operations using the AgentFS Python SDK, including writing, reading, listing directories, and getting file statistics. It supports automatic directory creation and reading files as bytes. ```python # Write a file (creates parent directories automatically) await agent.fs.write_file('/data/config.json', '{"key": "value"}') # Read a file content = await agent.fs.read_file('/data/config.json') # Read as bytes data = await agent.fs.read_file('/data/image.png', encoding=None) # List directory entries = await agent.fs.readdir('/data') # Get file stats stats = await agent.fs.stat('/data/config.json') print(f"Size: {stats.size} bytes") print(f"Modified: {stats.mtime}") print(f"Is file: {stats.is_file()}") # Delete a file await agent.fs.delete_file('/data/config.json') ``` -------------------------------- ### Rust SDK: Use Key-Value Store Source: https://context7.com/tursodatabase/agentfs/llms.txt Shows how to utilize the persistent key-value store provided by the AgentFS Rust SDK for managing agent state. It covers setting, getting, and deleting key-value pairs, with automatic JSON serialization/deserialization for complex types. Dependencies include `agentfs_sdk`, `tokio`, and `serde`. ```rust use agentfs_sdk::{AgentFS, AgentFSOptions}; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug)] struct User { id: i32, name: String, } #[tokio::main] async fn main() -> Result<(), Box> { let agent = AgentFS::open(AgentFSOptions::with_id("kv-demo")).await?; // Set values (automatically serialized to JSON) agent.kv.set("username", &"alice").await?; agent.kv.set("counter", &42).await?; agent.kv.set("user:123", &User { id: 123, name: "Alice".into() }).await?; // Get values let username: Option = agent.kv.get("username").await?; println!("Username: {:?}", username); let user: Option = agent.kv.get("user:123").await?; if let Some(u) = user { println!("User: {} ({})", u.name, u.id); } // Delete agent.kv.delete("username").await?; Ok(()) } ``` -------------------------------- ### Synchronize Agent Filesystem with Turso Database Source: https://github.com/tursodatabase/agentfs/blob/main/MANUAL.md Synchronizes an agent filesystem with a remote Turso database. Supports subcommands for pulling remote changes, pushing local changes, viewing sync statistics, and creating checkpoints. ```bash agentfs sync ``` -------------------------------- ### Python SDK: Filesystem Operations Source: https://context7.com/tursodatabase/agentfs/llms.txt Illustrates various filesystem operations using the AgentFS Python SDK, including writing and reading text/binary files, getting file statistics, listing directories, creating/removing directories, and file manipulation like renaming and copying. It emphasizes the asynchronous nature of these operations. ```python import asyncio from datetime import datetime from agentfs_sdk import AgentFS, AgentFSOptions async def main(): agent = await AgentFS.open(AgentFSOptions(id='fs-demo')) # Write text files (parent dirs created automatically) await agent.fs.write_file('/documents/readme.txt', 'Hello, world!') # Write binary data await agent.fs.write_file('/images/icon.png', b'\x89PNG\r\n') # Read text files content = await agent.fs.read_file('/documents/readme.txt') print(content) # "Hello, world!" # Read binary files binary = await agent.fs.read_file('/images/icon.png', encoding=None) print(binary) # b'\x89PNG\r\n' # Get file statistics stats = await agent.fs.stat('/documents/readme.txt') print(f"Inode: {stats.ino}") print(f"Size: {stats.size} bytes") print(f"Mode: {oct(stats.mode)}") # 0o100644 print(f"Is file: {stats.is_file()}") print(f"Is directory: {stats.is_directory()}") print(f"Modified: {datetime.fromtimestamp(stats.mtime)}") # List directory files = await agent.fs.readdir('/documents') print(files) # ['readme.txt'] # Create directory await agent.fs.mkdir('/new-folder') # Remove files await agent.fs.unlink('/documents/readme.txt') # Remove directories await agent.fs.rmdir('/empty-folder') await agent.fs.rm('/folder', recursive=True, force=True) # Rename/move await agent.fs.rename('/old.txt', '/new.txt') # Copy files await agent.fs.copy_file('/source.txt', '/dest.txt') # Check existence try: await agent.fs.access('/path/to/file') print("File exists") except Exception: print("File not found") await agent.close() asyncio.run(main()) ``` -------------------------------- ### Run Program in Sandboxed Environment Source: https://github.com/tursodatabase/agentfs/blob/main/MANUAL.md Executes a program within a sandboxed environment with a copy-on-write filesystem. It allows specifying allowed directories, encryption keys for delta layers, and experimental sandbox features like ptrace-based syscall interception on Linux. ```bash agentfs run [OPTIONS] [ARGS]... ``` -------------------------------- ### Display Agent Action Timeline Source: https://github.com/tursodatabase/agentfs/blob/main/MANUAL.md Displays the agent action timeline from the tool call audit log. Supports options for limiting entries, filtering by tool name or status, and specifying the output format (table or JSON). ```bash agentfs timeline [OPTIONS] ``` -------------------------------- ### Cloudflare Workers Integration with AgentFS Source: https://context7.com/tursodatabase/agentfs/llms.txt Demonstrates how to use AgentFS within Cloudflare Workers, leveraging Durable Objects for persistent storage. This example shows creating an AgentFS instance backed by Durable Object storage and integrating it with the just-bash tool. It requires `agentfs-sdk/cloudflare`, `agentfs-sdk/just-bash`, and `just-bash`. ```typescript // In a Durable Object class import { AgentFS } from 'agentfs-sdk/cloudflare'; import { agentfs } from 'agentfs-sdk/just-bash'; import { createBashTool } from 'just-bash'; export class AgentDO implements DurableObject { private agentFs: AgentFS; constructor(ctx: DurableObjectState) { // Create AgentFS backed by Durable Objects storage this.agentFs = AgentFS.create(ctx.storage); } async fetch(request: Request) { // Use filesystem await this.agentFs.fs.writeFile('/data/result.json', JSON.stringify({ status: 'ok' })); // Use with just-bash const fs = agentfs({ fs: this.agentFs }); const bashTool = createBashTool({ fs }); return new Response('OK'); } } ``` -------------------------------- ### AgentFS Python SDK: Tool Calls Tracking Source: https://github.com/tursodatabase/agentfs/blob/main/sdk/python/README.md Details how to track and analyze tool or function calls using the AgentFS Python SDK. It covers starting, marking success/failure, recording, querying, and retrieving statistics for tool calls. ```python # Start a tool call call_id = await agent.tools.start('search', {'query': 'Python'}) # Mark as successful await agent.tools.success(call_id, {'results': [...]}) # Or mark as failed await agent.tools.error(call_id, 'Connection timeout') # Record a completed call await agent.tools.record( 'search', started_at=1234567890, completed_at=1234567892, parameters={'query': 'Python'}, result={'results': [...]} ) # Query tool calls calls = await agent.tools.get_by_name('search', limit=10) recent = await agent.tools.get_recent(since=1234567890) # Get statistics stats = await agent.tools.get_stats() for stat in stats: print(f"{stat.name}: {stat.successful}/{stat.total_calls} successful") ``` -------------------------------- ### Mount Agent Filesystem Source: https://github.com/tursodatabase/agentfs/blob/main/MANUAL.md Mounts an agent filesystem or lists currently mounted filesystems. Options include automatic unmounting, allowing root access, running in foreground, and setting user/group IDs. Unmounting procedures differ between Linux and macOS. ```bash agentfs mount [OPTIONS] [ID_OR_PATH] [MOUNT_POINT] ``` ```bash # Unmounting on Linux: fusermount -u # Unmounting on macOS: umount ``` -------------------------------- ### Rust SDK: Opening and Configuring AgentFS Source: https://context7.com/tursodatabase/agentfs/llms.txt Shows how to open and configure an AgentFS instance using the Rust SDK. It covers creating instances with persistent storage, ephemeral in-memory databases, custom file paths, overlay filesystems for copy-on-write behavior, and local encryption using a provided key and algorithm. Requires the `agentfs_sdk` and `tokio` crates. ```rust use agentfs_sdk::{AgentFS, AgentFSOptions, SyncOptions, EncryptionConfig}; #[tokio::main] async fn main() -> Result<(), Box> { // Open with persistent storage let agent = AgentFS::open(AgentFSOptions::with_id("my-agent")).await?; // Open ephemeral in-memory database let ephemeral = AgentFS::open(AgentFSOptions::ephemeral()).await?; // Open with custom path let custom = AgentFS::open(AgentFSOptions::with_path("./data/agent.db")).await?; // Open with overlay filesystem (copy-on-write) let overlay = AgentFS::open( AgentFSOptions::with_id("sandbox-agent") .with_base("/path/to/project") ).await?; // Open with local encryption let encrypted = AgentFS::open( AgentFSOptions::with_id("secure-agent") .with_encryption_key( "b1bbfda4f589dc9daaf004fe21111e00dc00c98237102f5c7002a5669fc76327", "aegis256" ) ).await?; // Access the interfaces let _kv = &agent.kv; let _fs = &agent.fs; let _tools = &agent.tools; Ok(()) } ``` -------------------------------- ### Initialize and Sync AgentFS with Turso Cloud (Bash) Source: https://context7.com/tursodatabase/agentfs/llms.txt This snippet demonstrates how to initialize an agent with remote synchronization enabled using Turso Cloud and perform basic sync operations like pulling, pushing, and checking statistics. It requires the agentfs CLI tool. ```bash # Initialize with remote sync agentfs init my-agent --sync-remote-url libsql://mydb-org.turso.io # Sync operations agentfs sync my-agent pull # Pull remote changes agentfs sync my-agent push # Push local changes agentfs sync my-agent stats # View sync statistics agentfs sync my-agent checkpoint # Create checkpoint ``` -------------------------------- ### Initialize Agent Filesystem Source: https://context7.com/tursodatabase/agentfs/llms.txt Creates a new AgentFS instance, which is stored as a SQLite database file. Supports initialization with or without a base directory for copy-on-write overlays, and with local encryption. ```bash # Initialize a new agent filesystem agentfs init my-agent # Output: Created agent filesystem: .agentfs/my-agent.db # Agent ID: my-agent # Initialize with overlay (copy-on-write) on a base directory agentfs init my-agent --base /path/to/project # Initialize with local encryption KEY=$(openssl rand -hex 32) agentfs init my-secure-agent --key $KEY --cipher aes256gcm ``` -------------------------------- ### Python SDK: Open AgentFS Instance Source: https://context7.com/tursodatabase/agentfs/llms.txt Shows how to open an AgentFS instance in Python using asynchronous programming. It covers opening with persistent storage by ID, custom paths, and using AgentFS as an asynchronous context manager for automatic resource management. ```python import asyncio from agentfs_sdk import AgentFS, AgentFSOptions async def main(): # Open with persistent storage agent = await AgentFS.open(AgentFSOptions(id='my-agent')) # Open with custom path agent2 = await AgentFS.open(AgentFSOptions(path='./data/custom.db')) # Use as async context manager (auto-closes) async with await AgentFS.open(AgentFSOptions(id='demo')) as agent: # Access filesystem, kv, and tools await agent.fs.write_file('/test.txt', 'Hello') await agent.kv.set('key', 'value') # Manual close await agent.close() asyncio.run(main()) ``` -------------------------------- ### Interact with AI Agent via curl Source: https://github.com/tursodatabase/agentfs/blob/main/examples/cloudflare/README.md Sends a POST request to the deployed AI agent endpoint to interact with it. This example demonstrates creating a file. ```bash curl -X POST https://your-worker.workers.dev/chat \ -H "Content-Type: application/json" \ -d '{"message": "Create a file called hello.txt with Hello World"}' ``` -------------------------------- ### Path Resolution SQL Query Source: https://github.com/tursodatabase/agentfs/blob/main/SPEC.md SQL query used to resolve a path component to its corresponding inode number. This query is executed iteratively for each component of a path, starting from the root directory. ```sql SELECT ino FROM fs_dentry WHERE parent_ino = ? AND name = ? ``` -------------------------------- ### TypeScript SDK: Record and Analyze Tool Calls Source: https://context7.com/tursodatabase/agentfs/llms.txt Demonstrates how to record completed tool calls directly, track tool calls in real-time using start/success/error methods, and query tool call history and performance statistics using the AgentFS TypeScript SDK. It covers recording parameters, results, and error messages. ```typescript import { AgentFS } from 'agentfs-sdk'; const agent = await AgentFS.open({ id: 'tools-demo' }); // Method 1: Record completed tool call directly const callId = await agent.tools.record( 'web_search', // tool name Date.now() / 1000, // started_at (Unix timestamp) Date.now() / 1000 + 1.5, // completed_at { query: 'AI agents', maxResults: 10 }, // parameters { results: [{ title: 'AI Guide', url: 'https://example.com' }] } // result ); console.log(`Recorded tool call: ${callId}`); // Method 2: Start/complete flow for real-time tracking const searchId = await agent.tools.start('database_query', { sql: 'SELECT * FROM users WHERE active = true' }); try { // Perform the actual work... const results = [{ id: 1, name: 'Alice' }]; await agent.tools.success(searchId, { rows: results, count: 1 }); } catch (err) { await agent.tools.error(searchId, err.message); } // Record a failed tool call await agent.tools.record( 'api_call', Date.now() / 1000, Date.now() / 1000 + 0.3, { endpoint: '/users', method: 'GET' }, undefined, // no result 'Connection timeout after 30s' // error message ); // Query tool calls by name const searches = await agent.tools.getByName('web_search', 10); for (const call of searches) { console.log(`${call.name}: ${call.status} (${call.duration_ms}ms)`); } // Get recent tool calls const oneHourAgo = Math.floor(Date.now() / 1000) - 3600; const recent = await agent.tools.getRecent(oneHourAgo); // Get a specific tool call by ID const call = await agent.tools.get(callId); console.log(call?.parameters); // Get performance statistics across all tools const stats = await agent.tools.getStats(); for (const stat of stats) { console.log(`${stat.name}:`); console.log(` Total: ${stat.total_calls}`); console.log(` Success: ${stat.successful}, Failed: ${stat.failed}`); console.log(` Avg duration: ${stat.avg_duration_ms.toFixed(2)}ms`); } ``` -------------------------------- ### Perform Filesystem Operations Source: https://github.com/tursodatabase/agentfs/blob/main/MANUAL.md Performs filesystem operations on agent databases, such as listing files, viewing file contents, and writing to files. Requires common options for encryption keys and cipher algorithms if the database is encrypted. ```bash agentfs fs [OPTIONS] ls [FS_PATH] ``` ```bash agentfs fs [OPTIONS] cat ``` ```bash agentfs fs [OPTIONS] write ``` -------------------------------- ### Filesystem Operations with TypeScript SDK Source: https://context7.com/tursodatabase/agentfs/llms.txt Demonstrates POSIX-like filesystem operations using the AgentFS TypeScript SDK. Supports reading, writing, creating directories, file management, and retrieving file statistics. ```typescript import { AgentFS } from 'agentfs-sdk'; const agent = await AgentFS.open({ id: 'fs-demo' }); // Write files (parent directories created automatically) await agent.fs.writeFile('/documents/readme.txt', 'Hello, world!'); await agent.fs.writeFile('/data/config.json', JSON.stringify({ key: 'value' })); // Write binary data const imageBuffer = Buffer.from([0x89, 0x50, 0x4e, 0x47]); await agent.fs.writeFile('/images/icon.png', imageBuffer); // Read files const content = await agent.fs.readFile('/documents/readme.txt', 'utf-8'); console.log(content); // "Hello, world!" const binary = await agent.fs.readFile('/images/icon.png'); console.log(binary); // // Get file statistics const stats = await agent.fs.stat('/documents/readme.txt'); console.log({ inode: stats.ino, size: stats.size, mode: stats.mode.toString(8), // "100644" for regular file isFile: stats.isFile(), // true isDirectory: stats.isDirectory(), // false modified: new Date(stats.mtime * 1000) }); // List directory contents const files = await agent.fs.readdir('/documents'); console.log(files); // ['readme.txt'] // Create directories await agent.fs.mkdir('/new-folder'); // Remove files and directories await agent.fs.unlink('/documents/readme.txt'); await agent.fs.rmdir('/empty-folder'); await agent.fs.rm('/folder', { recursive: true, force: true }); // Rename/move files await agent.fs.rename('/old-name.txt', '/new-name.txt'); // Copy files await agent.fs.copyFile('/source.txt', '/destination.txt'); // Check file access (existence) try { await agent.fs.access('/documents/readme.txt'); console.log('File exists'); } catch (e) { console.log('File does not exist'); } ``` -------------------------------- ### Create Key-Value Store Table and Indexes (SQL) Source: https://github.com/tursodatabase/agentfs/blob/main/SPEC.md Defines the schema for the `kv_store` table, used for storing arbitrary key-value pairs for agent context and state. Includes automatic timestamping for creation and updates, and an index on `created_at`. ```sql CREATE TABLE kv_store ( key TEXT PRIMARY KEY, value TEXT NOT NULL, created_at INTEGER DEFAULT (unixepoch()), updated_at INTEGER DEFAULT (unixepoch()) ) CREATE INDEX idx_kv_store_created_at ON kv_store(created_at) ``` -------------------------------- ### Python SDK: Tool Call Tracking and Analysis Source: https://context7.com/tursodatabase/agentfs/llms.txt Illustrates how to track and analyze tool invocations using the AgentFS Python SDK. This includes recording completed calls, managing start/success/error states for calls, querying calls by name or recent activity, retrieving specific calls, and accessing performance statistics. Requires the `agentfs_sdk` library. ```python import asyncio import time from agentfs_sdk import AgentFS, AgentFSOptions async def main(): agent = await AgentFS.open(AgentFSOptions(id='tools-demo')) # Record a completed tool call call_id = await agent.tools.record( name='web_search', started_at=int(time.time()), completed_at=int(time.time()) + 2, parameters={'query': 'Python async'}, result={'results': [{'title': 'Async Guide'}]} ) print(f"Recorded: {call_id}") # Start/complete flow search_id = await agent.tools.start('database_query', {'sql': 'SELECT *'}) try: # Do work... await agent.tools.success(search_id, {'rows': 10}) except Exception as e: await agent.tools.error(search_id, str(e)) # Record failed call await agent.tools.record( name='api_call', started_at=int(time.time()), completed_at=int(time.time()), parameters={'endpoint': '/users'}, error='Timeout' ) # Query by name calls = await agent.tools.get_by_name('web_search', limit=10) for call in calls: print(f"{call.name}: {call.status} ({call.duration_ms}ms)") # Get recent calls one_hour_ago = int(time.time()) - 3600 recent = await agent.tools.get_recent(one_hour_ago) # Get specific call call = await agent.tools.get(call_id) print(call.parameters) # Performance statistics stats = await agent.tools.get_stats() for stat in stats: print(f"{stat.name}:") print(f" Total: {stat.total_calls}") print(f" Success: {stat.successful}, Failed: {stat.failed}") print(f" Avg: {stat.avg_duration_ms:.2f}ms") await agent.close() asyncio.run(main()) ``` -------------------------------- ### List All Keys in Key-Value Store Source: https://github.com/tursodatabase/agentfs/blob/main/SPEC.md Retrieves all keys from the key-value store, ordered alphabetically. This query is essential for iterating through all stored key-value pairs and understanding the current state of the store. It selects the key, creation timestamp, and last update timestamp. ```sql SELECT key, created_at, updated_at FROM kv_store ORDER BY key ASC ``` -------------------------------- ### Create File in AgentFS Source: https://github.com/tursodatabase/agentfs/blob/main/SPEC.md Steps to create a file, involving resolving parent paths, inserting inode and directory entries, splitting data into chunks, and updating inode size. It relies on SQL queries for database interactions. ```sql SELECT value FROM fs_config WHERE key = 'chunk_size' INSERT INTO fs_inode (mode, uid, gid, size, atime, mtime, ctime) VALUES (?, ?, ?, 0, ?, ?, ?) RETURNING ino INSERT INTO fs_dentry (name, parent_ino, ino) VALUES (?, ?, ?) UPDATE fs_inode SET nlink = nlink + 1 WHERE ino = ? INSERT INTO fs_data (ino, chunk_index, data) VALUES (?, ?, ?) UPDATE fs_inode SET size = ?, mtime = ? WHERE ino = ? ``` -------------------------------- ### Analyze Tool Performance (SQL) Source: https://github.com/tursodatabase/agentfs/blob/main/SPEC.md Calculates performance metrics for each tool, including total calls, successful calls, failed calls, and average duration. Results are grouped by tool name and ordered by the total number of calls. ```sql SELECT name, COUNT(*) as total_calls, SUM(CASE WHEN error IS NULL THEN 1 ELSE 0 END) as successful, SUM(CASE WHEN error IS NOT NULL THEN 1 ELSE 0 END) as failed, AVG(duration_ms) as avg_duration_ms FROM tool_calls GROUP BY name ORDER BY total_calls DESC ``` -------------------------------- ### Initialize AgentFS Database Source: https://github.com/tursodatabase/agentfs/blob/main/SPEC.md Initializes the agentfs database by setting the chunk size configuration and creating the root directory inode. ```sql -- Initialize filesystem configuration INSERT INTO fs_config (key, value) VALUES ('chunk_size', '4096'); -- Initialize root directory INSERT INTO fs_inode (ino, mode, nlink, uid, gid, size, atime, mtime, ctime) VALUES (1, 16877, 1, 0, 0, 0, unixepoch(), unixepoch(), unixepoch()); ``` -------------------------------- ### AgentFS Python SDK: Configuration with Custom Path Source: https://github.com/tursodatabase/agentfs/blob/main/sdk/python/README.md Demonstrates how to specify a custom path for the AgentFS database file, allowing more control over storage location. ```python agent = await AgentFS.open(AgentFSOptions(path='./data/mydb.db')) ``` -------------------------------- ### AgentFS Python SDK: Configuration with ID and Custom Path Source: https://github.com/tursodatabase/agentfs/blob/main/sdk/python/README.md Illustrates how to specify both an agent ID and a custom path for the AgentFS database, providing clarity and explicit control over the database file. ```python agent = await AgentFS.open(AgentFSOptions(id='my-agent', path='./data/mydb.db')) ``` -------------------------------- ### Open AgentFS Instance with TypeScript SDK Source: https://context7.com/tursodatabase/agentfs/llms.txt Opens an AgentFS instance using the TypeScript SDK. Supports persistent storage (creating a database file) or ephemeral in-memory storage. Provides access to filesystem, key-value store, and tool call tracking interfaces. ```typescript import { AgentFS } from 'agentfs-sdk'; // Open with persistent storage (creates .agentfs/my-agent.db) const agent = await AgentFS.open({ id: 'my-agent' }); // Open with custom database path const agent2 = await AgentFS.open({ path: './data/custom.db' }); // Open ephemeral in-memory database (no persistence) const ephemeral = await AgentFS.open({}); // Access the three main interfaces agent.fs; // Filesystem operations agent.kv; // Key-value store agent.tools; // Tool call tracking // Get underlying database for custom queries const db = agent.getDatabase(); // Close when done await agent.close(); ``` -------------------------------- ### AgentFS CLI Filesystem Commands Source: https://context7.com/tursodatabase/agentfs/llms.txt Provides commands to interact with the AgentFS filesystem, including listing directory contents, reading file contents, and writing data to files. Can operate using agent IDs or direct database paths, and supports encrypted filesystems. ```bash # List files in the root directory agentfs fs ls my-agent # Output: # f hello.txt # d documents # List files in a subdirectory agentfs fs ls my-agent /documents # Read file contents agentfs fs cat my-agent /documents/readme.txt # Output: Hello, world! # Write content to a file agentfs fs write my-agent /notes.txt "Meeting notes for today" # Use database path directly instead of agent ID agentfs fs cat .agentfs/my-agent.db /hello.txt # Access encrypted filesystem agentfs fs ls my-secure-agent --key $KEY --cipher aes256gcm ``` -------------------------------- ### AgentFS Python SDK: Using Async Context Manager Source: https://github.com/tursodatabase/agentfs/blob/main/sdk/python/README.md Explains how to use the AgentFS Python SDK with Python's asynchronous context managers (`async with`), ensuring the database is automatically closed upon exiting the block. ```python async with await AgentFS.open(AgentFSOptions(id='my-agent')) as agent: await agent.kv.set('key', 'value') # Database is automatically closed when exiting the context ``` -------------------------------- ### Ask a Research Question with npm Source: https://github.com/tursodatabase/agentfs/blob/main/examples/mastra/research-assistant/README.md Executes the research assistant to answer a database research question. The question is passed as a command-line argument. ```console npm run ask -- "How do learned indexes compare to B+ trees?" ``` -------------------------------- ### Retrieve Value by Key (SQL) Source: https://github.com/tursodatabase/agentfs/blob/main/SPEC.md SQL query to fetch the value associated with a specific key from the key-value store. This is used for retrieving agent context or state. ```sql SELECT value FROM kv_store WHERE key = ? ``` -------------------------------- ### Create Whiteout Table and Index (SQL) Source: https://github.com/tursodatabase/agentfs/blob/main/SPEC.md Defines the schema for the `fs_whiteout` table, which tracks deleted paths in an overlay filesystem to prevent visibility of base layer files. Includes a primary key on `path` and an index on `parent_path` for efficient lookups. ```sql CREATE TABLE fs_whiteout ( path TEXT PRIMARY KEY, parent_path TEXT NOT NULL, created_at INTEGER NOT NULL ) CREATE INDEX idx_fs_whiteout_parent ON fs_whiteout(parent_path) ``` -------------------------------- ### Query Tool Calls by Name (SQL) Source: https://github.com/tursodatabase/agentfs/blob/main/SPEC.md Retrieves all tool call records for a specific tool name, ordered by the most recent calls first. Useful for debugging and auditing specific tools. ```sql SELECT * FROM tool_calls WHERE name = ? ORDER BY started_at DESC ``` -------------------------------- ### Insert or Update Whiteout Entry (SQL) Source: https://github.com/tursodatabase/agentfs/blob/main/SPEC.md SQL statement to insert a new whiteout entry or update the `created_at` timestamp if the path already exists. This operation is used when deleting a file that is present in the base layer of the overlay filesystem. ```sql INSERT INTO fs_whiteout (path, parent_path, created_at) VALUES (?, ?, ?) ON CONFLICT(path) DO UPDATE SET created_at = excluded.created_at ``` -------------------------------- ### Record a Tool Call (SQL) Source: https://github.com/tursodatabase/agentfs/blob/main/SPEC.md SQL statement to insert a new record into the 'tool_calls' table, capturing the details of a completed tool invocation. This is an insert-only operation. ```sql INSERT INTO tool_calls (name, parameters, result, error, started_at, completed_at, duration_ms) VALUES (?, ?, ?, ?, ?, ?, ?) ``` -------------------------------- ### Set or Update Key-Value Pair (SQL) Source: https://github.com/tursodatabase/agentfs/blob/main/SPEC.md SQL statement to insert a new key-value pair or update the value and `updated_at` timestamp if the key already exists. This is the primary operation for setting agent state in the key-value store. ```sql INSERT INTO kv_store (key, value, updated_at) VALUES (?, ?, unixepoch()) ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = unixepoch() ``` -------------------------------- ### Sandboxed Execution with agentfs run Source: https://context7.com/tursodatabase/agentfs/llms.txt Executes commands within a sandboxed environment using copy-on-write isolation. Changes are isolated to a delta layer. Supports named sessions for persistence, allowing additional writable directories, and encrypted delta layers. ```bash # Run bash in sandbox (creates session-based overlay) agentfs run /bin/bash # Inside sandbox: # - /agent directory for agent-specific files # - Root filesystem has copy-on-write semantics # - Changes are isolated from host # Run with named session for persistence agentfs run --session my-session /bin/bash # Allow additional writable directories agentfs run --allow /tmp/workspace --allow ~/.config /bin/bash # View changes made in sandbox agentfs diff my-session # Run with encryption for delta layer agentfs run --key $KEY --cipher aes256gcm /bin/bash ```