mirror of
https://github.com/outbackdingo/optimclaw.git
synced 2026-08-26 23:50:17 +00:00
feat: WASM channel attachments with LLM pipeline integration (#596)
* feat: add inbound attachment support to WASM channel system Add attachment record to WIT interface and implement inbound media parsing across all four channel implementations (Telegram, Slack, WhatsApp, Discord). Attachments flow from WASM channels through EmittedMessage to IncomingMessage with validation (size limits, MIME allowlist, count caps) at the host boundary. - Add `attachment` record to `emitted-message` in wit/channel.wit - Add `IncomingAttachment` struct to channel.rs and re-export - Add host-side validation (20MB total, 10 max, MIME allowlist) - Telegram: parse photo, document, audio, video, voice, sticker - Slack: parse file attachments with url_private - WhatsApp: parse image, audio, video, document with captions - Discord: backward-compatible empty attachments - Update FEATURE_PARITY.md section 7 - Add fixture-based tests per channel and host integration tests [skip-regression-check] Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat: integrate outbound attachment support and reconcile WIT types (#409) Reconcile PR #409's outbound attachment work with our inbound attachment support into a unified design: WIT type split: - `inbound-attachment` in channel-host: metadata-only (id, mime_type, filename, size_bytes, source_url, storage_key, extracted_text) - `attachment` in channel: raw bytes (filename, mime_type, data) on agent-response for outbound sending Outbound features (from PR #409): - `on-broadcast` WIT export for proactive messages without prior inbound - Telegram: multipart sendPhoto/sendDocument with auto photo→document fallback for files >10MB - wrapper.rs: `call_on_broadcast`, `read_attachments` from disk, attachment params threaded through `call_on_respond` - HTTP tool: `save_to` param for binary downloads to /tmp/ (50MB limit, path traversal protection, SSRF-safe redirect following) - Message tool: allow /tmp/ paths for attachments alongside base_dir - Credential env var fallback in inject_channel_credentials Channel updates: - All 4 channels implement on_broadcast (Telegram full, others stub) - Telegram: polling_enabled config, adjusted poll timeout - Inbound attachment types renamed to InboundAttachment in all channels Tests: 1965 passing (9 new), 0 clippy warnings [skip-regression-check] Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat: add audio transcription pipeline and extensible WIT attachment design Add host-side transcription middleware (OpenAI Whisper) that detects audio attachments with inline data on incoming messages and transcribes them automatically. Refactor WIT inbound-attachment to use extras-json and a store-attachment-data host function instead of typed fields, so future attachment properties (dimensions, codec, etc.) don't require WIT changes that invalidate all channel plugins. - Add src/transcription/ module: TranscriptionProvider trait, TranscriptionMiddleware, AudioFormat enum, OpenAI Whisper provider - Add src/config/transcription.rs: TRANSCRIPTION_ENABLED/MODEL/BASE_URL - Wire middleware into agent message loop via AgentDeps - WIT: replace data + duration-secs with extras-json + store-attachment-data - Host: parse extras-json for well-known keys, merge stored binary data - Telegram: download voice files via store-attachment-data, add duration to extras-json, add /file/bot to HTTP allowlist, voice-only placeholder - Add reqwest multipart feature for Whisper API uploads - 5 regression tests for transcription middleware Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat: wire attachment processing into LLM pipeline with multimodal image support Attachments on incoming messages are now augmented into user text via XML tags before entering the turn system, and images with data are passed as multimodal content parts (base64 data URIs) to LLM providers. This enables audio transcripts, document text, and image content to reach the LLM without changes to ChatMessage serialization or provider interfaces. - Add src/agent/attachments.rs with augment_with_attachments() and 9 unit tests - Add ContentPart/ImageUrl types to llm::provider with OpenAI-compatible serde - Carry image_content_parts transiently on Turn (skipped in serialization) - Update nearai_chat and rig_adapter to serialize multimodal content - Add 3 e2e tests verifying attachments flow through the full agent loop Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: CI failures — formatting, version bumps, and Telegram voice test - Fix cargo fmt formatting in attachments.rs, nearai_chat.rs, rig_adapter.rs, e2e_attachments.rs - Bump channel registry versions 0.1.0 → 0.2.0 (discord, slack, telegram, whatsapp) to satisfy version-bump CI check - Fix Telegram test_extract_attachments_voice: add missing required `duration` field to voice fixture JSON Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: bump WIT channel version to 0.3.0, fix Telegram voice test, add pre-commit hook - Bump wit/channel.wit package version 0.2.0 → 0.3.0 (interface changed with store-attachment-data) - Update WIT_CHANNEL_VERSION constant and registry wit_version fields to match - Fix Telegram test_extract_attachments_voice: gate voice download behind #[cfg(target_arch = "wasm32")] so host functions aren't called in native tests, update assertions for generated filename and extras_json duration - Add @0.3.0 linker stubs in wit_compat.rs - Add .githooks/pre-commit hook that runs scripts/check-version-bumps.sh when WIT or extension sources are staged - Symlink commit-msg regression hook into .githooks/ [skip-regression-check] Co-Authored-By: Claude Opus 4.6 <[email protected]> * refactor: extract voice download from extract_attachments into handle_message Move download_voice_file + store_attachment_data calls out of extract_attachments into a separate download_and_store_voice function called from handle_message. This keeps extract_attachments as a pure data-mapping function with no host calls, making it fully testable in native unit tests without #[cfg(target_arch)] gates. [skip-regression-check] Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: address PR review comments — security, correctness, and code quality Security fixes: - Add path validation to read_attachments (restrict to /tmp/) preventing arbitrary file reads from compromised tools - Escape XML special characters in attachment filenames, MIME types, and extracted text to prevent prompt injection via tag spoofing - Percent-encode file_id in Telegram getFile URL to prevent query injection - Clone SecretString directly instead of expose_secret().to_string() Correctness fixes: - Fix store_attachment_data overwrite accounting: subtract old entry size before adding new to prevent inflated totals and false rejections - Use max(reported, stored_size) for attachment size accounting to prevent WASM channels from under-reporting size_bytes to bypass limits - Add application/octet-stream to MIME allowlist (channels default unknown types to this) Code quality: - Extract send_response helper in Telegram, deduplicating on_respond and on_broadcast - Rename misleading Discord test to test_parse_slash_command_interaction - Fix .githooks/commit-msg to use relative symlink (portable across machines) [skip-regression-check] Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat: add tool_upgrade command + fix TOCTOU in save_to path validation Add `tool_upgrade` — a new extension management tool that automatically detects and reinstalls WASM extensions with outdated WIT versions. Preserves authentication secrets during upgrade. Supports upgrading a single extension by name or all installed WASM tools/channels at once. Fix TOCTOU in `validate_save_to_path`: validate the path *before* creating parent directories, so traversal paths like `/tmp/../../etc/` cannot cause filesystem mutations outside /tmp before being rejected. [skip-regression-check] Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: unify WIT package version to 0.3.0 across tool.wit and all capabilities tool.wit and channel.wit share the `near:agent` package namespace, so they must declare the same version. Bumps tool.wit from 0.2.0 to 0.3.0 and updates all capabilities files and registry entries to match. Fixes `cargo component build` failure: "package identifier near:[email protected] does not match previous package name of near:[email protected]" [skip-regression-check] Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: move WIT file comments after package declaration WIT treats `//` comments before `package` as doc comments. When both tool.wit and channel.wit had header comments, the parser rejected them as "doc comments on multiple 'package' items". Move comments after the package declaration in both files. Also bumps tool registry versions to 0.2.0 to match the WIT 0.3.0 bump. [skip-regression-check] Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat: display extension versions in gateway Extensions tab Add version field to InstalledExtension and RegistryEntry types, pipe through the web API (ExtensionInfo, RegistryEntryInfo), and render as a badge in the gateway UI for both installed and available extensions. For installed WASM extensions, version is read from the capabilities file with a fallback to the registry entry when the local file has no version (old installations). Bump all extension Cargo.toml and registry JSON versions from 0.1.0 to 0.2.0 to keep them in sync. [skip-regression-check] Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat: add document text extraction middleware for PDF, Office, and text files Extract text from document attachments (PDF, DOCX, PPTX, XLSX, RTF, plain text, code files) so the LLM can reason about uploaded documents. Uses pdf-extract for PDFs, zip+XML parsing for Office XML formats, and UTF-8 decode for text files. Wired into the agent loop after transcription middleware. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: download document files in Telegram channel for text extraction The DocumentExtractionMiddleware needs file bytes in the attachment `data` field, but only voice files were being downloaded. Document attachments (PDFs, DOCX, etc.) had empty `data` and a source_url with a credential placeholder that only works inside the WASM host's http_request. Add `download_and_store_documents()` that downloads non-voice, non-image, non-audio attachments via the existing two-step getFile→download flow and stores bytes via `store_attachment_data` for host-side extraction. Also rename `download_voice_file` → `download_telegram_file` since it's generic for any file_id. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: allow Office MIME types and increase file download limit for Telegram Two issues preventing document extraction from Telegram: 1. PPTX/DOCX/XLSX MIME types (application/vnd.*) were dropped by the WASM host attachment allowlist — add application/vnd., application/msword, and application/rtf prefixes. 2. Telegram file downloads over 10 MB failed with "Response body too large" — set max_response_bytes to 20 MB in Telegram capabilities. [skip-regression-check] Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: report document extraction errors back to user instead of silently skipping - Bump max_response_bytes to 50 MB for Telegram file downloads - When document extraction fails (too large, download error, parse error), set extracted_text to a user-friendly error message instead of leaving it None. This ensures the LLM tells the user what went wrong. - On Telegram download failure, set extracted_text with the error so the user sees feedback even when the file never reaches the extraction middleware. Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat: store extracted document text in workspace memory for search/recall After document extraction succeeds, write the extracted text to workspace memory at `documents/{date}/{filename}`. This enables: - Full-text and semantic search over past uploaded documents - Cross-conversation recall ("what did that PDF say?") - Automatic chunking and embedding via the workspace pipeline Documents are stored with metadata header (uploader, channel, date, MIME type). Error messages (extraction failures) are not stored — only successful extractions. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: CI failures — formatting, unused assignment warning - Run cargo fmt on document_extraction and agent_loop modules - Suppress unused_assignments warning on trace_llm_ref (used only behind #[cfg(feature = "libsql")]) [skip-regression-check] Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: address PR review comments — security, correctness, and code quality Security fixes: - Remove SSRF-prone download() from DocumentExtractionMiddleware (#13) - Sanitize filenames in workspace path to prevent directory traversal (#11) - Pre-check file size before reading in WASM wrapper to prevent OOM (#2) - Percent-encode file_id in Telegram source URLs (#7) Correctness fixes: - Clear image_content_parts on turn end to prevent memory leak (#1) - Find first *successful* transcription instead of first overall (#3) - Enforce data.len() size limit in document extraction (#10) - Use UTF-8 safe truncation with char_indices() (#12) Robustness & code quality: - Add 120s timeout to OpenAI Whisper HTTP client (#5) - Trim trailing slash from Whisper base_url (#6) - Allow ~/.ironclaw/ paths in WASM wrapper (#8) - Return error from on_broadcast in Slack/Discord/WhatsApp (#9) - Fix doc comment in HTTP tool (#4) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: formatting — cargo fmt Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: address latest PR review — doc comments, error messages, version bumps - Fix DocumentExtractionMiddleware doc comment (no longer downloads from source_url) - Fix error message: "no inline data" instead of "no download URL" - Log error + fallback instead of silent unwrap_or_default on Whisper HTTP client - Bump all capabilities.json versions from 0.1.0 to 0.2.0 to match Cargo.toml Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: remove unsupported profile: minimal from CI workflows [skip-regression-check] dtolnay/rust-toolchain@stable does not accept the 'profile' input (it was a parameter for the deprecated actions-rs/toolchain action). Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: merge with latest main — resolve compilation errors and PR review nits - Add version: None to RegistryEntry/InstalledExtension test constructors - Fix MessageContent type mismatches in nearai_chat tests (String → MessageContent::Text) - Fix .contains() calls on MessageContent — use .as_text().unwrap() - Remove redundant trace_llm_ref = None assignment in test_rig - Check data size before clone in document extraction to avoid unnecessary allocation [skip-regression-check] Co-Authored-By: Claude Opus 4.6 <[email protected]> --------- Co-authored-by: Claude Opus 4.6 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 4.6
parent
30790439ee
commit
d144484b06
@@ -106,6 +106,7 @@ impl OnlineDiscovery {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::Dcr,
|
||||
version: None,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
@@ -181,6 +182,7 @@ impl OnlineDiscovery {
|
||||
source: ExtensionSource::Discovered { url },
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::Dcr,
|
||||
version: None,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
|
||||
+348
-9
@@ -18,7 +18,8 @@ use crate::extensions::discovery::OnlineDiscovery;
|
||||
use crate::extensions::registry::ExtensionRegistry;
|
||||
use crate::extensions::{
|
||||
ActivateResult, AuthResult, ExtensionError, ExtensionKind, ExtensionSource, InstallResult,
|
||||
InstalledExtension, RegistryEntry, ResultSource, SearchResult, ToolAuthState,
|
||||
InstalledExtension, RegistryEntry, ResultSource, SearchResult, ToolAuthState, UpgradeOutcome,
|
||||
UpgradeResult,
|
||||
};
|
||||
use crate::hooks::HookRegistry;
|
||||
use crate::pairing::PairingStore;
|
||||
@@ -412,6 +413,7 @@ impl ExtensionManager {
|
||||
has_auth: false,
|
||||
installed: true,
|
||||
activation_error: None,
|
||||
version: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -427,15 +429,28 @@ impl ExtensionManager {
|
||||
{
|
||||
match discover_tools(&self.wasm_tools_dir).await {
|
||||
Ok(tools) => {
|
||||
for (name, _discovered) in tools {
|
||||
for (name, discovered) in tools {
|
||||
let active = self.tool_registry.has(&name).await;
|
||||
|
||||
let display_name = self
|
||||
let registry_entry = self
|
||||
.registry
|
||||
.get_with_kind(&name, Some(ExtensionKind::WasmTool))
|
||||
.await
|
||||
.map(|e| e.display_name);
|
||||
.await;
|
||||
let display_name = registry_entry.as_ref().map(|e| e.display_name.clone());
|
||||
let auth_state = self.check_tool_auth_status(&name).await;
|
||||
let version = if let Some(ref cap_path) = discovered.capabilities_path {
|
||||
tokio::fs::read(cap_path)
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|bytes| {
|
||||
crate::tools::wasm::CapabilitiesFile::from_bytes(&bytes).ok()
|
||||
})
|
||||
.and_then(|cap| cap.version)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let version =
|
||||
version.or_else(|| registry_entry.and_then(|e| e.version.clone()));
|
||||
extensions.push(InstalledExtension {
|
||||
name: name.clone(),
|
||||
kind: ExtensionKind::WasmTool,
|
||||
@@ -449,6 +464,7 @@ impl ExtensionManager {
|
||||
has_auth: auth_state != ToolAuthState::NoAuth,
|
||||
installed: true,
|
||||
activation_error: None,
|
||||
version,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -466,15 +482,31 @@ impl ExtensionManager {
|
||||
Ok(channels) => {
|
||||
let active_names = self.active_channel_names.read().await;
|
||||
let errors = self.activation_errors.read().await;
|
||||
for (name, _discovered) in channels {
|
||||
for (name, discovered) in channels {
|
||||
let active = active_names.contains(&name);
|
||||
let auth_state = self.check_channel_auth_status(&name).await;
|
||||
let activation_error = errors.get(&name).cloned();
|
||||
let display_name = self
|
||||
let registry_entry = self
|
||||
.registry
|
||||
.get_with_kind(&name, Some(ExtensionKind::WasmChannel))
|
||||
.await
|
||||
.map(|e| e.display_name);
|
||||
.await;
|
||||
let display_name = registry_entry.as_ref().map(|e| e.display_name.clone());
|
||||
let version = if let Some(ref cap_path) = discovered.capabilities_path {
|
||||
tokio::fs::read(cap_path)
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|bytes| {
|
||||
crate::channels::wasm::ChannelCapabilitiesFile::from_bytes(
|
||||
&bytes,
|
||||
)
|
||||
.ok()
|
||||
})
|
||||
.and_then(|cap| cap.version)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let version =
|
||||
version.or_else(|| registry_entry.and_then(|e| e.version.clone()));
|
||||
extensions.push(InstalledExtension {
|
||||
name,
|
||||
kind: ExtensionKind::WasmChannel,
|
||||
@@ -488,6 +520,7 @@ impl ExtensionManager {
|
||||
has_auth: false,
|
||||
installed: true,
|
||||
activation_error,
|
||||
version,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -526,6 +559,7 @@ impl ExtensionManager {
|
||||
has_auth: false,
|
||||
installed: false,
|
||||
activation_error: None,
|
||||
version: entry.version,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -637,6 +671,207 @@ impl ExtensionManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Upgrade installed WASM extensions to match the current host WIT version.
|
||||
///
|
||||
/// If `name` is `Some`, upgrades only that extension. If `None`, checks all
|
||||
/// installed WASM tools and channels and upgrades any that are outdated.
|
||||
///
|
||||
/// The upgrade preserves authentication secrets — only the `.wasm` binary
|
||||
/// (and `.capabilities.json`) are replaced.
|
||||
pub async fn upgrade(&self, name: Option<&str>) -> Result<UpgradeResult, ExtensionError> {
|
||||
// Collect extensions to check
|
||||
let mut candidates: Vec<(String, ExtensionKind)> = Vec::new();
|
||||
|
||||
if let Some(name) = name {
|
||||
Self::validate_extension_name(name)?;
|
||||
let kind = self.determine_installed_kind(name).await?;
|
||||
if kind == ExtensionKind::McpServer {
|
||||
return Err(ExtensionError::Other(
|
||||
"MCP servers don't have WIT versions and cannot be upgraded this way"
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
candidates.push((name.to_string(), kind));
|
||||
} else {
|
||||
// Discover all installed WASM tools
|
||||
if self.wasm_tools_dir.exists()
|
||||
&& let Ok(tools) = discover_tools(&self.wasm_tools_dir).await
|
||||
{
|
||||
for (tool_name, _) in tools {
|
||||
candidates.push((tool_name, ExtensionKind::WasmTool));
|
||||
}
|
||||
}
|
||||
// Discover all installed WASM channels
|
||||
if self.wasm_channels_dir.exists()
|
||||
&& let Ok(channels) =
|
||||
crate::channels::wasm::discover_channels(&self.wasm_channels_dir).await
|
||||
{
|
||||
for (ch_name, _) in channels {
|
||||
candidates.push((ch_name, ExtensionKind::WasmChannel));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if candidates.is_empty() {
|
||||
return Ok(UpgradeResult {
|
||||
results: Vec::new(),
|
||||
message: "No WASM extensions installed.".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
let mut outcomes = Vec::new();
|
||||
|
||||
for (ext_name, kind) in &candidates {
|
||||
let outcome = self.upgrade_one(ext_name, *kind).await;
|
||||
outcomes.push(outcome);
|
||||
}
|
||||
|
||||
let upgraded = outcomes.iter().filter(|o| o.status == "upgraded").count();
|
||||
let up_to_date = outcomes
|
||||
.iter()
|
||||
.filter(|o| o.status == "already_up_to_date")
|
||||
.count();
|
||||
let failed = outcomes.iter().filter(|o| o.status == "failed").count();
|
||||
|
||||
let message = format!(
|
||||
"{} extension(s) checked: {} upgraded, {} already up to date, {} failed",
|
||||
outcomes.len(),
|
||||
upgraded,
|
||||
up_to_date,
|
||||
failed
|
||||
);
|
||||
|
||||
Ok(UpgradeResult {
|
||||
results: outcomes,
|
||||
message,
|
||||
})
|
||||
}
|
||||
|
||||
/// Upgrade a single WASM extension if its WIT version is outdated.
|
||||
async fn upgrade_one(&self, name: &str, kind: ExtensionKind) -> UpgradeOutcome {
|
||||
let (cap_dir, host_wit) = match kind {
|
||||
ExtensionKind::WasmTool => (&self.wasm_tools_dir, crate::tools::wasm::WIT_TOOL_VERSION),
|
||||
ExtensionKind::WasmChannel => (
|
||||
&self.wasm_channels_dir,
|
||||
crate::tools::wasm::WIT_CHANNEL_VERSION,
|
||||
),
|
||||
ExtensionKind::McpServer => {
|
||||
return UpgradeOutcome {
|
||||
name: name.to_string(),
|
||||
kind,
|
||||
status: "failed".to_string(),
|
||||
detail: "MCP servers cannot be upgraded this way".to_string(),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
// Read current WIT version from capabilities
|
||||
let cap_path = cap_dir.join(format!("{}.capabilities.json", name));
|
||||
let declared_wit = if cap_path.exists() {
|
||||
match tokio::fs::read(&cap_path).await {
|
||||
Ok(bytes) => {
|
||||
let wit: Option<String> = match kind {
|
||||
ExtensionKind::WasmTool => {
|
||||
crate::tools::wasm::CapabilitiesFile::from_bytes(&bytes)
|
||||
.ok()
|
||||
.and_then(|c| c.wit_version)
|
||||
}
|
||||
ExtensionKind::WasmChannel => {
|
||||
crate::channels::wasm::ChannelCapabilitiesFile::from_bytes(&bytes)
|
||||
.ok()
|
||||
.and_then(|c| c.wit_version)
|
||||
}
|
||||
ExtensionKind::McpServer => None,
|
||||
};
|
||||
wit
|
||||
}
|
||||
Err(_) => None,
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// Check if upgrade is needed
|
||||
let needs_upgrade =
|
||||
crate::tools::wasm::check_wit_version_compat(name, declared_wit.as_deref(), host_wit)
|
||||
.is_err();
|
||||
|
||||
if !needs_upgrade {
|
||||
return UpgradeOutcome {
|
||||
name: name.to_string(),
|
||||
kind,
|
||||
status: "already_up_to_date".to_string(),
|
||||
detail: format!(
|
||||
"WIT {} matches host WIT {}",
|
||||
declared_wit.as_deref().unwrap_or("unknown"),
|
||||
host_wit
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
// Check registry for a newer version
|
||||
let entry = self.registry.get_with_kind(name, Some(kind)).await;
|
||||
let Some(entry) = entry else {
|
||||
return UpgradeOutcome {
|
||||
name: name.to_string(),
|
||||
kind,
|
||||
status: "not_in_registry".to_string(),
|
||||
detail: format!(
|
||||
"Extension '{}' has outdated WIT {} (host: {}), \
|
||||
but is not in the registry. Reinstall manually with a URL.",
|
||||
name,
|
||||
declared_wit.as_deref().unwrap_or("unknown"),
|
||||
host_wit
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
// Delete old .wasm file (keep secrets intact)
|
||||
let wasm_path = cap_dir.join(format!("{}.wasm", name));
|
||||
if wasm_path.exists()
|
||||
&& let Err(e) = tokio::fs::remove_file(&wasm_path).await
|
||||
{
|
||||
return UpgradeOutcome {
|
||||
name: name.to_string(),
|
||||
kind,
|
||||
status: "failed".to_string(),
|
||||
detail: format!("Failed to remove old WASM binary: {}", e),
|
||||
};
|
||||
}
|
||||
// Also remove old capabilities so install_from_entry can write the new one
|
||||
if cap_path.exists() {
|
||||
let _ = tokio::fs::remove_file(&cap_path).await;
|
||||
}
|
||||
|
||||
// Reinstall from registry
|
||||
match self.install_from_entry(&entry).await {
|
||||
Ok(_) => {
|
||||
tracing::info!(
|
||||
extension = %name,
|
||||
old_wit = ?declared_wit,
|
||||
new_host_wit = %host_wit,
|
||||
"Upgraded WASM extension"
|
||||
);
|
||||
UpgradeOutcome {
|
||||
name: name.to_string(),
|
||||
kind,
|
||||
status: "upgraded".to_string(),
|
||||
detail: format!(
|
||||
"Upgraded from WIT {} to host WIT {}. Restart to activate.",
|
||||
declared_wit.as_deref().unwrap_or("unknown"),
|
||||
host_wit
|
||||
),
|
||||
}
|
||||
}
|
||||
Err(e) => UpgradeOutcome {
|
||||
name: name.to_string(),
|
||||
kind,
|
||||
status: "failed".to_string(),
|
||||
detail: format!("Reinstall failed: {}. Old files were removed.", e),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Get detailed info about an installed extension (version, wit_version, host compatibility).
|
||||
pub async fn extension_info(&self, name: &str) -> Result<serde_json::Value, ExtensionError> {
|
||||
Self::validate_extension_name(name)?;
|
||||
@@ -3336,6 +3571,7 @@ fn combine_install_errors(
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::extensions::ExtensionManager;
|
||||
use crate::extensions::manager::{
|
||||
FallbackDecision, combine_install_errors, fallback_decision, infer_kind_from_url,
|
||||
};
|
||||
@@ -3621,4 +3857,107 @@ mod tests {
|
||||
assert_eq!(std::fs::read_to_string(&tool_cap).unwrap(), tool_caps);
|
||||
assert_eq!(std::fs::read_to_string(&channel_cap).unwrap(), channel_caps);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_upgrade_no_installed_extensions() {
|
||||
let manager = make_manager_with_temp_dirs();
|
||||
let result = manager.upgrade(None).await.unwrap();
|
||||
assert!(result.results.is_empty());
|
||||
assert!(result.message.contains("No WASM extensions installed"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_upgrade_mcp_server_rejected() {
|
||||
let manager = make_manager_with_temp_dirs();
|
||||
// MCP servers can't be upgraded via tool_upgrade
|
||||
let err = manager.upgrade(Some("some-mcp")).await;
|
||||
// It will fail with NotInstalled because there's no MCP server named "some-mcp",
|
||||
// but if it were installed, the MCP code path would be rejected.
|
||||
assert!(err.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_upgrade_up_to_date_extension() {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
let channels_dir = dir.path().join("channels");
|
||||
std::fs::create_dir_all(&channels_dir).unwrap();
|
||||
|
||||
// Write a fake .wasm file and capabilities with current WIT version
|
||||
let wasm_path = channels_dir.join("test-channel.wasm");
|
||||
std::fs::write(&wasm_path, b"\0asm fake").unwrap();
|
||||
|
||||
let cap_path = channels_dir.join("test-channel.capabilities.json");
|
||||
let caps = serde_json::json!({
|
||||
"type": "channel",
|
||||
"name": "test-channel",
|
||||
"wit_version": crate::tools::wasm::WIT_CHANNEL_VERSION,
|
||||
});
|
||||
std::fs::write(&cap_path, serde_json::to_string(&caps).unwrap()).unwrap();
|
||||
|
||||
let manager = make_manager_custom_dirs(dir.path().join("tools"), channels_dir);
|
||||
|
||||
let result = manager.upgrade(Some("test-channel")).await.unwrap();
|
||||
assert_eq!(result.results.len(), 1);
|
||||
assert_eq!(result.results[0].status, "already_up_to_date");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_upgrade_outdated_not_in_registry() {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
let channels_dir = dir.path().join("channels");
|
||||
std::fs::create_dir_all(&channels_dir).unwrap();
|
||||
|
||||
// Write a fake .wasm file and capabilities with OLD WIT version
|
||||
let wasm_path = channels_dir.join("custom-channel.wasm");
|
||||
std::fs::write(&wasm_path, b"\0asm fake").unwrap();
|
||||
|
||||
let cap_path = channels_dir.join("custom-channel.capabilities.json");
|
||||
let caps = serde_json::json!({
|
||||
"type": "channel",
|
||||
"name": "custom-channel",
|
||||
"wit_version": "0.1.0",
|
||||
});
|
||||
std::fs::write(&cap_path, serde_json::to_string(&caps).unwrap()).unwrap();
|
||||
|
||||
let manager = make_manager_custom_dirs(dir.path().join("tools"), channels_dir);
|
||||
|
||||
let result = manager.upgrade(Some("custom-channel")).await.unwrap();
|
||||
assert_eq!(result.results.len(), 1);
|
||||
assert_eq!(result.results[0].status, "not_in_registry");
|
||||
}
|
||||
|
||||
fn make_manager_with_temp_dirs() -> ExtensionManager {
|
||||
let dir = tempfile::tempdir().expect("temp dir");
|
||||
make_manager_custom_dirs(dir.path().join("tools"), dir.path().join("channels"))
|
||||
}
|
||||
|
||||
fn make_manager_custom_dirs(
|
||||
tools_dir: std::path::PathBuf,
|
||||
channels_dir: std::path::PathBuf,
|
||||
) -> ExtensionManager {
|
||||
use crate::secrets::{InMemorySecretsStore, SecretsCrypto};
|
||||
use crate::tools::ToolRegistry;
|
||||
use crate::tools::mcp::session::McpSessionManager;
|
||||
|
||||
std::fs::create_dir_all(&tools_dir).ok();
|
||||
std::fs::create_dir_all(&channels_dir).ok();
|
||||
|
||||
let master_key =
|
||||
secrecy::SecretString::from("0123456789abcdef0123456789abcdef".to_string());
|
||||
let crypto = Arc::new(SecretsCrypto::new(master_key).unwrap());
|
||||
|
||||
ExtensionManager::new(
|
||||
Arc::new(McpSessionManager::new()),
|
||||
Arc::new(InMemorySecretsStore::new(crypto)),
|
||||
Arc::new(ToolRegistry::new()),
|
||||
None,
|
||||
None,
|
||||
tools_dir,
|
||||
channels_dir,
|
||||
None,
|
||||
"test".to_string(),
|
||||
None,
|
||||
Vec::new(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,6 +70,9 @@ pub struct RegistryEntry {
|
||||
pub fallback_source: Option<Box<ExtensionSource>>,
|
||||
/// How authentication works.
|
||||
pub auth_hint: AuthHint,
|
||||
/// Extension version (semver), if known.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub version: Option<String>,
|
||||
}
|
||||
|
||||
/// Where the extension binary or server lives.
|
||||
@@ -146,6 +149,26 @@ pub struct InstallResult {
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// Result of upgrading one or more extensions.
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct UpgradeResult {
|
||||
/// Per-extension upgrade outcomes.
|
||||
pub results: Vec<UpgradeOutcome>,
|
||||
/// Summary message.
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// Outcome for a single extension upgrade.
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct UpgradeOutcome {
|
||||
pub name: String,
|
||||
pub kind: ExtensionKind,
|
||||
/// What happened: "upgraded", "already_up_to_date", "failed", "not_in_registry".
|
||||
pub status: String,
|
||||
/// Human-readable detail.
|
||||
pub detail: String,
|
||||
}
|
||||
|
||||
/// Auth readiness state for the extensions list UI.
|
||||
///
|
||||
/// Used by `check_tool_auth_status` and `check_channel_auth_status` to
|
||||
@@ -453,6 +476,9 @@ pub struct InstalledExtension {
|
||||
/// Last activation error for WASM channels.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub activation_error: Option<String>,
|
||||
/// Extension version from capabilities file (semver).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub version: Option<String>,
|
||||
}
|
||||
|
||||
/// Error type for extension operations.
|
||||
@@ -769,6 +795,7 @@ mod tests {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::Dcr,
|
||||
version: None,
|
||||
};
|
||||
let sr = SearchResult {
|
||||
entry,
|
||||
@@ -798,6 +825,7 @@ mod tests {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::None,
|
||||
version: None,
|
||||
};
|
||||
let sr = SearchResult {
|
||||
entry,
|
||||
@@ -885,6 +913,7 @@ mod tests {
|
||||
has_auth: true,
|
||||
installed: false,
|
||||
activation_error: Some("token expired".to_string()),
|
||||
version: None,
|
||||
};
|
||||
let json = serde_json::to_value(&ext).unwrap();
|
||||
assert_eq!(json["display_name"], "Gmail Tool");
|
||||
|
||||
@@ -245,6 +245,7 @@ fn builtin_entries() -> Vec<RegistryEntry> {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::Dcr,
|
||||
version: None,
|
||||
},
|
||||
RegistryEntry {
|
||||
name: "linear".to_string(),
|
||||
@@ -265,6 +266,7 @@ fn builtin_entries() -> Vec<RegistryEntry> {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::Dcr,
|
||||
version: None,
|
||||
},
|
||||
RegistryEntry {
|
||||
name: "github".to_string(),
|
||||
@@ -285,6 +287,7 @@ fn builtin_entries() -> Vec<RegistryEntry> {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::Dcr,
|
||||
version: None,
|
||||
},
|
||||
RegistryEntry {
|
||||
name: "slack-mcp".to_string(),
|
||||
@@ -305,6 +308,7 @@ fn builtin_entries() -> Vec<RegistryEntry> {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::Dcr,
|
||||
version: None,
|
||||
},
|
||||
RegistryEntry {
|
||||
name: "sentry".to_string(),
|
||||
@@ -325,6 +329,7 @@ fn builtin_entries() -> Vec<RegistryEntry> {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::Dcr,
|
||||
version: None,
|
||||
},
|
||||
RegistryEntry {
|
||||
name: "stripe".to_string(),
|
||||
@@ -345,6 +350,7 @@ fn builtin_entries() -> Vec<RegistryEntry> {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::Dcr,
|
||||
version: None,
|
||||
},
|
||||
RegistryEntry {
|
||||
name: "cloudflare".to_string(),
|
||||
@@ -365,6 +371,7 @@ fn builtin_entries() -> Vec<RegistryEntry> {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::Dcr,
|
||||
version: None,
|
||||
},
|
||||
RegistryEntry {
|
||||
name: "asana".to_string(),
|
||||
@@ -383,6 +390,7 @@ fn builtin_entries() -> Vec<RegistryEntry> {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::Dcr,
|
||||
version: None,
|
||||
},
|
||||
RegistryEntry {
|
||||
name: "intercom".to_string(),
|
||||
@@ -402,6 +410,7 @@ fn builtin_entries() -> Vec<RegistryEntry> {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::Dcr,
|
||||
version: None,
|
||||
},
|
||||
// WASM channels (telegram, slack, discord, whatsapp) come from the embedded
|
||||
// registry catalog (registry/channels/*.json) with WasmDownload URLs pointing
|
||||
@@ -427,6 +436,7 @@ mod tests {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::Dcr,
|
||||
version: None,
|
||||
};
|
||||
|
||||
let score = score_entry(&entry, &["notion".to_string()]);
|
||||
@@ -450,6 +460,7 @@ mod tests {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::Dcr,
|
||||
version: None,
|
||||
};
|
||||
|
||||
let score = score_entry(&entry, &["calendar".to_string()]);
|
||||
@@ -473,6 +484,7 @@ mod tests {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::Dcr,
|
||||
version: None,
|
||||
};
|
||||
|
||||
let score = score_entry(&entry, &["wiki".to_string()]);
|
||||
@@ -496,6 +508,7 @@ mod tests {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::Dcr,
|
||||
version: None,
|
||||
};
|
||||
|
||||
let score = score_entry(&entry, &["xyzfoobar".to_string()]);
|
||||
@@ -560,6 +573,7 @@ mod tests {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::Dcr,
|
||||
version: None,
|
||||
};
|
||||
|
||||
registry.cache_discovered(vec![discovered]).await;
|
||||
@@ -586,6 +600,7 @@ mod tests {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::None,
|
||||
version: None,
|
||||
};
|
||||
|
||||
registry.cache_discovered(vec![entry.clone()]).await;
|
||||
@@ -611,6 +626,7 @@ mod tests {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::CapabilitiesAuth,
|
||||
version: None,
|
||||
},
|
||||
// This shares a name with the builtin slack-mcp but has a different kind, so both should appear
|
||||
RegistryEntry {
|
||||
@@ -626,6 +642,7 @@ mod tests {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::CapabilitiesAuth,
|
||||
version: None,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -662,6 +679,7 @@ mod tests {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::Dcr,
|
||||
version: None,
|
||||
}];
|
||||
|
||||
let registry = ExtensionRegistry::new_with_catalog(catalog_entries);
|
||||
@@ -689,6 +707,7 @@ mod tests {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::CapabilitiesAuth,
|
||||
version: None,
|
||||
},
|
||||
RegistryEntry {
|
||||
name: "telegram".to_string(),
|
||||
@@ -703,6 +722,7 @@ mod tests {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::CapabilitiesAuth,
|
||||
version: None,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -765,6 +785,7 @@ mod tests {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::None,
|
||||
version: None,
|
||||
};
|
||||
let channel_entry = RegistryEntry {
|
||||
name: "cached-ext".to_string(),
|
||||
@@ -779,6 +800,7 @@ mod tests {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::None,
|
||||
version: None,
|
||||
};
|
||||
|
||||
registry
|
||||
@@ -822,6 +844,7 @@ mod tests {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::CapabilitiesAuth,
|
||||
version: None,
|
||||
},
|
||||
RegistryEntry {
|
||||
name: "telegram".to_string(),
|
||||
@@ -836,6 +859,7 @@ mod tests {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::CapabilitiesAuth,
|
||||
version: None,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -884,6 +908,7 @@ mod tests {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::None,
|
||||
version: None,
|
||||
},
|
||||
RegistryEntry {
|
||||
name: "myext".to_string(),
|
||||
@@ -898,6 +923,7 @@ mod tests {
|
||||
},
|
||||
fallback_source: None,
|
||||
auth_hint: AuthHint::None,
|
||||
version: None,
|
||||
},
|
||||
];
|
||||
|
||||
|
||||
Reference in New Issue
Block a user