Files
optimclaw/tools-src/google-slides/src/lib.rs
T
a53b2c10b5 fix: Fix wasm tool schemas and runtime (#42)
* feat: Move debug log truncation from agent loop to REPL channel

Full tool output now flows through StatusUpdate so the web gateway
gets untruncated content. The REPL channel truncates at display time
(200 chars for tool results, thinking, and status messages).

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: Flatten WASM tool schemas and fix host HTTP runtime contention

LLMs can't reliably follow oneOf + const discriminator patterns in JSON
Schema, causing tools like Google Calendar to receive malformed params
(e.g., {"operation":"list_events","data":{"calendarId":"primary"}} instead
of {"action":"list_events","calendar_id":"primary"}). Replace all 9 WASM
tool schemas with flat action enum + top-level properties. The serde
#[serde(tag = "action")] deserialization works identically.

Also fixes WASM host HTTP requests (channels and tools) stalling during
startup by replacing Handle::current().block_on() with a dedicated
single-threaded runtime per request, avoiding I/O driver contention.

Reduces verbose LLM debug logging (full request/response payloads) and
changes tower_http default from debug to warn.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* feat: Built-in OAuth credentials and combined Google scopes

Add infrastructure for shipping default OAuth credentials with the binary,
similar to how gcloud/rclone bake in their client_id. Credentials are set
at compile time via IRONCLAW_GOOGLE_CLIENT_ID / IRONCLAW_GOOGLE_CLIENT_SECRET
env vars, or can be hardcoded in src/cli/oauth_defaults.rs.

The fallback chain is: capabilities file > runtime env var > built-in defaults.

Also, when authing any Google tool, scopes from ALL installed Google tools
are now combined into a single OAuth request (they all share the same
google_oauth_token secret). One login covers Gmail, Calendar, Drive, etc.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* feat: Ship default Google OAuth credentials for zero-config auth

Google Desktop App credentials are not secret (per Google's own docs).
Hardcode them so `ironclaw tool auth <google-tool>` works out of the box
without requiring users to register their own OAuth app.

Credentials can still be overridden at compile time
(IRONCLAW_GOOGLE_CLIENT_ID) or runtime (GOOGLE_OAUTH_CLIENT_ID).

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: Consistent OAuth callback port and polished landing page

- Use fixed port 9876 instead of scanning 9876-9886 (one redirect URI
  to register in provider OAuth apps, deterministic behavior)
- Replace broken unicode checkmark with SVG icons (charset was missing,
  rendered as mojibake)
- Dark themed landing page with proper card layout for both success
  and error states
- Add charset=utf-8 to Content-Type headers

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* refactor: Unify OAuth callback server across all auth flows

All three OAuth flows (WASM tool auth, MCP server auth, NEAR AI login)
now share the same code from cli::oauth_defaults:

- Fixed port 9876 (one redirect URI to register per provider)
- Shared landing page HTML (dark card with SVG icons, proper charset)
- Parameterized wait_for_callback(listener, path, param, display_name)

Removes ~120 lines of duplicated callback/HTML code.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* Support for oauth token refresh

* refactor: Replace bootstrap.json with ~/.ironclaw/.env for DATABASE_URL

Kill the 4-field BootstrapConfig JSON file. Only DATABASE_URL actually
needs disk persistence (chicken-and-egg before DB connect). The other
three fields are now derived: pool_size defaults to 10 via env var,
secrets master key is auto-detected (env then keychain probe), and
onboard_completed is inferred from DATABASE_URL presence.

The new format is a standard .env file loaded via dotenvy early in
main, so DATABASE_URL is available as a regular env var everywhere.

Handles three upgrade paths:
- Clean start: wizard writes .env, reload after wizard completes
- Returning user: .env loaded at startup, business as usual
- Legacy upgrade: bootstrap.json auto-migrated to .env on first run

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: Address PR review findings

- Fix UTF-8 panic in truncate_for_preview (byte-slice on char boundary)
- Cap WASM guest timeout_ms at 5 minutes to prevent resource exhaustion
- Fix localhost detection in requires_auth() to avoid substring matches
  (e.g. "notlocalhost.com" no longer matches)
- Fix query param injection to insert before URL fragment
- Fix extract_host_from_url for IPv6 bracket notation
- Remove misleading schema defaults: Slack limit, Slides insertion_index,
  Docs index (per-action defaults documented in descriptions instead)

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* style: Fix cargo fmt formatting

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: IPv6 loopback support for OAuth listener and localhost detection

- bind_callback_listener: try [::1] first, fall back to 127.0.0.1,
  so OAuth redirects work on systems where localhost resolves to ::1
- is_localhost_url: replace manual string parsing with url::Url for
  correct handling of IPv6 brackets, ports, userinfo, etc.
- Add url crate as direct dependency (already a transitive dep)

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: Address PR review feedback on runtime reuse, onboard check, and OAuth binding

- Remove session file check from check_onboard_needed(); DATABASE_URL is sufficient
- Detect AddrInUse on IPv6 bind and fail immediately instead of falling through to IPv4
- Reuse dedicated tokio runtime across HTTP calls in both tool and channel WASM wrappers

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: HTML-escape provider name in OAuth landing page, simplify Slack limit description

- Add html_escape() to prevent XSS in landing_html() where provider_name
  was interpolated directly into HTML (defense-in-depth, source is trusted
  but escaping costs nothing)
- Remove per-action default numbers from Slack limit field description to
  avoid confusing LLMs with conflicting defaults

Addresses review feedback from zmanian on PR #42.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: Save all bootstrap fields from wizard, fix config module comment

- Wizard now saves secrets_master_key_source and database_pool_size to
  bootstrap.json (was only saving database_url and onboard_completed,
  which broke secrets after fresh onboard since SecretsConfig::resolve
  reads key source from bootstrap)
- Update config.rs module doc to reflect bootstrap.json priority chain
  instead of the removed ~/.ironclaw/.env approach

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* refactor: Replace BootstrapConfig with .env-based bootstrap

DATABASE_URL is the only setting that needs disk persistence before
the database is available. Instead of a custom bootstrap.json with 4
fields, use a standard ~/.ironclaw/.env file loaded via dotenvy.

- Remove BootstrapConfig struct entirely
- Restore ironclaw_env_path(), load_ironclaw_env(), save_database_url()
- SecretsConfig::resolve() now auto-detects (env var then keychain probe)
  instead of reading a saved source from bootstrap.json
- DatabaseConfig::resolve() reads DATABASE_URL from env only (dotenvy
  loads ~/.ironclaw/.env into the environment early in startup)
- check_onboard_needed() is now sync (just checks env vars)
- Wizard save_and_summarize() works for both postgres and libsql backends
- One-time migration from bootstrap.json to .env preserved

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: Ensure load_ironclaw_env() runs in all Config paths, fix .env priority

- Config::from_env() and Config::from_db() now call load_ironclaw_env()
  internally (after dotenvy::dotenv()), so CLI commands like `memory`
  and `config` correctly load DATABASE_URL from ~/.ironclaw/.env
- Fix load order: standard ./.env first (higher priority), then
  ~/.ironclaw/.env, matching the documented priority chain
- Collapse nested if/if-let into let-chains (clippy::collapsible_if)
  in oauth_defaults.rs, tool.rs, and secrets/store.rs
- Fix rename_to_migrated to take &Path instead of &PathBuf

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: Address PR review comments (quoting, SSRF, error mapping)

- Quote DATABASE_URL in .env writes so `#` in passwords isn't treated
  as a dotenv comment (e.g., `DATABASE_URL="postgres://..."`)
- Add SSRF defenses to refresh_oauth_token(): require HTTPS, reject
  private/loopback IPs (with DNS resolution), disable redirects.
  token_url comes from tool capabilities JSON, so a malicious tool
  could otherwise exfiltrate refresh tokens.
- Fix IPv4 bind error mapping: only map AddrInUse to PortInUse,
  use generic Io variant for other bind failures

Co-Authored-By: Claude Opus 4.6 <[email protected]>

---------

Co-authored-by: Claude Opus 4.6 <[email protected]>
2026-02-14 21:21:22 +00:00

410 lines
16 KiB
Rust

//! Google Slides WASM Tool for IronClaw.
//!
//! Provides Google Slides integration for creating, reading, editing,
//! and formatting presentations. Use Google Drive tool to search for
//! existing presentations by name.
//!
//! # Capabilities Required
//!
//! - HTTP: `slides.googleapis.com/v1/presentations*`
//! - Secrets: `google_oauth_token` (shared OAuth 2.0 token, injected automatically)
//!
//! # Supported Actions
//!
//! - `create_presentation`: Create a new blank presentation
//! - `get_presentation`: Get presentation metadata (slides, elements, text)
//! - `get_thumbnail`: Get a thumbnail image URL for a slide
//! - `create_slide`: Add a new slide with a predefined layout
//! - `delete_object`: Delete a slide or page element
//! - `insert_text`: Insert text into a shape or text box
//! - `delete_text`: Delete text from a shape
//! - `replace_all_text`: Find and replace text across the presentation
//! - `create_shape`: Create a text box or shape on a slide
//! - `insert_image`: Insert an image on a slide
//! - `format_text`: Format text (bold, italic, font, color, size)
//! - `format_paragraph`: Set paragraph alignment
//! - `replace_shapes_with_image`: Replace placeholder shapes with an image
//! - `batch_update`: Execute multiple raw Slides API operations atomically
//!
//! # Tips
//!
//! - Presentation IDs are the same as Google Drive file IDs. Use
//! google-drive tool's list_files to find presentations.
//! - Positions and sizes are specified in points (1 inch = 72 points).
//! A standard slide is 720x405 points (10x5.625 inches).
//! - To add text to a slide: first create_shape (TEXT_BOX), then
//! insert_text into the returned object_id.
//! - Use get_presentation to discover object IDs for existing elements.
//! - For template workflows: create shapes with placeholder text, then
//! use replace_all_text or replace_shapes_with_image.
//!
//! # Example Usage
//!
//! ```json
//! {"action": "create_presentation", "title": "Q1 Report"}
//! {"action": "create_slide", "presentation_id": "abc123", "layout": "TITLE_AND_BODY"}
//! {"action": "get_presentation", "presentation_id": "abc123"}
//! {"action": "create_shape", "presentation_id": "abc123", "slide_object_id": "slide1", "shape_type": "TEXT_BOX", "x": 50, "y": 50, "width": 300, "height": 40}
//! {"action": "insert_text", "presentation_id": "abc123", "object_id": "shape1", "text": "Hello World"}
//! {"action": "format_text", "presentation_id": "abc123", "object_id": "shape1", "bold": true, "font_size": 24}
//! ```
mod api;
mod types;
use types::GoogleSlidesAction;
wit_bindgen::generate!({
world: "sandboxed-tool",
path: "../../wit/tool.wit",
});
struct GoogleSlidesTool;
impl exports::near::agent::tool::Guest for GoogleSlidesTool {
fn execute(req: exports::near::agent::tool::Request) -> exports::near::agent::tool::Response {
match execute_inner(&req.params) {
Ok(result) => exports::near::agent::tool::Response {
output: Some(result),
error: None,
},
Err(e) => exports::near::agent::tool::Response {
output: None,
error: Some(e),
},
}
}
fn schema() -> String {
r#"{
"type": "object",
"required": ["action"],
"properties": {
"action": {
"type": "string",
"enum": ["create_presentation", "get_presentation", "get_thumbnail", "create_slide", "delete_object", "insert_text", "delete_text", "replace_all_text", "create_shape", "insert_image", "format_text", "format_paragraph", "replace_shapes_with_image", "batch_update"],
"description": "The Google Slides operation to perform"
},
"title": {
"type": "string",
"description": "Presentation title. Required for: create_presentation"
},
"presentation_id": {
"type": "string",
"description": "Presentation ID (same as Google Drive file ID). Required for all actions except create_presentation"
},
"slide_object_id": {
"type": "string",
"description": "Slide object ID. Required for: get_thumbnail, create_shape, insert_image"
},
"object_id": {
"type": "string",
"description": "Object ID of a slide element. Required for: delete_object, insert_text, delete_text, format_text, format_paragraph"
},
"text": {
"type": "string",
"description": "Text to insert. Required for: insert_text"
},
"insertion_index": {
"type": "integer",
"description": "Position to insert at (0-based). Used by: create_slide (omit to append at end), insert_text (default: 0)"
},
"layout": {
"type": "string",
"enum": ["BLANK", "TITLE", "TITLE_AND_BODY", "TITLE_AND_TWO_COLUMNS", "TITLE_ONLY", "SECTION_HEADER", "CAPTION_ONLY", "BIG_NUMBER", "ONE_COLUMN_TEXT", "MAIN_POINT"],
"description": "Predefined slide layout (default: BLANK). Used by: create_slide",
"default": "BLANK"
},
"start_index": {
"type": "integer",
"description": "Start index (inclusive, 0-based). Used by: delete_text, format_text, format_paragraph"
},
"end_index": {
"type": "integer",
"description": "End index (exclusive). Used by: delete_text, format_text, format_paragraph"
},
"find": {
"type": "string",
"description": "Text to search for. Required for: replace_all_text, replace_shapes_with_image"
},
"replace": {
"type": "string",
"description": "Replacement text. Required for: replace_all_text"
},
"match_case": {
"type": "boolean",
"description": "Case-sensitive match (default: true). Used by: replace_all_text, replace_shapes_with_image",
"default": true
},
"shape_type": {
"type": "string",
"enum": ["TEXT_BOX", "RECTANGLE", "ROUND_RECTANGLE", "ELLIPSE"],
"description": "Shape type (default: TEXT_BOX). Used by: create_shape",
"default": "TEXT_BOX"
},
"x": {
"type": "number",
"description": "X position in points from left edge. Required for: create_shape, insert_image"
},
"y": {
"type": "number",
"description": "Y position in points from top edge. Required for: create_shape, insert_image"
},
"width": {
"type": "number",
"description": "Width in points. Required for: create_shape, insert_image"
},
"height": {
"type": "number",
"description": "Height in points. Required for: create_shape, insert_image"
},
"image_url": {
"type": "string",
"description": "Publicly accessible image URL. Required for: insert_image, replace_shapes_with_image"
},
"bold": {
"type": "boolean",
"description": "Make text bold. Used by: format_text"
},
"italic": {
"type": "boolean",
"description": "Make text italic. Used by: format_text"
},
"underline": {
"type": "boolean",
"description": "Underline text. Used by: format_text"
},
"font_size": {
"type": "number",
"description": "Font size in points (e.g., 12, 18, 24). Used by: format_text"
},
"font_family": {
"type": "string",
"description": "Font family (e.g., 'Arial', 'Roboto'). Used by: format_text"
},
"foreground_color": {
"type": "string",
"description": "Text color as hex (e.g., '#FF0000'). Used by: format_text"
},
"alignment": {
"type": "string",
"enum": ["START", "CENTER", "END", "JUSTIFIED"],
"description": "Paragraph alignment. Required for: format_paragraph"
},
"requests": {
"type": "array",
"items": { "type": "object" },
"description": "Array of raw Slides API batchUpdate request objects. Required for: batch_update"
}
}
}"#
.to_string()
}
fn description() -> String {
"Google Slides integration for creating, reading, editing, and formatting presentations. \
Supports slide management (create, delete, reorder), text operations (insert, delete, \
find-replace), shapes and text boxes, image insertion, text formatting (bold, italic, \
font, color, size), paragraph alignment, thumbnails, and template-based image replacement. \
Also provides a batch_update action for complex multi-step edits executed atomically. \
Positions and sizes use points (standard slide is 720x405 pt). Presentation IDs are the \
same as Google Drive file IDs, so use the google-drive tool to search for existing \
presentations. Requires a Google OAuth token with the presentations scope."
.to_string()
}
}
fn execute_inner(params: &str) -> Result<String, String> {
if !crate::near::agent::host::secret_exists("google_oauth_token") {
return Err(
"Google OAuth token not configured. Run `ironclaw tool auth google-slides` to set up \
OAuth, or set the GOOGLE_OAUTH_TOKEN environment variable."
.to_string(),
);
}
let action: GoogleSlidesAction =
serde_json::from_str(params).map_err(|e| format!("Invalid parameters: {}", e))?;
crate::near::agent::host::log(
crate::near::agent::host::LogLevel::Info,
&format!("Executing Google Slides action: {:?}", action),
);
let result = match action {
GoogleSlidesAction::CreatePresentation { title } => {
let result = api::create_presentation(&title)?;
serde_json::to_string(&result).map_err(|e| e.to_string())?
}
GoogleSlidesAction::GetPresentation { presentation_id } => {
let result = api::get_presentation(&presentation_id)?;
serde_json::to_string(&result).map_err(|e| e.to_string())?
}
GoogleSlidesAction::GetThumbnail {
presentation_id,
slide_object_id,
} => {
let result = api::get_thumbnail(&presentation_id, &slide_object_id)?;
serde_json::to_string(&result).map_err(|e| e.to_string())?
}
GoogleSlidesAction::CreateSlide {
presentation_id,
insertion_index,
layout,
} => {
let result = api::create_slide(&presentation_id, insertion_index, &layout)?;
serde_json::to_string(&result).map_err(|e| e.to_string())?
}
GoogleSlidesAction::DeleteObject {
presentation_id,
object_id,
} => {
let result = api::delete_object(&presentation_id, &object_id)?;
serde_json::to_string(&result).map_err(|e| e.to_string())?
}
GoogleSlidesAction::InsertText {
presentation_id,
object_id,
text,
insertion_index,
} => {
let result = api::insert_text(&presentation_id, &object_id, &text, insertion_index)?;
serde_json::to_string(&result).map_err(|e| e.to_string())?
}
GoogleSlidesAction::DeleteText {
presentation_id,
object_id,
start_index,
end_index,
} => {
let result = api::delete_text(&presentation_id, &object_id, start_index, end_index)?;
serde_json::to_string(&result).map_err(|e| e.to_string())?
}
GoogleSlidesAction::ReplaceAllText {
presentation_id,
find,
replace,
match_case,
} => {
let result = api::replace_all_text(&presentation_id, &find, &replace, match_case)?;
serde_json::to_string(&result).map_err(|e| e.to_string())?
}
GoogleSlidesAction::CreateShape {
presentation_id,
slide_object_id,
shape_type,
x,
y,
width,
height,
} => {
let result = api::create_shape(
&presentation_id,
&slide_object_id,
&shape_type,
x,
y,
width,
height,
)?;
serde_json::to_string(&result).map_err(|e| e.to_string())?
}
GoogleSlidesAction::InsertImage {
presentation_id,
slide_object_id,
image_url,
x,
y,
width,
height,
} => {
let result = api::insert_image(
&presentation_id,
&slide_object_id,
&image_url,
x,
y,
width,
height,
)?;
serde_json::to_string(&result).map_err(|e| e.to_string())?
}
GoogleSlidesAction::FormatText {
presentation_id,
object_id,
start_index,
end_index,
bold,
italic,
underline,
font_size,
font_family,
foreground_color,
} => {
let result = api::format_text(api::FormatTextOptions {
presentation_id: &presentation_id,
object_id: &object_id,
start_index,
end_index,
bold,
italic,
underline,
font_size,
font_family: font_family.as_deref(),
foreground_color: foreground_color.as_deref(),
})?;
serde_json::to_string(&result).map_err(|e| e.to_string())?
}
GoogleSlidesAction::FormatParagraph {
presentation_id,
object_id,
alignment,
start_index,
end_index,
} => {
let result = api::format_paragraph(
&presentation_id,
&object_id,
&alignment,
start_index,
end_index,
)?;
serde_json::to_string(&result).map_err(|e| e.to_string())?
}
GoogleSlidesAction::ReplaceShapesWithImage {
presentation_id,
find,
image_url,
match_case,
} => {
let result =
api::replace_shapes_with_image(&presentation_id, &find, &image_url, match_case)?;
serde_json::to_string(&result).map_err(|e| e.to_string())?
}
GoogleSlidesAction::BatchUpdate {
presentation_id,
requests,
} => {
let result = api::batch_update(&presentation_id, requests)?;
serde_json::to_string(&result).map_err(|e| e.to_string())?
}
};
Ok(result)
}
export!(GoogleSlidesTool);