# Drive Storage Tools

## 📦 **Persistent Cloud Storage for Agents**

Drive Storage Tools provide agents with persistent, cloud-based file system capabilities that survive across all agent sessions and turns. Unlike temporary code execution sandboxes, Drive storage maintains files indefinitely until explicitly deleted.

### **Key Features**

* **Persistent Storage**: Files remain available across all agent sessions
* **Workspace Isolation**: Each agent has private, isolated storage within its project
* **Working Directory Scoping**: Optionally restrict operations to specific subfolders
* **Cloud-Based**: All files are stored in secure cloud storage
* **Full CRUD Operations**: Create, read, update, delete, rename, and organize files
* **URL Upload**: Download files from internet URLs directly to Drive storage
* **Binary File Support**: Handle images, PDFs, and other binary formats with download URLs

***

## ⚙️ **Configuration Options**

### **Enable Drive Storage**

Toggle to activate Drive storage tools for your agent:

* **Enabled**: Agent can create, read, modify, and organize files in Drive storage
* **Disabled**: Agent has no access to persistent file storage

### **Working Directory (Optional)**

Restrict all file operations to a specific subfolder:

**Example Configuration:**

```
Working Directory: "agent-workspace"
```

**Behavior:**

* Agent can only access files within `agent-workspace/`
* Paths are automatically scoped (e.g., `data.csv` becomes `agent-workspace/data.csv`)
* Prevents agents from accessing files outside their designated folder
* Empty path operates on the working directory itself

**Use Cases:**

* Multi-agent systems where each agent needs isolated storage
* Security isolation to prevent cross-contamination
* Organized project structure with dedicated agent folders

### **Individual Tool Permissions**

Control which specific file operations the agent can perform:

| Tool                | Description                                   | Default   |
| ------------------- | --------------------------------------------- | --------- |
| **View**            | Read file contents or list directory contents |  Enabled |
| **Create**          | Create new files or overwrite existing files  |  Enabled |
| **String Replace**  | Replace exact string matches in files         |  Enabled |
| **Insert**          | Insert content at specific line numbers       |  Enabled |
| **Delete**          | Delete files or directories                   |  Enabled |
| **Rename**          | Rename or move files/directories              |  Enabled |
| **Upload from URL** | Download files from URLs to Drive storage     |  Enabled |

**Permission Settings:**

* **Allowed**: Tool is available to the agent
* **Not Allowed**: Tool is hidden and cannot be used

**Security Considerations:**

* Disable `Delete` for read-only agents
* Disable `Create` and `String Replace` for analysis-only agents
* Disable `Upload from URL` if external downloads are not needed

***

## 🔧 **Available Drive Tools**

### **1. View (\_drive\_view)**

**Purpose:** Read file contents or list directory contents

**Parameters:**

* `file_path` (string, required): Path to file or directory
* `start_line` (integer, optional): First line to display (1-indexed, for text files)
* `end_line` (integer, optional): Last line to display (inclusive, for text files)

**Behavior:**

* **Text Files**: Returns content with line numbers (max 500 lines per view)
* **Binary Files**: Returns download URL (images, PDFs, archives, etc.)
* **Directories**: Lists all files and subdirectories, one per line
* **Empty Directories**: Returns "(empty directory)"

**Examples:**

```python
# List root directory
_drive_view(file_path="")

# Read entire text file
_drive_view(file_path="notes.txt")

# View specific line range
_drive_view(file_path="data.csv", start_line=1, end_line=100)

# Get download URL for binary file
_drive_view(file_path="report.pdf")

# List subdirectory
_drive_view(file_path="documents")
```

***

### **2. Create (\_drive\_create)**

**Purpose:** Create new files or overwrite existing files

**Parameters:**

* `file_path` (string, required): Path where file should be created
* `content` (string, required): Content to write to the file
* `replace` (boolean, optional, default: False): Allow overwriting existing files

**Behavior:**

* Automatically creates parent directories if they don't exist
* Fails if file exists and `replace=False` (prevents accidental overwrites)
* Supports any text-based content (JSON, CSV, TXT, code files, etc.)

**Examples:**

