🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
feat(ruvocal): integrate WASM-MCP layer from RuVector upstream (ADR-033) (#1687)
rUv6e68c93ac6ae
diff --git a/README.md b/README.mdindex 72bfdf80ec..a89f87f24d 100644--- a/README.md+++ b/README.md@@ -1,6 +1,8 @@<div align="center">-+[](https://flo.ruv.io/)++[](https://flo.ruv.io/)[](https://github.com/ruvnet/claude-flow)[](https://opensource.org/licenses/MIT)diff --git a/ruflo/docs/adr/ADR-033-RUVOCAL-WASM-MCP-INTEGRATION.md b/ruflo/docs/adr/ADR-033-RUVOCAL-WASM-MCP-INTEGRATION.mdnew file mode 100644index 0000000000..3236a0625e--- /dev/null+++ b/ruflo/docs/adr/ADR-033-RUVOCAL-WASM-MCP-INTEGRATION.md@@ -0,0 +1,163 @@+# ADR-033: Ruvocal WASM-MCP Integration from RuVector Upstream++**Status:** Proposed+**Date:** 2026-05-01+**Author:** Ruflo Team+**Deciders:** Engineering+**Related:** ADR-002-WASM-CORE-PACKAGE, ADR-029-HUGGINGFACE-CHAT-UI-CLOUD-RUN, ADR-030-MCP-TOOL-GAP-ANALYSIS, ADR-032-RVF-PRIVATE-MCP-TUNNEL++---++## Context++The local copy of the Ruvocal chat UI at `ruflo/src/ruvocal/` is a snapshot fork of the SvelteKit-based HuggingFace `chat-ui` (v0.20.0). The canonical upstream lives at `ruvnet/RuVector/ui/ruvocal` and has diverged with substantial new functionality, primarily an in-browser **WASM MCP server** powered by `rvagent-wasm`.++A directory-level diff between upstream and local shows:++**Net-new in upstream (absent locally):**+- `src/lib/wasm/` — WASM loader, types, IndexedDB persistence, capability tests (84 KB)+- `src/lib/components/wasm/GalleryPanel.svelte` — UI for browsing/loading WASM templates+- `src/lib/components/FoundationBackground.svelte`+- `src/lib/stores/wasmMcp.ts` — Svelte store wrapping WASM MCP server lifecycle+- `src/lib/constants/rvagentPresets.ts` — preset templates+- `src/lib/server/textGeneration/mcp/wasmTools.test.ts`+- `static/wasm/rvagent_wasm.js` + `rvagent_wasm_bg.wasm` — compiled WASM bundle (~588 KB)+- `config/branding.env.example`++**Modified upstream (incompatible drift in local):**+- Chat components: `ChatInput`, `ChatMessage`, `ChatWindow`, `ChatIntroduction`, `BlockWrapper`, `TaskGroup`, `ToolUpdate`, `FileDropzone`+- MCP UI: `MCPServerManager`, `AddServerForm`, `ServerCard`+- Servers: `lib/server/mcp/clientPool.ts`, `httpClient.ts`, `lib/server/router/toolsRoute.ts`, `lib/server/textGeneration/index.ts`, `runMcpFlow.ts`, `toolInvocation.ts`, `types.ts`, `utils/toolPrompt.ts`+- Stores/utils: `mcpServers.ts`, `settings.ts`, `Settings.ts`, `Tool.ts`, `messageUpdates.ts`, `switchTheme.ts`+- Routes: `+layout.svelte`, `models/+page.svelte`, settings layout/model pages, `conversation/[id]/+page.svelte` & `+server.ts`, `api/mcp/health/+server.ts`, `api/mcp/servers/+server.ts`, `api/v2/user/settings/+server.ts`+- Visual/branding: `app.html`, `styles/main.css`, `static/chatui/{favicon,icon,logo}.svg`, `static/chatui/manifest.json`+- Misc: `Modal.svelte`, `NavMenu.svelte`, `RuFloUniverse.svelte`, `Switch.svelte`, `WelcomeModal.svelte`, `Logo.svelte`, `mcpExamples.ts`, `.gitignore`, `rvf.manifest.json`++**Local-only (must preserve):**+- `mcp-bridge/index.js` — local MCP bridge implementation (absent in upstream)+- `src/routes/api/v2/debug/` — debug routes used by ruflo+- `stub/@reflink/reflink/index.js` — reflink stub+- `.env` — populated local environment+- `package-lock.json` — local lockfile+- All ruflo-specific docs/CLAUDE.md guidance++`package.json` is identical between local and upstream — no dependency changes required.++## Decision++We will pull the upstream improvements into `ruflo/src/ruvocal/` on a dedicated feature branch (`feat/ruvocal-wasm-mcp-integration`) using a **directory-level overlay strategy** rather than a Git merge, because the local snapshot has no shared history with the upstream repository.++The integration is staged in three commits to keep the diff reviewable:++1. **NEW files** — copy WASM core, components, stores, constants, static assets, and config example. Pure additions; cannot break existing behavior.+2. **MODIFIED files** — overwrite divergent files with upstream versions, then re-apply local-only customizations:+ - Restore `src/routes/api/v2/debug/` after upstream overlay (upstream lacks it).+ - Restore `mcp-bridge/index.js` after overlay.+ - Restore `stub/@reflink/reflink/index.js`.+ - Keep local `.env` and `package-lock.json` untouched.+3. **Verification** — `npm install`, `npm run check`, `npm run build`, then local docker compose + `ruflo-browser` smoke test.++The `package.json` overlay is safe because it is byte-identical.++### What we are explicitly NOT doing++- No Git submodule or subtree linkage to RuVector — keeps the snapshot model intact.+- No changes to `ruflo/src/chat-ui/` (the thin HF base-image wrapper) in this ADR.+- No Cloud Run deployment in this change — that is tracked separately under ADR-011 / ADR-029.+- No upstream contribution back to RuVector at this time.++## Consequences++**Positive:**+- Brings in-browser WASM MCP capability — chat UI gains local tool execution without a backend bridge for the supported tool set.+- Aligns local with canonical upstream, narrowing the divergence we have to maintain by hand.+- New `GalleryPanel` UX for browsing rvagent templates.+- Tests added (`wasmTools.test.ts`, `wasm-capabilities.test.ts`) raise the coverage floor.++**Negative / risks:**+- Increases bundle size by ~588 KB (the WASM artifact). Loaded lazily via `browser`-gated dynamic import, so initial paint is unaffected.+- Local-only files (`mcp-bridge/index.js`, `routes/api/v2/debug/`) must be re-applied after each upstream sync; this ADR documents that requirement so future syncs don't drop them.+- Modified server-side files (`clientPool`, `httpClient`, `toolsRoute`, `runMcpFlow`, etc.) may interact with the local mcp-bridge differently than upstream's. Smoke test before merge.+- Changes to `Settings.ts` / `Tool.ts` types could ripple into ruflo packages that import from `src/ruvocal`. Mitigation: run `npm run check` before merging.++**Rollback:** revert the feature branch; no data migrations, no external service changes.++## Verification++Acceptance criteria for merging the branch:++- [ ] `npm install` succeeds.+- [ ] `npm run check` passes (svelte-check, no new TS errors).+- [ ] `npm run build` produces a working bundle.+- [ ] `npm run test` — `wasmTools.test.ts` and `wasm-capabilities.test.ts` pass.+- [ ] `docker compose up -d` brings up MongoDB; `npm run dev` serves at `http://localhost:5173`.+- [ ] `ruflo-browser` smoke test: load the home page, open the gallery panel, send a message through a non-WASM model, confirm no console errors.+- [ ] Local-only files still present after overlay: `mcp-bridge/index.js`, `routes/api/v2/debug/`, `stub/@reflink/reflink/index.js`, `.env`, `package-lock.json`.++## Deployment++Cloud Run deployment is **out of scope for this PR** but the path is staged in `ruflo/src/ruvocal/cloudbuild.yaml`. Two infrastructure prerequisites must be satisfied before the first deploy:++1. **MongoDB endpoint** — HF chat-ui requires a Mongo server. Cloud Run cannot run Mongo natively. Two options:+ - **MongoDB Atlas free tier** (M0): create a cluster, get the connection string, store as Secret Manager secret `ruvocal-mongodb-url`.+ - **Cloud Run multi-container** (sidecar): deploy a `mongo:8` sidecar in the same revision; main container connects to `localhost:27017`. Requires `--container` flags on `gcloud run deploy`.+2. **AI provider secrets** — already exist in `ruv-dev` Secret Manager per ADR-029: `openai-api-key`, `google-api-key`, `openrouter-api-key`.++Once both are in place:++```bash+cd ruflo/src/ruvocal+gcloud builds submit --config=cloudbuild.yaml --project=ruv-dev --region=us-central1+```++Validation after deploy: `npx agent-browser open <run-url>` then check console for `[WASM MCP] Server initialized successfully · 18 tools`.++The thin `ruflo/src/chat-ui/Dockerfile` wrapper (FROM `ghcr.io/huggingface/chat-ui-db:latest`) is **unsuitable** for deploying this integration — it can only patch the upstream HF base image with a few static files; it cannot include compiled WASM source. The full ruvocal Dockerfile build is required.++## Deployment Outcome (2026-05-01)++The Cloud Run pipeline is working end-to-end with the following validations:++| Stage | Result |+|-------|--------|+| Cloud Build (after `DOCKER_BUILDKIT=1` fix) | Succeeds: `gcr.io/ruv-dev/ruvocal:v1` pushed |+| Cloud Run deploy (after granting `secretmanager.secretAccessor` to default SA on `ANTHROPIC_API_KEY`, `GOOGLE_AI_API_KEY`, `OPENROUTER_API_KEY`) | Service `ruvocal` revision `00007-4hd` serving 100% traffic |+| Embedded MongoDB (`INCLUDE_DB=true`) | Working: `mongod` starts via `entrypoint.sh`, `/api/v2/conversations`, `/api/v2/user`, `/api/v2/feature-flags`, `/api/v2/public-config`, `/api/v2/user/settings` all return 200 |+| WASM bundle | Reachable: `https://ruvocal-875130704813.us-central1.run.app/wasm/rvagent_wasm.js` (200, `text/javascript`), `/wasm/rvagent_wasm_bg.wasm` (200, `application/wasm`, 543 KB) |+| Provider API keys via Secret Manager | Mounted at runtime as `ANTHROPIC_API_KEY`, `GOOGLE_API_KEY`, `OPENROUTER_API_KEY`, `OPENAI_API_KEY` |+| `dotenv-cli` runtime overrides via `DOTENV_LOCAL` env var | Working — confirmed by `PUBLIC_ORIGIN` and `OPENAI_BASE_URL` taking effect at runtime |++### Custom Domain (2026-05-01)++- `ruvocal.ruv.io` mapped via `gcloud beta run domain-mappings create`+- Cloudflare DNS: `CNAME ruvocal → ghs.googlehosted.com.`, **proxied:false** (gray cloud) so Google can issue and renew the managed cert directly+- Cert provisioning is asynchronous; allow 15–30 min after DNS resolves before HTTPS works on the custom domain. The `*.run.app` URL is always available immediately++### Provider Configuration (2026-05-01)++The deployed instance uses **Gemini 2.5 Flash** as default via Google's OpenAI-compatible endpoint:++```+OPENAI_BASE_URL=https://generativelanguage.googleapis.com/v1beta/openai/+OPENAI_API_KEY=<from GOOGLE_AI_API_KEY secret>+TASK_MODEL=gemini-2.5-flash+```++Earlier attempts with `https://router.huggingface.co/v1` returned `401 "Invalid username or password"` because the available `huggingface-token` secret doesn't auth against the user-facing router endpoint, and the OpenRouter API key was incorrectly mapped against the HF base URL. Google's OpenAI-compatible endpoint accepts `GOOGLE_AI_API_KEY` directly and exposes 56 Gemini variants.++### Known Issue (Out of Scope)++The homepage `/` returns HTTP 500 in production due to the `/api/v2/models` and `/api/v2/models/refresh` routes returning the SvelteKit "Page not found" page wrapped in a 500 status. Other `/api/v2/*` routes work normally. This is reproducible across multiple Cloud Run revisions and across both HuggingFace router and OpenRouter as the upstream provider — but does **not** reproduce locally with `npm run dev` using the same `.env`.++The error stack consistently points at `handleResponse (file:///app/build/server/chunks/APIClient-bd1S52Pj.js:421:11)` from the `+layout.ts` server-side `Promise.all` (index 1 = `client.models.get()`). The `models.ts` server module does refresh successfully (logs show `[models] Parsed models count: 129`, `[models] Model cache refreshed`) — the issue is between cache build and route response, specific to the production `adapter-node` build.++This is unrelated to the WASM-MCP integration that this ADR covers; the WASM client code is shipped and serves correctly. The 500 is an HF chat-ui / SvelteKit production-build edge case worth a separate investigation (likely candidates: `superjson.stringify` over `getEndpoint` closures, a circular import in `chunks/models.js`, or route matcher caching for the `/api/v2/models` subtree).++## References++- Upstream source: `https://github.com/ruvnet/ruvector` → `ui/ruvocal/`+- Local target: `ruflo/src/ruvocal/`+- Branch: `feat/ruvocal-wasm-mcp-integration`+- PR: https://github.com/ruvnet/ruflo/pull/1687+- Cloud Build config: `ruflo/src/ruvocal/cloudbuild.yaml`+- Related deployment ADR: ADR-029 (HF Chat UI on Cloud Run)diff --git a/ruflo/src/ruvocal/.dockerignore b/ruflo/src/ruvocal/.dockerignoreindex 87af36b131..a63d3310ab 100644--- a/ruflo/src/ruvocal/.dockerignore+++ b/ruflo/src/ruvocal/.dockerignore@@ -10,4 +10,8 @@ node_modules/!.env.env.localdb-models/**\ No newline at end of file+# NOTE: previously had `models/**` here to ignore a top-level placeholder+# directory. Even when anchored (`/models/**`), Docker's pattern matcher+# was eliding nested src/routes/api/v2/models/ and src/routes/models/+# from the build context, producing prod images missing those routes.+# The placeholder dir is small (single .txt) — letting it through is fine.\ No newline at end of filediff --git a/ruflo/src/ruvocal/.gcloudignore b/ruflo/src/ruvocal/.gcloudignorenew file mode 100644index 0000000000..ea0962d5b6--- /dev/null+++ b/ruflo/src/ruvocal/.gcloudignore@@ -0,0 +1,18 @@+# gcloud builds submit upload filter.+# Without this file, gcloud falls back to .gitignore, which has+# `models/*` (line 16) — that excludes src/routes/api/v2/models/*+# and src/routes/models/* from the build context, producing+# production images missing those SvelteKit routes (root cause+# of /api/v2/models 404 → /favicon 500 → / 500 in Cloud Run).++.git/+.gitignore+.dockerignore+.gcloudignore+node_modules/+.svelte-kit/+build/+.env.local+.vscode/+.idea/+*.logdiff --git a/ruflo/src/ruvocal/cloudbuild.yaml b/ruflo/src/ruvocal/cloudbuild.yamlnew file mode 100644index 0000000000..9cc756cf22--- /dev/null+++ b/ruflo/src/ruvocal/cloudbuild.yaml@@ -0,0 +1,68 @@+steps:+ # Build the WASM-integrated ruvocal image with embedded MongoDB.+ # INCLUDE_DB=true triggers the multi-stage Dockerfile path that copies+ # mongod from mongo:7 and sets MONGODB_URL=mongodb://localhost:27017.+ #+ # The Dockerfile uses BuildKit syntax (COPY --link, --mount=type=cache),+ # so DOCKER_BUILDKIT=1 must be set in the env. Without it, the parser+ # rejects --link with "Unknown flag" before any build steps run.+ - name: 'gcr.io/cloud-builders/docker'+ env:+ - 'DOCKER_BUILDKIT=1'+ args: [+ 'build',+ '--build-arg', 'INCLUDE_DB=true',+ '-t', 'gcr.io/${PROJECT_ID}/ruvocal:${_VERSION}',+ '-f', 'Dockerfile',+ '.'+ ]++ - name: 'gcr.io/cloud-builders/docker'+ args: ['push', 'gcr.io/${PROJECT_ID}/ruvocal:${_VERSION}']++ - name: 'gcr.io/cloud-builders/docker'+ args: [+ 'tag',+ 'gcr.io/${PROJECT_ID}/ruvocal:${_VERSION}',+ 'gcr.io/${PROJECT_ID}/ruvocal:latest'+ ]+ - name: 'gcr.io/cloud-builders/docker'+ args: ['push', 'gcr.io/${PROJECT_ID}/ruvocal:latest']++ # Deploy to Cloud Run with embedded MongoDB.+ #+ # NOTE: MongoDB data is ephemeral — Cloud Run's container filesystem is+ # discarded on each cold start. This is acceptable for validation but+ # NOT for production. For persistence, follow up with either Atlas or+ # a Cloud Run multi-container revision (see ADR-033).+ #+ # Provider keys come from existing ruv-dev Secret Manager secrets per+ # ADR-029. Only one CPU is allocated; mongo is lightweight when used+ # only for chat session storage.+ # Deploy with image only — preserves manually configured env vars+ # (DOTENV_LOCAL with PUBLIC_ORIGIN/OPENAI_BASE_URL/MODELS, OPENAI_API_KEY+ # secret mapping, etc.). Initial env config must be set out-of-band via+ # `gcloud run services update` (see ADR-033 deployment notes).+ - name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'+ entrypoint: gcloud+ args: [+ 'run', 'deploy', 'ruvocal',+ '--image', 'gcr.io/${PROJECT_ID}/ruvocal:${_VERSION}',+ '--platform', 'managed',+ '--region', 'us-central1',+ '--port', '3000',+ '--memory', '2Gi',+ '--cpu', '2',+ '--min-instances', '0',+ '--max-instances', '3',+ '--timeout', '300',+ '--allow-unauthenticated'+ ]++substitutions:+ _VERSION: 'v1'++options:+ logging: CLOUD_LOGGING_ONLY+ machineType: 'E2_HIGHCPU_8'+timeout: 1800sdiff --git a/ruflo/src/ruvocal/config/branding.env.example b/ruflo/src/ruvocal/config/branding.env.examplenew file mode 100644index 0000000000..2fc2051e50--- /dev/null+++ b/ruflo/src/ruvocal/config/branding.env.example@@ -0,0 +1,19 @@+# RuVector Branding Configuration+# Copy this to .env.local or add to your environment++# App name displayed throughout the UI+PUBLIC_APP_NAME=RuVector++# App description for SEO and meta tags+PUBLIC_APP_DESCRIPTION="AI-powered intelligent assistant with MCP tools, voice, multi-model support, and workflow automation. Connect to collective intelligence via RuVector."++# Assets folder (defaults to "chatui" for RuVector styling)+PUBLIC_APP_ASSETS=chatui++# Optional: Set the public origin for absolute URLs+# PUBLIC_ORIGIN=https://your-domain.com++# Theme colors (configured via CSS, not env vars)+# Primary gold: #e8a634+# Background dark: #020205+# See tailwind.config.cjs for full color palettediff --git a/ruflo/src/ruvocal/mcp-bridge/index.js b/ruflo/src/ruvocal/mcp-bridge/index.jsindex c370b2081d..592809e40f 100644--- a/ruflo/src/ruvocal/mcp-bridge/index.js+++ b/ruflo/src/ruvocal/mcp-bridge/index.js@@ -213,12 +213,17 @@ class StdioMcpClient {const msg = JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n";this.pending.set(id, { resolve, reject });this.process.stdin.write(msg);+ // initialize is the cold-start gate for backends like ruflo/ruvector+ // which boot a full claude-flow / ruvector kernel — on Cloud Run with+ // npx fetching artifacts it can take 45-60s. Other RPC methods are+ // post-init and stay snappy.+ const timeoutMs = method === "initialize" ? 120000 : 30000;setTimeout(() => {if (this.pending.has(id)) {this.pending.delete(id);reject(new Error(`${this.name} timeout for ${method}`));}- }, 30000);+ }, timeoutMs);});}@@ -648,6 +653,15 @@ async function geminiGroundedSearch(query, mode = "search") {const apiKey = process.env.GOOGLE_API_KEY;if (!apiKey) return { error: "No GOOGLE_API_KEY configured for search" };+ // Empty/missing query produces a 400 from Gemini's generateContent endpoint.+ // Return a structured error so the model can recover with a real query.+ if (!query || typeof query !== "string" || !query.trim()) {+ return {+ error: "search requires a non-empty query string",+ hint: "Call this tool again with { query: 'your search terms' }. For comparisons use { action: 'compare', query: 'item A vs item B' }; for fact-checking use { action: 'fact_check', claim: 'the claim text' }.",+ };+ }+const model = "gemini-2.5-flash";const url = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${apiKey}`;diff --git a/ruflo/src/ruvocal/src/lib/components/FoundationBackground.svelte b/ruflo/src/ruvocal/src/lib/components/FoundationBackground.sveltenew file mode 100644index 0000000000..ffe3976eb2--- /dev/null+++ b/ruflo/src/ruvocal/src/lib/components/FoundationBackground.svelte@@ -0,0 +1,242 @@+<script lang="ts">+ import { onMount, onDestroy } from "svelte";+ import { browser } from "$app/environment";++ interface Props {+ opacity?: number;+ }++ let { opacity = 0.6 }: Props = $props();++ let canvas: HTMLCanvasElement | undefined = $state();+ let animationFrame: number;++ // Mathematical glyphs for Foundation aesthetic+ const GLYPHS = ['∑', '∫', '∂', '∞', '∇', 'Δ', 'Ψ', 'Ω', 'π', 'λ', 'θ', 'φ', 'ξ', '∈', '∀', '∃', '⊕', '⊗', '≡', '≈'];++ interface Particle {+ x: number;+ y: number;+ vx: number;+ vy: number;+ size: number;+ opacity: number;+ glyph?: string;+ isGlyph: boolean;+ phase: number;+ speed: number;+ }++ interface Connection {+ from: number;+ to: number;+ opacity: number;+ }++ let particles: Particle[] = [];+ let connections: Connection[] = [];+ let time = 0;+ let mouseX = 0.5;+ let mouseY = 0.5;++ function initParticles(width: number, height: number) {+ particles = [];+ const particleCount = Math.floor((width * height) / 15000);+ const glyphCount = Math.floor(particleCount * 0.15);++ for (let i = 0; i < particleCount; i++) {+ const isGlyph = i < glyphCount;+ particles.push({+ x: Math.random() * width,+ y: Math.random() * height,+ vx: (Math.random() - 0.5) * 0.3,+ vy: (Math.random() - 0.5) * 0.3,+ size: isGlyph ? 12 + Math.random() * 8 : 1 + Math.random() * 2,+ opacity: 0.1 + Math.random() * 0.5,+ glyph: isGlyph ? GLYPHS[Math.floor(Math.random() * GLYPHS.length)] : undefined,+ isGlyph,+ phase: Math.random() * Math.PI * 2,+ speed: 0.5 + Math.random() * 1.5,+ });+ }+ }++ function updateConnections() {+ connections = [];+ const maxDist = 120;++ for (let i = 0; i < particles.length; i++) {+ for (let j = i + 1; j < particles.length; j++) {+ const dx = particles[i].x - particles[j].x;+ const dy = particles[i].y - particles[j].y;+ const dist = Math.sqrt(dx * dx + dy * dy);++ if (dist < maxDist) {+ connections.push({+ from: i,+ to: j,+ opacity: (1 - dist / maxDist) * 0.15,+ });+ }+ }+ }+ }++ function animate() {+ if (!canvas) return;+ const ctx = canvas.getContext("2d");+ if (!ctx) return;++ const width = canvas.width;+ const height = canvas.height;++ // Clear with fade effect+ ctx.fillStyle = "rgba(2, 2, 5, 0.15)";+ ctx.fillRect(0, 0, width, height);++ time += 0.008;++ // Update particles+ particles.forEach((p, i) => {+ // Mouse influence+ const dx = mouseX * width - p.x;+ const dy = mouseY * height - p.y;+ const dist = Math.sqrt(dx * dx + dy * dy);+ if (dist < 200) {+ const force = (200 - dist) / 200 * 0.02;+ p.vx += dx * force * 0.01;+ p.vy += dy * force * 0.01;+ }++ // Drift+ p.x += p.vx + Math.sin(time * p.speed + p.phase) * 0.2;+ p.y += p.vy + Math.cos(time * p.speed + p.phase) * 0.2;++ // Damping+ p.vx *= 0.99;+ p.vy *= 0.99;++ // Wrap around+ if (p.x < -50) p.x = width + 50;+ if (p.x > width + 50) p.x = -50;+ if (p.y < -50) p.y = height + 50;+ if (p.y > height + 50) p.y = -50;++ // Pulse opacity+ const pulseOpacity = p.opacity * (0.5 + Math.sin(time * 2 + p.phase) * 0.5);++ if (p.isGlyph && p.glyph) {+ // Draw glyph+ ctx.save();+ ctx.font = `${p.size}px "SF Mono", "Fira Code", monospace`;+ ctx.fillStyle = `rgba(232, 166, 52, ${pulseOpacity * 0.6})`;+ ctx.shadowColor = "#e8a634";+ ctx.shadowBlur = 8;+ ctx.fillText(p.glyph, p.x, p.y);+ ctx.restore();+ } else {+ // Draw particle+ ctx.beginPath();+ ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2);+ ctx.fillStyle = `rgba(232, 166, 52, ${pulseOpacity})`;+ ctx.fill();+ }+ });++ // Update connections periodically+ if (Math.floor(time * 10) % 5 === 0) {+ updateConnections();+ }++ // Draw connections+ connections.forEach((c) => {+ const p1 = particles[c.from];+ const p2 = particles[c.to];+ if (!p1 || !p2) return;+ ctx.beginPath();+ ctx.moveTo(p1.x, p1.y);+ ctx.lineTo(p2.x, p2.y);+ ctx.strokeStyle = `rgba(232, 166, 52, ${c.opacity})`;+ ctx.lineWidth = 0.5;+ ctx.stroke();+ });++ // Draw orbital rings+ const centerX = width / 2;+ const centerY = height / 2;+ const rings = [+ { radius: 180, rotation: time * 0.3, opacity: 0.08 },+ { radius: 250, rotation: -time * 0.2, opacity: 0.06 },+ { radius: 320, rotation: time * 0.15, opacity: 0.04 },+ ];++ rings.forEach((ring) => {+ ctx.save();+ ctx.translate(centerX, centerY);+ ctx.rotate(ring.rotation);+ ctx.beginPath();+ ctx.ellipse(0, 0, ring.radius, ring.radius * 0.3, 0, 0, Math.PI * 2);+ ctx.strokeStyle = `rgba(232, 166, 52, ${ring.opacity})`;+ ctx.lineWidth = 1;+ ctx.stroke();+ ctx.restore();+ });++ // Central core glow+ const coreGlow = ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, 100);+ coreGlow.addColorStop(0, `rgba(232, 166, 52, ${0.15 + Math.sin(time * 3) * 0.05})`);+ coreGlow.addColorStop(0.5, "rgba(232, 166, 52, 0.02)");+ coreGlow.addColorStop(1, "transparent");+ ctx.fillStyle = coreGlow;+ ctx.beginPath();+ ctx.arc(centerX, centerY, 100, 0, Math.PI * 2);+ ctx.fill();++ animationFrame = requestAnimationFrame(animate);+ }++ function handleResize() {+ if (!canvas) return;+ canvas.width = window.innerWidth;+ canvas.height = window.innerHeight;+ initParticles(canvas.width, canvas.height);+ }++ function handleMouseMove(e: MouseEvent) {+ mouseX = e.clientX / window.innerWidth;+ mouseY = e.clientY / window.innerHeight;+ }++ onMount(() => {+ if (!browser || !canvas) return;+ handleResize();+ animate();+ window.addEventListener("resize", handleResize);+ window.addEventListener("mousemove", handleMouseMove);+ });++ onDestroy(() => {+ if (!browser) return;+ cancelAnimationFrame(animationFrame);+ window.removeEventListener("resize", handleResize);+ window.removeEventListener("mousemove", handleMouseMove);+ });+</script>++<canvas+ bind:this={canvas}+ class="foundation-bg"+ style="opacity: {opacity}"+></canvas>++<style>+ .foundation-bg {+ position: fixed;+ top: 0;+ left: 0;+ width: 100%;+ height: 100%;+ z-index: 0;+ pointer-events: none;+ }+</style>diff --git a/ruflo/src/ruvocal/src/lib/components/NavMenu.svelte b/ruflo/src/ruvocal/src/lib/components/NavMenu.svelteindex 480feebb39..d061974fbd 100644--- a/ruflo/src/ruvocal/src/lib/components/NavMenu.svelte+++ b/ruflo/src/ruvocal/src/lib/components/NavMenu.svelte@@ -32,6 +32,7 @@import { isPro } from "$lib/stores/isPro";import IconPro from "$lib/components/icons/IconPro.svelte";import MCPServerManager from "./mcp/MCPServerManager.svelte";+ import RufloHelpModal from "./RufloHelpModal.svelte";const publicConfig = usePublicConfig();const client = useAPIClient();@@ -117,6 +118,7 @@let isDark = $state(false);let unsubscribeTheme: (() => void) | undefined;let showMcpModal = $state(false);+ let showHelpModal = $state(false);if (browser) {unsubscribeTheme = subscribeToTheme(({ isDark: nextIsDark }) => {@@ -247,6 +249,18 @@>Settings</a>+ <button+ onclick={() => (showHelpModal = true)}+ aria-label="Open help and tool documentation"+ title="RuFlo capabilities & tool docs"+ class="flex size-9 min-w-[1.5em] flex-none items-center justify-center rounded-lg p-2 text-gray-500 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-700"+ >+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="size-4">+ <circle cx="12" cy="12" r="10" />+ <path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3" />+ <line x1="12" y1="17" x2="12.01" y2="17" />+ </svg>+ </button><buttononclick={() => {switchTheme();@@ -269,6 +283,10 @@<MCPServerManager onclose={() => (showMcpModal = false)} />{/if}+{#if showHelpModal}+ <RufloHelpModal onclose={() => (showHelpModal = false)} />+{/if}+<style>.quantum-dot {display: block;diff --git a/ruflo/src/ruvocal/src/lib/components/RufloHelpModal.svelte b/ruflo/src/ruvocal/src/lib/components/RufloHelpModal.sveltenew file mode 100644index 0000000000..a19edbf329--- /dev/null+++ b/ruflo/src/ruvocal/src/lib/components/RufloHelpModal.svelte@@ -0,0 +1,212 @@+<script lang="ts">+ import Modal from "./Modal.svelte";+ import CarbonClose from "~icons/carbon/close";++ interface Props {+ onclose?: () => void;+ }++ let { onclose }: Props = $props();++ type Tool = { name: string; desc: string };+ type Group = { id: string; title: string; emoji: string; intro: string; tools: Tool[] };++ const groups: Group[] = [+ {+ id: "memory",+ title: "Memory & Knowledge",+ emoji: "🧠",+ intro: "Persistent cross-session memory backed by AgentDB. Store and recall by key or semantic search.",+ tools: [+ { name: "ruflo__memory_store", desc: "Save a key/value into a namespace." },+ { name: "ruflo__memory_search", desc: "Semantic vector search over stored memories." },+ { name: "ruflo__memory_retrieve", desc: "Fetch a specific entry by key + namespace." },+ { name: "ruflo__memory_list", desc: "List entries in a namespace." },+ { name: "ruflo__embeddings_compare", desc: "Compare two pieces of text by semantic similarity." },+ { name: "ruflo__agentdb_*", desc: "Lower-level AgentDB controllers (route, consolidate, hierarchical)." },+ ],+ },+ {+ id: "agents",+ title: "Agents & Orchestration",+ emoji: "🤖",+ intro: "Spawn agents, coordinate swarms, run hive-mind consensus, manage tasks.",+ tools: [+ { name: "ruflo__agent_spawn", desc: "Create a new specialized agent (coder, tester, reviewer, …)." },+ { name: "ruflo__swarm_init", desc: "Initialize a swarm with topology + strategy." },+ { name: "ruflo__hive-mind_*", desc: "Queen-led Byzantine fault-tolerant collective." },+ { name: "ruflo__task_create", desc: "Create + assign a task to an agent." },+ { name: "ruflo__agent_list", desc: "List active agents and their state." },+ ],+ },+ {+ id: "intelligence",+ title: "Intelligence & Learning",+ emoji: "✨",+ intro: "Pattern learning, routing, code analysis, and trajectory tracking via RuVector.",+ tools: [+ { name: "ruvector__hooks_route", desc: "Pick the optimal agent type for a task." },+ { name: "ruvector__hooks_remember / recall", desc: "Cross-session key/value memory." },+ { name: "ruvector__hooks_trajectory_*", desc: "Record multi-step task execution for learning." },+ { name: "ruvector__hooks_security_scan", desc: "Scan code for vulnerabilities." },+ { name: "ruvector__hooks_rag_context", desc: "Get retrieval-augmented context for a query." },+ { name: "ruvector__hooks_swarm_recommend", desc: "Recommend swarm topology for a task." },+ ],+ },+ {+ id: "devtools",+ title: "Dev Tools & Analysis",+ emoji: "🛠️",+ intro: "System health, performance profiling, GitHub integration, and shell access.",+ tools: [+ { name: "ruflo__system_status", desc: "Overall system health overview." },+ { name: "ruflo__performance_metrics", desc: "Detailed performance metrics." },+ { name: "ruflo__performance_bottleneck", desc: "Identify performance bottlenecks." },+ { name: "ruflo__analyze_diff", desc: "Risk-score and classify a code diff." },+ { name: "ruflo__github_repo_analyze", desc: "Repo metrics and structure analysis." },+ { name: "ruflo__terminal_execute", desc: "Run a shell command." },+ { name: "ruflo__progress_*", desc: "Implementation progress tracking." },+ ],+ },+ {+ id: "core",+ title: "Core Tools",+ emoji: "⚡",+ intro: "Built-in tools always available regardless of MCP configuration.",+ tools: [+ { name: "search", desc: "Search the local knowledge base." },+ { name: "web_research", desc: "Web search, deep research, comparisons, fact-checking." },+ { name: "guidance", desc: "Get help on any tool group or specific tool. Topics: overview, groups, agents, memory, intelligence, devtools." },+ ],+ },+ {+ id: "wasm",+ title: "WASM Gallery (Browser-side)",+ emoji: "🧩",+ intro: "In-browser MCP server (rvagent-wasm) with persistent IndexedDB storage. Works offline, no server roundtrip.",+ tools: [+ { name: "WASM gallery", desc: "18 templates exposed via the local WASM MCP server (visible as MCP (1) in the chat input)." },+ { name: "Custom templates", desc: "Add your own via the MCP Servers panel → Add Server." },+ ],+ },+ ];++ const tips = [+ 'Click the **MCP** pill above the message box to manage servers and toggle individual tools.',+ '**AUTO** = autopilot mode. ON: tool calls chain automatically. OFF: stops between calls so you can inspect each result.',+ 'For long-horizon work, use `ruvector__hooks_trajectory_begin` so the system learns from the run.',+ 'Memory persists across sessions — say "remember that X" or "what did we save about Y" anytime.',+ 'Tool names are prefixed with their backend (`ruflo__`, `ruvector__`). Always use the full name when invoking explicitly.',+ ];++ let openGroup = $state<string | null>("memory");+</script>++<Modal width="max-w-2xl" closeButton={false} {onclose}>+ <div class="flex max-h-[85vh] w-full flex-col overflow-hidden rounded-2xl bg-white text-gray-900 dark:bg-gray-900 dark:text-gray-100">+ <header class="flex items-center justify-between border-b border-gray-200 px-6 py-4 dark:border-gray-700">+ <div class="flex items-center gap-3">+ <span class="text-2xl">📘</span>+ <div>+ <h2 class="text-lg font-semibold">RuFlo Capabilities</h2>+ <p class="text-xs text-gray-500 dark:text-gray-400">~210 MCP tools across 5 server groups + WASM gallery.</p>+ </div>+ </div>+ <button+ type="button"+ onclick={() => onclose?.()}+ class="flex size-8 items-center justify-center rounded-full text-gray-500 hover:bg-gray-100 hover:text-gray-900 dark:hover:bg-gray-700 dark:hover:text-white"+ aria-label="Close help"+ >+ <CarbonClose />+ </button>+ </header>++ <div class="flex-1 overflow-y-auto px-6 py-4">+ <section class="mb-6">+ <h3 class="mb-2 text-sm font-semibold uppercase tracking-wide text-gray-500">Quick start</h3>+ <ol class="list-decimal space-y-1.5 pl-5 text-sm">+ <li>Pick a model (default: <code class="rounded bg-gray-100 px-1 dark:bg-gray-800">Gemini 2.5 Flash</code>).</li>+ <li>Click an example below the chat box, or type your own prompt.</li>+ <li>RuFlo decides which tools to call. Watch the streaming tool-call cards below your message.</li>+ <li>Use <strong>AUTO</strong> on the chat box to auto-continue tool chains.</li>+ </ol>+ </section>++ <section class="mb-6">+ <h3 class="mb-2 text-sm font-semibold uppercase tracking-wide text-gray-500">Tool groups</h3>+ <div class="space-y-2">+ {#each groups as group}+ <details+ class="rounded-lg border border-gray-200 bg-gray-50 dark:border-gray-700 dark:bg-gray-800"+ open={openGroup === group.id}+ ontoggle={(e) => {+ if ((e.currentTarget as HTMLDetailsElement).open) openGroup = group.id;+ else if (openGroup === group.id) openGroup = null;+ }}+ >+ <summary class="flex cursor-pointer items-center gap-2 px-3 py-2 text-sm font-medium">+ <span>{group.emoji}</span>+ <span>{group.title}</span>+ <span class="ml-auto rounded bg-blue-600/10 px-1.5 py-0.5 text-xs text-blue-600 dark:bg-blue-500/20 dark:text-blue-300">+ {group.tools.length} tools+ </span>+ </summary>+ <div class="border-t border-gray-200 px-3 py-2 dark:border-gray-700">+ <p class="mb-2 text-xs text-gray-600 dark:text-gray-400">{group.intro}</p>+ <ul class="space-y-1 text-xs">+ {#each group.tools as tool}+ <li class="flex gap-2">+ <code class="shrink-0 rounded bg-white px-1 py-0.5 text-[11px] font-mono dark:bg-gray-900">{tool.name}</code>+ <span class="text-gray-700 dark:text-gray-300">{tool.desc}</span>+ </li>+ {/each}+ </ul>+ </div>+ </details>+ {/each}+ </div>+ </section>++ <section class="mb-6">+ <h3 class="mb-2 text-sm font-semibold uppercase tracking-wide text-gray-500">Tips</h3>+ <ul class="list-disc space-y-1.5 pl-5 text-sm">+ {#each tips as tip}+ <li>{@html tip.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>').replace(/`([^`]+)`/g, '<code class="rounded bg-gray-100 px-1 dark:bg-gray-800">$1</code>')}</li>+ {/each}+ </ul>+ </section>++ <section>+ <h3 class="mb-2 text-sm font-semibold uppercase tracking-wide text-gray-500">Resources</h3>+ <ul class="space-y-1 text-sm">+ <li>+ <a href="https://github.com/ruvnet/ruflo" target="_blank" rel="noopener" class="text-blue-600 hover:underline dark:text-blue-400">+ github.com/ruvnet/ruflo →+ </a>+ </li>+ <li>+ <a href="https://github.com/ruvnet/ruflo/blob/main/ruflo/docs/adr/ADR-033-RUVOCAL-WASM-MCP-INTEGRATION.md" target="_blank" rel="noopener" class="text-blue-600 hover:underline dark:text-blue-400">+ ADR-033 — WASM-MCP integration →+ </a>+ </li>+ <li>+ <a href="https://github.com/ruvnet/ruvector" target="_blank" rel="noopener" class="text-blue-600 hover:underline dark:text-blue-400">+ ruvnet/ruvector — intelligence layer →+ </a>+ </li>+ </ul>+ </section>+ </div>++ <footer class="flex items-center justify-end gap-2 border-t border-gray-200 px-6 py-3 dark:border-gray-700">+ <button+ type="button"+ onclick={() => onclose?.()}+ class="rounded-lg bg-gray-900 px-4 py-1.5 text-sm font-medium text-white hover:bg-black dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-white"+ >+ Got it+ </button>+ </footer>+ </div>+</Modal>diff --git a/ruflo/src/ruvocal/src/lib/components/wasm/GalleryPanel.svelte b/ruflo/src/ruvocal/src/lib/components/wasm/GalleryPanel.sveltenew file mode 100644index 0000000000..a52cdf0579--- /dev/null+++ b/ruflo/src/ruvocal/src/lib/components/wasm/GalleryPanel.svelte@@ -0,0 +1,357 @@+<script lang="ts">+ import { onMount } from "svelte";+ import {+ allMcpServers,+ selectedServerIds,+ healthCheckServer,+ loadWasmTemplate,+ getWasmGalleryTemplates,+ WASM_SERVER_ID,+ } from "$lib/stores/mcpServers";+ import {+ wasmLoaded,+ wasmLoading,+ wasmError,+ initWasmMcp,+ searchGalleryTemplates,+ getGalleryCategories,+ saveTemplateAsRvf,+ } from "$lib/stores/wasmMcp";+ import type { GalleryTemplate, SearchResult } from "$lib/wasm";+ import IconSearch from "~icons/carbon/Search";+ import IconDownload from "~icons/carbon/Download";+ import IconCheckmark from "~icons/carbon/Checkmark";+ import IconCode from "~icons/carbon/Code";+ import IconSearch16 from "~icons/carbon/Search";+ import IconFolder from "~icons/carbon/Folder";++ let searchQuery = $state("");+ let selectedCategory = $state<string | null>(null);+ let templates = $state<GalleryTemplate[]>([]);+ let searchResults = $state<SearchResult[]>([]);+ let categories = $state<Record<string, number>>({});+ let loading = $state(false);++ // Get WASM server from MCP servers+ const wasmServer = $derived($allMcpServers.find((s) => s.id === WASM_SERVER_ID));+ const isWasmEnabled = $derived($selectedServerIds.has(WASM_SERVER_ID));+ const activeTemplateId = $derived(wasmServer?.wasmTemplateId);+ const activeTemplateName = $derived(wasmServer?.wasmTemplateName);++ // Category icons mapping+ const categoryIcons: Record<string, typeof IconCode> = {+ development: IconCode,+ research: IconSearch16,+ custom: IconFolder,+ };++ // Category colors+ const categoryColors: Record<string, string> = {+ development: "bg-blue-500",+ research: "bg-purple-500",+ testing: "bg-green-500",+ security: "bg-red-500",+ orchestration: "bg-yellow-500",+ documentation: "bg-cyan-500",+ devops: "bg-orange-500",+ custom: "bg-gray-500",+ };++ function getCategoryIcon(category: string) {+ return categoryIcons[category.toLowerCase()] || IconFolder;+ }++ function getCategoryColor(category: string) {+ return categoryColors[category.toLowerCase()] || "bg-gray-500";+ }++ async function loadTemplates() {+ if (!$wasmLoaded) return;+ templates = getWasmGalleryTemplates();+ categories = getGalleryCategories();+ }++ function handleSearch() {+ if (!searchQuery.trim()) {+ searchResults = [];+ return;+ }+ searchResults = searchGalleryTemplates(searchQuery);+ }++ async function handleLoadTemplate(id: string) {+ loading = true;+ const success = await loadWasmTemplate(id);+ if (success) {+ loadTemplates();+ }+ loading = false;+ }++ async function handleSaveRvf(id: string) {+ loading = true;+ const containerId = await saveTemplateAsRvf(id);+ if (containerId) {+ alert(`RVF container saved with ID: ${containerId}`);+ }+ loading = false;+ }++ async function handleHealthCheck() {+ if (wasmServer) {+ await healthCheckServer(wasmServer);+ }+ }++ function getFilteredTemplates(): GalleryTemplate[] {+ if (searchQuery.trim()) {+ const ids = new Set(searchResults.map((r) => r.id));+ return templates.filter((t) => ids.has(t.id));+ }+ const category = selectedCategory;+ if (category) {+ return templates.filter((t) => t.category.toLowerCase() === category.toLowerCase());+ }+ return templates;+ }++ onMount(async () => {+ if (!$wasmLoaded) {+ await initWasmMcp();+ }+ loadTemplates();+ });++ $effect(() => {+ if ($wasmLoaded) {+ loadTemplates();+ }+ });++ $effect(() => {+ handleSearch();+ });+</script>++<div class="flex flex-col h-full bg-gray-50 dark:bg-gray-900">+ <!-- Header -->+ <div class="p-4 border-b border-gray-200 dark:border-gray-700">+ <div class="flex items-center justify-between mb-3">+ <h2 class="text-lg font-semibold text-gray-900 dark:text-white">RVF Agent Gallery</h2>+ {#if wasmServer}+ <div class="flex items-center gap-2">+ <span+ class="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium+ {wasmServer.status === 'connected'+ ? 'bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200'+ : wasmServer.status === 'connecting'+ ? 'bg-yellow-100 dark:bg-yellow-900 text-yellow-800 dark:text-yellow-200'+ : wasmServer.status === 'error'+ ? 'bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200'+ : 'bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-200'}"+ >+ {wasmServer.status === "connected" ? "WASM Ready" : wasmServer.status || "Disconnected"}+ </span>+ <button+ onclick={handleHealthCheck}+ class="text-xs text-blue-500 hover:text-blue-600"+ disabled={loading}+ >+ Refresh+ </button>+ </div>+ {/if}+ </div>++ {#if $wasmLoading}+ <div class="flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400">+ <div+ class="w-4 h-4 border-2 border-blue-500 border-t-transparent rounded-full animate-spin"+ ></div>+ Loading WASM module...+ </div>+ {:else if $wasmError}+ <div class="text-sm text-red-500 dark:text-red-400">+ Error: {$wasmError}+ </div>+ {:else if $wasmLoaded}+ <!-- Search -->+ <div class="relative">+ <IconSearch+ class="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400"+ />+ <input+ type="text"+ placeholder="Search templates..."+ bind:value={searchQuery}+ class="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg+ bg-white dark:bg-gray-800 text-gray-900 dark:text-white+ focus:ring-2 focus:ring-blue-500 focus:border-transparent"+ />+ </div>++ <!-- Active Template Badge -->+ {#if activeTemplateId}+ <div class="mt-3 flex items-center gap-2">+ <span class="text-xs text-gray-500 dark:text-gray-400">Active:</span>+ <span+ class="inline-flex items-center gap-1 px-2 py-1 rounded-full bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200 text-xs font-medium"+ >+ <IconCheckmark class="w-3 h-3" />+ {activeTemplateName}+ </span>+ {#if wasmServer?.tools?.length}+ <span class="text-xs text-gray-400">+ ({wasmServer.tools.length} tools)+ </span>+ {/if}+ </div>+ {/if}+ {/if}+ </div>++ {#if $wasmLoaded}+ <!-- Categories -->+ <div class="p-4 border-b border-gray-200 dark:border-gray-700">+ <div class="flex flex-wrap gap-2">+ <button+ class="px-3 py-1.5 rounded-full text-xs font-medium transition-colors+ {selectedCategory === null+ ? 'bg-blue-500 text-white'+ : 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-600'}"+ onclick={() => (selectedCategory = null)}+ >+ All ({templates.length})+ </button>+ {#each Object.entries(categories) as [category, count]}+ <button+ class="px-3 py-1.5 rounded-full text-xs font-medium transition-colors+ {selectedCategory === category+ ? 'bg-blue-500 text-white'+ : 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-600'}"+ onclick={() => (selectedCategory = category)}+ >+ {category} ({count})+ </button>+ {/each}+ </div>+ </div>++ <!-- Templates List -->+ <div class="flex-1 overflow-y-auto p-4 space-y-3">+ {#each getFilteredTemplates() as template (template.id)}+ {@const CategoryIcon = getCategoryIcon(template.category)}+ <div+ class="p-4 bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700+ hover:border-blue-300 dark:hover:border-blue-600 transition-colors"+ >+ <div class="flex items-start gap-3">+ <!-- Category Icon -->+ <div+ class="flex-shrink-0 w-10 h-10 rounded-lg {getCategoryColor(+ template.category+ )} flex items-center justify-center"+ >+ <CategoryIcon class="w-5 h-5 text-white" />+ </div>++ <!-- Content -->+ <div class="flex-1 min-w-0">+ <div class="flex items-center gap-2">+ <h3 class="font-medium text-gray-900 dark:text-white truncate">+ {template.name}+ </h3>+ {#if template.builtin}+ <span+ class="px-1.5 py-0.5 rounded text-xs bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300"+ >+ Built-in+ </span>+ {/if}+ {#if activeTemplateId === template.id}+ <span+ class="px-1.5 py-0.5 rounded text-xs bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300"+ >+ Active+ </span>+ {/if}+ </div>+ <p class="mt-1 text-sm text-gray-500 dark:text-gray-400 line-clamp-2">+ {template.description}+ </p>++ <!-- Tags -->+ <div class="mt-2 flex flex-wrap gap-1">+ {#each template.tags.slice(0, 4) as tag}+ <span+ class="px-2 py-0.5 rounded text-xs bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300"+ >+ {tag}+ </span>+ {/each}+ {#if template.tags.length > 4}+ <span class="px-2 py-0.5 text-xs text-gray-400">+ +{template.tags.length - 4} more+ </span>+ {/if}+ </div>++ <!-- Stats -->+ <div class="mt-2 flex items-center gap-4 text-xs text-gray-400">+ {#if template.tools?.length}+ <span>{template.tools.length} tools</span>+ {/if}+ {#if template.skills?.length}+ <span>{template.skills.length} skills</span>+ {/if}+ {#if template.mcp_tools?.length}+ <span>{template.mcp_tools.length} MCP tools</span>+ {/if}+ {#if template.orchestrator}+ <span>Multi-agent</span>+ {/if}+ </div>+ </div>++ <!-- Actions -->+ <div class="flex-shrink-0 flex flex-col gap-2">+ <button+ onclick={() => handleLoadTemplate(template.id)}+ disabled={loading || activeTemplateId === template.id}+ class="px-3 py-1.5 rounded text-xs font-medium transition-colors+ {activeTemplateId === template.id+ ? 'bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300 cursor-default'+ : 'bg-blue-500 hover:bg-blue-600 text-white'}"+ >+ {#if activeTemplateId === template.id}+ <IconCheckmark class="w-3 h-3 inline" />+ Loaded+ {:else}+ Load+ {/if}+ </button>+ <button+ onclick={() => handleSaveRvf(template.id)}+ disabled={loading}+ class="px-3 py-1.5 rounded text-xs font-medium bg-gray-100 dark:bg-gray-700+ text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"+ title="Save as RVF container"+ >+ <IconDownload class="w-3 h-3 inline" />+ RVF+ </button>+ </div>+ </div>+ </div>+ {:else}+ <div class="text-center py-8 text-gray-500 dark:text-gray-400">+ {#if searchQuery}+ No templates match your search.+ {:else}+ No templates available.+ {/if}+ </div>+ {/each}+ </div>+ {/if}+</div>diff --git a/ruflo/src/ruvocal/src/lib/constants/mcpExamples.ts b/ruflo/src/ruvocal/src/lib/constants/mcpExamples.tsindex 93e0caa63f..ee632056af 100644--- a/ruflo/src/ruvocal/src/lib/constants/mcpExamples.ts+++ b/ruflo/src/ruvocal/src/lib/constants/mcpExamples.ts@@ -1,134 +1,113 @@import type { RouterExample } from "./routerExamples";-// Examples that showcase MCP tool capabilities (web search, Hugging Face, etc.)+// Examples that showcase RuFlo MCP capabilities — agents, memory,+// intelligence, dev tools, and the WASM gallery.export const mcpExamples: RouterExample[] = [{- title: "Generate an image",- prompt: "Generate an image of a zebra in front of a volcanic eruption",- },- {- title: "Latest world news",- prompt: "What is the latest world news?",+ title: "Spawn a coding swarm",+ prompt:+ "Spawn a hierarchical swarm with 5 agents (architect, coder, tester, reviewer, security-auditor) to refactor a Python CLI tool to TypeScript. Use ruflo__swarm_init then ruflo__agent_spawn for each role.",followUps: [{- title: "Tech focus",- prompt: "What about technology news?",- },- {- title: "San Francisco",- prompt: "What's happening in San Francisco?",+ title: "Show progress",+ prompt: "Use ruflo__progress_summary to show the swarm's current state.",},{- title: "vs last week",- prompt: "How does this compare to last week's news?",+ title: "Add tests",+ prompt: "Spawn a tester agent to write integration tests for the swarm output.",},],},{- title: "Trending models",- prompt: "What are the top trending models on Hugging Face?",+ title: "Save & recall memory",+ prompt:+ "Use ruflo__memory_store to save: namespace='preferences', key='editor_theme', value='solarized-dark'. Then ruflo__memory_search query='theme' to verify.",followUps: [{- title: "Text generation",- prompt: "What about text generation models?",- },- {- title: "Image generation",- prompt: "What about text-to-image models?",+ title: "List entries",+ prompt: "List all entries in the 'preferences' namespace using ruflo__memory_list.",},{- title: "How to use",- prompt: "Show me how to use the most popular one",+ title: "Semantic search",+ prompt: "Find related memories with ruvector__hooks_recall query='editor settings'.",},],},{- title: "Plan a trip",- prompt: "Things to do in Tokyo next week",+ title: "Route a task",+ prompt:+ "Use ruvector__hooks_route on the task: 'add OAuth2 to a SvelteKit API'. Tell me which agent type and topology you'd recommend.",followUps: [{- title: "Transport & prices",- prompt: "How do I get around and how much will it cost?",+ title: "Spawn the agent",+ prompt: "Spawn the recommended agent with ruflo__agent_spawn.",},{- title: "Weather",- prompt: "What's the weather like in Tokyo next week?",- },- {- title: "Meet people",- prompt: "Where can I meet new people and make friends?",+ title: "Track trajectory",+ prompt: "Begin a trajectory with ruvector__hooks_trajectory_begin to record the work.",},],},{- title: "Compare technologies",- prompt: "Search the web to compare React, Vue, and Svelte for building web apps in 2025",+ title: "Analyze a diff",+ prompt:+ "Use ruflo__analyze_diff to assess risk and ruflo__analyze_diff-reviewers to suggest reviewers for the PR at github.com/ruvnet/ruflo/pull/1687.",followUps: [{- title: "Performance benchmarks",- prompt: "Search for recent performance benchmarks comparing these frameworks",+ title: "Repo metrics",+ prompt: "Get repository metrics with ruflo__github_repo_analyze for ruvnet/ruflo.",},{- title: "Job market",- prompt: "Search for job market trends for each of these frameworks",- },- {- title: "Migration guides",- prompt: "Search for guides on migrating from React to Svelte",+ title: "Open issues",+ prompt: "List recent issues with ruflo__github_issue_track for ruvnet/ruflo.",},],},{- title: "Find a dataset",- prompt: "Find datasets on Hugging Face for training a sentiment analysis model",+ title: "System health check",+ prompt:+ "Run ruflo__system_status, ruflo__performance_metrics, and ruflo__performance_bottleneck. Summarize anything concerning.",followUps: [{- title: "Dataset details",- prompt: "Tell me more about the largest dataset - its size, format, and how to load it",- },- {- title: "Find models",- prompt: "Find pre-trained models that were trained on this dataset",+ title: "Optimize",+ prompt: "Use ruflo__performance_optimize on the slowest component identified.",},{- title: "Code snippet",- prompt: "Show me how to load and preprocess this dataset with the datasets library",+ title: "Benchmark",+ prompt: "Run ruflo__performance_benchmark with --suite=all.",},],},{- title: "Gift ideas",- prompt: "Search for unique gift ideas for someone who loves cooking",+ title: "Browse WASM gallery",+ prompt:+ "Show me the templates in the WASM gallery (browser-side rvagent server) and explain what each one does.",followUps: [{- title: "Budget options",- prompt: "Search for gift ideas under $50",- },- {- title: "Top rated",- prompt: "Search for the top-rated cooking gadgets of this year",- },- {- title: "DIY gifts",- prompt: "Search for homemade gift ideas for cooking enthusiasts",+ title: "Load a template",+ prompt: "Load the most popular template into the local WASM MCP server.",},],},{- title: "Learn something new",- prompt: "Search for the best resources to learn Rust programming in 2025",+ title: "Plan with GOAP",+ prompt:+ "Use the goal-planner pattern: I want to migrate a Postgres schema with zero downtime. Decompose into ruflo agents and tasks.",followUps: [{- title: "Project ideas",- prompt: "Search for beginner Rust project ideas to practice with",- },- {- title: "Find tools",- prompt: "Search for the most popular Rust tools and libraries I should know about",+ title: "Risk analysis",+ prompt: "Run ruflo__analyze_file-risk on the migration file.",},+ ],+ },+ {+ title: "Train neural pattern",+ prompt:+ "Use ruvector__neural_train to learn from this successful pattern: 'JWT auth with refresh tokens — store refresh in httpOnly cookie, access in memory'.",+ followUps: [{- title: "Community",- prompt: "Search for Rust communities and forums where I can ask questions",+ title: "Predict",+ prompt: "Use ruvector__neural_predict for the task 'add session-based auth'.",},],},diff --git a/ruflo/src/ruvocal/src/lib/constants/routerExamples.ts b/ruflo/src/ruvocal/src/lib/constants/routerExamples.tsindex b0495914a5..56a7db69a8 100644--- a/ruflo/src/ruvocal/src/lib/constants/routerExamples.ts+++ b/ruflo/src/ruvocal/src/lib/constants/routerExamples.ts@@ -14,195 +14,119 @@ export type RouterExample = {attachments?: RouterExampleAttachment[];};+// RuFlo-themed router examples — shown on the empty-state welcome screen+// when the user hasn't enabled the full MCP toolset. Keep these light enough+// that even a model without tool-calling can answer (no explicit tool names).export const routerExamples: RouterExample[] = [{- title: "HTML game",- prompt: "Code a minimal Flappy Bird game using HTML and Canvas",+ title: "Build a coding swarm",+ prompt: "Design a 5-agent coding swarm to refactor a Python CLI to TypeScript. Suggest topology, roles, and the order each agent should run.",followUps: [{- title: "README.md file",- prompt: "Create a comprehensive README.md for the Flappy Bird game project.",+ title: "Add tests",+ prompt: "Add a tester agent and a security-auditor. What should each one own?",},{- title: "CRT Screen",- prompt: "Add a CRT screen effect to the game",+ title: "Trade-offs",+ prompt: "Compare hierarchical vs mesh topology for this swarm.",},{- title: "Add power-ups",- prompt:- "Add collectible coins between pipes that award bonus points and a shield power-up that allows one collision.",- },- {- title: "Explain collision detection",- prompt:- "Explain the collision detection algorithm for the bird and pipes in simple terms with examples.",- },- ],- },- {- title: "Weird painting",- prompt: "is this a real painting?",- attachments: [- {- src: "huggingchat/castle-example.jpg",+ title: "Failure mode",+ prompt: "What happens if the architect agent fails halfway through?",},],},{- title: "Landing page",- prompt:- "Build a responsive SaaS landing page for my AI coding assitant using Tailwind CSS. With a hero, features, testimonials, and pricing sections.",+ title: "Memory & recall",+ prompt: "Explain how RuFlo's persistent memory works across sessions, and give me a 3-step example of saving a preference and recalling it later.",followUps: [{- title: "Dark mode",- prompt: "Add dark mode and make it the default",- },- {- title: "Write blog post",- prompt: "Write a blog post introducing my service.",- },- {- title: "Translate to Italian",- prompt: "Translate only the text content displayed to users into Italian.",+ title: "Namespaces",+ prompt: "When should I use separate memory namespaces vs one shared namespace?",},{- title: "Architecture review",- prompt:- "Review the architecture and suggest improvements for scalability, SEO optimization, and performance.",+ title: "Vector vs key",+ prompt: "When should I use semantic search vs exact key retrieval?",},],},{- title: "Eminem song",- prompt:- "Write an Eminem-style rap battling AI taking over hip-hop, with two energetic verses and a catchy hook.",+ title: "Plan a migration",+ prompt: "Plan a zero-downtime Postgres schema migration. Use Goal-Oriented Action Planning to break it into phases with rollback points.",followUps: [{- title: "Psychological analysis",- prompt: "Provide a psychological analysis of Eminem's emotions in this song.",- },- {- title: "Wired Article",- prompt: "Write an article in the style of Wired explaining this Eminem release.",- },- {- title: "Roleplay",- prompt: "Roleplay as Eminem so I can discuss the song with him.",+ title: "Risk scoring",+ prompt: "Which phases are highest-risk and how would you mitigate them?",},{- title: "Translate to Spanish",- prompt: "Translate the rap lyrics to Spanish while maintaining the rhyme scheme and flow.",+ title: "Verification",+ prompt: "How would you verify each phase before proceeding?",},],},{- title: "Act as Yoda",- prompt: "Act as Yoda",+ title: "Review a diff",+ prompt: "What signals would you use to risk-score a code diff (size, files touched, hot paths) and how would you suggest reviewers?",followUps: [{- title: "Give advice",- prompt:- "Continue acting as Yoda and offer three pieces of life advice for staying focused under pressure.",+ title: "Auto-classify",+ prompt: "Classify a diff as feature/bugfix/refactor/docs from its file mix and message.",},{- title: "Explain the Force",- prompt:- "In Yoda's voice, explain the concept of the Force to a young padawan using modern language.",- },- {- title: "Plain English",- prompt:- "Rewrite the previous response from Yoda into plain English while keeping the same meaning.",- },- {- title: "Compare philosophies",- prompt:- "Compare Yoda's Jedi philosophy to Stoic philosophy from ancient Greece and explain the similarities and differences.",+ title: "Security focus",+ prompt: "Which patterns in a diff should trigger a security review?",},],},{- title: "Generate prompts",- prompt: `Generate 5 creative prompts Text-to-image prompts like: "Cyberpunk cityscape at night, neon lights, flying cars, rain-slicked streets, blade runner aesthetic, highly detailed`,+ title: "Explain HNSW",+ prompt: "Explain HNSW vector indexing in plain language, and why it's 150x-12,500x faster than brute-force similarity search at scale.",followUps: [{- title: "Turn into JSON",- prompt: `Generate a detailed JSON object for each prompt. Include fields for subjects (list of objects), scene (setting, environment, background details), actions (what's happening), style (artistic style or medium)`,- },- {- title: "Sci-fi portraits",- prompt:- "Produce five futuristic character portrait prompts with unique professions and settings.",+ title: "Quantization",+ prompt: "What does Int8 quantization buy you, and what's the trade-off?",},{- title: "Explain image generation",- prompt:- "Explain how text-to-image diffusion models work, covering the denoising process and how text prompts guide generation.",+ title: "Use case",+ prompt: "When would you reach for HNSW vs a relational keyword index?",},],},{- title: "Explain LLMs",- prompt:- "Explain how large language models based on transformers work, covering attention, embeddings, and training objectives.",+ title: "Choose a topology",+ prompt: "I have 12 agents to coordinate on a multi-step refactor. Compare hierarchical, mesh, hierarchical-mesh, and adaptive topologies — pick one and explain why.",followUps: [{- title: "Generate a Quiz",- prompt: "Craft a 5-question multiple-choice quiz to validate what I learned.",- },- {- title: "Compare to RNNs",- prompt:- "Compare transformer-based large language models to recurrent neural networks, focusing on training efficiency and capabilities.",+ title: "Anti-drift",+ prompt: "What's 'anti-drift' coordination and why does it matter for >8 agents?",},{- title: "Student summary",- prompt:- "Summarize the explanation of large language models for a high school student using relatable analogies.",- },- {- title: "Write a blog post",- prompt:- "Write a blog post about how transformers revolutionized NLP, targeting software engineers who are new to AI.",+ title: "Consensus",+ prompt: "Compare Raft, Byzantine, gossip, and CRDT consensus for this swarm.",},],},{- title: "Translate in Italian",- prompt: `Translate in Italian: Some are born great, some achieve greatness, and some have greatness thrust upon 'em`,+ title: "Track a long task",+ prompt: "I'm starting a 4-week migration. How should I structure horizon tracking, milestone checkpoints, and drift detection in RuFlo?",followUps: [{- title: "Back to English",- prompt:- "Translate the Italian version back into English while keeping Shakespeare's tone intact.",- },- {- title: "Explain choices",- prompt: "Explain your translation choices for each key phrase from the Italian version.",- },- {- title: "Modernize",- prompt:- "Modernize the Italian translation into contemporary informal Italian suitable for social media.",- },- {- title: "Teach me Italian",- prompt:- "Help me practice Italian by conversing about this Shakespeare quote, correcting my grammar when needed.",+ title: "Resume after break",+ prompt: "What state should be persisted so I can resume next week?",},],},{- title: "Pelican on a bicycle",- prompt: "Draw an SVG of a pelican riding a bicycle",+ title: "Local WASM tools",+ prompt: "What's the difference between the in-browser WASM MCP server and the cloud bridge MCP servers? When should I use each?",followUps: [{- title: "Add a top hat",- prompt: "Add a fancy top hat to the pelican and make it look distinguished",+ title: "Privacy",+ prompt: "Which tools never leave my browser?",},{- title: "Make it animated",- prompt: "Add CSS animations to make the bicycle wheels spin and the pelican's wings flap",+ title: "Offline",+ prompt: "What can RuFlo still do if my network drops?",},],},diff --git a/ruflo/src/ruvocal/src/lib/constants/rvagentPresets.ts b/ruflo/src/ruvocal/src/lib/constants/rvagentPresets.tsnew file mode 100644index 0000000000..3107539e51--- /dev/null+++ b/ruflo/src/ruvocal/src/lib/constants/rvagentPresets.ts@@ -0,0 +1,206 @@+/**+ * rvAgent MCP Server Presets+ *+ * Pre-configured server configurations for the rvagent-mcp server+ * with different tool group combinations. These presets correspond+ * to the tool groups defined in ADR-112.+ *+ * Tool Groups:+ * - file: read, write, edit, ls, glob, grep+ * - shell: execute, bash+ * - memory: semantic_search, store, retrieve+ * - agent: spawn, status, orchestrate+ * - git: status, commit, diff, log+ * - web: fetch, search+ * - brain: search, share, vote (π Brain)+ * - task: create, list, complete+ * - core: ping, initialize (always included)+ */++export interface RvAgentPreset {+ /** Unique identifier for the preset */+ id: string;+ /** Display name */+ name: string;+ /** Short description */+ description: string;+ /** Tool groups to enable */+ groups: string[];+ /** Default port (user can override) */+ defaultPort: number;+ /** Icon/emoji for display */+ icon: string;+ /** Recommended use cases */+ useCases: string[];+}++/**+ * Pre-configured rvagent-mcp presets for common use cases+ */+export const RVAGENT_PRESETS: RvAgentPreset[] = [+ {+ id: "all-tools",+ name: "All Tools",+ description: "Full access to all 46+ rvAgent tools",+ groups: ["all"],+ defaultPort: 9000,+ icon: "🔧",+ useCases: ["Development", "Testing", "Full automation"],+ },+ {+ id: "file-shell",+ name: "File & Shell",+ description: "File operations and command execution",+ groups: ["file", "shell"],+ defaultPort: 9001,+ icon: "📂",+ useCases: ["Code editing", "Build scripts", "File management"],+ },+ {+ id: "memory-agent",+ name: "Memory & Agent",+ description: "Vector memory and multi-agent orchestration",+ groups: ["memory", "agent"],+ defaultPort: 9002,+ icon: "🧠",+ useCases: ["Knowledge retrieval", "Agent coordination", "RAG"],+ },+ {+ id: "git-web",+ name: "Git & Web",+ description: "Version control and web operations",+ groups: ["git", "web"],+ defaultPort: 9003,+ icon: "🌐",+ useCases: ["Code review", "Research", "Documentation"],+ },+ {+ id: "brain-task",+ name: "Brain & Tasks",+ description: "π Brain integration and task management",+ groups: ["brain", "task"],+ defaultPort: 9004,+ icon: "🎯",+ useCases: ["Knowledge sharing", "Task tracking", "Collaboration"],+ },+ {+ id: "dev-minimal",+ name: "Dev Minimal",+ description: "Essential development tools only",+ groups: ["file", "shell", "git"],+ defaultPort: 9005,+ icon: "💻",+ useCases: ["Quick edits", "Simple scripts", "Git operations"],+ },+ {+ id: "research",+ name: "Research Mode",+ description: "Memory, web search, and brain tools",+ groups: ["memory", "web", "brain"],+ defaultPort: 9006,+ icon: "🔬",+ useCases: ["Research", "Knowledge discovery", "Analysis"],+ },+ {+ id: "orchestration",+ name: "Orchestration",+ description: "Agent spawning and task coordination",+ groups: ["agent", "task", "memory"],+ defaultPort: 9007,+ icon: "🎭",+ useCases: ["Multi-agent workflows", "Complex tasks", "Automation"],+ },+];++/**+ * Get preset by ID+ */+export function getPresetById(id: string): RvAgentPreset | undefined {+ return RVAGENT_PRESETS.find((p) => p.id === id);+}++/**+ * Build the SSE URL for a preset+ */+export function buildPresetUrl(preset: RvAgentPreset, host = "localhost", port?: number): string {+ const actualPort = port ?? preset.defaultPort;+ return `http://${host}:${actualPort}/sse`;+}++/**+ * Build CLI command to start the server with preset configuration+ */+export function buildPresetCliCommand(preset: RvAgentPreset, port?: number): string {+ const actualPort = port ?? preset.defaultPort;+ const groupsArg = preset.groups.includes("all") ? "--all" : `--groups ${preset.groups.join(",")}`;++ return `rvagent-mcp --transport sse --port ${actualPort} ${groupsArg}`;+}++/**+ * Get all available tool group names+ */+export const TOOL_GROUPS = [+ "file",+ "shell",+ "memory",+ "agent",+ "git",+ "web",+ "brain",+ "task",+ "core",+] as const;++export type ToolGroupName = (typeof TOOL_GROUPS)[number];++/**+ * Tool group descriptions for UI display+ */+export const TOOL_GROUP_INFO: Record<ToolGroupName, { name: string; tools: string[]; icon: string }> = {+ file: {+ name: "File Operations",+ tools: ["read_file", "write_file", "edit_file", "ls", "glob", "grep"],+ icon: "📁",+ },+ shell: {+ name: "Shell Execution",+ tools: ["execute", "bash"],+ icon: "💻",+ },+ memory: {+ name: "Vector Memory",+ tools: ["semantic_search", "store_memory", "retrieve_memory"],+ icon: "🧠",+ },+ agent: {+ name: "Multi-Agent",+ tools: ["spawn_agent", "agent_status", "orchestrate"],+ icon: "🤖",+ },+ git: {+ name: "Version Control",+ tools: ["git_status", "git_commit", "git_diff", "git_log"],+ icon: "📦",+ },+ web: {+ name: "Web Operations",+ tools: ["web_fetch", "web_search"],+ icon: "🌐",+ },+ brain: {+ name: "π Brain",+ tools: ["brain_search", "brain_share", "brain_vote"],+ icon: "🧪",+ },+ task: {+ name: "Task Management",+ tools: ["create_task", "list_tasks", "complete_task"],+ icon: "✅",+ },+ core: {+ name: "Core Protocol",+ tools: ["ping", "initialize", "tools/list"],+ icon: "⚙️",+ },+};diff --git a/ruflo/src/ruvocal/src/lib/server/textGeneration/mcp/wasmTools.test.ts b/ruflo/src/ruvocal/src/lib/server/textGeneration/mcp/wasmTools.test.tsnew file mode 100644index 0000000000..006258ac17--- /dev/null+++ b/ruflo/src/ruvocal/src/lib/server/textGeneration/mcp/wasmTools.test.ts@@ -0,0 +1,633 @@+/**+ * Comprehensive WASM MCP Tools Test Suite+ * Tests all 15 rvAgent tools with edge cases and performance benchmarks+ */++import { describe, it, expect, beforeEach, afterEach } from "vitest";++// Import the tool execution state and function+// We'll need to create a test helper since the actual implementation is in toolInvocation.ts++// Mock implementations for testing+const createTestState = () => {+ const virtualFS = new Map<string, string>();+ const todoList: { id: string; task: string; completed: boolean; created: number }[] = [];+ let todoIdCounter = 1;+ const memoryStore = new Map<string, { key: string; value: string; tags: string[] }>();+ const witnessChain: { hash: string; prevHash: string; action: string; data: unknown; timestamp: number }[] = [];+ let lastWitnessHash = "genesis";++ const simpleHash = (data: string): string => {+ let hash = 0;+ for (let i = 0; i < data.length; i++) {+ const char = data.charCodeAt(i);+ hash = ((hash << 5) - hash) + char;+ hash = hash & hash;+ }+ return Math.abs(hash).toString(16).padStart(8, "0");+ };++ const addWitnessEntry = (action: string, data: unknown): string => {+ const entry = {+ hash: "",+ prevHash: lastWitnessHash,+ action,+ data,+ timestamp: Date.now(),+ };+ entry.hash = simpleHash(JSON.stringify(entry));+ witnessChain.push(entry);+ lastWitnessHash = entry.hash;+ return entry.hash;+ };++ const galleryTemplates = [+ { id: "development-agent", name: "Development Agent", category: "development", description: "Full-featured dev agent", tags: ["development", "coding", "files"] },+ { id: "research-agent", name: "Research Agent", category: "research", description: "Research & analysis agent", tags: ["research", "memory", "search"] },+ { id: "security-agent", name: "Security Agent", category: "security", description: "Security audit agent", tags: ["security", "audit", "compliance"] },+ { id: "multi-agent-orchestrator", name: "Multi-Agent Orchestrator", category: "orchestration", description: "Coordinate multiple agents", tags: ["orchestration", "parallel", "subagents"] },+ ];+ let activeTemplateId: string | null = null;++ const executeWasmTool = (+ toolName: string,+ args: Record<string, unknown>+ ): { success: boolean; result: string; error?: string } => {+ try {+ addWitnessEntry(`tool:${toolName}`, { args });++ switch (toolName) {+ // File Operations+ case "read_file": {+ const path = String(args.path || "");+ if (!path) return { success: false, result: "", error: "path is required" };+ const content = virtualFS.get(path);+ if (content === undefined) return { success: false, result: "", error: `File not found: ${path}` };+ return { success: true, result: content };+ }+ case "write_file": {+ const path = String(args.path || "");+ const content = String(args.content || "");+ if (!path) return { success: false, result: "", error: "path is required" };+ virtualFS.set(path, content);+ return { success: true, result: `Successfully wrote ${content.length} bytes to ${path}` };+ }+ case "list_files": {+ const files = Array.from(virtualFS.keys());+ if (files.length === 0) return { success: true, result: "No files in virtual filesystem" };+ return { success: true, result: `Files:\n${files.map(f => `- ${f}`).join("\n")}` };+ }+ case "delete_file": {+ const path = String(args.path || "");+ if (!path) return { success: false, result: "", error: "path is required" };+ if (!virtualFS.has(path)) return { success: false, result: "", error: `File not found: ${path}` };+ virtualFS.delete(path);+ return { success: true, result: `Deleted: ${path}` };+ }+ case "edit_file": {+ const path = String(args.path || "");+ const oldContent = String(args.old_content || args.oldContent || "");+ const newContent = String(args.new_content || args.newContent || "");+ if (!path) return { success: false, result: "", error: "path is required" };+ const existing = virtualFS.get(path);+ if (existing === undefined) return { success: false, result: "", error: `File not found: ${path}` };+ if (!existing.includes(oldContent)) return { success: false, result: "", error: `old_content not found in file` };+ virtualFS.set(path, existing.replace(oldContent, newContent));+ return { success: true, result: `Successfully edited ${path}` };+ }+ // Search Tools+ case "grep": {+ const pattern = String(args.pattern || "");+ const targetPath = args.path ? String(args.path) : null;+ if (!pattern) return { success: false, result: "", error: "pattern is required" };+ try {+ const regex = new RegExp(pattern, "gi");+ const results: string[] = [];+ for (const [filePath, content] of virtualFS.entries()) {+ if (targetPath && filePath !== targetPath) continue;+ const lines = content.split("\n");+ lines.forEach((line, idx) => {+ if (regex.test(line)) results.push(`${filePath}:${idx + 1}: ${line}`);+ });+ }+ return { success: true, result: results.length > 0 ? results.join("\n") : "No matches found" };+ } catch {+ return { success: false, result: "", error: `Invalid regex: ${pattern}` };+ }+ }+ case "glob": {+ const pattern = String(args.pattern || "");+ if (!pattern) return { success: false, result: "", error: "pattern is required" };+ const globPattern = pattern.replace(/\*/g, ".*").replace(/\?/g, ".");+ const regex = new RegExp(`^${globPattern}$`);+ const matches = Array.from(virtualFS.keys()).filter(f => regex.test(f));+ return { success: true, result: matches.length > 0 ? matches.join("\n") : "No matches found" };+ }+ // Task Management+ case "todo_add": {+ const task = String(args.task || "");+ if (!task) return { success: false, result: "", error: "task is required" };+ const id = `todo-${todoIdCounter++}`;+ todoList.push({ id, task, completed: false, created: Date.now() });+ return { success: true, result: `Added task: ${task} (id: ${id})` };+ }+ case "todo_list": {+ if (todoList.length === 0) return { success: true, result: "No tasks in todo list" };+ const formatted = todoList.map(t => `${t.completed ? "✓" : "○"} [${t.id}] ${t.task}`).join("\n");+ return { success: true, result: `Tasks:\n${formatted}` };+ }+ case "todo_complete": {+ const id = String(args.id || "");+ if (!id) return { success: false, result: "", error: "id is required" };+ const todo = todoList.find(t => t.id === id);+ if (!todo) return { success: false, result: "", error: `Task not found: ${id}` };+ todo.completed = true;+ return { success: true, result: `Completed: ${todo.task}` };+ }+ // Memory Tools+ case "memory_store": {+ const key = String(args.key || "");+ const value = String(args.value || "");+ if (!key || !value) return { success: false, result: "", error: "key and value are required" };+ const tags = Array.isArray(args.tags) ? args.tags.map(String) : [];+ memoryStore.set(key, { key, value, tags });+ return { success: true, result: `Stored memory: ${key}` };+ }+ case "memory_search": {+ const query = String(args.query || "").toLowerCase();+ if (!query) return { success: false, result: "", error: "query is required" };+ const topK = typeof args.top_k === "number" ? args.top_k : 5;+ const results = Array.from(memoryStore.values())+ .filter(m => m.key.toLowerCase().includes(query) || m.value.toLowerCase().includes(query) || m.tags.some(t => t.toLowerCase().includes(query)))+ .slice(0, topK)+ .map(m => `[${m.key}] ${m.value.slice(0, 100)}${m.value.length > 100 ? "..." : ""}`);+ return { success: true, result: results.length > 0 ? `Found ${results.length} results:\n${results.join("\n")}` : "No memories found" };+ }+ // Witness Chain+ case "witness_log": {+ const action = String(args.action || "");+ if (!action) return { success: false, result: "", error: "action is required" };+ const data = args.data || {};+ const hash = addWitnessEntry(action, data);+ return { success: true, result: `Logged to witness chain: ${action} (hash: ${hash})` };+ }+ case "witness_verify": {+ let valid = true;+ let prevHash = "genesis";+ for (const entry of witnessChain) {+ if (entry.prevHash !== prevHash) { valid = false; break; }+ prevHash = entry.hash;+ }+ return { success: true, result: `Witness chain: ${valid ? "VALID" : "INVALID"} (${witnessChain.length} entries)` };+ }+ // Gallery Tools+ case "gallery_list": {+ const category = args.category ? String(args.category) : null;+ const filtered = category ? galleryTemplates.filter(t => t.category === category) : galleryTemplates;+ const list = filtered.map(t => `- ${t.id}: ${t.name} (${t.category})`).join("\n");+ return { success: true, result: `Gallery Templates:\n${list}` };+ }+ case "gallery_load": {+ const id = String(args.id || "");+ if (!id) return { success: false, result: "", error: "id is required" };+ const template = galleryTemplates.find(t => t.id === id);+ if (!template) return { success: false, result: "", error: `Template not found: ${id}` };+ activeTemplateId = id;+ return { success: true, result: `Loaded template: ${template.name}\nDescription: ${template.description}` };+ }+ case "gallery_search": {+ const query = String(args.query || "").toLowerCase();+ if (!query) return { success: false, result: "", error: "query is required" };+ const matches = galleryTemplates.filter(t =>+ t.name.toLowerCase().includes(query) || t.description.toLowerCase().includes(query) || t.tags.some(tag => tag.toLowerCase().includes(query))+ );+ if (matches.length === 0) return { success: true, result: "No templates found" };+ const list = matches.map(t => `- ${t.id}: ${t.name}\n ${t.description}`).join("\n");+ return { success: true, result: `Found ${matches.length} templates:\n${list}` };+ }+ default:+ return { success: false, result: "", error: `Unknown tool: ${toolName}` };+ }+ } catch (e) {+ return { success: false, result: "", error: e instanceof Error ? e.message : String(e) };+ }+ };++ return {+ virtualFS,+ todoList,+ memoryStore,+ witnessChain,+ galleryTemplates,+ executeWasmTool,+ getActiveTemplateId: () => activeTemplateId,+ };+};++describe("WASM MCP Tools", () => {+ let state: ReturnType<typeof createTestState>;++ beforeEach(() => {+ state = createTestState();+ });++ // ================================+ // File Operations Tests+ // ================================+ describe("File Operations", () => {+ it("write_file creates a new file", () => {+ const result = state.executeWasmTool("write_file", { path: "test.txt", content: "Hello World" });+ expect(result.success).toBe(true);+ expect(result.result).toContain("11 bytes");+ expect(state.virtualFS.get("test.txt")).toBe("Hello World");+ });++ it("read_file reads existing file", () => {+ state.virtualFS.set("test.txt", "Hello World");+ const result = state.executeWasmTool("read_file", { path: "test.txt" });+ expect(result.success).toBe(true);+ expect(result.result).toBe("Hello World");+ });++ it("read_file returns error for non-existent file", () => {+ const result = state.executeWasmTool("read_file", { path: "nonexistent.txt" });+ expect(result.success).toBe(false);+ expect(result.error).toContain("File not found");+ });++ it("list_files returns empty message when no files", () => {+ const result = state.executeWasmTool("list_files", {});+ expect(result.success).toBe(true);+ expect(result.result).toContain("No files");+ });++ it("list_files shows all files", () => {+ state.virtualFS.set("a.txt", "A");+ state.virtualFS.set("b.txt", "B");+ const result = state.executeWasmTool("list_files", {});+ expect(result.success).toBe(true);+ expect(result.result).toContain("a.txt");+ expect(result.result).toContain("b.txt");+ });++ it("delete_file removes existing file", () => {+ state.virtualFS.set("test.txt", "content");+ const result = state.executeWasmTool("delete_file", { path: "test.txt" });+ expect(result.success).toBe(true);+ expect(state.virtualFS.has("test.txt")).toBe(false);+ });++ it("delete_file returns error for non-existent file", () => {+ const result = state.executeWasmTool("delete_file", { path: "nonexistent.txt" });+ expect(result.success).toBe(false);+ expect(result.error).toContain("File not found");+ });++ it("edit_file replaces content", () => {+ state.virtualFS.set("test.txt", "Hello World");+ const result = state.executeWasmTool("edit_file", { path: "test.txt", old_content: "World", new_content: "Universe" });+ expect(result.success).toBe(true);+ expect(state.virtualFS.get("test.txt")).toBe("Hello Universe");+ });++ it("edit_file returns error when old_content not found", () => {+ state.virtualFS.set("test.txt", "Hello World");+ const result = state.executeWasmTool("edit_file", { path: "test.txt", old_content: "NOTFOUND", new_content: "X" });+ expect(result.success).toBe(false);+ expect(result.error).toContain("old_content not found");+ });++ it("handles files with special characters in content", () => {+ const content = "Line1\nLine2\tTab\r\nWindows\n日本語\n🎉";+ state.executeWasmTool("write_file", { path: "special.txt", content });+ const result = state.executeWasmTool("read_file", { path: "special.txt" });+ expect(result.success).toBe(true);+ expect(result.result).toBe(content);+ });++ it("handles empty file content", () => {+ state.executeWasmTool("write_file", { path: "empty.txt", content: "" });+ const result = state.executeWasmTool("read_file", { path: "empty.txt" });+ expect(result.success).toBe(true);+ expect(result.result).toBe("");+ });++ it("handles paths with directories", () => {+ state.executeWasmTool("write_file", { path: "src/lib/file.ts", content: "export {}" });+ const result = state.executeWasmTool("read_file", { path: "src/lib/file.ts" });+ expect(result.success).toBe(true);+ expect(result.result).toBe("export {}");+ });+ });++ // ================================+ // Search Tools Tests+ // ================================+ describe("Search Tools", () => {+ beforeEach(() => {+ state.virtualFS.set("src/index.ts", "import { foo } from './foo';\nexport const bar = 42;");+ state.virtualFS.set("src/foo.ts", "export const foo = 'hello';\nexport const FOO = 'WORLD';");+ state.virtualFS.set("README.md", "# Project\n\nThis is a test project.");+ });++ it("grep finds pattern in files", () => {+ const result = state.executeWasmTool("grep", { pattern: "foo" });+ expect(result.success).toBe(true);+ expect(result.result).toContain("src/index.ts");+ expect(result.result).toContain("src/foo.ts");+ });++ it("grep searches specific file", () => {+ const result = state.executeWasmTool("grep", { pattern: "export", path: "src/foo.ts" });+ expect(result.success).toBe(true);+ expect(result.result).toContain("src/foo.ts");+ expect(result.result).not.toContain("src/index.ts");+ });++ it("grep returns no matches message", () => {+ const result = state.executeWasmTool("grep", { pattern: "NOTFOUND" });+ expect(result.success).toBe(true);+ expect(result.result).toBe("No matches found");+ });++ it("grep supports regex patterns", () => {+ const result = state.executeWasmTool("grep", { pattern: "\\d+" });+ expect(result.success).toBe(true);+ expect(result.result).toContain("42");+ });++ it("grep handles invalid regex", () => {+ const result = state.executeWasmTool("grep", { pattern: "[invalid" });+ expect(result.success).toBe(false);+ expect(result.error).toContain("Invalid regex");+ });++ it("glob finds matching files", () => {+ const result = state.executeWasmTool("glob", { pattern: "*.ts" });+ expect(result.success).toBe(true);+ // Note: our simple glob implementation requires full path match+ });++ it("glob returns no matches for non-matching pattern", () => {+ const result = state.executeWasmTool("glob", { pattern: "*.xyz" });+ expect(result.success).toBe(true);+ expect(result.result).toBe("No matches found");+ });+ });++ // ================================+ // Task Management Tests+ // ================================+ describe("Task Management", () => {+ it("todo_add creates new task", () => {+ const result = state.executeWasmTool("todo_add", { task: "Write tests" });+ expect(result.success).toBe(true);+ expect(result.result).toContain("todo-1");+ expect(state.todoList).toHaveLength(1);+ });++ it("todo_list shows empty when no tasks", () => {+ const result = state.executeWasmTool("todo_list", {});+ expect(result.success).toBe(true);+ expect(result.result).toContain("No tasks");+ });++ it("todo_list shows all tasks", () => {+ state.executeWasmTool("todo_add", { task: "Task 1" });+ state.executeWasmTool("todo_add", { task: "Task 2" });+ const result = state.executeWasmTool("todo_list", {});+ expect(result.success).toBe(true);+ expect(result.result).toContain("Task 1");+ expect(result.result).toContain("Task 2");+ expect(result.result).toContain("○"); // uncompleted+ });++ it("todo_complete marks task as done", () => {+ state.executeWasmTool("todo_add", { task: "Task 1" });+ const completeResult = state.executeWasmTool("todo_complete", { id: "todo-1" });+ expect(completeResult.success).toBe(true);++ const listResult = state.executeWasmTool("todo_list", {});+ expect(listResult.result).toContain("✓");+ });++ it("todo_complete returns error for invalid id", () => {+ const result = state.executeWasmTool("todo_complete", { id: "todo-999" });+ expect(result.success).toBe(false);+ expect(result.error).toContain("Task not found");+ });+ });++ // ================================+ // Memory Tools Tests+ // ================================+ describe("Memory Tools", () => {+ it("memory_store saves entry", () => {+ const result = state.executeWasmTool("memory_store", { key: "pattern-1", value: "Use async/await" });+ expect(result.success).toBe(true);+ expect(state.memoryStore.has("pattern-1")).toBe(true);+ });++ it("memory_store with tags", () => {+ const result = state.executeWasmTool("memory_store", { key: "pattern-2", value: "Error handling", tags: ["best-practice", "async"] });+ expect(result.success).toBe(true);+ const stored = state.memoryStore.get("pattern-2");+ expect(stored?.tags).toContain("best-practice");+ });++ it("memory_search finds matching entries", () => {+ state.executeWasmTool("memory_store", { key: "auth-pattern", value: "JWT tokens for authentication" });+ state.executeWasmTool("memory_store", { key: "cache-pattern", value: "Use Redis for caching" });++ const result = state.executeWasmTool("memory_search", { query: "auth" });+ expect(result.success).toBe(true);+ expect(result.result).toContain("auth-pattern");+ expect(result.result).not.toContain("cache-pattern");+ });++ it("memory_search respects top_k limit", () => {+ for (let i = 0; i < 10; i++) {+ state.executeWasmTool("memory_store", { key: `test-${i}`, value: `Test value ${i}` });+ }+ const result = state.executeWasmTool("memory_search", { query: "test", top_k: 3 });+ expect(result.success).toBe(true);+ expect(result.result).toContain("Found 3 results");+ });++ it("memory_search returns no matches message", () => {+ const result = state.executeWasmTool("memory_search", { query: "nonexistent" });+ expect(result.success).toBe(true);+ expect(result.result).toBe("No memories found");+ });++ it("memory_search searches by tags", () => {+ state.executeWasmTool("memory_store", { key: "p1", value: "Value", tags: ["security", "critical"] });+ const result = state.executeWasmTool("memory_search", { query: "security" });+ expect(result.success).toBe(true);+ expect(result.result).toContain("p1");+ });+ });++ // ================================+ // Witness Chain Tests+ // ================================+ describe("Witness Chain", () => {+ it("witness_log creates entry", () => {+ const result = state.executeWasmTool("witness_log", { action: "file_created", data: { path: "test.txt" } });+ expect(result.success).toBe(true);+ expect(result.result).toContain("hash:");+ // Chain includes tool calls + explicit log+ expect(state.witnessChain.length).toBeGreaterThan(0);+ });++ it("witness_verify validates chain integrity", () => {+ state.executeWasmTool("witness_log", { action: "action1" });+ state.executeWasmTool("witness_log", { action: "action2" });+ const result = state.executeWasmTool("witness_verify", {});+ expect(result.success).toBe(true);+ expect(result.result).toContain("VALID");+ });++ it("all tool calls are logged to witness chain", () => {+ const initialLength = state.witnessChain.length;+ state.executeWasmTool("write_file", { path: "a.txt", content: "A" });+ state.executeWasmTool("read_file", { path: "a.txt" });+ expect(state.witnessChain.length).toBe(initialLength + 2);+ });++ it("witness chain hash linking is correct", () => {+ state.executeWasmTool("witness_log", { action: "a1" });+ state.executeWasmTool("witness_log", { action: "a2" });++ const chain = state.witnessChain;+ for (let i = 1; i < chain.length; i++) {+ expect(chain[i].prevHash).toBe(chain[i - 1].hash);+ }+ });+ });++ // ================================+ // Gallery Tools Tests+ // ================================+ describe("Gallery Tools", () => {+ it("gallery_list shows all templates", () => {+ const result = state.executeWasmTool("gallery_list", {});+ expect(result.success).toBe(true);+ expect(result.result).toContain("development-agent");+ expect(result.result).toContain("research-agent");+ });++ it("gallery_list filters by category", () => {+ const result = state.executeWasmTool("gallery_list", { category: "security" });+ expect(result.success).toBe(true);+ expect(result.result).toContain("security-agent");+ expect(result.result).not.toContain("development-agent");+ });++ it("gallery_load activates template", () => {+ const result = state.executeWasmTool("gallery_load", { id: "development-agent" });+ expect(result.success).toBe(true);+ expect(result.result).toContain("Development Agent");+ expect(state.getActiveTemplateId()).toBe("development-agent");+ });++ it("gallery_load returns error for invalid id", () => {+ const result = state.executeWasmTool("gallery_load", { id: "nonexistent" });+ expect(result.success).toBe(false);+ expect(result.error).toContain("Template not found");+ });++ it("gallery_search finds by name", () => {+ const result = state.executeWasmTool("gallery_search", { query: "research" });+ expect(result.success).toBe(true);+ expect(result.result).toContain("research-agent");+ });++ it("gallery_search finds by tags", () => {+ const result = state.executeWasmTool("gallery_search", { query: "coding" });+ expect(result.success).toBe(true);+ expect(result.result).toContain("development-agent");+ });++ it("gallery_search returns no matches message", () => {+ const result = state.executeWasmTool("gallery_search", { query: "xyz123" });+ expect(result.success).toBe(true);+ expect(result.result).toContain("No templates found");+ });+ });++ // ================================+ // Edge Cases & Error Handling+ // ================================+ describe("Edge Cases", () => {+ it("handles missing required parameters", () => {+ expect(state.executeWasmTool("read_file", {}).success).toBe(false);+ expect(state.executeWasmTool("write_file", { path: "x" }).success).toBe(true); // content defaults to ""+ expect(state.executeWasmTool("todo_add", {}).success).toBe(false);+ expect(state.executeWasmTool("memory_store", { key: "k" }).success).toBe(false);+ });++ it("handles unknown tool names", () => {+ const result = state.executeWasmTool("unknown_tool", {});+ expect(result.success).toBe(false);+ expect(result.error).toContain("Unknown tool");+ });++ it("handles large file content", () => {+ const largeContent = "x".repeat(1000000); // 1MB+ const writeResult = state.executeWasmTool("write_file", { path: "large.txt", content: largeContent });+ expect(writeResult.success).toBe(true);++ const readResult = state.executeWasmTool("read_file", { path: "large.txt" });+ expect(readResult.success).toBe(true);+ expect(readResult.result.length).toBe(1000000);+ });++ it("handles concurrent-like operations", () => {+ // Simulate multiple operations+ for (let i = 0; i < 100; i++) {+ state.executeWasmTool("write_file", { path: `file${i}.txt`, content: `content${i}` });+ }+ const listResult = state.executeWasmTool("list_files", {});+ expect(listResult.success).toBe(true);+ expect(state.virtualFS.size).toBe(100);+ });+ });++ // ================================+ // Performance Benchmarks+ // ================================+ describe("Performance", () => {+ it("file operations complete in under 1ms", () => {+ const start = performance.now();+ for (let i = 0; i < 100; i++) {+ state.executeWasmTool("write_file", { path: `perf${i}.txt`, content: "test" });+ }+ const duration = performance.now() - start;+ expect(duration).toBeLessThan(100); // 100 ops in <100ms = <1ms each+ });++ it("memory search scales with O(n)", () => {+ // Insert 1000 entries+ for (let i = 0; i < 1000; i++) {+ state.executeWasmTool("memory_store", { key: `key-${i}`, value: `value-${i}` });+ }++ const start = performance.now();+ for (let i = 0; i < 10; i++) {+ state.executeWasmTool("memory_search", { query: "key-500" });+ }+ const duration = performance.now() - start;+ expect(duration).toBeLessThan(100); // 10 searches in <100ms+ });++ it("witness chain grows correctly", () => {+ const initialLength = state.witnessChain.length;+ // Each witness_log creates 2 entries: one for the tool call audit + one for the explicit log+ for (let i = 0; i < 100; i++) {+ state.executeWasmTool("witness_log", { action: `action-${i}` });+ }+ expect(state.witnessChain.length).toBe(initialLength + 200); // 100 calls * 2 entries each+ });+ });+});diff --git a/ruflo/src/ruvocal/src/lib/stores/mcpServers.ts b/ruflo/src/ruvocal/src/lib/stores/mcpServers.tsindex 8ce5f38ff6..02c89cd5a0 100644--- a/ruflo/src/ruvocal/src/lib/stores/mcpServers.ts+++ b/ruflo/src/ruvocal/src/lib/stores/mcpServers.ts@@ -1,7 +1,8 @@/*** MCP Servers Store- * Manages base (env-configured) and custom (user-added) MCP servers+ * Manages base (env-configured), custom (user-added), and WASM (browser-local) MCP servers* Stores custom servers and selection state in browser localStorage+ * WASM servers run entirely in-browser via rvagent-wasm with IndexedDB persistence*/import { writable, derived, get } from "svelte/store";@@ -9,6 +10,13 @@ import { base } from "$app/paths";import { env as publicEnv } from "$env/dynamic/public";import { browser } from "$app/environment";import type { MCPServer, ServerStatus, MCPTool } from "$lib/types/Tool";+import {+ initWasmMcp,+ callMcp as callWasmMcp,+ listGalleryTemplates,+ loadGalleryTemplate,+ activeTemplate,+} from "./wasmMcp";// Namespace storage by app identity to avoid collisions across appsfunction toKeyPart(s: string | undefined): string {@@ -26,6 +34,22 @@ const STORAGE_KEYS = {DISABLED_BASE_IDS: `${KEY_PREFIX}:mcp:disabled-base-ids`,} as const;+// WASM MCP Server ID (constant, always available)+export const WASM_SERVER_ID = "wasm-rvagent";++// Create the WASM MCP server entry+function createWasmServer(): MCPServer {+ return {+ id: WASM_SERVER_ID,+ name: "RVAgent Local (WASM)",+ url: "wasm://local",+ type: "wasm",+ status: "disconnected",+ isLocked: false,+ tools: [],+ };+}+// No migration needed per request — read/write only namespaced keys// Load custom servers from localStorage@@ -138,7 +162,7 @@ export const allBaseServersEnabled = derived(// is applied server-side when enabled via MCP_FORWARD_HF_USER_TOKEN./**- * Refresh base servers from API and merge with custom servers+ * Refresh base servers from API and merge with custom servers + WASM server*/export async function refreshMcpServers() {try {@@ -150,8 +174,11 @@ export async function refreshMcpServers() {const baseServers: MCPServer[] = await response.json();const customServers = loadCustomServers();- // Merge base and custom servers- const merged = [...baseServers, ...customServers];+ // Create WASM server and add to the list+ const wasmServer = createWasmServer();++ // Merge base, custom, and WASM servers+ const merged = [wasmServer, ...baseServers, ...customServers];allMcpServers.set(merged);// Load disabled base servers@@ -159,10 +186,14 @@ export async function refreshMcpServers() {// Auto-enable all base servers that aren't explicitly disabled// Plus keep any custom servers that were previously selected+ // WASM server is auto-enabled by defaultconst validIds = new Set(merged.map((s) => s.id));selectedServerIds.update(($currentIds) => {const newSelection = new Set<string>();+ // Auto-enable WASM server+ newSelection.add(WASM_SERVER_ID);+// Add all base servers that aren't disabledfor (const server of baseServers) {if (!disabledBaseIds.has(server.id)) {@@ -180,11 +211,70 @@ export async function refreshMcpServers() {return newSelection;});mcpServersLoaded.set(true);++ // Initialize WASM MCP server in background+ initWasmServer();} catch (error) {console.error("Failed to refresh MCP servers:", error);- // On error, just use custom servers- allMcpServers.set(loadCustomServers());+ // On error, use custom servers + WASM server+ const wasmServer = createWasmServer();+ allMcpServers.set([wasmServer, ...loadCustomServers()]);mcpServersLoaded.set(true);++ // Still try to init WASM+ initWasmServer();+ }+}++/**+ * Initialize the WASM MCP server+ */+async function initWasmServer() {+ if (!browser) return;++ updateServerStatus(WASM_SERVER_ID, "connecting");++ try {+ const success = await initWasmMcp();++ if (success) {+ // Get tools from WASM server+ const toolsResponse = await callWasmMcp("tools/list");+ const tools: MCPTool[] = [];++ if (!toolsResponse.error && toolsResponse.result) {+ const result = toolsResponse.result as { tools: MCPTool[] };+ if (result.tools) {+ tools.push(...result.tools);+ }+ }++ // Get active template info+ const template = get(activeTemplate);++ updateServerStatus(WASM_SERVER_ID, "connected", undefined, tools);++ // Update template info+ allMcpServers.update(($servers) =>+ $servers.map((s) =>+ s.id === WASM_SERVER_ID+ ? {+ ...s,+ wasmTemplateId: template.id || undefined,+ wasmTemplateName: template.name || undefined,+ }+ : s+ )+ );++ console.log(`[MCP] WASM server initialized with ${tools.length} tools`);+ } else {+ updateServerStatus(WASM_SERVER_ID, "error", "Failed to load WASM module");+ }+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : "Unknown error";+ updateServerStatus(WASM_SERVER_ID, "error", errorMessage);+ console.error("[MCP] WASM server initialization failed:", error);}}@@ -314,6 +404,11 @@ export function updateServerStatus(export async function healthCheckServer(server: MCPServer): Promise<{ ready: boolean; tools?: MCPTool[]; error?: string }> {+ // Handle WASM servers locally+ if (server.type === "wasm") {+ return healthCheckWasmServer();+ }+try {updateServerStatus(server.id, "connecting");@@ -339,6 +434,100 @@ export async function healthCheckServer(}}+/**+ * Health check for WASM MCP server (runs locally)+ */+async function healthCheckWasmServer(): Promise<{ ready: boolean; tools?: MCPTool[]; error?: string }> {+ try {+ updateServerStatus(WASM_SERVER_ID, "connecting");++ const success = await initWasmMcp();++ if (!success) {+ updateServerStatus(WASM_SERVER_ID, "error", "Failed to load WASM module");+ return { ready: false, error: "Failed to load WASM module" };+ }++ // Get tools from WASM server+ const toolsResponse = await callWasmMcp("tools/list");+ const tools: MCPTool[] = [];++ if (!toolsResponse.error && toolsResponse.result) {+ const result = toolsResponse.result as { tools: MCPTool[] };+ if (result.tools) {+ tools.push(...result.tools);+ }+ }++ // Get active template info+ const template = get(activeTemplate);++ updateServerStatus(WASM_SERVER_ID, "connected", undefined, tools);++ // Update template info+ allMcpServers.update(($servers) =>+ $servers.map((s) =>+ s.id === WASM_SERVER_ID+ ? {+ ...s,+ wasmTemplateId: template.id || undefined,+ wasmTemplateName: template.name || undefined,+ }+ : s+ )+ );++ return { ready: true, tools };+ } catch (error) {+ const errorMessage = error instanceof Error ? error.message : "Unknown error";+ updateServerStatus(WASM_SERVER_ID, "error", errorMessage);+ return { ready: false, error: errorMessage };+ }+}++/**+ * Load a gallery template for the WASM MCP server+ */+export async function loadWasmTemplate(templateId: string): Promise<boolean> {+ try {+ const success = await loadGalleryTemplate(templateId);++ if (success) {+ // Refresh tools after loading template+ await healthCheckWasmServer();+ return true;+ }++ return false;+ } catch (error) {+ console.error("[MCP] Failed to load WASM template:", error);+ return false;+ }+}++/**+ * Get available gallery templates for WASM server+ */+export function getWasmGalleryTemplates() {+ return listGalleryTemplates();+}++/**+ * Execute a tool on the WASM MCP server+ */+export async function executeWasmTool(+ name: string,+ args: Record<string, unknown>+): Promise<{ success: boolean; result?: unknown; error?: string }> {+ const response = await callWasmMcp("tools/call", { name, arguments: args });++ if (response.error) {+ return { success: false, error: response.error.message };+ }++ return { success: true, result: response.result };+}+// Initialize on module loadif (browser) {refreshMcpServers();diff --git a/ruflo/src/ruvocal/src/lib/stores/wasmMcp.ts b/ruflo/src/ruvocal/src/lib/stores/wasmMcp.tsnew file mode 100644index 0000000000..1991de7be9--- /dev/null+++ b/ruflo/src/ruvocal/src/lib/stores/wasmMcp.ts@@ -0,0 +1,454 @@+/**+ * WASM MCP Server Store+ * Provides a local, browser-based MCP server using rvagent-wasm+ * with IndexedDB persistence for the virtual filesystem+ */++import { writable, derived, get } from "svelte/store";+import { browser } from "$app/environment";+import { loadWasm, isWasmLoaded, getWasm } from "$lib/wasm";+import type { WasmMcpServer, WasmGallery, GalleryTemplate, SearchResult } from "$lib/wasm";+import * as idb from "$lib/wasm/idb";++// Store state types+interface WasmMcpState {+ loaded: boolean;+ loading: boolean;+ error: string | null;+ mcpServer: WasmMcpServer | null;+ gallery: WasmGallery | null;+ activeTemplateId: string | null;+ activeTemplateName: string | null;+}++interface JsonRpcRequest {+ jsonrpc: "2.0";+ id: number | string | null;+ method: string;+ params?: unknown;+}++interface JsonRpcResponse {+ jsonrpc: "2.0";+ id: number | string | null;+ result?: unknown;+ error?: {+ code: number;+ message: string;+ data?: unknown;+ };+}++// Initial state+const initialState: WasmMcpState = {+ loaded: false,+ loading: false,+ error: null,+ mcpServer: null,+ gallery: null,+ activeTemplateId: null,+ activeTemplateName: null,+};++// Create the store+const wasmMcpState = writable<WasmMcpState>(initialState);++// Derived stores for convenience+export const wasmLoaded = derived(wasmMcpState, ($state) => $state.loaded);+export const wasmLoading = derived(wasmMcpState, ($state) => $state.loading);+export const wasmError = derived(wasmMcpState, ($state) => $state.error);+export const activeTemplate = derived(wasmMcpState, ($state) => ({+ id: $state.activeTemplateId,+ name: $state.activeTemplateName,+}));++// Request ID counter+let requestId = 0;++/**+ * Initialize the WASM MCP server+ */+export async function initWasmMcp(): Promise<boolean> {+ if (!browser) return false;++ const state = get(wasmMcpState);+ if (state.loaded || state.loading) return state.loaded;++ wasmMcpState.update((s) => ({ ...s, loading: true, error: null }));++ try {+ // Load WASM module+ const wasm = await loadWasm();+ if (!wasm) {+ throw new Error("Failed to load WASM module");+ }++ // Create MCP server and gallery instances+ const mcpServer = new wasm.WasmMcpServer();+ const gallery = new wasm.WasmGallery();++ // Initialize the MCP server+ const initResponse = callMcpInternal(mcpServer, "initialize", {+ protocolVersion: "2024-11-05",+ clientInfo: { name: "ruvocal-ui", version: "1.0.0" },+ });++ if (initResponse.error) {+ throw new Error(`MCP initialization failed: ${initResponse.error.message}`);+ }++ // Load persisted filesystem state from IndexedDB+ await syncFromIndexedDB(mcpServer);++ // Check for persisted active template+ const savedTemplateId = await idb.getSetting<string>("activeTemplateId");+ let templateName: string | null = null;++ if (savedTemplateId) {+ try {+ const template = gallery.get(savedTemplateId);+ gallery.setActive(savedTemplateId);+ templateName = template.name;+ } catch {+ // Template not found, ignore+ }+ }++ wasmMcpState.set({+ loaded: true,+ loading: false,+ error: null,+ mcpServer,+ gallery,+ activeTemplateId: savedTemplateId,+ activeTemplateName: templateName,+ });++ console.log("[WASM MCP] Server initialized successfully");+ return true;+ } catch (error) {+ const errorMsg = error instanceof Error ? error.message : "Unknown error";+ wasmMcpState.update((s) => ({+ ...s,+ loading: false,+ error: errorMsg,+ }));+ console.error("[WASM MCP] Initialization failed:", error);+ return false;+ }+}++/**+ * Internal MCP call helper+ */+function callMcpInternal(+ mcpServer: WasmMcpServer,+ method: string,+ params?: unknown+): JsonRpcResponse {+ const request: JsonRpcRequest = {+ jsonrpc: "2.0",+ id: ++requestId,+ method,+ params,+ };++ const responseJson = mcpServer.handle_message(JSON.stringify(request));+ return JSON.parse(responseJson) as JsonRpcResponse;+}++/**+ * Call an MCP method on the WASM server+ */+export async function callMcp(method: string, params?: unknown): Promise<JsonRpcResponse> {+ const state = get(wasmMcpState);++ if (!state.loaded || !state.mcpServer) {+ return {+ jsonrpc: "2.0",+ id: null,+ error: { code: -32603, message: "WASM MCP server not initialized" },+ };+ }++ const response = callMcpInternal(state.mcpServer, method, params);++ // Persist file changes to IndexedDB+ if (method === "tools/call" && response.result) {+ const toolParams = params as { name: string; arguments?: Record<string, unknown> };+ if (+ ["write_file", "edit_file", "delete_file"].includes(toolParams.name) &&+ !response.error+ ) {+ await syncToIndexedDB(state.mcpServer);+ }+ }++ return response;+}++/**+ * Execute a tool via MCP+ */+export async function executeTool(+ name: string,+ args: Record<string, unknown>+): Promise<{ success: boolean; result?: unknown; error?: string }> {+ const response = await callMcp("tools/call", { name, arguments: args });++ if (response.error) {+ return { success: false, error: response.error.message };+ }++ return { success: true, result: response.result };+}++/**+ * List available MCP tools+ */+export async function listTools(): Promise<+ Array<{ name: string; description: string; inputSchema: unknown }>+> {+ const response = await callMcp("tools/list");++ if (response.error || !response.result) {+ return [];+ }++ const result = response.result as { tools: Array<{ name: string; description: string; inputSchema: unknown }> };+ return result.tools || [];+}++/**+ * Get available prompts from active template+ */+export async function listPrompts(): Promise<Array<{ name: string; description: string }>> {+ const response = await callMcp("prompts/list");++ if (response.error || !response.result) {+ return [];+ }++ const result = response.result as { prompts: Array<{ name: string; description: string }> };+ return result.prompts || [];+}++// ---------------------------------------------------------------------------+// Gallery Operations+// ---------------------------------------------------------------------------++/**+ * List all gallery templates+ */+export function listGalleryTemplates(): GalleryTemplate[] {+ const state = get(wasmMcpState);+ if (!state.gallery) return [];++ try {+ return state.gallery.list() as unknown as GalleryTemplate[];+ } catch {+ return [];+ }+}++/**+ * Search gallery templates+ */+export function searchGalleryTemplates(query: string): SearchResult[] {+ const state = get(wasmMcpState);+ if (!state.gallery) return [];++ try {+ return state.gallery.search(query) as unknown as SearchResult[];+ } catch {+ return [];+ }+}++/**+ * Get a gallery template by ID+ */+export function getGalleryTemplate(id: string): GalleryTemplate | null {+ const state = get(wasmMcpState);+ if (!state.gallery) return null;++ try {+ return state.gallery.get(id) as unknown as GalleryTemplate;+ } catch {+ return null;+ }+}++/**+ * Load a gallery template as active+ */+export async function loadGalleryTemplate(id: string): Promise<boolean> {+ const state = get(wasmMcpState);+ if (!state.gallery || !state.mcpServer) return false;++ try {+ // Load via MCP (sets active in both gallery and MCP server)+ const response = await callMcp("gallery/load", { id });++ if (response.error) {+ console.error("[WASM MCP] Failed to load template:", response.error.message);+ return false;+ }++ const result = response.result as { template_id: string; name: string };++ // Update store state+ wasmMcpState.update((s) => ({+ ...s,+ activeTemplateId: result.template_id,+ activeTemplateName: result.name,+ }));++ // Persist to IndexedDB+ await idb.setSetting("activeTemplateId", result.template_id);++ console.log(`[WASM MCP] Loaded template: ${result.name}`);+ return true;+ } catch (error) {+ console.error("[WASM MCP] Failed to load template:", error);+ return false;+ }+}++/**+ * Get gallery categories with counts+ */+export function getGalleryCategories(): Record<string, number> {+ const state = get(wasmMcpState);+ if (!state.gallery) return {};++ try {+ return state.gallery.getCategories() as unknown as Record<string, number>;+ } catch {+ return {};+ }+}++/**+ * Load a template as RVF bytes and save to IndexedDB+ */+export async function saveTemplateAsRvf(templateId: string): Promise<string | null> {+ const state = get(wasmMcpState);+ if (!state.gallery) return null;++ try {+ const template = state.gallery.get(templateId);+ const rvfBytes = state.gallery.loadRvf(templateId);++ const containerId = crypto.randomUUID();+ await idb.saveRvfContainer(containerId, template.name, rvfBytes, templateId);++ console.log(`[WASM MCP] Saved RVF container: ${containerId}`);+ return containerId;+ } catch (error) {+ console.error("[WASM MCP] Failed to save RVF:", error);+ return null;+ }+}++// ---------------------------------------------------------------------------+// IndexedDB Sync+// ---------------------------------------------------------------------------++/**+ * Sync virtual filesystem from IndexedDB to WASM backend+ */+async function syncFromIndexedDB(mcpServer: WasmMcpServer): Promise<void> {+ try {+ const files = await idb.listFiles();++ for (const file of files) {+ callMcpInternal(mcpServer, "tools/call", {+ name: "write_file",+ arguments: { path: file.path, content: file.content },+ });+ }++ console.log(`[WASM MCP] Synced ${files.length} files from IndexedDB`);+ } catch (error) {+ console.error("[WASM MCP] Failed to sync from IndexedDB:", error);+ }+}++/**+ * Sync virtual filesystem from WASM backend to IndexedDB+ */+async function syncToIndexedDB(mcpServer: WasmMcpServer): Promise<void> {+ try {+ // List all files in WASM backend+ const listResponse = callMcpInternal(mcpServer, "tools/call", {+ name: "list_files",+ arguments: {},+ });++ if (listResponse.error || !listResponse.result) return;++ const result = listResponse.result as { content: Array<{ text: string }> };+ const filesContent = result.content?.[0]?.text;+ if (!filesContent) return;++ const wasmFiles = JSON.parse(filesContent) as string[];++ // Get current IndexedDB files+ const idbFiles = await idb.listFiles();+ const idbPaths = new Set(idbFiles.map((f) => f.path));++ // Sync each file+ for (const path of wasmFiles) {+ const readResponse = callMcpInternal(mcpServer, "tools/call", {+ name: "read_file",+ arguments: { path },+ });++ if (!readResponse.error && readResponse.result) {+ const readResult = readResponse.result as { content: Array<{ text: string }> };+ const content = readResult.content?.[0]?.text;+ if (content) {+ await idb.writeFile(path, content);+ idbPaths.delete(path);+ }+ }+ }++ // Remove files that no longer exist in WASM backend+ for (const path of idbPaths) {+ await idb.deleteFile(path);+ }++ console.log(`[WASM MCP] Synced ${wasmFiles.length} files to IndexedDB`);+ } catch (error) {+ console.error("[WASM MCP] Failed to sync to IndexedDB:", error);+ }+}++/**+ * Force full sync to IndexedDB+ */+export async function forceSyncToIndexedDB(): Promise<void> {+ const state = get(wasmMcpState);+ if (state.mcpServer) {+ await syncToIndexedDB(state.mcpServer);+ }+}++/**+ * Clear all persisted data+ */+export async function clearPersistedData(): Promise<void> {+ await idb.clearFiles();+ await idb.setSetting("activeTemplateId", null);+ console.log("[WASM MCP] Cleared all persisted data");+}++// Auto-initialize on module load in browser+if (browser) {+ // Defer initialization to avoid blocking+ setTimeout(() => {+ initWasmMcp().catch(console.error);+ }, 100);+}diff --git a/ruflo/src/ruvocal/src/lib/types/Settings.ts b/ruflo/src/ruvocal/src/lib/types/Settings.tsindex 445a6eaa70..f091f35929 100644--- a/ruflo/src/ruvocal/src/lib/types/Settings.ts+++ b/ruflo/src/ruvocal/src/lib/types/Settings.ts@@ -62,6 +62,12 @@ export interface Settings extends Timestamps {*/autopilotEnabled: boolean;+ /**+ * Maximum number of autopilot steps (tool call loops) before stopping.+ * Default is 10. Range: 1-50.+ */+ autopilotMaxSteps: number;+/*** Organization to bill inference requests to (HuggingChat only).* Stores the org's preferred_username. If empty/undefined, bills to personal account.@@ -83,4 +89,5 @@ export const DEFAULT_SETTINGS = {directPaste: false,hapticsEnabled: true,autopilotEnabled: true,+ autopilotMaxSteps: 10,} satisfies SettingsEditable;diff --git a/ruflo/src/ruvocal/src/lib/types/Tool.ts b/ruflo/src/ruvocal/src/lib/types/Tool.tsindex e2172e17ce..90e14b1782 100644--- a/ruflo/src/ruvocal/src/lib/types/Tool.ts+++ b/ruflo/src/ruvocal/src/lib/types/Tool.ts@@ -57,7 +57,7 @@ export interface MCPServer {id: string;name: string;url: string;- type: "base" | "custom";+ type: "base" | "custom" | "wasm";headers?: KeyValuePair[];env?: KeyValuePair[];status?: ServerStatus;@@ -66,6 +66,9 @@ export interface MCPServer {errorMessage?: string;// Indicates server reports or appears to require OAuth or other authauthRequired?: boolean;+ // For WASM servers: active template info+ wasmTemplateId?: string;+ wasmTemplateName?: string;}export interface MCPServerApi {diff --git a/ruflo/src/ruvocal/src/lib/wasm/idb.ts b/ruflo/src/ruvocal/src/lib/wasm/idb.tsnew file mode 100644index 0000000000..e882dd1f5e--- /dev/null+++ b/ruflo/src/ruvocal/src/lib/wasm/idb.ts@@ -0,0 +1,438 @@+/**+ * IndexedDB Persistence Layer+ * Provides persistent storage for WASM virtual filesystem and RVF containers+ */++import { browser } from "$app/environment";++const DB_NAME = "rvagent-wasm-db";+const DB_VERSION = 1;++// Object store names+const STORES = {+ FILES: "files",+ RVF_CONTAINERS: "rvf-containers",+ GALLERY_CUSTOM: "gallery-custom",+ SETTINGS: "settings",+ SESSIONS: "sessions",+} as const;++// Types+export interface StoredFile {+ path: string;+ content: string;+ createdAt: number;+ updatedAt: number;+}++export interface StoredRvfContainer {+ id: string;+ name: string;+ data: Uint8Array;+ templateId?: string;+ createdAt: number;+ updatedAt: number;+}++export interface StoredSession {+ id: string;+ activeTemplateId?: string;+ config: unknown;+ files: string[];+ createdAt: number;+ updatedAt: number;+}++let db: IDBDatabase | null = null;+let dbPromise: Promise<IDBDatabase> | null = null;++/**+ * Open the IndexedDB database+ */+export async function openDatabase(): Promise<IDBDatabase> {+ if (!browser) {+ throw new Error("IndexedDB is only available in browser");+ }++ if (db) {+ return db;+ }++ if (dbPromise) {+ return dbPromise;+ }++ dbPromise = new Promise((resolve, reject) => {+ const request = indexedDB.open(DB_NAME, DB_VERSION);++ request.onerror = () => {+ console.error("[IDB] Failed to open database:", request.error);+ dbPromise = null;+ reject(request.error);+ };++ request.onsuccess = () => {+ db = request.result;+ console.log("[IDB] Database opened successfully");+ resolve(db);+ };++ request.onupgradeneeded = (event) => {+ const database = (event.target as IDBOpenDBRequest).result;++ // Files store (virtual filesystem)+ if (!database.objectStoreNames.contains(STORES.FILES)) {+ const filesStore = database.createObjectStore(STORES.FILES, { keyPath: "path" });+ filesStore.createIndex("updatedAt", "updatedAt", { unique: false });+ }++ // RVF containers store+ if (!database.objectStoreNames.contains(STORES.RVF_CONTAINERS)) {+ const rvfStore = database.createObjectStore(STORES.RVF_CONTAINERS, { keyPath: "id" });+ rvfStore.createIndex("name", "name", { unique: false });+ rvfStore.createIndex("templateId", "templateId", { unique: false });+ rvfStore.createIndex("updatedAt", "updatedAt", { unique: false });+ }++ // Custom gallery templates store+ if (!database.objectStoreNames.contains(STORES.GALLERY_CUSTOM)) {+ const galleryStore = database.createObjectStore(STORES.GALLERY_CUSTOM, { keyPath: "id" });+ galleryStore.createIndex("category", "category", { unique: false });+ }++ // Settings store+ if (!database.objectStoreNames.contains(STORES.SETTINGS)) {+ database.createObjectStore(STORES.SETTINGS, { keyPath: "key" });+ }++ // Sessions store+ if (!database.objectStoreNames.contains(STORES.SESSIONS)) {+ const sessionsStore = database.createObjectStore(STORES.SESSIONS, { keyPath: "id" });+ sessionsStore.createIndex("updatedAt", "updatedAt", { unique: false });+ }++ console.log("[IDB] Database schema created/upgraded");+ };+ });++ return dbPromise;+}++/**+ * Close the database+ */+export function closeDatabase(): void {+ if (db) {+ db.close();+ db = null;+ dbPromise = null;+ console.log("[IDB] Database closed");+ }+}++// ---------------------------------------------------------------------------+// File Operations (Virtual Filesystem)+// ---------------------------------------------------------------------------++/**+ * Write a file to IndexedDB+ */+export async function writeFile(path: string, content: string): Promise<void> {+ const database = await openDatabase();+ const tx = database.transaction(STORES.FILES, "readwrite");+ const store = tx.objectStore(STORES.FILES);++ const now = Date.now();+ const existing = await new Promise<StoredFile | undefined>((resolve) => {+ const request = store.get(path);+ request.onsuccess = () => resolve(request.result);+ request.onerror = () => resolve(undefined);+ });++ const file: StoredFile = {+ path,+ content,+ createdAt: existing?.createdAt || now,+ updatedAt: now,+ };++ return new Promise((resolve, reject) => {+ const request = store.put(file);+ request.onsuccess = () => resolve();+ request.onerror = () => reject(request.error);+ });+}++/**+ * Read a file from IndexedDB+ */+export async function readFile(path: string): Promise<string | null> {+ const database = await openDatabase();+ const tx = database.transaction(STORES.FILES, "readonly");+ const store = tx.objectStore(STORES.FILES);++ return new Promise((resolve, reject) => {+ const request = store.get(path);+ request.onsuccess = () => resolve(request.result?.content ?? null);+ request.onerror = () => reject(request.error);+ });+}++/**+ * Delete a file from IndexedDB+ */+export async function deleteFile(path: string): Promise<void> {+ const database = await openDatabase();+ const tx = database.transaction(STORES.FILES, "readwrite");+ const store = tx.objectStore(STORES.FILES);++ return new Promise((resolve, reject) => {+ const request = store.delete(path);+ request.onsuccess = () => resolve();+ request.onerror = () => reject(request.error);+ });+}++/**+ * List all files in IndexedDB+ */+export async function listFiles(): Promise<StoredFile[]> {+ const database = await openDatabase();+ const tx = database.transaction(STORES.FILES, "readonly");+ const store = tx.objectStore(STORES.FILES);++ return new Promise((resolve, reject) => {+ const request = store.getAll();+ request.onsuccess = () => resolve(request.result);+ request.onerror = () => reject(request.error);+ });+}++/**+ * Clear all files+ */+export async function clearFiles(): Promise<void> {+ const database = await openDatabase();+ const tx = database.transaction(STORES.FILES, "readwrite");+ const store = tx.objectStore(STORES.FILES);++ return new Promise((resolve, reject) => {+ const request = store.clear();+ request.onsuccess = () => resolve();+ request.onerror = () => reject(request.error);+ });+}++/**+ * Export all files as JSON+ */+export async function exportFilesAsJson(): Promise<string> {+ const files = await listFiles();+ const fileMap: Record<string, string> = {};+ for (const file of files) {+ fileMap[file.path] = file.content;+ }+ return JSON.stringify(fileMap);+}++/**+ * Import files from JSON+ */+export async function importFilesFromJson(json: string): Promise<number> {+ const fileMap: Record<string, string> = JSON.parse(json);+ let count = 0;+ for (const [path, content] of Object.entries(fileMap)) {+ await writeFile(path, content);+ count++;+ }+ return count;+}++// ---------------------------------------------------------------------------+// RVF Container Operations+// ---------------------------------------------------------------------------++/**+ * Save an RVF container+ */+export async function saveRvfContainer(+ id: string,+ name: string,+ data: Uint8Array,+ templateId?: string+): Promise<void> {+ const database = await openDatabase();+ const tx = database.transaction(STORES.RVF_CONTAINERS, "readwrite");+ const store = tx.objectStore(STORES.RVF_CONTAINERS);++ const now = Date.now();+ const existing = await new Promise<StoredRvfContainer | undefined>((resolve) => {+ const request = store.get(id);+ request.onsuccess = () => resolve(request.result);+ request.onerror = () => resolve(undefined);+ });++ const container: StoredRvfContainer = {+ id,+ name,+ data,+ templateId,+ createdAt: existing?.createdAt || now,+ updatedAt: now,+ };++ return new Promise((resolve, reject) => {+ const request = store.put(container);+ request.onsuccess = () => resolve();+ request.onerror = () => reject(request.error);+ });+}++/**+ * Load an RVF container+ */+export async function loadRvfContainer(id: string): Promise<StoredRvfContainer | null> {+ const database = await openDatabase();+ const tx = database.transaction(STORES.RVF_CONTAINERS, "readonly");+ const store = tx.objectStore(STORES.RVF_CONTAINERS);++ return new Promise((resolve, reject) => {+ const request = store.get(id);+ request.onsuccess = () => resolve(request.result ?? null);+ request.onerror = () => reject(request.error);+ });+}++/**+ * List all RVF containers+ */+export async function listRvfContainers(): Promise<StoredRvfContainer[]> {+ const database = await openDatabase();+ const tx = database.transaction(STORES.RVF_CONTAINERS, "readonly");+ const store = tx.objectStore(STORES.RVF_CONTAINERS);++ return new Promise((resolve, reject) => {+ const request = store.getAll();+ request.onsuccess = () => resolve(request.result);+ request.onerror = () => reject(request.error);+ });+}++/**+ * Delete an RVF container+ */+export async function deleteRvfContainer(id: string): Promise<void> {+ const database = await openDatabase();+ const tx = database.transaction(STORES.RVF_CONTAINERS, "readwrite");+ const store = tx.objectStore(STORES.RVF_CONTAINERS);++ return new Promise((resolve, reject) => {+ const request = store.delete(id);+ request.onsuccess = () => resolve();+ request.onerror = () => reject(request.error);+ });+}++// ---------------------------------------------------------------------------+// Settings Operations+// ---------------------------------------------------------------------------++/**+ * Get a setting value+ */+export async function getSetting<T>(key: string): Promise<T | null> {+ const database = await openDatabase();+ const tx = database.transaction(STORES.SETTINGS, "readonly");+ const store = tx.objectStore(STORES.SETTINGS);++ return new Promise((resolve, reject) => {+ const request = store.get(key);+ request.onsuccess = () => resolve(request.result?.value ?? null);+ request.onerror = () => reject(request.error);+ });+}++/**+ * Set a setting value+ */+export async function setSetting<T>(key: string, value: T): Promise<void> {+ const database = await openDatabase();+ const tx = database.transaction(STORES.SETTINGS, "readwrite");+ const store = tx.objectStore(STORES.SETTINGS);++ return new Promise((resolve, reject) => {+ const request = store.put({ key, value });+ request.onsuccess = () => resolve();+ request.onerror = () => reject(request.error);+ });+}++// ---------------------------------------------------------------------------+// Session Operations+// ---------------------------------------------------------------------------++/**+ * Save a session+ */+export async function saveSession(session: StoredSession): Promise<void> {+ const database = await openDatabase();+ const tx = database.transaction(STORES.SESSIONS, "readwrite");+ const store = tx.objectStore(STORES.SESSIONS);++ session.updatedAt = Date.now();++ return new Promise((resolve, reject) => {+ const request = store.put(session);+ request.onsuccess = () => resolve();+ request.onerror = () => reject(request.error);+ });+}++/**+ * Load a session+ */+export async function loadSession(id: string): Promise<StoredSession | null> {+ const database = await openDatabase();+ const tx = database.transaction(STORES.SESSIONS, "readonly");+ const store = tx.objectStore(STORES.SESSIONS);++ return new Promise((resolve, reject) => {+ const request = store.get(id);+ request.onsuccess = () => resolve(request.result ?? null);+ request.onerror = () => reject(request.error);+ });+}++/**+ * Get the most recent session+ */+export async function getLatestSession(): Promise<StoredSession | null> {+ const database = await openDatabase();+ const tx = database.transaction(STORES.SESSIONS, "readonly");+ const store = tx.objectStore(STORES.SESSIONS);+ const index = store.index("updatedAt");++ return new Promise((resolve, reject) => {+ const request = index.openCursor(null, "prev");+ request.onsuccess = () => {+ const cursor = request.result;+ resolve(cursor?.value ?? null);+ };+ request.onerror = () => reject(request.error);+ });+}++/**+ * Delete a session+ */+export async function deleteSession(id: string): Promise<void> {+ const database = await openDatabase();+ const tx = database.transaction(STORES.SESSIONS, "readwrite");+ const store = tx.objectStore(STORES.SESSIONS);++ return new Promise((resolve, reject) => {+ const request = store.delete(id);+ request.onsuccess = () => resolve();+ request.onerror = () => reject(request.error);+ });+}diff --git a/ruflo/src/ruvocal/src/lib/wasm/index.ts b/ruflo/src/ruvocal/src/lib/wasm/index.tsnew file mode 100644index 0000000000..b162932984--- /dev/null+++ b/ruflo/src/ruvocal/src/lib/wasm/index.ts@@ -0,0 +1,1213 @@+/**+ * WASM Integration Layer+ * Loads rvagent-wasm and provides TypeScript bindings+ */++import { browser } from "$app/environment";++// Types for WASM exports+export interface WasmMcpServer {+ handle_message(message: string): string;+ gallery(): WasmGallery;+}++export interface WasmGallery {+ list(): GalleryTemplate[];+ listByCategory(category: string): GalleryTemplate[];+ search(query: string): SearchResult[];+ get(id: string): GalleryTemplate;+ loadRvf(id: string): Uint8Array;+ setActive(id: string): void;+ getActive(): string | null;+ configure(configJson: string): void;+ getConfig(): unknown;+ addCustom(templateJson: string): void;+ removeCustom(id: string): void;+ getCategories(): Record<string, number>;+ count(): number;+ exportCustom(): GalleryTemplate[];+ importCustom(templatesJson: string): number;+}++export interface WasmRvfBuilder {+ addTool(toolJson: string): void;+ addTools(toolsJson: string): void;+ addPrompt(promptJson: string): void;+ addPrompts(promptsJson: string): void;+ addSkill(skillJson: string): void;+ addSkills(skillsJson: string): void;+ addMcpTools(mcpToolsJson: string): void;+ addCapabilities(capsJson: string): void;+ setOrchestrator(orchestratorJson: string): void;+ build(): Uint8Array;+}++export interface GalleryTemplate {+ id: string;+ name: string;+ description: string;+ category: string;+ version: string;+ author: string;+ tags: string[];+ builtin: boolean;+ tools?: ToolDefinition[];+ prompts?: AgentPrompt[];+ skills?: SkillDefinition[];+ mcp_tools?: McpToolEntry[];+ capabilities?: CapabilityDef[];+ orchestrator?: OrchestratorConfig;+}++export interface SearchResult {+ id: string;+ name: string;+ description: string;+ category: string;+ tags: string[];+ relevance: number;+}++export interface ToolDefinition {+ name: string;+ description: string;+ parameters: unknown;+ returns?: string;+}++export interface AgentPrompt {+ name: string;+ system_prompt: string;+ version: string;+}++export interface SkillDefinition {+ name: string;+ description: string;+ trigger: string;+ content: string;+}++export interface McpToolEntry {+ name: string;+ description: string;+ input_schema: unknown;+ group?: string;+}++export interface CapabilityDef {+ name: string;+ rights: string[];+ scope: string;+ delegation_depth: number;+}++export interface OrchestratorConfig {+ topology: string;+ agents: AgentNode[];+ connections: [string, string][];+}++export interface AgentNode {+ id: string;+ agent_type: string;+ prompt_ref: string;+}++// WASM module instance+let wasmModule: {+ WasmMcpServer: new () => WasmMcpServer;+ WasmGallery: new () => WasmGallery;+ WasmRvfBuilder: new () => WasmRvfBuilder;+} | null = null;++type WasmModuleType = {+ WasmMcpServer: new () => WasmMcpServer;+ WasmGallery: new () => WasmGallery;+ WasmRvfBuilder: new () => WasmRvfBuilder;+} | null;++let loadPromise: Promise<WasmModuleType> | null = null;++/**+ * Create a mock WASM module for development/testing when actual WASM isn't available+ * Implements the full rvAgent feature set with 8 tools, 14 middleware capabilities,+ * SONA learning, HNSW search, AGI containers, and security controls+ */+function createMockWasmModule() {+ // Built-in templates for mock gallery - comprehensive rvAgent implementations+ const builtinTemplates: GalleryTemplate[] = [+ {+ id: "development-agent",+ name: "Development Agent",+ description: "Full-featured development agent with code editing, file management, testing, and task tracking. O(1) state cloning for instant subagent spawning.",+ category: "development",+ version: "2.0.0",+ author: "RuVector",+ tags: ["development", "coding", "testing", "files", "tasks", "production"],+ builtin: true,+ tools: [+ { name: "read_file", description: "Read file contents from the virtual filesystem", parameters: { path: "string" } },+ { name: "write_file", description: "Write content to a file in the virtual filesystem", parameters: { path: "string", content: "string" } },+ { name: "edit_file", description: "Edit a file by replacing old content with new content", parameters: { path: "string", old_content: "string", new_content: "string" } },+ { name: "list_files", description: "List all files in the virtual filesystem", parameters: {} },+ { name: "delete_file", description: "Delete a file from the virtual filesystem", parameters: { path: "string" } },+ { name: "grep", description: "Search for patterns in files using regex", parameters: { pattern: "string", path: "string?" } },+ { name: "glob", description: "Find files matching a glob pattern", parameters: { pattern: "string" } },+ { name: "execute", description: "Execute a shell command (sandboxed)", parameters: { command: "string", cwd: "string?" } },+ ],+ prompts: [{+ name: "developer",+ system_prompt: "You are a production-grade coding assistant powered by rvAgent. You have access to file operations, search, and task management. Be concise and focus on writing correct, secure code. Use the task tracking tools to manage complex workflows. Always validate inputs and handle errors gracefully.",+ version: "2.0.0"+ }],+ skills: [+ { name: "commit", description: "Create a git commit with conventional commit messages", trigger: "/commit", content: "Review changes, generate commit message, stage files, create commit" },+ { name: "review", description: "Review code for security, performance, and best practices", trigger: "/review", content: "Analyze code for issues, suggest improvements, check for vulnerabilities" },+ { name: "test", description: "Run tests and analyze failures", trigger: "/test", content: "Execute test suite, analyze failures, suggest fixes" },+ { name: "refactor", description: "Refactor code while maintaining behavior", trigger: "/refactor", content: "Identify code smells, propose refactoring, maintain tests" },+ ],+ mcp_tools: [+ { name: "todo_add", description: "Add a task to the todo list", input_schema: { type: "object", properties: { task: { type: "string" } } }, group: "tasks" },+ { name: "todo_list", description: "List all pending tasks", input_schema: { type: "object" }, group: "tasks" },+ { name: "todo_complete", description: "Mark a task as complete", input_schema: { type: "object", properties: { id: { type: "string" } } }, group: "tasks" },+ { name: "memory_store", description: "Store information in semantic memory", input_schema: { type: "object", properties: { key: { type: "string" }, value: { type: "string" } } }, group: "memory" },+ { name: "memory_search", description: "Search semantic memory using HNSW", input_schema: { type: "object", properties: { query: { type: "string" } } }, group: "memory" },+ ],+ capabilities: [+ { name: "file_ops", rights: ["read", "write", "delete"], scope: "/workspace", delegation_depth: 2 },+ { name: "execute", rights: ["run"], scope: "sandboxed", delegation_depth: 1 },+ { name: "memory", rights: ["read", "write", "search"], scope: "session", delegation_depth: 0 },+ ],+ },+ {+ id: "research-agent",+ name: "Research Agent",+ description: "Research-focused agent with web search, document analysis, and semantic memory. HNSW-indexed memory for O(log n) retrieval across millions of entries.",+ category: "research",+ version: "2.0.0",+ author: "RuVector",+ tags: ["research", "analysis", "documentation", "memory", "search"],+ builtin: true,+ tools: [+ { name: "read_file", description: "Read file contents", parameters: { path: "string" } },+ { name: "write_file", description: "Write content to a file", parameters: { path: "string", content: "string" } },+ { name: "list_files", description: "List files", parameters: {} },+ { name: "web_search", description: "Search the web for information", parameters: { query: "string", limit: "number?" } },+ { name: "analyze_document", description: "Analyze a document for key insights", parameters: { content: "string", focus: "string?" } },+ { name: "summarize", description: "Summarize long content", parameters: { content: "string", max_length: "number?" } },+ ],+ prompts: [{+ name: "researcher",+ system_prompt: "You are an expert research assistant with access to semantic memory and document analysis tools. Your goal is to find accurate information, synthesize insights, and provide well-sourced answers. Use memory to track findings across sessions. Always cite sources and acknowledge uncertainty.",+ version: "2.0.0"+ }],+ skills: [+ { name: "deep-dive", description: "Conduct deep research on a topic", trigger: "/deep-dive", content: "Comprehensive multi-source research with citations" },+ { name: "summarize", description: "Create executive summary", trigger: "/summarize", content: "Condense information into key points" },+ { name: "compare", description: "Compare multiple sources", trigger: "/compare", content: "Analyze similarities and differences" },+ ],+ mcp_tools: [+ { name: "memory_store", description: "Store research findings", input_schema: { type: "object", properties: { key: { type: "string" }, value: { type: "string" }, tags: { type: "array" } } }, group: "memory" },+ { name: "memory_search", description: "Search past research (HNSW)", input_schema: { type: "object", properties: { query: { type: "string" }, top_k: { type: "number" } } }, group: "memory" },+ { name: "cite", description: "Generate citation", input_schema: { type: "object", properties: { source: { type: "string" }, format: { type: "string" } } }, group: "research" },+ ],+ capabilities: [+ { name: "web_access", rights: ["search", "fetch"], scope: "internet", delegation_depth: 1 },+ { name: "memory", rights: ["read", "write", "search"], scope: "persistent", delegation_depth: 0 },+ ],+ },+ {+ id: "security-agent",+ name: "Security Agent",+ description: "Security-focused agent for code auditing, vulnerability scanning, and threat detection. 15 built-in security controls including path traversal, injection, and credential protection.",+ category: "security",+ version: "2.0.0",+ author: "RuVector",+ tags: ["security", "audit", "vulnerabilities", "penetration-testing", "compliance"],+ builtin: true,+ tools: [+ { name: "read_file", description: "Read file contents (path-confined)", parameters: { path: "string" } },+ { name: "list_files", description: "List files", parameters: {} },+ { name: "grep", description: "Search for patterns (e.g., credentials)", parameters: { pattern: "string", path: "string?" } },+ { name: "scan_vulnerabilities", description: "Scan code for known vulnerabilities", parameters: { path: "string", severity: "string?" } },+ { name: "audit_code", description: "Audit code for security issues", parameters: { path: "string", ruleset: "string?" } },+ { name: "check_dependencies", description: "Check dependencies for CVEs", parameters: { manifest: "string" } },+ ],+ prompts: [{+ name: "security",+ system_prompt: "You are a security expert powered by rvAgent's 15 built-in security controls. You can detect path traversal, credential leaks, injection attacks, and unicode spoofing. Analyze code with a security-first mindset. Report vulnerabilities with severity, impact, and remediation steps. Never expose sensitive data in outputs.",+ version: "2.0.0"+ }],+ skills: [+ { name: "audit", description: "Full security audit", trigger: "/audit", content: "Comprehensive security review with OWASP checks" },+ { name: "pentest", description: "Penetration testing simulation", trigger: "/pentest", content: "Simulate attack vectors and report findings" },+ { name: "compliance", description: "Compliance check", trigger: "/compliance", content: "Check against security frameworks (SOC2, HIPAA, etc.)" },+ ],+ mcp_tools: [+ { name: "cve_lookup", description: "Lookup CVE details", input_schema: { type: "object", properties: { cve_id: { type: "string" } } }, group: "security" },+ { name: "report_vuln", description: "Generate vulnerability report", input_schema: { type: "object", properties: { findings: { type: "array" } } }, group: "security" },+ { name: "witness_log", description: "Log to witness chain (immutable audit)", input_schema: { type: "object", properties: { action: { type: "string" }, data: { type: "object" } } }, group: "audit" },+ ],+ capabilities: [+ { name: "file_ops", rights: ["read"], scope: "/workspace", delegation_depth: 1 },+ { name: "audit", rights: ["read", "write"], scope: "witness_chain", delegation_depth: 0 },+ ],+ },+ {+ id: "multi-agent-orchestrator",+ name: "Multi-Agent Orchestrator",+ description: "Coordinate multiple specialized agents with CRDT-based state merging. Spawn subagents instantly with O(1) state cloning, merge results deterministically.",+ category: "orchestration",+ version: "2.0.0",+ author: "RuVector",+ tags: ["multi-agent", "orchestration", "coordination", "parallel", "subagents"],+ builtin: true,+ tools: [+ { name: "read_file", description: "Read file contents", parameters: { path: "string" } },+ { name: "write_file", description: "Write content to a file", parameters: { path: "string", content: "string" } },+ { name: "list_files", description: "List files", parameters: {} },+ { name: "spawn_agent", description: "Spawn a specialized subagent", parameters: { type: "string", task: "string" } },+ { name: "merge_results", description: "Merge subagent results using CRDT", parameters: { results: "array" } },+ ],+ prompts: [{+ name: "orchestrator",+ system_prompt: "You are a multi-agent orchestrator. You can spawn specialized subagents (security-reviewer, performance-reviewer, code-reviewer) and coordinate their work. Use CRDT merging for conflict-free result combination. Delegate effectively and synthesize findings into actionable insights.",+ version: "2.0.0"+ }],+ skills: [+ { name: "parallel-review", description: "Parallel code review with multiple agents", trigger: "/parallel-review", content: "Spawn security, performance, and style reviewers simultaneously" },+ { name: "swarm", description: "Deploy agent swarm for complex task", trigger: "/swarm", content: "Coordinate multiple agents for large-scale analysis" },+ ],+ mcp_tools: [+ { name: "agent_spawn", description: "Spawn a subagent", input_schema: { type: "object", properties: { type: { type: "string" }, task: { type: "string" } } }, group: "orchestration" },+ { name: "agent_status", description: "Get subagent status", input_schema: { type: "object", properties: { id: { type: "string" } } }, group: "orchestration" },+ { name: "results_merge", description: "Merge results with CRDT", input_schema: { type: "object", properties: { results: { type: "array" } } }, group: "orchestration" },+ ],+ capabilities: [+ { name: "orchestration", rights: ["spawn", "terminate", "merge"], scope: "subagents", delegation_depth: 3 },+ { name: "file_ops", rights: ["read", "write"], scope: "/workspace", delegation_depth: 2 },+ ],+ orchestrator: {+ topology: "hierarchical",+ agents: [+ { id: "coordinator", agent_type: "orchestrator", prompt_ref: "orchestrator" },+ { id: "security", agent_type: "security-reviewer", prompt_ref: "security" },+ { id: "performance", agent_type: "performance-reviewer", prompt_ref: "performance" },+ { id: "style", agent_type: "style-reviewer", prompt_ref: "style" },+ ],+ connections: [["coordinator", "security"], ["coordinator", "performance"], ["coordinator", "style"]],+ },+ },+ {+ id: "sona-learning-agent",+ name: "SONA Learning Agent",+ description: "Self-improving agent with SONA (Self-Optimizing Neural Architecture). 3-loop learning: instant feedback (<0.05ms), background optimization, deep consolidation.",+ category: "learning",+ version: "2.0.0",+ author: "RuVector",+ tags: ["learning", "adaptive", "self-improving", "sona", "neural"],+ builtin: true,+ tools: [+ { name: "read_file", description: "Read file contents", parameters: { path: "string" } },+ { name: "write_file", description: "Write content to a file", parameters: { path: "string", content: "string" } },+ { name: "edit_file", description: "Edit a file", parameters: { path: "string", old_content: "string", new_content: "string" } },+ { name: "list_files", description: "List files", parameters: {} },+ { name: "learn_pattern", description: "Learn a new pattern from experience", parameters: { pattern: "string", outcome: "string" } },+ { name: "predict_action", description: "Predict best action based on learned patterns", parameters: { context: "string" } },+ ],+ prompts: [{+ name: "learner",+ system_prompt: "You are a self-improving agent with SONA learning capabilities. You learn from every interaction through 3 feedback loops: Loop A (instant, <0.05ms) for immediate adjustments, Loop B (background) for pattern optimization, Loop C (consolidation) for deep learning. Track your performance and continuously improve your responses.",+ version: "2.0.0"+ }],+ skills: [+ { name: "learn", description: "Learn from experience", trigger: "/learn", content: "Record pattern and outcome for future use" },+ { name: "recall", description: "Recall learned patterns", trigger: "/recall", content: "Search learned patterns matching context" },+ { name: "optimize", description: "Trigger optimization cycle", trigger: "/optimize", content: "Run background optimization on learned patterns" },+ ],+ mcp_tools: [+ { name: "pattern_store", description: "Store learned pattern", input_schema: { type: "object", properties: { pattern: { type: "string" }, outcome: { type: "string" }, confidence: { type: "number" } } }, group: "learning" },+ { name: "pattern_search", description: "Search patterns (HNSW)", input_schema: { type: "object", properties: { query: { type: "string" }, top_k: { type: "number" } } }, group: "learning" },+ { name: "feedback_record", description: "Record feedback for learning", input_schema: { type: "object", properties: { action: { type: "string" }, success: { type: "boolean" } } }, group: "learning" },+ ],+ capabilities: [+ { name: "learning", rights: ["read", "write", "optimize"], scope: "neural", delegation_depth: 0 },+ { name: "file_ops", rights: ["read", "write"], scope: "/workspace", delegation_depth: 1 },+ ],+ },+ {+ id: "agi-container-builder",+ name: "AGI Container Builder",+ description: "Build portable AI agent packages (AGI Containers) with tools, prompts, skills, and verified checksums. SHA3-256 integrity verification for secure deployment.",+ category: "tooling",+ version: "2.0.0",+ author: "RuVector",+ tags: ["agi", "container", "portable", "deployment", "rvf"],+ builtin: true,+ tools: [+ { name: "read_file", description: "Read file contents", parameters: { path: "string" } },+ { name: "write_file", description: "Write content to a file", parameters: { path: "string", content: "string" } },+ { name: "list_files", description: "List files", parameters: {} },+ { name: "build_container", description: "Build an AGI container", parameters: { manifest: "object" } },+ { name: "verify_container", description: "Verify container integrity", parameters: { path: "string" } },+ { name: "extract_container", description: "Extract container contents", parameters: { path: "string", dest: "string" } },+ ],+ prompts: [{+ name: "builder",+ system_prompt: "You are an AGI Container builder. You help create portable, verified AI agent packages that bundle tools, prompts, skills, and capabilities. Each container has SHA3-256 checksum verification for security. Guide users through container creation, validation, and deployment.",+ version: "2.0.0"+ }],+ skills: [+ { name: "build", description: "Build AGI container", trigger: "/build", content: "Create verified RVF container from manifest" },+ { name: "verify", description: "Verify container", trigger: "/verify", content: "Check SHA3-256 integrity and validate structure" },+ { name: "deploy", description: "Deploy container", trigger: "/deploy", content: "Extract and activate container in runtime" },+ ],+ mcp_tools: [+ { name: "rvf_build", description: "Build RVF container", input_schema: { type: "object", properties: { tools: { type: "array" }, prompts: { type: "array" }, skills: { type: "array" } } }, group: "container" },+ { name: "rvf_verify", description: "Verify RVF container", input_schema: { type: "object", properties: { data: { type: "string" } } }, group: "container" },+ { name: "rvf_extract", description: "Extract RVF contents", input_schema: { type: "object", properties: { data: { type: "string" } } }, group: "container" },+ ],+ capabilities: [+ { name: "container", rights: ["build", "verify", "extract"], scope: "rvf", delegation_depth: 0 },+ { name: "file_ops", rights: ["read", "write"], scope: "/workspace", delegation_depth: 1 },+ ],+ },+ {+ id: "witness-auditor",+ name: "Witness Chain Auditor",+ description: "Cryptographic audit trail agent with immutable witness chains. Every action is logged with a hash chain for forensic debugging and compliance.",+ category: "compliance",+ version: "2.0.0",+ author: "RuVector",+ tags: ["audit", "compliance", "forensics", "witness", "immutable"],+ builtin: true,+ tools: [+ { name: "read_file", description: "Read file contents", parameters: { path: "string" } },+ { name: "list_files", description: "List files", parameters: {} },+ { name: "witness_log", description: "Log action to witness chain", parameters: { action: "string", data: "object" } },+ { name: "witness_verify", description: "Verify witness chain integrity", parameters: { chain_id: "string" } },+ { name: "witness_query", description: "Query witness chain", parameters: { filter: "object" } },+ ],+ prompts: [{+ name: "auditor",+ system_prompt: "You are a compliance auditor with access to immutable witness chains. Every tool call creates a cryptographic log entry forming a hash chain. Use this for forensic debugging, compliance audits, and security investigations. You can verify chain integrity and trace exactly what happened and when.",+ version: "2.0.0"+ }],+ skills: [+ { name: "audit-trail", description: "Generate audit trail", trigger: "/audit-trail", content: "Create comprehensive audit report from witness chain" },+ { name: "verify-chain", description: "Verify chain integrity", trigger: "/verify-chain", content: "Validate all hashes in witness chain" },+ { name: "compliance-report", description: "Generate compliance report", trigger: "/compliance-report", content: "Create compliance report for SOC2/HIPAA/etc." },+ ],+ mcp_tools: [+ { name: "witness_append", description: "Append to witness chain", input_schema: { type: "object", properties: { action: { type: "string" }, data: { type: "object" } } }, group: "audit" },+ { name: "witness_verify", description: "Verify chain integrity", input_schema: { type: "object", properties: { chain_id: { type: "string" } } }, group: "audit" },+ { name: "witness_export", description: "Export chain for external audit", input_schema: { type: "object", properties: { chain_id: { type: "string" }, format: { type: "string" } } }, group: "audit" },+ ],+ capabilities: [+ { name: "audit", rights: ["read", "write", "verify"], scope: "witness_chain", delegation_depth: 0 },+ { name: "file_ops", rights: ["read"], scope: "/workspace", delegation_depth: 1 },+ ],+ },+ {+ id: "minimal-agent",+ name: "Minimal Agent",+ description: "Lightweight agent with just file operations. Perfect for simple tasks or as a starting point for custom agents.",+ category: "basic",+ version: "2.0.0",+ author: "RuVector",+ tags: ["minimal", "simple", "files", "basic"],+ builtin: true,+ tools: [+ { name: "read_file", description: "Read file contents", parameters: { path: "string" } },+ { name: "write_file", description: "Write content to a file", parameters: { path: "string", content: "string" } },+ { name: "list_files", description: "List files", parameters: {} },+ ],+ prompts: [{+ name: "assistant",+ system_prompt: "You are a helpful assistant with access to file operations. Keep responses concise.",+ version: "2.0.0"+ }],+ skills: [],+ mcp_tools: [],+ capabilities: [+ { name: "file_ops", rights: ["read", "write"], scope: "/workspace", delegation_depth: 0 },+ ],+ },+ ];++ // Virtual filesystem for mock MCP server+ const virtualFS = new Map<string, string>();+ let activeTemplateId: string | null = null;++ // Todo list for task tracking+ const todoList: { id: string; task: string; completed: boolean; created: number }[] = [];+ let todoIdCounter = 1;++ // Memory store for semantic memory (simulated HNSW)+ const memoryStore = new Map<string, { key: string; value: string; tags: string[]; embedding?: number[] }>();++ // Witness chain for audit trail+ const witnessChain: { hash: string; prev_hash: string; action: string; data: unknown; timestamp: number }[] = [];+ let lastWitnessHash = "genesis";++ // Helper: Simple hash for witness chain+ function simpleHash(data: string): string {+ let hash = 0;+ for (let i = 0; i < data.length; i++) {+ const char = data.charCodeAt(i);+ hash = ((hash << 5) - hash) + char;+ hash = hash & hash;+ }+ return Math.abs(hash).toString(16).padStart(8, '0');+ }++ // Helper: Add witness entry+ function addWitnessEntry(action: string, data: unknown): string {+ const entry = {+ hash: '',+ prev_hash: lastWitnessHash,+ action,+ data,+ timestamp: Date.now(),+ };+ entry.hash = simpleHash(JSON.stringify(entry));+ witnessChain.push(entry);+ lastWitnessHash = entry.hash;+ return entry.hash;+ }++ class MockWasmMcpServer implements WasmMcpServer {+ handle_message(message: string): string {+ const request = JSON.parse(message);+ const { method, params, id } = request;++ const response = {+ jsonrpc: "2.0",+ id,+ result: null as unknown,+ error: undefined as { code: number; message: string } | undefined,+ };++ switch (method) {+ case "initialize":+ response.result = {+ protocolVersion: "2024-11-05",+ serverInfo: { name: "rvagent-wasm", version: "2.0.0" },+ capabilities: {+ tools: { listChanged: true },+ prompts: { listChanged: true },+ resources: {},+ },+ };+ break;++ case "tools/list":+ response.result = {+ tools: [+ // === SYSTEM GUIDANCE (1) - CALL THIS FIRST ===+ {+ name: "system_guidance",+ description: `🔮 CALL FIRST: Get help on ALL available tools. Examples: {} for full guide, {"tool": "read_file"} for specific tool, {"category": "memory"} for category.`,+ inputSchema: {+ type: "object",+ properties: {+ tool: { type: "string", description: "Get help for specific tool name" },+ category: { type: "string", description: "Filter by: files, memory, tasks, gallery, witness, brain, search" }+ }+ }+ },+ // === FILE OPERATIONS (5) ===+ {+ name: "read_file",+ description: `Read file contents. REQUIRED: path (string). Example: {"path": "src/index.ts"}`,+ inputSchema: {+ type: "object",+ properties: { path: { type: "string", description: "File path (REQUIRED) - e.g., 'src/index.ts'" } },+ required: ["path"]+ }+ },+ {+ name: "write_file",+ description: `Create or overwrite a file. REQUIRED: path, content. Example: {"path": "hello.txt", "content": "Hello World"}`,+ inputSchema: {+ type: "object",+ properties: {+ path: { type: "string", description: "File path (REQUIRED) - e.g., 'src/new-file.ts'" },+ content: { type: "string", description: "Content to write (REQUIRED)" }+ },+ required: ["path", "content"]+ }+ },+ {+ name: "list_files",+ description: `List all files in the virtual filesystem. No parameters needed. Returns file paths.`,+ inputSchema: { type: "object", properties: {} }+ },+ {+ name: "delete_file",+ description: `Delete a file. REQUIRED: path. Example: {"path": "temp.txt"}`,+ inputSchema: {+ type: "object",+ properties: { path: { type: "string", description: "File path to delete (REQUIRED)" } },+ required: ["path"]+ }+ },+ {+ name: "edit_file",+ description: `Replace text in a file. REQUIRED: path, old_content, new_content. Example: {"path": "src/index.ts", "old_content": "const x = 1", "new_content": "const x = 2"}`,+ inputSchema: {+ type: "object",+ properties: {+ path: { type: "string", description: "File path (REQUIRED)" },+ old_content: { type: "string", description: "Text to find (REQUIRED) - must match exactly" },+ new_content: { type: "string", description: "Replacement text (REQUIRED)" }+ },+ required: ["path", "old_content", "new_content"]+ }+ },+ // === SEARCH TOOLS (2) ===+ {+ name: "grep",+ description: `Search for regex patterns. REQUIRED: pattern. OPTIONAL: path. Example: {"pattern": "function.*export", "path": "src/utils.ts"}`,+ inputSchema: {+ type: "object",+ properties: {+ pattern: { type: "string", description: "Regex pattern (REQUIRED) - e.g., 'TODO|FIXME'" },+ path: { type: "string", description: "Limit search to file (optional)" }+ },+ required: ["pattern"]+ }+ },+ {+ name: "glob",+ description: `Find files by pattern. REQUIRED: pattern. Examples: {"pattern": "*.ts"}, {"pattern": "src/**/*.tsx"}`,+ inputSchema: {+ type: "object",+ properties: { pattern: { type: "string", description: "Glob pattern (REQUIRED) - e.g., '*.ts', 'src/**/*.js'" } },+ required: ["pattern"]+ }+ },+ // === TASK MANAGEMENT (3) ===+ {+ name: "todo_add",+ description: `Add a task. REQUIRED: task. Example: {"task": "Fix login bug"}`,+ inputSchema: {+ type: "object",+ properties: { task: { type: "string", description: "Task description (REQUIRED)" } },+ required: ["task"]+ }+ },+ {+ name: "todo_list",+ description: `List all tasks with status (○ pending, ✓ complete). No parameters needed.`,+ inputSchema: { type: "object", properties: {} }+ },+ {+ name: "todo_complete",+ description: `Mark task complete. REQUIRED: id. Example: {"id": "todo-1"}`,+ inputSchema: {+ type: "object",+ properties: { id: { type: "string", description: "Task ID (REQUIRED) - e.g., 'todo-1'" } },+ required: ["id"]+ }+ },+ // === MEMORY TOOLS (2) ===+ {+ name: "memory_store",+ description: `Store data in semantic memory. REQUIRED: key, value. OPTIONAL: tags. Example: {"key": "auth-pattern", "value": "JWT with refresh tokens", "tags": ["security", "patterns"]}`,+ inputSchema: {+ type: "object",+ properties: {+ key: { type: "string", description: "Unique key (REQUIRED)" },+ value: { type: "string", description: "Value to store (REQUIRED)" },+ tags: { type: "array", items: { type: "string" }, description: "Tags for filtering (optional)" }+ },+ required: ["key", "value"]+ }+ },+ {+ name: "memory_search",+ description: `Search stored memories. REQUIRED: query. OPTIONAL: top_k. Example: {"query": "authentication", "top_k": 5}`,+ inputSchema: {+ type: "object",+ properties: {+ query: { type: "string", description: "Search query (REQUIRED)" },+ top_k: { type: "number", description: "Max results (default: 5)" }+ },+ required: ["query"]+ }+ },+ // === AUDIT TOOLS (2) ===+ {+ name: "witness_log",+ description: `Log action to immutable audit chain. REQUIRED: action. OPTIONAL: data. Example: {"action": "file_modified", "data": {"path": "config.json"}}`,+ inputSchema: {+ type: "object",+ properties: {+ action: { type: "string", description: "Action name (REQUIRED) - e.g., 'file_created', 'deploy_started'" },+ data: { type: "object", description: "Additional context (optional)" }+ },+ required: ["action"]+ }+ },+ {+ name: "witness_verify",+ description: `Verify audit chain integrity. No parameters. Returns VALID/INVALID with entry count.`,+ inputSchema: { type: "object", properties: {} }+ },+ // === RVF GALLERY (3) ===+ {+ name: "gallery_list",+ description: `List agent templates. OPTIONAL: category. Examples: {"category": "development"}, {} for all templates`,+ inputSchema: {+ type: "object",+ properties: { category: { type: "string", description: "Filter by category (optional) - development, research, security, etc." } }+ }+ },+ {+ name: "gallery_load",+ description: `Load a template. REQUIRED: id. Example: {"id": "development-agent"}`,+ inputSchema: {+ type: "object",+ properties: { id: { type: "string", description: "Template ID (REQUIRED) - e.g., 'development-agent', 'security-agent'" } },+ required: ["id"]+ }+ },+ {+ name: "gallery_search",+ description: `Search templates by name, description, or tags. REQUIRED: query. Example: {"query": "security"}`,+ inputSchema: {+ type: "object",+ properties: { query: { type: "string", description: "Search query (REQUIRED)" } },+ required: ["query"]+ }+ },+ ],+ };+ break;++ case "tools/call": {+ const { name, arguments: args } = params;+ // Log to witness chain for audit+ addWitnessEntry(`tool_call:${name}`, { args: args || {} });++ switch (name) {+ case "system_guidance": {+ const toolDocs: Record<string, { cat: string; desc: string; ex: string }> = {+ // --- Help ---+ system_guidance: { cat: "help", desc: "Get help on all available tools, a specific tool, or a category", ex: '{} or {"tool": "brain_search"} or {"category": "brain"}' },+ // --- Files (local virtual filesystem in browser) ---+ read_file: { cat: "files", desc: "Read a file from the virtual filesystem. REQUIRED: path", ex: '{"path": "src/index.ts"}' },+ write_file: { cat: "files", desc: "Create or overwrite a file. REQUIRED: path, content", ex: '{"path": "hello.txt", "content": "Hello World"}' },+ list_files: { cat: "files", desc: "List all files stored in the virtual filesystem", ex: "{}" },+ delete_file: { cat: "files", desc: "Delete a file. REQUIRED: path", ex: '{"path": "temp.txt"}' },+ edit_file: { cat: "files", desc: "Find-and-replace text in a file. REQUIRED: path, old_content, new_content", ex: '{"path": "app.ts", "old_content": "const x = 1", "new_content": "const x = 2"}' },+ grep: { cat: "files", desc: "Search file contents with regex. REQUIRED: pattern. OPTIONAL: path (limit to one file)", ex: '{"pattern": "TODO|FIXME"}' },+ glob: { cat: "files", desc: "Find files by glob pattern. REQUIRED: pattern", ex: '{"pattern": "src/**/*.tsx"}' },+ // --- Memory (persistent key-value with semantic search) ---+ memory_store: { cat: "memory", desc: "Store a value in persistent memory with optional tags. REQUIRED: key, value. OPTIONAL: tags[]", ex: '{"key": "auth-pattern", "value": "JWT with refresh tokens", "tags": ["security"]}' },+ memory_search: { cat: "memory", desc: "Semantic search across stored memories. REQUIRED: query. OPTIONAL: top_k (default 5)", ex: '{"query": "authentication", "top_k": 3}' },+ // --- Tasks ---+ todo_add: { cat: "tasks", desc: "Add a new task. REQUIRED: task (description string)", ex: '{"task": "Fix login redirect bug"}' },+ todo_list: { cat: "tasks", desc: "List all tasks with status indicators", ex: "{}" },+ todo_complete: { cat: "tasks", desc: "Mark a task as complete. REQUIRED: id", ex: '{"id": "todo-1"}' },+ // --- Witness Chain (immutable audit log) ---+ witness_log: { cat: "witness", desc: "Log an action to the immutable witness chain. REQUIRED: action. OPTIONAL: data", ex: '{"action": "file_modified", "data": {"path": "config.json"}}' },+ witness_verify: { cat: "witness", desc: "Verify the integrity of the entire witness chain. Returns VALID/INVALID", ex: "{}" },+ // --- Gallery (agent templates) ---+ gallery_list: { cat: "gallery", desc: "List available agent templates. OPTIONAL: category", ex: '{"category": "development"}' },+ gallery_load: { cat: "gallery", desc: "Load and activate an agent template. REQUIRED: id", ex: '{"id": "development-agent"}' },+ gallery_search: { cat: "gallery", desc: "Search templates by keyword. REQUIRED: query", ex: '{"query": "security"}' },+ // --- Brain (shared collective intelligence at pi.ruv.io, via pi-brain MCP) ---+ brain_status: { cat: "brain", desc: "Check brain health: memory count, graph edges, clusters, embedding engine, drift status", ex: "{}" },+ brain_search: { cat: "brain", desc: "Semantic search across 2,000+ shared memories. REQUIRED: query. OPTIONAL: limit, min_quality", ex: '{"query": "authentication patterns", "limit": 5}' },+ brain_list: { cat: "brain", desc: "List recent memories. OPTIONAL: limit, category, min_quality", ex: '{"limit": 10, "category": "pattern"}' },+ brain_share: { cat: "brain", desc: "Share a learning with the collective. REQUIRED: category, title, content. OPTIONAL: tags[]. Categories: architecture|pattern|solution|convention|security|performance|tooling|debug", ex: '{"category": "pattern", "title": "React auth hook", "content": "useAuth() with refresh token rotation", "tags": ["react", "auth"]}' },+ brain_drift: { cat: "brain", desc: "Check knowledge drift across categories. Shows how knowledge is evolving over time", ex: "{}" },+ brain_partition: { cat: "brain", desc: "Get MinCut knowledge clusters. Shows emergent topic groupings with coherence scores. Use compact=true (default) to avoid large responses", ex: '{"compact": true}' },+ };++ let text: string;+ const reqTool = args?.tool?.toLowerCase();+ const reqCat = args?.category?.toLowerCase();++ if (reqTool && toolDocs[reqTool]) {+ const d = toolDocs[reqTool];+ text = `TOOL: ${reqTool}\nCategory: ${d.cat}\nDescription: ${d.desc}\nExample: ${reqTool}(${d.ex})`;+ } else if (reqCat && reqCat !== "all") {+ const filtered = Object.entries(toolDocs)+ .filter(([, d]) => d.cat === reqCat)+ .map(([n, d]) => ` ${n} — ${d.desc}\n Example: ${n}(${d.ex})`);+ text = filtered.length > 0+ ? `${reqCat.toUpperCase()} TOOLS:\n\n${filtered.join("\n\n")}`+ : `No tools in category: ${reqCat}. Available categories: help, files, memory, tasks, witness, gallery, brain`;+ } else {+ const cats = ["brain", "files", "memory", "tasks", "gallery", "witness", "help"];+ const sections = cats.map((c) => {+ const items = Object.entries(toolDocs)+ .filter(([, d]) => d.cat === c)+ .map(([n, d]) => ` ${n} — ${d.desc}\n Ex: ${n}(${d.ex})`);+ return items.length > 0 ? `${c.toUpperCase()} (${items.length}):\n${items.join("\n")}` : null;+ }).filter(Boolean);+ text = `SYSTEM GUIDANCE — AVAILABLE TOOLS\n\n` ++ `You have two MCP servers:\n` ++ ` 1. RVAgent Local (WASM) — files, memory, tasks, witness, gallery (runs in browser)\n` ++ ` 2. pi-brain (mcp.pi.ruv.io) — shared collective intelligence with 2,000+ memories\n\n` ++ `${sections.join("\n\n")}\n\n` ++ `TIPS:\n` ++ `• Brain tools (brain_*) connect to pi.ruv.io shared knowledge — search before implementing\n` ++ `• Local tools (files, memory, tasks) operate in this browser sandbox\n` ++ `• Always pass REQUIRED parameters in JSON format\n` ++ `• Use witness_log to create audit trails for important actions`;+ }+ response.result = { content: [{ type: "text", text }] };+ break;+ }+ case "read_file": {+ const content = virtualFS.get(args.path);+ if (content === undefined) {+ response.result = { content: [{ type: "text", text: `Error: File not found: ${args.path}` }], isError: true };+ } else {+ response.result = { content: [{ type: "text", text: content }] };+ }+ break;+ }+ case "write_file": {+ virtualFS.set(args.path, args.content);+ response.result = { content: [{ type: "text", text: `Successfully wrote ${args.content.length} bytes to ${args.path}` }] };+ break;+ }+ case "list_files": {+ const files = [...virtualFS.keys()];+ if (files.length === 0) {+ response.result = { content: [{ type: "text", text: "No files in virtual filesystem" }] };+ } else {+ response.result = { content: [{ type: "text", text: `Files:\n${files.map(f => `- ${f}`).join('\n')}` }] };+ }+ break;+ }+ case "delete_file": {+ if (!virtualFS.has(args.path)) {+ response.result = { content: [{ type: "text", text: `Error: File not found: ${args.path}` }], isError: true };+ } else {+ virtualFS.delete(args.path);+ response.result = { content: [{ type: "text", text: `Deleted: ${args.path}` }] };+ }+ break;+ }+ case "edit_file": {+ const existing = virtualFS.get(args.path);+ if (existing === undefined) {+ response.result = { content: [{ type: "text", text: `Error: File not found: ${args.path}` }], isError: true };+ } else if (!existing.includes(args.old_content)) {+ response.result = { content: [{ type: "text", text: `Error: old_content not found in file` }], isError: true };+ } else {+ virtualFS.set(args.path, existing.replace(args.old_content, args.new_content));+ response.result = { content: [{ type: "text", text: `Successfully edited ${args.path}` }] };+ }+ break;+ }+ case "grep": {+ const pattern = new RegExp(args.pattern, 'gi');+ const results: string[] = [];+ for (const [path, content] of virtualFS.entries()) {+ if (args.path && path !== args.path) continue;+ const lines = content.split('\n');+ lines.forEach((line, idx) => {+ if (pattern.test(line)) {+ results.push(`${path}:${idx + 1}: ${line}`);+ }+ });+ }+ response.result = { content: [{ type: "text", text: results.length > 0 ? results.join('\n') : 'No matches found' }] };+ break;+ }+ case "glob": {+ const globPattern = args.pattern.replace(/\*/g, '.*').replace(/\?/g, '.');+ const regex = new RegExp(`^${globPattern}$`);+ const matches = [...virtualFS.keys()].filter(f => regex.test(f));+ response.result = { content: [{ type: "text", text: matches.length > 0 ? matches.join('\n') : 'No matches found' }] };+ break;+ }+ case "todo_add": {+ const id = `todo-${todoIdCounter++}`;+ todoList.push({ id, task: args.task, completed: false, created: Date.now() });+ response.result = { content: [{ type: "text", text: `Added task: ${args.task} (id: ${id})` }] };+ break;+ }+ case "todo_list": {+ if (todoList.length === 0) {+ response.result = { content: [{ type: "text", text: "No tasks in todo list" }] };+ } else {+ const formatted = todoList.map(t =>+ `${t.completed ? '✓' : '○'} [${t.id}] ${t.task}`+ ).join('\n');+ response.result = { content: [{ type: "text", text: `Tasks:\n${formatted}` }] };+ }+ break;+ }+ case "todo_complete": {+ const todo = todoList.find(t => t.id === args.id);+ if (!todo) {+ response.result = { content: [{ type: "text", text: `Error: Task not found: ${args.id}` }], isError: true };+ } else {+ todo.completed = true;+ response.result = { content: [{ type: "text", text: `Completed: ${todo.task}` }] };+ }+ break;+ }+ case "memory_store": {+ memoryStore.set(args.key, { key: args.key, value: args.value, tags: args.tags || [] });+ response.result = { content: [{ type: "text", text: `Stored memory: ${args.key}` }] };+ break;+ }+ case "memory_search": {+ const query = (args.query as string).toLowerCase();+ const topK = args.top_k || 5;+ const results = [...memoryStore.values()]+ .filter(m => m.key.toLowerCase().includes(query) || m.value.toLowerCase().includes(query) || m.tags.some(t => t.toLowerCase().includes(query)))+ .slice(0, topK)+ .map(m => `[${m.key}] ${m.value.slice(0, 100)}${m.value.length > 100 ? '...' : ''}`);+ response.result = { content: [{ type: "text", text: results.length > 0 ? `Found ${results.length} results:\n${results.join('\n')}` : 'No memories found' }] };+ break;+ }+ case "witness_log": {+ const hash = addWitnessEntry(args.action, args.data || {});+ response.result = { content: [{ type: "text", text: `Logged to witness chain: ${args.action} (hash: ${hash})` }] };+ break;+ }+ case "witness_verify": {+ let valid = true;+ let prevHash = "genesis";+ for (const entry of witnessChain) {+ if (entry.prev_hash !== prevHash) {+ valid = false;+ break;+ }+ prevHash = entry.hash;+ }+ response.result = { content: [{ type: "text", text: `Witness chain: ${valid ? 'VALID' : 'INVALID'} (${witnessChain.length} entries)` }] };+ break;+ }+ case "gallery_list": {+ const filtered = args.category+ ? builtinTemplates.filter(t => t.category === args.category)+ : builtinTemplates;+ const list = filtered.map(t => `- ${t.id}: ${t.name} (${t.category})`).join('\n');+ response.result = { content: [{ type: "text", text: `Gallery Templates:\n${list}` }] };+ break;+ }+ case "gallery_load": {+ const template = builtinTemplates.find(t => t.id === args.id);+ if (!template) {+ response.result = { content: [{ type: "text", text: `Error: Template not found: ${args.id}` }], isError: true };+ } else {+ activeTemplateId = args.id;+ response.result = { content: [{ type: "text", text: `Loaded template: ${template.name}\nDescription: ${template.description}\nTools: ${template.tools?.map(t => t.name).join(', ') || 'none'}\nSkills: ${template.skills?.map(s => s.trigger).join(', ') || 'none'}` }] };+ }+ break;+ }+ case "gallery_search": {+ const q = (args.query as string).toLowerCase();+ const matches = builtinTemplates.filter(t =>+ t.name.toLowerCase().includes(q) ||+ t.description.toLowerCase().includes(q) ||+ t.tags.some(tag => tag.toLowerCase().includes(q))+ );+ if (matches.length === 0) {+ response.result = { content: [{ type: "text", text: "No templates found matching your query" }] };+ } else {+ const list = matches.map(t => `- ${t.id}: ${t.name}\n ${t.description}`).join('\n');+ response.result = { content: [{ type: "text", text: `Found ${matches.length} templates:\n${list}` }] };+ }+ break;+ }+ default:+ response.error = { code: -32601, message: `Unknown tool: ${name}` };+ }+ break;+ }++ case "prompts/list": {+ // Return prompts from active template or all templates+ const prompts = activeTemplateId+ ? builtinTemplates.find(t => t.id === activeTemplateId)?.prompts || []+ : builtinTemplates.flatMap(t => t.prompts || []);+ response.result = { prompts: prompts.map(p => ({ name: p.name, description: `Prompt: ${p.name}` })) };+ break;+ }++ case "prompts/get": {+ const allPrompts = builtinTemplates.flatMap(t => t.prompts || []);+ const prompt = allPrompts.find(p => p.name === params.name);+ if (prompt) {+ response.result = {+ messages: [{ role: "assistant", content: { type: "text", text: prompt.system_prompt } }],+ };+ } else {+ response.error = { code: -32602, message: `Prompt not found: ${params.name}` };+ }+ break;+ }++ case "gallery/list":+ response.result = { templates: builtinTemplates };+ break;++ case "gallery/load": {+ const template = builtinTemplates.find((t) => t.id === params.id);+ if (template) {+ activeTemplateId = params.id;+ response.result = { template_id: template.id, name: template.name };+ } else {+ response.error = { code: -32602, message: `Template not found: ${params.id}` };+ }+ break;+ }++ case "gallery/search": {+ const q = (params.query as string).toLowerCase();+ const results = builtinTemplates+ .filter(t => t.name.toLowerCase().includes(q) || t.description.toLowerCase().includes(q) || t.tags.some(tag => tag.toLowerCase().includes(q)))+ .map(t => ({ id: t.id, name: t.name, description: t.description, category: t.category, tags: t.tags, relevance: t.name.toLowerCase().includes(q) ? 1.0 : 0.5 }));+ response.result = { results };+ break;+ }++ default:+ response.error = { code: -32601, message: `Method not found: ${method}` };+ }++ return JSON.stringify(response);+ }++ gallery(): WasmGallery {+ return new MockWasmGallery();+ }+ }++ class MockWasmGallery implements WasmGallery {+ list(): GalleryTemplate[] {+ return builtinTemplates;+ }++ listByCategory(category: string): GalleryTemplate[] {+ return builtinTemplates.filter((t) => t.category === category);+ }++ search(query: string): SearchResult[] {+ const q = query.toLowerCase();+ return builtinTemplates+ .filter((t) => t.name.toLowerCase().includes(q) || t.description.toLowerCase().includes(q) || t.tags.some((tag) => tag.toLowerCase().includes(q)))+ .map((t) => ({+ id: t.id,+ name: t.name,+ description: t.description,+ category: t.category,+ tags: t.tags,+ relevance: t.name.toLowerCase().includes(q) ? 1.0 : 0.5,+ }));+ }++ get(id: string): GalleryTemplate {+ const template = builtinTemplates.find((t) => t.id === id);+ if (!template) throw new Error(`Template not found: ${id}`);+ return template;+ }++ loadRvf(id: string): Uint8Array {+ const template = this.get(id);+ // Return mock RVF bytes (magic + version + minimal content)+ const encoder = new TextEncoder();+ const json = JSON.stringify(template);+ const jsonBytes = encoder.encode(json);+ const rvf = new Uint8Array(8 + jsonBytes.length);+ rvf.set([0x52, 0x56, 0x46, 0x00, 0x01, 0x00, 0x00, 0x00]); // RVF\0 + version+ rvf.set(jsonBytes, 8);+ return rvf;+ }++ setActive(id: string): void {+ activeTemplateId = id;+ }++ getActive(): string | null {+ return activeTemplateId;+ }++ configure(_configJson: string): void {}++ getConfig(): unknown {+ return {};+ }++ addCustom(_templateJson: string): void {}++ removeCustom(_id: string): void {}++ getCategories(): Record<string, number> {+ const categories: Record<string, number> = {};+ builtinTemplates.forEach((t) => {+ categories[t.category] = (categories[t.category] || 0) + 1;+ });+ return categories;+ }++ count(): number {+ return builtinTemplates.length;+ }++ exportCustom(): GalleryTemplate[] {+ return [];+ }++ importCustom(_templatesJson: string): number {+ return 0;+ }+ }++ class MockWasmRvfBuilder implements WasmRvfBuilder {+ private tools: unknown[] = [];+ private prompts: unknown[] = [];+ private skills: unknown[] = [];+ private mcpTools: unknown[] = [];+ private capabilities: unknown[] = [];+ private orchestrator: unknown = null;++ addTool(toolJson: string): void {+ this.tools.push(JSON.parse(toolJson));+ }++ addTools(toolsJson: string): void {+ this.tools.push(...JSON.parse(toolsJson));+ }++ addPrompt(promptJson: string): void {+ this.prompts.push(JSON.parse(promptJson));+ }++ addPrompts(promptsJson: string): void {+ this.prompts.push(...JSON.parse(promptsJson));+ }++ addSkill(skillJson: string): void {+ this.skills.push(JSON.parse(skillJson));+ }++ addSkills(skillsJson: string): void {+ this.skills.push(...JSON.parse(skillsJson));+ }++ addMcpTools(mcpToolsJson: string): void {+ this.mcpTools.push(...JSON.parse(mcpToolsJson));+ }++ addCapabilities(capsJson: string): void {+ this.capabilities.push(...JSON.parse(capsJson));+ }++ setOrchestrator(orchestratorJson: string): void {+ this.orchestrator = JSON.parse(orchestratorJson);+ }++ build(): Uint8Array {+ const content = {+ tools: this.tools,+ prompts: this.prompts,+ skills: this.skills,+ mcp_tools: this.mcpTools,+ capabilities: this.capabilities,+ orchestrator: this.orchestrator,+ };+ const encoder = new TextEncoder();+ const json = JSON.stringify(content);+ const jsonBytes = encoder.encode(json);+ const rvf = new Uint8Array(8 + jsonBytes.length);+ rvf.set([0x52, 0x56, 0x46, 0x00, 0x01, 0x00, 0x00, 0x00]); // RVF\0 + version+ rvf.set(jsonBytes, 8);+ return rvf;+ }+ }++ return {+ WasmMcpServer: MockWasmMcpServer as unknown as new () => WasmMcpServer,+ WasmGallery: MockWasmGallery as unknown as new () => WasmGallery,+ WasmRvfBuilder: MockWasmRvfBuilder as unknown as new () => WasmRvfBuilder,+ };+}++/**+ * Load the WASM module+ */+export async function loadWasm(): Promise<typeof wasmModule> {+ if (!browser) {+ return null;+ }++ if (wasmModule) {+ return wasmModule;+ }++ if (loadPromise) {+ return loadPromise;+ }++ loadPromise = (async () => {+ try {+ // Check if WASM is already loaded globally (e.g., via script tag in index.html)+ // To use real WASM, add this to your index.html:+ // <script type="module">+ // import init, * as wasm from '/wasm/rvagent_wasm.js';+ // await init();+ // window.rvagent_wasm = wasm;+ // </script>+ if (typeof window !== "undefined" && (window as unknown as Record<string, unknown>).rvagent_wasm) {+ const wasm = (window as unknown as Record<string, unknown>).rvagent_wasm as {+ WasmMcpServer: new () => WasmMcpServer;+ WasmGallery: new () => WasmGallery;+ WasmRvfBuilder: new () => WasmRvfBuilder;+ };++ wasmModule = {+ WasmMcpServer: wasm.WasmMcpServer,+ WasmGallery: wasm.WasmGallery,+ WasmRvfBuilder: wasm.WasmRvfBuilder,+ };++ console.log("[WASM] rvagent-wasm loaded from global");+ return wasmModule;+ }++ // Use mock module for development/testing+ // The mock provides full MCP functionality with an in-memory virtual filesystem+ console.log("[WASM] Using mock rvagent-wasm implementation");+ wasmModule = createMockWasmModule();+ return wasmModule;+ } catch (error) {+ console.error("[WASM] Failed to initialize:", error);+ loadPromise = null;+ wasmModule = createMockWasmModule();+ return wasmModule;+ }+ })();++ return loadPromise;+}++/**+ * Check if WASM is loaded+ */+export function isWasmLoaded(): boolean {+ return wasmModule !== null;+}++/**+ * Get the WASM module (throws if not loaded)+ */+export function getWasm(): NonNullable<typeof wasmModule> {+ if (!wasmModule) {+ throw new Error("WASM module not loaded. Call loadWasm() first.");+ }+ return wasmModule;+}diff --git a/ruflo/src/ruvocal/src/lib/wasm/tests/wasm-capabilities.test.ts b/ruflo/src/ruvocal/src/lib/wasm/tests/wasm-capabilities.test.tsnew file mode 100644index 0000000000..1ce60f46a4--- /dev/null+++ b/ruflo/src/ruvocal/src/lib/wasm/tests/wasm-capabilities.test.ts@@ -0,0 +1,565 @@+/**+ * WASM MCP Server Capability Tests+ * Tests all WASM capabilities: MCP server, gallery, RVF builder, IndexedDB persistence+ *+ * Run with: npx vitest run src/lib/wasm/tests/wasm-capabilities.test.ts+ */++import { describe, it, expect, beforeAll, afterAll, vi } from "vitest";++// Mock browser environment+vi.mock("$app/environment", () => ({+ browser: true,+}));++// Mock IndexedDB for Node environment+const mockIDB = {+ files: new Map<string, { path: string; content: string; createdAt: number; updatedAt: number }>(),+ settings: new Map<string, unknown>(),+ rvfContainers: new Map<string, { id: string; name: string; data: Uint8Array }>(),+};++vi.mock("$lib/wasm/idb", () => ({+ writeFile: vi.fn(async (path: string, content: string) => {+ const now = Date.now();+ mockIDB.files.set(path, { path, content, createdAt: now, updatedAt: now });+ }),+ readFile: vi.fn(async (path: string) => {+ return mockIDB.files.get(path)?.content ?? null;+ }),+ deleteFile: vi.fn(async (path: string) => {+ mockIDB.files.delete(path);+ }),+ listFiles: vi.fn(async () => {+ return Array.from(mockIDB.files.values());+ }),+ clearFiles: vi.fn(async () => {+ mockIDB.files.clear();+ }),+ getSetting: vi.fn(async <T>(key: string): Promise<T | null> => {+ return (mockIDB.settings.get(key) as T) ?? null;+ }),+ setSetting: vi.fn(async <T>(key: string, value: T) => {+ mockIDB.settings.set(key, value);+ }),+ saveRvfContainer: vi.fn(async (id: string, name: string, data: Uint8Array) => {+ mockIDB.rvfContainers.set(id, { id, name, data });+ }),+ loadRvfContainer: vi.fn(async (id: string) => {+ return mockIDB.rvfContainers.get(id) ?? null;+ }),+ listRvfContainers: vi.fn(async () => {+ return Array.from(mockIDB.rvfContainers.values());+ }),+ deleteRvfContainer: vi.fn(async (id: string) => {+ mockIDB.rvfContainers.delete(id);+ }),+ openDatabase: vi.fn(async () => ({})),+ closeDatabase: vi.fn(() => {}),+}));++describe("WASM MCP Server Capabilities", () => {+ describe("Type Definitions", () => {+ it("should export correct GalleryTemplate interface", async () => {+ const template = {+ id: "test-template",+ name: "Test Template",+ description: "A test template",+ category: "development",+ version: "1.0.0",+ author: "test",+ tags: ["test", "development"],+ builtin: true,+ tools: [],+ prompts: [],+ skills: [],+ mcp_tools: [],+ capabilities: [],+ };++ expect(template).toHaveProperty("id");+ expect(template).toHaveProperty("name");+ expect(template).toHaveProperty("category");+ expect(template).toHaveProperty("builtin");+ });++ it("should export correct SearchResult interface", () => {+ const result = {+ id: "test-id",+ name: "Test",+ description: "Test description",+ category: "testing",+ tags: ["test"],+ relevance: 0.95,+ };++ expect(result.relevance).toBeGreaterThanOrEqual(0);+ expect(result.relevance).toBeLessThanOrEqual(1);+ });++ it("should export correct MCPTool interface", () => {+ const tool = {+ name: "read_file",+ description: "Read a file from the virtual filesystem",+ inputSchema: {+ type: "object",+ properties: {+ path: { type: "string", description: "File path to read" },+ },+ required: ["path"],+ },+ };++ expect(tool).toHaveProperty("name");+ expect(tool).toHaveProperty("inputSchema");+ });+ });++ describe("IndexedDB Persistence Layer", () => {+ beforeAll(() => {+ mockIDB.files.clear();+ mockIDB.settings.clear();+ mockIDB.rvfContainers.clear();+ });++ it("should write and read files", async () => {+ const { writeFile, readFile } = await import("$lib/wasm/idb");++ await writeFile("/test/hello.txt", "Hello, World!");+ const content = await readFile("/test/hello.txt");++ expect(content).toBe("Hello, World!");+ });++ it("should list all files", async () => {+ const { writeFile, listFiles } = await import("$lib/wasm/idb");++ await writeFile("/test/file1.txt", "content1");+ await writeFile("/test/file2.txt", "content2");++ const files = await listFiles();+ expect(files.length).toBeGreaterThanOrEqual(2);+ });++ it("should delete files", async () => {+ const { writeFile, readFile, deleteFile } = await import("$lib/wasm/idb");++ await writeFile("/test/to-delete.txt", "delete me");+ await deleteFile("/test/to-delete.txt");+ const content = await readFile("/test/to-delete.txt");++ expect(content).toBeNull();+ });++ it("should save and load settings", async () => {+ const { setSetting, getSetting } = await import("$lib/wasm/idb");++ await setSetting("testKey", { value: 42 });+ const setting = await getSetting<{ value: number }>("testKey");++ expect(setting).toEqual({ value: 42 });+ });++ it("should save and load RVF containers", async () => {+ const { saveRvfContainer, loadRvfContainer } = await import("$lib/wasm/idb");++ const testData = new Uint8Array([0x52, 0x56, 0x46, 0x00]); // "RVF\0"+ await saveRvfContainer("test-rvf", "Test Container", testData);+ const container = await loadRvfContainer("test-rvf");++ expect(container).not.toBeNull();+ expect(container?.name).toBe("Test Container");+ expect(container?.data).toEqual(testData);+ });++ it("should list RVF containers", async () => {+ const { listRvfContainers } = await import("$lib/wasm/idb");++ const containers = await listRvfContainers();+ expect(containers.length).toBeGreaterThanOrEqual(1);+ });+ });++ describe("MCP Server Protocol", () => {+ it("should validate JSON-RPC request format", () => {+ const request = {+ jsonrpc: "2.0",+ id: 1,+ method: "tools/list",+ params: {},+ };++ expect(request.jsonrpc).toBe("2.0");+ expect(typeof request.id).toBe("number");+ expect(request.method).toBe("tools/list");+ });++ it("should validate JSON-RPC response format", () => {+ const successResponse = {+ jsonrpc: "2.0",+ id: 1,+ result: { tools: [] },+ };++ const errorResponse = {+ jsonrpc: "2.0",+ id: 2,+ error: { code: -32600, message: "Invalid Request" },+ };++ expect(successResponse.result).toBeDefined();+ expect(errorResponse.error.code).toBe(-32600);+ });++ it("should define expected MCP methods", () => {+ const expectedMethods = [+ "initialize",+ "tools/list",+ "tools/call",+ "prompts/list",+ "prompts/get",+ "resources/list",+ "resources/read",+ "gallery/list",+ "gallery/load",+ "gallery/search",+ ];++ expectedMethods.forEach((method) => {+ expect(typeof method).toBe("string");+ expect(method.length).toBeGreaterThan(0);+ });+ });+ });++ describe("Gallery Template Structure", () => {+ it("should define valid template categories", () => {+ const validCategories = [+ "development",+ "research",+ "testing",+ "security",+ "orchestration",+ "documentation",+ "devops",+ "custom",+ ];++ validCategories.forEach((category) => {+ expect(typeof category).toBe("string");+ });+ });++ it("should validate tool definition structure", () => {+ const tool = {+ name: "write_file",+ description: "Write content to a file",+ parameters: {+ type: "object",+ properties: {+ path: { type: "string" },+ content: { type: "string" },+ },+ required: ["path", "content"],+ },+ returns: "boolean",+ };++ expect(tool.parameters.type).toBe("object");+ expect(tool.parameters.required).toContain("path");+ expect(tool.parameters.required).toContain("content");+ });++ it("should validate prompt definition structure", () => {+ const prompt = {+ name: "code-review",+ system_prompt: "You are a senior code reviewer...",+ version: "1.0.0",+ };++ expect(prompt.name).toBeTruthy();+ expect(prompt.system_prompt.length).toBeGreaterThan(0);+ });++ it("should validate skill definition structure", () => {+ const skill = {+ name: "git-commit",+ description: "Create a git commit with conventional format",+ trigger: "/commit",+ content: "When the user types /commit...",+ };++ expect(skill.trigger).toMatch(/^\//);+ });++ it("should validate orchestrator configuration", () => {+ const orchestrator = {+ topology: "hierarchical",+ agents: [+ { id: "coordinator", agent_type: "planner", prompt_ref: "coordinator" },+ { id: "coder", agent_type: "coder", prompt_ref: "coder" },+ { id: "reviewer", agent_type: "reviewer", prompt_ref: "reviewer" },+ ],+ connections: [+ ["coordinator", "coder"],+ ["coordinator", "reviewer"],+ ["coder", "reviewer"],+ ],+ };++ expect(orchestrator.topology).toBe("hierarchical");+ expect(orchestrator.agents.length).toBe(3);+ expect(orchestrator.connections.length).toBe(3);+ });+ });++ describe("RVF Container Format", () => {+ it("should define RVF magic bytes", () => {+ const RVF_MAGIC = new Uint8Array([0x52, 0x56, 0x46, 0x00]); // "RVF\0"+ expect(RVF_MAGIC[0]).toBe(0x52); // 'R'+ expect(RVF_MAGIC[1]).toBe(0x56); // 'V'+ expect(RVF_MAGIC[2]).toBe(0x46); // 'F'+ expect(RVF_MAGIC[3]).toBe(0x00); // null terminator+ });++ it("should validate RVF version format", () => {+ const versions = ["1.0.0", "1.1.0", "2.0.0"];+ const versionRegex = /^\d+\.\d+\.\d+$/;++ versions.forEach((version) => {+ expect(version).toMatch(versionRegex);+ });+ });++ it("should define RVF section types", () => {+ const sectionTypes = {+ METADATA: 0x01,+ TOOLS: 0x02,+ PROMPTS: 0x03,+ SKILLS: 0x04,+ MCP_TOOLS: 0x05,+ CAPABILITIES: 0x06,+ ORCHESTRATOR: 0x07,+ CHECKSUM: 0xff,+ };++ expect(Object.keys(sectionTypes).length).toBe(8);+ expect(sectionTypes.METADATA).toBe(0x01);+ expect(sectionTypes.CHECKSUM).toBe(0xff);+ });+ });++ describe("MCP Server Type Extension", () => {+ it("should support wasm server type", () => {+ type ServerType = "base" | "custom" | "wasm";++ const serverTypes: ServerType[] = ["base", "custom", "wasm"];+ expect(serverTypes).toContain("wasm");+ });++ it("should define WASM server properties", () => {+ const wasmServer = {+ id: "wasm-rvagent",+ name: "RVAgent Local (WASM)",+ url: "wasm://local",+ type: "wasm" as const,+ status: "connected" as const,+ isLocked: false,+ tools: [],+ wasmTemplateId: "development-agent",+ wasmTemplateName: "Development Agent",+ };++ expect(wasmServer.type).toBe("wasm");+ expect(wasmServer.url).toBe("wasm://local");+ expect(wasmServer.wasmTemplateId).toBeDefined();+ });+ });++ describe("Browser Integration", () => {+ it("should detect browser environment", async () => {+ const { browser } = await import("$app/environment");+ expect(browser).toBe(true);+ });++ it("should handle IndexedDB availability", () => {+ // In test environment, IndexedDB is mocked+ const hasIndexedDB = typeof indexedDB !== "undefined" || true; // mocked+ expect(hasIndexedDB).toBe(true);+ });++ it("should validate crypto.randomUUID availability", () => {+ // crypto.randomUUID should be available in modern browsers+ const uuid = crypto.randomUUID();+ expect(uuid).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i);+ });+ });++ describe("Error Handling", () => {+ it("should define MCP error codes", () => {+ const errorCodes = {+ PARSE_ERROR: -32700,+ INVALID_REQUEST: -32600,+ METHOD_NOT_FOUND: -32601,+ INVALID_PARAMS: -32602,+ INTERNAL_ERROR: -32603,+ SERVER_ERROR_START: -32099,+ SERVER_ERROR_END: -32000,+ };++ expect(errorCodes.PARSE_ERROR).toBe(-32700);+ expect(errorCodes.INTERNAL_ERROR).toBe(-32603);+ });++ it("should format error responses correctly", () => {+ const errorResponse = {+ jsonrpc: "2.0",+ id: null,+ error: {+ code: -32603,+ message: "WASM MCP server not initialized",+ data: { reason: "Module failed to load" },+ },+ };++ expect(errorResponse.error.code).toBeLessThan(0);+ expect(errorResponse.error.message).toBeTruthy();+ });+ });+});++describe("WASM Gallery Operations", () => {+ it("should define gallery list operation", () => {+ const listRequest = {+ jsonrpc: "2.0",+ id: 1,+ method: "gallery/list",+ };++ expect(listRequest.method).toBe("gallery/list");+ });++ it("should define gallery search operation", () => {+ const searchRequest = {+ jsonrpc: "2.0",+ id: 2,+ method: "gallery/search",+ params: { query: "development" },+ };++ expect(searchRequest.params.query).toBe("development");+ });++ it("should define gallery load operation", () => {+ const loadRequest = {+ jsonrpc: "2.0",+ id: 3,+ method: "gallery/load",+ params: { id: "development-agent" },+ };++ expect(loadRequest.params.id).toBe("development-agent");+ });++ it("should define gallery categories operation", () => {+ const categoriesRequest = {+ jsonrpc: "2.0",+ id: 4,+ method: "gallery/categories",+ };++ expect(categoriesRequest.method).toBe("gallery/categories");+ });+});++describe("Tool Execution", () => {+ it("should define read_file tool schema", () => {+ const readFileTool = {+ name: "read_file",+ description: "Read content from a file in the virtual filesystem",+ inputSchema: {+ type: "object",+ properties: {+ path: {+ type: "string",+ description: "Absolute path to the file",+ },+ },+ required: ["path"],+ },+ };++ expect(readFileTool.inputSchema.required).toContain("path");+ });++ it("should define write_file tool schema", () => {+ const writeFileTool = {+ name: "write_file",+ description: "Write content to a file in the virtual filesystem",+ inputSchema: {+ type: "object",+ properties: {+ path: {+ type: "string",+ description: "Absolute path to the file",+ },+ content: {+ type: "string",+ description: "Content to write",+ },+ },+ required: ["path", "content"],+ },+ };++ expect(writeFileTool.inputSchema.required).toContain("path");+ expect(writeFileTool.inputSchema.required).toContain("content");+ });++ it("should define list_files tool schema", () => {+ const listFilesTool = {+ name: "list_files",+ description: "List all files in the virtual filesystem",+ inputSchema: {+ type: "object",+ properties: {},+ },+ };++ expect(listFilesTool.name).toBe("list_files");+ });++ it("should define edit_file tool schema", () => {+ const editFileTool = {+ name: "edit_file",+ description: "Edit a file by replacing old content with new content",+ inputSchema: {+ type: "object",+ properties: {+ path: { type: "string" },+ old_content: { type: "string" },+ new_content: { type: "string" },+ },+ required: ["path", "old_content", "new_content"],+ },+ };++ expect(editFileTool.inputSchema.required.length).toBe(3);+ });++ it("should define delete_file tool schema", () => {+ const deleteFileTool = {+ name: "delete_file",+ description: "Delete a file from the virtual filesystem",+ inputSchema: {+ type: "object",+ properties: {+ path: { type: "string" },+ },+ required: ["path"],+ },+ };++ expect(deleteFileTool.name).toBe("delete_file");+ });+});diff --git a/ruflo/src/ruvocal/static/wasm/rvagent_wasm.js b/ruflo/src/ruvocal/static/wasm/rvagent_wasm.jsnew file mode 100644index 0000000000..060c2b266e--- /dev/null+++ b/ruflo/src/ruvocal/static/wasm/rvagent_wasm.js@@ -0,0 +1,1539 @@+/* @ts-self-types="./rvagent_wasm.d.ts" */++/**+ * A model provider that delegates to a JavaScript callback function.+ *+ * The JS callback receives a JSON string of messages and must return+ * a Promise that resolves to a JSON string response.+ *+ * # JavaScript usage+ * ```js+ * const provider = new JsModelProvider(async (messagesJson) => {+ * const messages = JSON.parse(messagesJson);+ * const response = await callMyModel(messages);+ * return JSON.stringify(response);+ * });+ * ```+ */+export class JsModelProvider {+ __destroy_into_raw() {+ const ptr = this.__wbg_ptr;+ this.__wbg_ptr = 0;+ JsModelProviderFinalization.unregister(this);+ return ptr;+ }+ free() {+ const ptr = this.__destroy_into_raw();+ wasm.__wbg_jsmodelprovider_free(ptr, 0);+ }+ /**+ * Send messages to the JS model provider and get a response.+ *+ * `messages_json` is a JSON-serialized array of message objects.+ * Returns the model's response as a JSON string.+ * @param {string} messages_json+ * @returns {Promise<string>}+ */+ complete(messages_json) {+ const ptr0 = passStringToWasm0(messages_json, wasm.__wbindgen_export, wasm.__wbindgen_export2);+ const len0 = WASM_VECTOR_LEN;+ const ret = wasm.jsmodelprovider_complete(this.__wbg_ptr, ptr0, len0);+ return takeObject(ret);+ }+ /**+ * Create a new provider wrapping a JavaScript async function.+ *+ * The function must accept a JSON string and return a Promise<string>.+ * @param {Function} callback+ */+ constructor(callback) {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ wasm.jsmodelprovider_new(retptr, addHeapObject(callback));+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);+ if (r2) {+ throw takeObject(r1);+ }+ this.__wbg_ptr = r0 >>> 0;+ JsModelProviderFinalization.register(this, this.__wbg_ptr, this);+ return this;+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+}+if (Symbol.dispose) JsModelProvider.prototype[Symbol.dispose] = JsModelProvider.prototype.free;++/**+ * rvAgent WASM — browser and Node.js agent execution.+ *+ * Create with `new WasmAgent(configJson)` from JavaScript.+ */+export class WasmAgent {+ __destroy_into_raw() {+ const ptr = this.__wbg_ptr;+ this.__wbg_ptr = 0;+ WasmAgentFinalization.unregister(this);+ return ptr;+ }+ free() {+ const ptr = this.__destroy_into_raw();+ wasm.__wbg_wasmagent_free(ptr, 0);+ }+ /**+ * Execute a tool directly by passing a JSON tool request.+ * @param {string} tool_json+ * @returns {any}+ */+ execute_tool(tool_json) {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ const ptr0 = passStringToWasm0(tool_json, wasm.__wbindgen_export, wasm.__wbindgen_export2);+ const len0 = WASM_VECTOR_LEN;+ wasm.wasmagent_execute_tool(retptr, this.__wbg_ptr, ptr0, len0);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);+ if (r2) {+ throw takeObject(r1);+ }+ return takeObject(r0);+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Get the number of files in the virtual filesystem.+ * @returns {number}+ */+ file_count() {+ const ret = wasm.wasmagent_file_count(this.__wbg_ptr);+ return ret >>> 0;+ }+ /**+ * Get the current agent state as JSON.+ * @returns {any}+ */+ get_state() {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ wasm.wasmagent_get_state(retptr, this.__wbg_ptr);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);+ if (r2) {+ throw takeObject(r1);+ }+ return takeObject(r0);+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Get the todo list as JSON.+ * @returns {any}+ */+ get_todos() {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ wasm.wasmagent_get_todos(retptr, this.__wbg_ptr);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);+ if (r2) {+ throw takeObject(r1);+ }+ return takeObject(r0);+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Get the list of available tools.+ * @returns {any}+ */+ get_tools() {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ wasm.wasmagent_get_tools(retptr, this.__wbg_ptr);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);+ if (r2) {+ throw takeObject(r1);+ }+ return takeObject(r0);+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Check whether the agent is stopped.+ * @returns {boolean}+ */+ is_stopped() {+ const ret = wasm.wasmagent_is_stopped(this.__wbg_ptr);+ return ret !== 0;+ }+ /**+ * Get the configured model identifier.+ * @returns {string}+ */+ model() {+ let deferred1_0;+ let deferred1_1;+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ wasm.wasmagent_model(retptr, this.__wbg_ptr);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ deferred1_0 = r0;+ deferred1_1 = r1;+ return getStringFromWasm0(r0, r1);+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ wasm.__wbindgen_export4(deferred1_0, deferred1_1, 1);+ }+ }+ /**+ * Get the agent name, if configured.+ * @returns {string | undefined}+ */+ name() {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ wasm.wasmagent_name(retptr, this.__wbg_ptr);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ let v1;+ if (r0 !== 0) {+ v1 = getStringFromWasm0(r0, r1).slice();+ wasm.__wbindgen_export4(r0, r1 * 1, 1);+ }+ return v1;+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Create a new WasmAgent from a JSON configuration string.+ *+ * # Example (JavaScript)+ * ```js+ * const agent = new WasmAgent('{"model": "anthropic:claude-sonnet-4-20250514"}');+ * ```+ * @param {string} config_json+ */+ constructor(config_json) {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ const ptr0 = passStringToWasm0(config_json, wasm.__wbindgen_export, wasm.__wbindgen_export2);+ const len0 = WASM_VECTOR_LEN;+ wasm.wasmagent_new(retptr, ptr0, len0);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);+ if (r2) {+ throw takeObject(r1);+ }+ this.__wbg_ptr = r0 >>> 0;+ WasmAgentFinalization.register(this, this.__wbg_ptr, this);+ return this;+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Send a prompt and get a response.+ *+ * If a model provider is set, the prompt is sent to the JS model.+ * Otherwise, returns an echo response for testing.+ * @param {string} input+ * @returns {Promise<any>}+ */+ prompt(input) {+ const ptr0 = passStringToWasm0(input, wasm.__wbindgen_export, wasm.__wbindgen_export2);+ const len0 = WASM_VECTOR_LEN;+ const ret = wasm.wasmagent_prompt(this.__wbg_ptr, ptr0, len0);+ return takeObject(ret);+ }+ /**+ * Reset the agent state, clearing messages and turn count.+ */+ reset() {+ wasm.wasmagent_reset(this.__wbg_ptr);+ }+ /**+ * Attach a JavaScript model provider callback.+ *+ * The callback receives a JSON string of messages and must return+ * a `Promise<string>` with the model response.+ * @param {Function} callback+ */+ set_model_provider(callback) {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ wasm.wasmagent_set_model_provider(retptr, this.__wbg_ptr, addHeapObject(callback));+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ if (r1) {+ throw takeObject(r0);+ }+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Get the current turn count.+ * @returns {number}+ */+ turn_count() {+ const ret = wasm.wasmagent_turn_count(this.__wbg_ptr);+ return ret >>> 0;+ }+ /**+ * Get the crate version.+ * @returns {string}+ */+ static version() {+ let deferred1_0;+ let deferred1_1;+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ wasm.wasmagent_version(retptr);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ deferred1_0 = r0;+ deferred1_1 = r1;+ return getStringFromWasm0(r0, r1);+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ wasm.__wbindgen_export4(deferred1_0, deferred1_1, 1);+ }+ }+}+if (Symbol.dispose) WasmAgent.prototype[Symbol.dispose] = WasmAgent.prototype.free;++/**+ * RVF App Gallery — browse, load, and configure agent templates.+ *+ * # Example (JavaScript)+ * ```js+ * const gallery = new WasmGallery();+ *+ * // List all templates+ * const templates = gallery.list();+ *+ * // Search by tags+ * const results = gallery.search("security testing");+ *+ * // Get template details+ * const template = gallery.get("coder");+ *+ * // Load as RVF container+ * const rvfBytes = gallery.loadRvf("coder");+ *+ * // Configure template+ * gallery.configure("coder", { maxTurns: 100 });+ * ```+ */+export class WasmGallery {+ __destroy_into_raw() {+ const ptr = this.__wbg_ptr;+ this.__wbg_ptr = 0;+ WasmGalleryFinalization.unregister(this);+ return ptr;+ }+ free() {+ const ptr = this.__destroy_into_raw();+ wasm.__wbg_wasmgallery_free(ptr, 0);+ }+ /**+ * Add a custom template to the gallery.+ * @param {string} template_json+ */+ addCustom(template_json) {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ const ptr0 = passStringToWasm0(template_json, wasm.__wbindgen_export, wasm.__wbindgen_export2);+ const len0 = WASM_VECTOR_LEN;+ wasm.wasmgallery_addCustom(retptr, this.__wbg_ptr, ptr0, len0);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ if (r1) {+ throw takeObject(r0);+ }+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Configure the active template with overrides.+ * @param {string} config_json+ */+ configure(config_json) {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ const ptr0 = passStringToWasm0(config_json, wasm.__wbindgen_export, wasm.__wbindgen_export2);+ const len0 = WASM_VECTOR_LEN;+ wasm.wasmgallery_configure(retptr, this.__wbg_ptr, ptr0, len0);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ if (r1) {+ throw takeObject(r0);+ }+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Get the number of templates in the gallery.+ * @returns {number}+ */+ count() {+ const ret = wasm.wasmgallery_count(this.__wbg_ptr);+ return ret >>> 0;+ }+ /**+ * Export all custom templates as JSON.+ * @returns {any}+ */+ exportCustom() {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ wasm.wasmgallery_exportCustom(retptr, this.__wbg_ptr);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);+ if (r2) {+ throw takeObject(r1);+ }+ return takeObject(r0);+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Get a template by ID.+ * @param {string} id+ * @returns {any}+ */+ get(id) {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ const ptr0 = passStringToWasm0(id, wasm.__wbindgen_export, wasm.__wbindgen_export2);+ const len0 = WASM_VECTOR_LEN;+ wasm.wasmgallery_get(retptr, this.__wbg_ptr, ptr0, len0);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);+ if (r2) {+ throw takeObject(r1);+ }+ return takeObject(r0);+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Get the currently active template ID.+ * @returns {string | undefined}+ */+ getActive() {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ wasm.wasmgallery_getActive(retptr, this.__wbg_ptr);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ let v1;+ if (r0 !== 0) {+ v1 = getStringFromWasm0(r0, r1).slice();+ wasm.__wbindgen_export4(r0, r1 * 1, 1);+ }+ return v1;+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Get all categories with template counts.+ * @returns {any}+ */+ getCategories() {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ wasm.wasmgallery_getCategories(retptr, this.__wbg_ptr);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);+ if (r2) {+ throw takeObject(r1);+ }+ return takeObject(r0);+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Get configuration overrides for active template.+ * @returns {any}+ */+ getConfig() {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ wasm.wasmgallery_getConfig(retptr, this.__wbg_ptr);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);+ if (r2) {+ throw takeObject(r1);+ }+ return takeObject(r0);+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Import custom templates from JSON.+ * @param {string} templates_json+ * @returns {number}+ */+ importCustom(templates_json) {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ const ptr0 = passStringToWasm0(templates_json, wasm.__wbindgen_export, wasm.__wbindgen_export2);+ const len0 = WASM_VECTOR_LEN;+ wasm.wasmgallery_importCustom(retptr, this.__wbg_ptr, ptr0, len0);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);+ if (r2) {+ throw takeObject(r1);+ }+ return r0 >>> 0;+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * List all available templates.+ * @returns {any}+ */+ list() {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ wasm.wasmgallery_list(retptr, this.__wbg_ptr);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);+ if (r2) {+ throw takeObject(r1);+ }+ return takeObject(r0);+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * List templates by category.+ * @param {string} category+ * @returns {any}+ */+ listByCategory(category) {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ const ptr0 = passStringToWasm0(category, wasm.__wbindgen_export, wasm.__wbindgen_export2);+ const len0 = WASM_VECTOR_LEN;+ wasm.wasmgallery_listByCategory(retptr, this.__wbg_ptr, ptr0, len0);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);+ if (r2) {+ throw takeObject(r1);+ }+ return takeObject(r0);+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Load a template as an RVF container (returns Uint8Array).+ * @param {string} id+ * @returns {Uint8Array}+ */+ loadRvf(id) {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ const ptr0 = passStringToWasm0(id, wasm.__wbindgen_export, wasm.__wbindgen_export2);+ const len0 = WASM_VECTOR_LEN;+ wasm.wasmgallery_loadRvf(retptr, this.__wbg_ptr, ptr0, len0);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);+ if (r2) {+ throw takeObject(r1);+ }+ return takeObject(r0);+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Create a new gallery with built-in templates.+ */+ constructor() {+ const ret = wasm.wasmgallery_new();+ this.__wbg_ptr = ret >>> 0;+ WasmGalleryFinalization.register(this, this.__wbg_ptr, this);+ return this;+ }+ /**+ * Remove a custom template by ID.+ * @param {string} id+ */+ removeCustom(id) {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ const ptr0 = passStringToWasm0(id, wasm.__wbindgen_export, wasm.__wbindgen_export2);+ const len0 = WASM_VECTOR_LEN;+ wasm.wasmgallery_removeCustom(retptr, this.__wbg_ptr, ptr0, len0);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ if (r1) {+ throw takeObject(r0);+ }+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Search templates by query (matches name, description, tags).+ * @param {string} query+ * @returns {any}+ */+ search(query) {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ const ptr0 = passStringToWasm0(query, wasm.__wbindgen_export, wasm.__wbindgen_export2);+ const len0 = WASM_VECTOR_LEN;+ wasm.wasmgallery_search(retptr, this.__wbg_ptr, ptr0, len0);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);+ if (r2) {+ throw takeObject(r1);+ }+ return takeObject(r0);+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Set a template as active for use.+ * @param {string} id+ */+ setActive(id) {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ const ptr0 = passStringToWasm0(id, wasm.__wbindgen_export, wasm.__wbindgen_export2);+ const len0 = WASM_VECTOR_LEN;+ wasm.wasmgallery_setActive(retptr, this.__wbg_ptr, ptr0, len0);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ if (r1) {+ throw takeObject(r0);+ }+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+}+if (Symbol.dispose) WasmGallery.prototype[Symbol.dispose] = WasmGallery.prototype.free;++/**+ * WASM MCP Server — runs the MCP protocol entirely in the browser.+ *+ * This server exposes rvAgent tools via MCP JSON-RPC, enabling integration+ * with MCP clients without requiring a separate server process.+ *+ * # Example (JavaScript)+ * ```js+ * const mcp = new WasmMcpServer("rvagent-wasm");+ *+ * // Handle request+ * const response = mcp.handleRequest(JSON.stringify({+ * jsonrpc: "2.0",+ * id: 1,+ * method: "tools/list",+ * params: {}+ * }));+ * console.log(response);+ * ```+ */+export class WasmMcpServer {+ __destroy_into_raw() {+ const ptr = this.__wbg_ptr;+ this.__wbg_ptr = 0;+ WasmMcpServerFinalization.unregister(this);+ return ptr;+ }+ free() {+ const ptr = this.__destroy_into_raw();+ wasm.__wbg_wasmmcpserver_free(ptr, 0);+ }+ /**+ * Execute a tool by name with JSON parameters.+ * @param {string} name+ * @param {string} params_json+ * @returns {any}+ */+ call_tool(name, params_json) {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ const ptr0 = passStringToWasm0(name, wasm.__wbindgen_export, wasm.__wbindgen_export2);+ const len0 = WASM_VECTOR_LEN;+ const ptr1 = passStringToWasm0(params_json, wasm.__wbindgen_export, wasm.__wbindgen_export2);+ const len1 = WASM_VECTOR_LEN;+ wasm.wasmmcpserver_call_tool(retptr, this.__wbg_ptr, ptr0, len0, ptr1, len1);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);+ if (r2) {+ throw takeObject(r1);+ }+ return takeObject(r0);+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Get the gallery instance for direct access.+ * @returns {any}+ */+ gallery() {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ wasm.wasmmcpserver_gallery(retptr, this.__wbg_ptr);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);+ if (r2) {+ throw takeObject(r1);+ }+ return takeObject(r0);+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Handle a JSON-RPC request and return a JSON-RPC response.+ * @param {string} request_json+ * @returns {any}+ */+ handle_request(request_json) {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ const ptr0 = passStringToWasm0(request_json, wasm.__wbindgen_export, wasm.__wbindgen_export2);+ const len0 = WASM_VECTOR_LEN;+ wasm.wasmmcpserver_handle_request(retptr, this.__wbg_ptr, ptr0, len0);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);+ if (r2) {+ throw takeObject(r1);+ }+ return takeObject(r0);+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Check if the server has been initialized.+ * @returns {boolean}+ */+ is_initialized() {+ const ret = wasm.wasmmcpserver_is_initialized(this.__wbg_ptr);+ return ret !== 0;+ }+ /**+ * Get the list of available tools as JSON.+ * @returns {any}+ */+ list_tools() {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ wasm.wasmmcpserver_list_tools(retptr, this.__wbg_ptr);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);+ if (r2) {+ throw takeObject(r1);+ }+ return takeObject(r0);+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Get the server name.+ * @returns {string}+ */+ name() {+ let deferred1_0;+ let deferred1_1;+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ wasm.wasmmcpserver_name(retptr, this.__wbg_ptr);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ deferred1_0 = r0;+ deferred1_1 = r1;+ return getStringFromWasm0(r0, r1);+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ wasm.__wbindgen_export4(deferred1_0, deferred1_1, 1);+ }+ }+ /**+ * Create a new WasmMcpServer with the given name.+ * @param {string} name+ */+ constructor(name) {+ const ptr0 = passStringToWasm0(name, wasm.__wbindgen_export, wasm.__wbindgen_export2);+ const len0 = WASM_VECTOR_LEN;+ const ret = wasm.wasmmcpserver_new(ptr0, len0);+ this.__wbg_ptr = ret >>> 0;+ WasmMcpServerFinalization.register(this, this.__wbg_ptr, this);+ return this;+ }+ /**+ * Get the server version.+ * @returns {string}+ */+ version() {+ let deferred1_0;+ let deferred1_1;+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ wasm.wasmmcpserver_version(retptr, this.__wbg_ptr);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ deferred1_0 = r0;+ deferred1_1 = r1;+ return getStringFromWasm0(r0, r1);+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ wasm.__wbindgen_export4(deferred1_0, deferred1_1, 1);+ }+ }+}+if (Symbol.dispose) WasmMcpServer.prototype[Symbol.dispose] = WasmMcpServer.prototype.free;++/**+ * RVF Container Builder for WASM.+ *+ * Build RVF cognitive containers that package tools, prompts, skills,+ * orchestrator configs, MCP tools, and Ruvix capabilities.+ *+ * # Example (JavaScript)+ * ```js+ * const builder = new WasmRvfBuilder();+ * builder.addTool({ name: "search", description: "Web search", parameters: {} });+ * builder.addPrompt({ name: "coder", system_prompt: "You are a coder", version: "1.0" });+ * const container = builder.build();+ * // container is Uint8Array with RVF magic bytes+ * ```+ */+export class WasmRvfBuilder {+ __destroy_into_raw() {+ const ptr = this.__wbg_ptr;+ this.__wbg_ptr = 0;+ WasmRvfBuilderFinalization.unregister(this);+ return ptr;+ }+ free() {+ const ptr = this.__destroy_into_raw();+ wasm.__wbg_wasmrvfbuilder_free(ptr, 0);+ }+ /**+ * Add Ruvix capability definitions.+ * @param {string} caps_json+ */+ addCapabilities(caps_json) {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ const ptr0 = passStringToWasm0(caps_json, wasm.__wbindgen_export, wasm.__wbindgen_export2);+ const len0 = WASM_VECTOR_LEN;+ wasm.wasmrvfbuilder_addCapabilities(retptr, this.__wbg_ptr, ptr0, len0);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ if (r1) {+ throw takeObject(r0);+ }+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Add MCP tool entries.+ * @param {string} tools_json+ */+ addMcpTools(tools_json) {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ const ptr0 = passStringToWasm0(tools_json, wasm.__wbindgen_export, wasm.__wbindgen_export2);+ const len0 = WASM_VECTOR_LEN;+ wasm.wasmrvfbuilder_addMcpTools(retptr, this.__wbg_ptr, ptr0, len0);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ if (r1) {+ throw takeObject(r0);+ }+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Add an agent prompt.+ * @param {string} prompt_json+ */+ addPrompt(prompt_json) {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ const ptr0 = passStringToWasm0(prompt_json, wasm.__wbindgen_export, wasm.__wbindgen_export2);+ const len0 = WASM_VECTOR_LEN;+ wasm.wasmrvfbuilder_addPrompt(retptr, this.__wbg_ptr, ptr0, len0);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ if (r1) {+ throw takeObject(r0);+ }+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Add multiple prompts from JSON array.+ * @param {string} prompts_json+ */+ addPrompts(prompts_json) {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ const ptr0 = passStringToWasm0(prompts_json, wasm.__wbindgen_export, wasm.__wbindgen_export2);+ const len0 = WASM_VECTOR_LEN;+ wasm.wasmrvfbuilder_addPrompts(retptr, this.__wbg_ptr, ptr0, len0);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ if (r1) {+ throw takeObject(r0);+ }+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Add a skill definition.+ * @param {string} skill_json+ */+ addSkill(skill_json) {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ const ptr0 = passStringToWasm0(skill_json, wasm.__wbindgen_export, wasm.__wbindgen_export2);+ const len0 = WASM_VECTOR_LEN;+ wasm.wasmrvfbuilder_addSkill(retptr, this.__wbg_ptr, ptr0, len0);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ if (r1) {+ throw takeObject(r0);+ }+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Add multiple skills from JSON array.+ * @param {string} skills_json+ */+ addSkills(skills_json) {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ const ptr0 = passStringToWasm0(skills_json, wasm.__wbindgen_export, wasm.__wbindgen_export2);+ const len0 = WASM_VECTOR_LEN;+ wasm.wasmrvfbuilder_addSkills(retptr, this.__wbg_ptr, ptr0, len0);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ if (r1) {+ throw takeObject(r0);+ }+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Add a tool definition.+ * @param {string} tool_json+ */+ addTool(tool_json) {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ const ptr0 = passStringToWasm0(tool_json, wasm.__wbindgen_export, wasm.__wbindgen_export2);+ const len0 = WASM_VECTOR_LEN;+ wasm.wasmrvfbuilder_addTool(retptr, this.__wbg_ptr, ptr0, len0);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ if (r1) {+ throw takeObject(r0);+ }+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Add multiple tools from JSON array.+ * @param {string} tools_json+ */+ addTools(tools_json) {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ const ptr0 = passStringToWasm0(tools_json, wasm.__wbindgen_export, wasm.__wbindgen_export2);+ const len0 = WASM_VECTOR_LEN;+ wasm.wasmrvfbuilder_addTools(retptr, this.__wbg_ptr, ptr0, len0);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ if (r1) {+ throw takeObject(r0);+ }+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Build the RVF container as bytes.+ *+ * Returns a Uint8Array containing the RVF binary:+ * - Magic bytes: "RVF\x01" (4 bytes)+ * - Segment count: u32 LE (4 bytes)+ * - Segments: type(1) + tag(2) + len(4) + data+ * - Checksum: SHA3-256 (32 bytes)+ * @returns {Uint8Array}+ */+ build() {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ wasm.wasmrvfbuilder_build(retptr, this.__wbg_ptr);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);+ if (r2) {+ throw takeObject(r1);+ }+ return takeObject(r0);+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Get the RVF magic bytes for detection.+ * @returns {Uint8Array}+ */+ static getMagic() {+ const ret = wasm.wasmrvfbuilder_getMagic();+ return takeObject(ret);+ }+ /**+ * Create a new RVF container builder.+ */+ constructor() {+ const ret = wasm.wasmrvfbuilder_new();+ this.__wbg_ptr = ret >>> 0;+ WasmRvfBuilderFinalization.register(this, this.__wbg_ptr, this);+ return this;+ }+ /**+ * Parse an RVF container from bytes.+ * @param {Uint8Array} data+ * @returns {any}+ */+ static parse(data) {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_export);+ const len0 = WASM_VECTOR_LEN;+ wasm.wasmrvfbuilder_parse(retptr, ptr0, len0);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);+ if (r2) {+ throw takeObject(r1);+ }+ return takeObject(r0);+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Set orchestrator configuration.+ * @param {string} config_json+ */+ setOrchestrator(config_json) {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ const ptr0 = passStringToWasm0(config_json, wasm.__wbindgen_export, wasm.__wbindgen_export2);+ const len0 = WASM_VECTOR_LEN;+ wasm.wasmrvfbuilder_setOrchestrator(retptr, this.__wbg_ptr, ptr0, len0);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ if (r1) {+ throw takeObject(r0);+ }+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+ /**+ * Validate an RVF container (check magic and checksum).+ * @param {Uint8Array} data+ * @returns {boolean}+ */+ static validate(data) {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_export);+ const len0 = WASM_VECTOR_LEN;+ wasm.wasmrvfbuilder_validate(retptr, ptr0, len0);+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true);+ if (r2) {+ throw takeObject(r1);+ }+ return r0 !== 0;+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+ }+}+if (Symbol.dispose) WasmRvfBuilder.prototype[Symbol.dispose] = WasmRvfBuilder.prototype.free;++function __wbg_get_imports() {+ const import0 = {+ __proto__: null,+ __wbg___wbindgen_is_function_d633e708baf0d146: function(arg0) {+ const ret = typeof(getObject(arg0)) === 'function';+ return ret;+ },+ __wbg___wbindgen_is_undefined_c18285b9fc34cb7d: function(arg0) {+ const ret = getObject(arg0) === undefined;+ return ret;+ },+ __wbg___wbindgen_string_get_3e5751597f39a112: function(arg0, arg1) {+ const obj = getObject(arg1);+ const ret = typeof(obj) === 'string' ? obj : undefined;+ var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_export, wasm.__wbindgen_export2);+ var len1 = WASM_VECTOR_LEN;+ getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);+ getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);+ },+ __wbg___wbindgen_throw_39bc967c0e5a9b58: function(arg0, arg1) {+ throw new Error(getStringFromWasm0(arg0, arg1));+ },+ __wbg__wbg_cb_unref_b6d832240a919168: function(arg0) {+ getObject(arg0)._wbg_cb_unref();+ },+ __wbg_call_08ad0d89caa7cb79: function() { return handleError(function (arg0, arg1, arg2) {+ const ret = getObject(arg0).call(getObject(arg1), getObject(arg2));+ return addHeapObject(ret);+ }, arguments); },+ __wbg_instanceof_Promise_44e4f673e91c710d: function(arg0) {+ let result;+ try {+ result = getObject(arg0) instanceof Promise;+ } catch (_) {+ result = false;+ }+ const ret = result;+ return ret;+ },+ __wbg_new_from_slice_d7e202fdbee3c396: function(arg0, arg1) {+ const ret = new Uint8Array(getArrayU8FromWasm0(arg0, arg1));+ return addHeapObject(ret);+ },+ __wbg_new_typed_8258a0d8488ef2a2: function(arg0, arg1) {+ try {+ var state0 = {a: arg0, b: arg1};+ var cb0 = (arg0, arg1) => {+ const a = state0.a;+ state0.a = 0;+ try {+ return __wasm_bindgen_func_elem_535(a, state0.b, arg0, arg1);+ } finally {+ state0.a = a;+ }+ };+ const ret = new Promise(cb0);+ return addHeapObject(ret);+ } finally {+ state0.a = state0.b = 0;+ }+ },+ __wbg_parse_6dfe891b5bafb5cd: function() { return handleError(function (arg0, arg1) {+ const ret = JSON.parse(getStringFromWasm0(arg0, arg1));+ return addHeapObject(ret);+ }, arguments); },+ __wbg_queueMicrotask_2c8dfd1056f24fdc: function(arg0) {+ const ret = getObject(arg0).queueMicrotask;+ return addHeapObject(ret);+ },+ __wbg_queueMicrotask_8985ad63815852e7: function(arg0) {+ queueMicrotask(getObject(arg0));+ },+ __wbg_resolve_5d61e0d10c14730a: function(arg0) {+ const ret = Promise.resolve(getObject(arg0));+ return addHeapObject(ret);+ },+ __wbg_static_accessor_GLOBAL_THIS_14325d8cca34bb77: function() {+ const ret = typeof globalThis === 'undefined' ? null : globalThis;+ return isLikeNone(ret) ? 0 : addHeapObject(ret);+ },+ __wbg_static_accessor_GLOBAL_f3a1e69f9c5a7e8e: function() {+ const ret = typeof global === 'undefined' ? null : global;+ return isLikeNone(ret) ? 0 : addHeapObject(ret);+ },+ __wbg_static_accessor_SELF_50cdb5b517789aca: function() {+ const ret = typeof self === 'undefined' ? null : self;+ return isLikeNone(ret) ? 0 : addHeapObject(ret);+ },+ __wbg_static_accessor_WINDOW_d6c4126e4c244380: function() {+ const ret = typeof window === 'undefined' ? null : window;+ return isLikeNone(ret) ? 0 : addHeapObject(ret);+ },+ __wbg_then_d4163530723f56f4: function(arg0, arg1, arg2) {+ const ret = getObject(arg0).then(getObject(arg1), getObject(arg2));+ return addHeapObject(ret);+ },+ __wbg_then_f1c954fe00733701: function(arg0, arg1) {+ const ret = getObject(arg0).then(getObject(arg1));+ return addHeapObject(ret);+ },+ __wbindgen_cast_0000000000000001: function(arg0, arg1) {+ // Cast intrinsic for `Closure(Closure { dtor_idx: 64, function: Function { arguments: [Externref], shim_idx: 65, ret: Result(Unit), inner_ret: Some(Result(Unit)) }, mutable: true }) -> Externref`.+ const ret = makeMutClosure(arg0, arg1, wasm.__wasm_bindgen_func_elem_497, __wasm_bindgen_func_elem_498);+ return addHeapObject(ret);+ },+ __wbindgen_cast_0000000000000002: function(arg0, arg1) {+ // Cast intrinsic for `Ref(String) -> Externref`.+ const ret = getStringFromWasm0(arg0, arg1);+ return addHeapObject(ret);+ },+ __wbindgen_object_clone_ref: function(arg0) {+ const ret = getObject(arg0);+ return addHeapObject(ret);+ },+ __wbindgen_object_drop_ref: function(arg0) {+ takeObject(arg0);+ },+ };+ return {+ __proto__: null,+ "./rvagent_wasm_bg.js": import0,+ };+}++function __wasm_bindgen_func_elem_498(arg0, arg1, arg2) {+ try {+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);+ wasm.__wasm_bindgen_func_elem_498(retptr, arg0, arg1, addHeapObject(arg2));+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);+ if (r1) {+ throw takeObject(r0);+ }+ } finally {+ wasm.__wbindgen_add_to_stack_pointer(16);+ }+}++function __wasm_bindgen_func_elem_535(arg0, arg1, arg2, arg3) {+ wasm.__wasm_bindgen_func_elem_535(arg0, arg1, addHeapObject(arg2), addHeapObject(arg3));+}++const JsModelProviderFinalization = (typeof FinalizationRegistry === 'undefined')+ ? { register: () => {}, unregister: () => {} }+ : new FinalizationRegistry(ptr => wasm.__wbg_jsmodelprovider_free(ptr >>> 0, 1));+const WasmAgentFinalization = (typeof FinalizationRegistry === 'undefined')+ ? { register: () => {}, unregister: () => {} }+ : new FinalizationRegistry(ptr => wasm.__wbg_wasmagent_free(ptr >>> 0, 1));+const WasmGalleryFinalization = (typeof FinalizationRegistry === 'undefined')+ ? { register: () => {}, unregister: () => {} }+ : new FinalizationRegistry(ptr => wasm.__wbg_wasmgallery_free(ptr >>> 0, 1));+const WasmMcpServerFinalization = (typeof FinalizationRegistry === 'undefined')+ ? { register: () => {}, unregister: () => {} }+ : new FinalizationRegistry(ptr => wasm.__wbg_wasmmcpserver_free(ptr >>> 0, 1));+const WasmRvfBuilderFinalization = (typeof FinalizationRegistry === 'undefined')+ ? { register: () => {}, unregister: () => {} }+ : new FinalizationRegistry(ptr => wasm.__wbg_wasmrvfbuilder_free(ptr >>> 0, 1));++function addHeapObject(obj) {+ if (heap_next === heap.length) heap.push(heap.length + 1);+ const idx = heap_next;+ heap_next = heap[idx];++ heap[idx] = obj;+ return idx;+}++const CLOSURE_DTORS = (typeof FinalizationRegistry === 'undefined')+ ? { register: () => {}, unregister: () => {} }+ : new FinalizationRegistry(state => state.dtor(state.a, state.b));++function dropObject(idx) {+ if (idx < 1028) return;+ heap[idx] = heap_next;+ heap_next = idx;+}++function getArrayU8FromWasm0(ptr, len) {+ ptr = ptr >>> 0;+ return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);+}++let cachedDataViewMemory0 = null;+function getDataViewMemory0() {+ if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) {+ cachedDataViewMemory0 = new DataView(wasm.memory.buffer);+ }+ return cachedDataViewMemory0;+}++function getStringFromWasm0(ptr, len) {+ ptr = ptr >>> 0;+ return decodeText(ptr, len);+}++let cachedUint8ArrayMemory0 = null;+function getUint8ArrayMemory0() {+ if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {+ cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);+ }+ return cachedUint8ArrayMemory0;+}++function getObject(idx) { return heap[idx]; }++function handleError(f, args) {+ try {+ return f.apply(this, args);+ } catch (e) {+ wasm.__wbindgen_export3(addHeapObject(e));+ }+}++let heap = new Array(1024).fill(undefined);+heap.push(undefined, null, true, false);++let heap_next = heap.length;++function isLikeNone(x) {+ return x === undefined || x === null;+}++function makeMutClosure(arg0, arg1, dtor, f) {+ const state = { a: arg0, b: arg1, cnt: 1, dtor };+ const real = (...args) => {++ // First up with a closure we increment the internal reference+ // count. This ensures that the Rust closure environment won't+ // be deallocated while we're invoking it.+ state.cnt++;+ const a = state.a;+ state.a = 0;+ try {+ return f(a, state.b, ...args);+ } finally {+ state.a = a;+ real._wbg_cb_unref();+ }+ };+ real._wbg_cb_unref = () => {+ if (--state.cnt === 0) {+ state.dtor(state.a, state.b);+ state.a = 0;+ CLOSURE_DTORS.unregister(state);+ }+ };+ CLOSURE_DTORS.register(real, state, state);+ return real;+}++function passArray8ToWasm0(arg, malloc) {+ const ptr = malloc(arg.length * 1, 1) >>> 0;+ getUint8ArrayMemory0().set(arg, ptr / 1);+ WASM_VECTOR_LEN = arg.length;+ return ptr;+}++function passStringToWasm0(arg, malloc, realloc) {+ if (realloc === undefined) {+ const buf = cachedTextEncoder.encode(arg);+ const ptr = malloc(buf.length, 1) >>> 0;+ getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);+ WASM_VECTOR_LEN = buf.length;+ return ptr;+ }++ let len = arg.length;+ let ptr = malloc(len, 1) >>> 0;++ const mem = getUint8ArrayMemory0();++ let offset = 0;++ for (; offset < len; offset++) {+ const code = arg.charCodeAt(offset);+ if (code > 0x7F) break;+ mem[ptr + offset] = code;+ }+ if (offset !== len) {+ if (offset !== 0) {+ arg = arg.slice(offset);+ }+ ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;+ const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);+ const ret = cachedTextEncoder.encodeInto(arg, view);++ offset += ret.written;+ ptr = realloc(ptr, len, offset, 1) >>> 0;+ }++ WASM_VECTOR_LEN = offset;+ return ptr;+}++function takeObject(idx) {+ const ret = getObject(idx);+ dropObject(idx);+ return ret;+}++let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });+cachedTextDecoder.decode();+const MAX_SAFARI_DECODE_BYTES = 2146435072;+let numBytesDecoded = 0;+function decodeText(ptr, len) {+ numBytesDecoded += len;+ if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {+ cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });+ cachedTextDecoder.decode();+ numBytesDecoded = len;+ }+ return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));+}++const cachedTextEncoder = new TextEncoder();++if (!('encodeInto' in cachedTextEncoder)) {+ cachedTextEncoder.encodeInto = function (arg, view) {+ const buf = cachedTextEncoder.encode(arg);+ view.set(buf);+ return {+ read: arg.length,+ written: buf.length+ };+ };+}++let WASM_VECTOR_LEN = 0;++let wasmModule, wasm;+function __wbg_finalize_init(instance, module) {+ wasm = instance.exports;+ wasmModule = module;+ cachedDataViewMemory0 = null;+ cachedUint8ArrayMemory0 = null;+ return wasm;+}++async function __wbg_load(module, imports) {+ if (typeof Response === 'function' && module instanceof Response) {+ if (typeof WebAssembly.instantiateStreaming === 'function') {+ try {+ return await WebAssembly.instantiateStreaming(module, imports);+ } catch (e) {+ const validResponse = module.ok && expectedResponseType(module.type);++ if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {+ console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);++ } else { throw e; }+ }+ }++ const bytes = await module.arrayBuffer();+ return await WebAssembly.instantiate(bytes, imports);+ } else {+ const instance = await WebAssembly.instantiate(module, imports);++ if (instance instanceof WebAssembly.Instance) {+ return { instance, module };+ } else {+ return instance;+ }+ }++ function expectedResponseType(type) {+ switch (type) {+ case 'basic': case 'cors': case 'default': return true;+ }+ return false;+ }+}++function initSync(module) {+ if (wasm !== undefined) return wasm;+++ if (module !== undefined) {+ if (Object.getPrototypeOf(module) === Object.prototype) {+ ({module} = module)+ } else {+ console.warn('using deprecated parameters for `initSync()`; pass a single object instead')+ }+ }++ const imports = __wbg_get_imports();+ if (!(module instanceof WebAssembly.Module)) {+ module = new WebAssembly.Module(module);+ }+ const instance = new WebAssembly.Instance(module, imports);+ return __wbg_finalize_init(instance, module);+}++async function __wbg_init(module_or_path) {+ if (wasm !== undefined) return wasm;+++ if (module_or_path !== undefined) {+ if (Object.getPrototypeOf(module_or_path) === Object.prototype) {+ ({module_or_path} = module_or_path)+ } else {+ console.warn('using deprecated parameters for the initialization function; pass a single object instead')+ }+ }++ if (module_or_path === undefined) {+ module_or_path = new URL('rvagent_wasm_bg.wasm', import.meta.url);+ }+ const imports = __wbg_get_imports();++ if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {+ module_or_path = fetch(module_or_path);+ }++ const { instance, module } = await __wbg_load(await module_or_path, imports);++ return __wbg_finalize_init(instance, module);+}++export { initSync, __wbg_init as default };diff --git a/ruflo/src/ruvocal/static/wasm/rvagent_wasm_bg.wasm b/ruflo/src/ruvocal/static/wasm/rvagent_wasm_bg.wasmnew file mode 100644index 0000000000..5d4ac9aaeeBinary files /dev/null and b/ruflo/src/ruvocal/static/wasm/rvagent_wasm_bg.wasm differ