```python
# Create simple text file
_drive_create(file_path="notes.txt", content="Meeting notes here")

# Create JSON configuration
_drive_create(
    file_path="config.json",
    content='{"api_key": "value", "timeout": 30}'
)

# Create file in nested directory (auto-creates "data" folder)
_drive_create(file_path="data/results.csv", content="Name,Score\nAlice,95\nBob,87")

# Overwrite existing file
_drive_create(file_path="notes.txt", content="Updated notes", replace=True)
```

***

### **3. String Replace (\_drive\_str\_replace)**

**Purpose:** Replace an exact string match in a file

**Parameters:**

* `file_path` (string, required): Path to the file to edit
* `old_str` (string, required): Exact string to find (must appear exactly once)
* `new_str` (string, required): Replacement string

**Behavior:**

* Searches for exact match of `old_str`
* **Fails if `old_str` appears 0 times** (not found)
* **Fails if `old_str` appears 2+ times** (ambiguous match)
* Use `\n` for newlines in multi-line replacements
* Only replaces first occurrence (enforced uniqueness)

**Examples:**

```python
# Simple text replacement
_drive_str_replace(
    file_path="config.json",
    old_str='"timeout": 30',
    new_str='"timeout": 60'
)

# Multi-line replacement
_drive_str_replace(
    file_path="readme.md",
    old_str="## Old Section\nOld content here",
    new_str="## New Section\nUpdated content here"
)

# Replace variable in code
_drive_str_replace(
    file_path="script.py",
    old_str='API_KEY = "old_key"',
    new_str='API_KEY = "new_key"'
)
```

***

### **4. Insert (\_drive\_insert)**

**Purpose:** Insert content at a specific line number

**Parameters:**

* `file_path` (string, required): Path to the file to edit
* `line` (integer, required): Line number where content should be inserted (1-indexed)
* `content` (string, required): Text to insert

**Behavior:**

* Line numbers are 1-indexed (line 1 is the first line)
* Content is inserted **before** the specified line
* Use `line=1` to insert at the beginning
* Automatically adds newline if inserting in the middle of the file

**Examples:**

```python
# Insert at beginning of file
_drive_insert(file_path="script.py", line=1, content="#!/usr/bin/env python3\n")

# Insert after line 5
_drive_insert(
    file_path="data.txt",
    line=6,
    content="New line inserted here\n"
)

# Add section header
_drive_insert(
    file_path="readme.md",
    line=10,
    content="## New Section\nDescription here\n"
)
```

***

### **5. Delete (\_drive\_delete)**

**Purpose:** Delete files or directories

**Parameters:**

* `file_path` (string, required): Path to file or directory to delete

**Behavior:**

* **Files**: Deleted immediately
* **Directories**: Recursively deletes all contents
* **Permanent for agent**: Agent cannot recover deleted items

**Examples:**

```python
# Delete single file
_drive_delete(file_path="old_notes.txt")

# Delete entire directory and all contents
_drive_delete(file_path="old_data")

# Delete nested file
_drive_delete(file_path="archive/2023/report.pdf")
```

***

### **6. Rename (\_drive\_rename)**

**Purpose:** Rename files/directories or move them to different locations

**Parameters:**

* `old_path` (string, required): Current path of the file or directory
* `new_path` (string, required): New path (can be in a different directory)

**Behavior:**

* Can rename in place: `notes.txt` → `readme.txt`
* Can move to different directory: `notes.txt` → `docs/notes.txt`
* Can move and rename: `old/file.txt` → `new/renamed.txt`
* Automatically creates parent directories if needed

**Examples:**

```python
# Simple rename
_drive_rename(old_path="notes.txt", new_path="readme.txt")

# Move to different directory
_drive_rename(old_path="report.pdf", new_path="archive/report.pdf")

# Move and rename
_drive_rename(old_path="temp/data.csv", new_path="processed/clean_data.csv")

# Rename directory
_drive_rename(old_path="old_folder", new_path="new_folder")
```

***

### **7. Upload from URL (\_drive\_upload\_from\_url)**

**Purpose:** Download files from internet URLs and save to Drive storage

**Parameters:**

* `url` (string, required): HTTP/HTTPS URL to download from
* `file_path` (string, required): Where to save the downloaded file in Drive
* `replace` (boolean, optional, default: False): Allow overwriting existing files

**Behavior:**

* Supports HTTP and HTTPS URLs only
* **SSRF Prevention**: Blocks private IP addresses and localhost
* Maximum download timeout: 60 seconds
* Preserves original MIME type from download
* Fails if file exists and `replace=False`

**Examples:**

```python
# Download CSV dataset
_drive_upload_from_url(
    url="https://example.com/data.csv",
    file_path="datasets/raw_data.csv"
)

# Download image
_drive_upload_from_url(
    url="https://example.com/logo.png",
    file_path="images/logo.png"
)

# Download and overwrite
_drive_upload_from_url(
    url="https://api.example.com/latest.json",
    file_path="cache/api_response.json",
    replace=True
)

# Download PDF report
_drive_upload_from_url(
    url="https://example.com/report.pdf",
    file_path="reports/monthly.pdf"
)
```

***

## 📋 **Typical Agent Workflows**

### **Workflow 1: Data Processing Pipeline**

```
1. Download dataset from URL
   _drive_upload_from_url(url="https://...", file_path="data/raw.csv")

2. View dataset to understand structure
   _drive_view(file_path="data/raw.csv", start_line=1, end_line=10)

3. Process data (using code execution tools)
   _code_upload_to_session(uri="pmlfs://project_id/data/raw.csv")
   _code_execute_python(code="import pandas as pd; df = pd.read_csv('raw.csv')...")

4. Save processed results back to Drive
   _code_download_from_session(sandbox_path="processed.csv", uri="pmlfs://project_id/data/processed.csv")

5. Organize files
   _drive_rename(old_path="data/raw.csv", new_path="archive/raw_2024.csv")
```

### **Workflow 2: Configuration Management**

```
1. Create initial configuration
   _drive_create(file_path="config.json", content='{"setting": "value"}')

2. Read configuration
   _drive_view(file_path="config.json")

3. Update specific setting
   _drive_str_replace(
       file_path="config.json",
       old_str='"setting": "value"',
       new_str='"setting": "new_value"'
   )

4. Verify changes
   _drive_view(file_path="config.json")
```

### **Workflow 3: Report Generation**

```
1. Create report directory structure
   _drive_create(file_path="reports/2024/summary.md", content="# Monthly Report\n")

2. Add sections incrementally
   _drive_insert(file_path="reports/2024/summary.md", line=2, content="## Executive Summary\n")
   _drive_insert(file_path="reports/2024/summary.md", line=3, content="Key findings...\n")

3. Download supporting documents
   _drive_upload_from_url(url="https://...", file_path="reports/2024/chart.png")

4. Organize final structure
   _drive_rename(old_path="reports/2024/summary.md", new_path="reports/2024/final_report.md")
```

***

## 🔒 **Security & Best Practices**

### **Security Features**

1. **Path Validation**
   * No path traversal (`..`) allowed
   * No backslashes (Windows-style paths) allowed
   * No null bytes allowed
2. **Working Directory Isolation**
   * Enforces subfolder restrictions
   * Prevents access outside designated directory
   * Automatically prefixes all paths

### **Best Practices**

1. **Use Working Directories for Multi-Agent Systems**

   ```
   Agent 1: working_dir = "agent1-workspace"
   Agent 2: working_dir = "agent2-workspace"
   Agent 3: working_dir = "agent3-workspace"
   ```
2. **Organize Files in Logical Folders**

   ```
   data/raw/
   data/processed/
   configs/
   reports/
   archive/
   ```
3. **Use Descriptive File Names**

   ```
    customer_data_2024_q1.csv
    api_config_production.json
   L data.csv
   L config.json
   ```
4. **Leverage replace=False to Prevent Overwrites**

   ```python
   # Fail if file exists (safe default)
   _drive_create(file_path="important.csv", content=data, replace=False)

   # Only use replace=True when intentional
   _drive_create(file_path="cache.json", content=data, replace=True)
   ```
5. **Handle Large Files Efficiently**

   ```python
   # View large files in chunks
   _drive_view(file_path="huge.log", start_line=1, end_line=500)
   _drive_view(file_path="huge.log", start_line=501, end_line=1000)

   # Binary files use download URLs (no context overflow)
   _drive_view(file_path="large_video.mp4")  # Returns URL
   ```

***

## ⚠️ **Important Limitations**

### **Drive vs Code Execution Sandbox**

Drive storage is **completely separate** from the code execution sandbox:

| Feature           | Drive Storage                     | Code Sandbox                   |
| ----------------- | --------------------------------- | ------------------------------ |
| **Persistence**   | Permanent (until deleted)         | Temporary (deleted after turn) |
| **Access Tools**  | `_drive_*` tools                  | `_code_*` tools                |
| **File Transfer** | Requires explicit upload/download | Direct file system access      |
| **Survival**      | Survives all sessions             | Cleared every turn             |

**To Use Drive Files in Code Execution:**

```python
# 1. Upload from Drive to sandbox
_code_upload_to_session(uri="pmlfs://project_id/data.csv")

# 2. Process in sandbox
_code_execute_python(code="import pandas as pd; df = pd.read_csv('data.csv')")

# 3. Download results back to Drive
_code_download_from_session(sandbox_path="output.csv", uri="pmlfs://project_id/results.csv")
```

### **File Size Considerations**

* **View Tool**: 500-line limit per view operation (prevents context overflow)
* **Binary Files**: Not loaded into context; download URLs provided instead
* **Large Text Files**: Use `start_line` and `end_line` parameters to view in chunks

### **Path Restrictions**

* Must use forward slashes: `folder/file.txt`
* No leading slash needed: `data.csv` not `/data.csv`
* Path `.` or `""` refers to root (or working directory if configured)
* Working directory paths are automatically prefixed

***

## 💼 **Use Cases by Agent Type**

### **Data Analysis Agents**

**Recommended Configuration:**

*  Enable: View, Create, String Replace, Rename, Upload from URL
* L Disable: Delete (preserve all data)
* Working Directory: `data-analysis/`

**Workflow:** Download datasets, process data, generate reports, organize results

***

### **Content Management Agents**

**Recommended Configuration:**

*  Enable: All tools
* Working Directory: `content/`

**Workflow:** Create articles, update documentation, organize media files, archive old content

***

### **Configuration Management Agents**

**Recommended Configuration:**

*  Enable: View, String Replace, Create (with replace=True)
* L Disable: Delete, Rename (prevent structure changes)
* Working Directory: `configs/`

**Workflow:** Read configurations, update settings, maintain version history

***

### **Read-Only Audit Agents**

**Recommended Configuration:**

*  Enable: View only
* L Disable: All modification tools
* Working Directory: `audit-logs/`

**Workflow:** Read logs, analyze data, generate audit reports without modification

***

### **File Organization Agents**

**Recommended Configuration:**

*  Enable: View, Rename, Delete, Create
* L Disable: String Replace, Insert (no content editing)
* Working Directory: None (full access)

**Workflow:** Organize files, clean up old data, maintain folder structure

***

## 💡 **Tips & Tricks**

### **1. Check Before Creating**

```python
# List directory first
contents = _drive_view(file_path="reports")

# Then create with appropriate name
_drive_create(file_path="reports/report_v2.txt", content=data)
```

### **2. Incremental File Building**

```python
# Create base file
_drive_create(file_path="report.md", content="# Report\n")

# Add sections incrementally
_drive_insert(file_path="report.md", line=2, content="## Section 1\nContent...\n")
_drive_insert(file_path="report.md", line=4, content="## Section 2\nContent...\n")
```

### **3. Safe Configuration Updates**

```python
# Read current config
current = _drive_view(file_path="config.json")

# Make targeted replacement
_drive_str_replace(
    file_path="config.json",
    old_str='"debug": false',
    new_str='"debug": true'
)

# Verify change
updated = _drive_view(file_path="config.json")
```

### **4. Batch Organization**

```python
# Create organized structure
_drive_create(file_path="archive/2024/q1/summary.txt", content="Q1 Summary")
_drive_rename(old_path="old_report.pdf", new_path="archive/2024/q1/report.pdf")
_drive_delete(file_path="temp")
```

***
