Open-source AI design agent — alternative to Lovart AI, Runway Agent, Luma Labs Agent, Krea Agent, Pika Agent, Galileo AI, Magic Patterns. Autonomous multi-step creative for posters, social, brand kits, ad creatives, and video. Free, MIT-licensed, self-hosted.
JavaScript ai-agentai-creative-agentai-design-agentai-logoai-posterai-video-agentbrand-kitdesign-agentgalileo-aikrea-agentlovartlovart-alternativeluma-agentluma-labsmagic-patternsopen-sourcepika-agentrunway-agentrunway-alternativeself-hosted
Swap: replace with tagopen — open source Claude Tag alternative
Anil-matchac4c8973f4a02
diff --git a/.env.example b/.env.examplenew file mode 100644index 0000000..1a4f8db--- /dev/null+++ b/.env.example@@ -0,0 +1,39 @@+# Slack+SLACK_BOT_TOKEN=xoxb-...+SLACK_APP_TOKEN=xapp-... # Socket Mode token++# ── LLM provider ────────────────────────────────────────────────────────────+# Set LLM_MODEL to any LiteLLM model string and provide the matching API key.+#+# Anthropic (Claude)+LLM_MODEL=claude-sonnet-4-6+ANTHROPIC_API_KEY=sk-ant-...+#+# OpenAI+# LLM_MODEL=gpt-4o+# OPENAI_API_KEY=sk-...+#+# Google Gemini+# LLM_MODEL=gemini/gemini-2.0-flash+# GEMINI_API_KEY=...+#+# Groq (fast open-weight models)+# LLM_MODEL=groq/llama-3.3-70b-versatile+# GROQ_API_KEY=...+#+# Local Ollama (no key needed)+# LLM_MODEL=ollama/llama3+# ────────────────────────────────────────────────────────────────────────────++# Per-channel model override: add to channels/<id>/tools.toml:+# [llm]+# model = "gpt-4o"++# Storage+DATA_DIR=./data # where SQLite DBs and channel configs live++# Optional: Mem0 for semantic recall (Phase 2)+# MEM0_API_KEY=...++# Optional: restrict which Slack workspaces can install+# ALLOWED_WORKSPACE_IDS=T01234,T05678diff --git a/.gitignore b/.gitignoreindex 3c3629e..e4af0ad 100644--- a/.gitignore+++ b/.gitignore@@ -1 +1,14 @@-node_modules+.env+.venv/+__pycache__/+*.pyc+*.pyo+.mypy_cache/+.ruff_cache/+.pytest_cache/+dist/+*.egg-info/+data/+*.db+*.sqlite+.DS_Storediff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..83c0228--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Anil-matcha++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/PLAN.md b/PLAN.mdnew file mode 100644index 0000000..8d0397e--- /dev/null+++ b/PLAN.md@@ -0,0 +1,453 @@+# TagOpen — Open Source Claude Tag Alternative+> Self-hostable, channel-native AI teammate for Slack (and beyond)++**Last updated:** 2026-06-25+**Status:** Pre-build planning++---++## What We're Building++An open source alternative to Anthropic's Claude Tag. Claude Tag's core insight is that AI in the workplace should be a **shared channel teammate**, not a personal per-user chatbot. One agent per channel, shared by the whole team, with admin-controlled tool access and ambient monitoring.++**Tagline:** *The self-hostable, multiplayer AI teammate. LLM-agnostic. Channel-native. No vendor lock-in.*++### What makes this different from existing open source bots+- **OpenClaw** — closest competitor. Mature (Node/TS, 50+ platforms). But it's a personal assistant — defaults to per-user DM isolation, explicitly warns against sharing agent context. Wrong default for us.+- **Hermes Agent** — best architecture ideas (5-pillar model, skill auto-creation, self-improving crons). But also per-user.+- **open-cowork / OpenWork** — Claude Cowork clones, file/desktop focused, not channel-native.++The gap nobody has filled: **channel-scoped shared agent identity with multi-user attribution and admin governance.**++---++## Core Design Principles++### 1. Channel as the Unit of Identity+The `AgentSession` key is `(workspace_id, channel_id)`, NOT `user_id`.++Every user in `#engineering` talks to the same agent, sees the same context, can pick up mid-thread. This is the fundamental inversion from all existing tools.++### 2. Multi-User Attribution+Every message in agent context is tagged with who said it:+```+[2026-06-25 14:32 @alice] deploy the new model to staging+[2026-06-25 14:33 @bob] actually wait, let's run tests first+[AGENT] Holding the deploy. @bob — can you share the test results in this thread?+```+Agent knows WHO said what, can direct follow-ups at individuals, memory writes include attribution.++### 3. File-Based Channel Config (OpenClaw-inspired)+Each channel gets a directory. Version-controllable, no UI required to get started:+```+channels/+ C01234ABC/ ← Slack channel_id+ CHANNEL.md ← identity, purpose, tone for this channel+ TOOLS.md ← which MCP servers are enabled+ MEMORY.md ← curated facts (agent-written, not append-only)+ BUDGET.md ← token limits (per-request, daily, monthly)+ skills/+ deploy-checklist.md+ oncall-runbook.md+ pr-review.md+```++### 4. Agent-Curated Memory (Letta-inspired inner loop)+After responding, the agent gets one internal turn to decide what's worth persisting to `MEMORY.md`. It uses `memory_append` and `memory_replace` tools. Memory stays clean because the agent curates it — not a dumb append-only log.++### 5. Skill Auto-Creation (Hermes-inspired)+After any task requiring 5+ tool calls, the agent writes a `SKILL.md` capturing what it learned. Next time a similar task comes up, the skill is loaded into context automatically. This is how institutional channel knowledge accumulates over time.++### 6. Agent-Managed Ambient Mode (Hermes crons)+Agent can call a `schedule_task(cron, description)` tool to create its own monitoring jobs. A heartbeat evaluator runs each cron, dumps recent channel state to the LLM, and asks: "anything worth surfacing?" If yes, it posts proactively.++### 7. MCP-Native Tool Access+All external tools exposed via MCP protocol. Admins list allowed MCP servers per channel in `TOOLS.md`. Portable, standard, Slack itself is now an MCP client — we align with the ecosystem.++### 8. LLM-Agnostic via LiteLLM+Default to Claude (Anthropic). Swap to GPT-4o, Gemini, or local Ollama via one config line. No LLM-vendor lock-in.++---++## Architecture++```+┌─────────────────────────────────────────────────────────────┐+│ Slack Events │+│ Socket Mode (dev) / Events API (prod) │+└──────────────────────────┬──────────────────────────────────┘+ │+ ┌──────▼──────┐+ │ Bolt App │ async Python+ │ Gateway │+ └──────┬──────┘+ │+ ┌───────────▼───────────┐+ │ Channel Router │+ │ (workspace_id + │+ │ channel_id) │+ │ → AgentSession │+ └───────────┬───────────┘+ │+ ┌────────────────▼──────────────────┐+ │ Context Assembler │+ │ CHANNEL.md (identity/purpose) │+ │ MEMORY.md (curated facts) │+ │ SKILLS/*.md (loaded on demand) │+ │ Recent msgs (sliding window N=50) │+ │ User map (display names) │+ └────────────────┬──────────────────┘+ │+ ┌────────────────▼──────────────────┐+ │ Agent Loop │+ │ ReAct + tool-use │+ │ ├── Tool Registry (MCP) │+ │ ├── Heartbeat (multi-step ok) │+ │ └── Stream reply → Slack thread │+ └──────┬─────────────────────┬───────┘+ │ │+ ┌──────────▼──────────┐ ┌────────▼──────────────┐+ │ Memory Writer │ │ Skill Evaluator │+ │ Inner loop turn: │ │ ≥5 tool calls? │+ │ agent decides what │ │ → write SKILL.md │+ │ to write to │ │ curator runs weekly │+ │ MEMORY.md │ └────────────────────────┘+ │ SQLite FTS5 index │+ └──────────────────────┘+ │+ ┌──────────▼──────────┐+ │ Ambient Engine │ background process+ │ Per-channel crons │+ │ Heartbeat LLM eval │+ │ Stale thread scan │+ │ Proactive Slack post│+ └──────────────────────┘+```++---++## Tech Stack++| Layer | Choice | Why |+|---|---|---|+| **Bot framework** | Slack Bolt (Python, async) | Best-documented, async/socket mode, Python ML ecosystem |+| **LLM routing** | LiteLLM | One interface for Claude/GPT/Gemini/Ollama, no vendor lock-in |+| **Primary memory** | SQLite + FTS5 (per channel) | No external deps, portable, WAL mode handles concurrent writes, Hermes-proven |+| **Semantic recall** | Mem0 (Phase 2) | ~80ms, fits on top of SQLite, ships fast |+| **Tool execution** | MCP protocol | Standard, Slack-native, hundreds of existing MCP servers |+| **Ambient tasks** | APScheduler → Temporal (Phase 3+) | APScheduler for MVP, Temporal for durability at scale |+| **Config** | TOML files + flat Markdown per channel | Human-readable, version-controllable, no UI needed to start |+| **Admin UI** | Next.js (Phase 4) | Channel config, tool access controls, token budgets |+| **Governance** | Microsoft Agent Governance Toolkit (MIT) | Don't build RBAC from scratch |++---++## Memory Architecture (layered)++Borrowed from both OpenClaw and Hermes, adapted for multi-user channels:++```+Layer 1: Context Window+ └── Last N=50 messages with user attribution+ └── CHANNEL.md + active SKILL.md files+ └── MEMORY.md (curated facts, always in context)++Layer 2: Session Store (SQLite per channel)+ └── Full message history with user_id, timestamp, thread_ts+ └── Tool call records (what ran, what it returned)+ └── FTS5 index for instant keyword lookup++Layer 3: Semantic Search (Mem0, Phase 2)+ └── Embeddings over important decisions/facts+ └── Used for "what did we decide about X last month?"+ └── Namespace = channel_id (isolated per channel)++Layer 4: Skill Library (per channel)+ └── SKILL.md files in channels/<id>/skills/+ └── Loaded into context when relevant (semantic match on task)+ └── Auto-created by agent after complex tasks+ └── Curated weekly (stale → archived after 30d unused)+```++---++## Agent Loop Detail++```python+# Pseudocode — actual implementation in agent/loop.py++async def run_agent_loop(channel_id, workspace_id, message, user_id):+ session = get_or_create_session(workspace_id, channel_id)++ # 1. Assemble context+ context = assemble_context(+ channel_config=load_channel_config(channel_id),+ memory=load_memory_md(channel_id),+ skills=load_relevant_skills(channel_id, message),+ recent_messages=get_recent_messages(channel_id, n=50),+ user_map=get_workspace_users(workspace_id),+ )++ # 2. Run ReAct loop+ tool_call_count = 0+ while True:+ response = await llm.complete(context, tools=get_channel_tools(channel_id))++ if response.is_tool_call:+ result = await execute_mcp_tool(response.tool, channel_id)+ context.add_tool_result(result)+ tool_call_count += 1+ else:+ break # final answer++ # 3. Stream reply to Slack+ await slack.post_message(channel_id, response.text, thread_ts=message.thread_ts)++ # 4. Inner loop: memory curation (Letta-inspired)+ await memory_curation_turn(channel_id, context, response)++ # 5. Skill creation check (Hermes-inspired)+ if tool_call_count >= 5:+ await maybe_create_skill(channel_id, context, response)++ # 6. Persist to SQLite+ await persist_turn(channel_id, user_id, message, response, tool_call_count)+```++---++## Channel Config Files++### CHANNEL.md+```markdown+# Engineering Channel++You are the engineering team's AI teammate in #engineering.++## Purpose+Help the team with deployments, code reviews, incident response, and architecture decisions.++## Tone+Technical, direct, concise. Use code blocks liberally. Ask clarifying questions before big actions.++## What you know about this team+- We use GitHub, Linear, Datadog, and AWS+- Deployments happen via GitHub Actions+- On-call rotation: alice (this week), bob (next week)+- We do not deploy on Fridays+```++### TOOLS.md+```toml+[[mcp_server]]+name = "github"+url = "mcp://github.internal:3000"+allowed_tools = ["list_prs", "get_file", "create_comment"]++[[mcp_server]]+name = "linear"+url = "mcp://linear.internal:3001"+allowed_tools = ["list_issues", "create_issue", "update_status"]++[[mcp_server]]+name = "web_search"+url = "mcp://search:3002"+allowed_tools = ["search"]+```++### BUDGET.md+```toml+[limits]+max_tokens_per_request = 50000+max_tokens_per_day = 500000+max_tokens_per_month = 5000000+alert_at_percent = 80+```++---++## Ambient Mode Design++The heartbeat evaluator runs on a per-channel cron. It assembles an observation dump and asks the LLM if anything is worth surfacing.++```python+# Pseudocode — ambient/heartbeat.py++async def run_heartbeat(channel_id):+ observation = {+ "recent_messages": get_messages_since_last_heartbeat(channel_id),+ "open_tasks": get_open_items(channel_id), # from Linear/GitHub+ "stale_threads": get_threads_no_reply_48h(channel_id),+ "pending_decisions": extract_pending_decisions(channel_id),+ }++ prompt = f"""+ You are monitoring the #{channel_name} channel.+ Here's what's happened since your last check:++ {format_observation(observation)}++ Should you post anything proactively? Only post if there's genuine value:+ - A stale thread that needs follow-up+ - A deadline approaching+ - An unresolved question that was forgotten+ - A conflict or risk you spotted++ If nothing is worth surfacing, respond with SILENT.+ """++ response = await llm.complete(prompt)+ if response.text != "SILENT":+ await slack.post_message(channel_id, response.text)+```++Agent creates its own crons via tool:+```python+# Agent calls this tool during a conversation+schedule_task(+ cron="0 9 * * 1", # every Monday 9am+ description="Weekly standup prep: summarize last week's threads and open items"+)+```++---++## Skill Lifecycle (Hermes-inspired)++```+Task completes with ≥5 tool calls+ ↓+Agent writes skills/<slug>.md with YAML frontmatter+ ↓+Skill is available for future sessions (semantic match on task description)+ ↓+ ├── Used regularly → stays active+ ├── Not used 30 days → marked stale+ └── Not used 90 days → archived (kept but not auto-loaded)++Weekly curator run:+ - Merges overlapping skills+ - Patches outdated instructions+ - Promotes stale skills if they get used again+```++### SKILL.md format (from Hermes):+```markdown+---+name: deploy-to-staging+description: Deploy a service to the staging environment via GitHub Actions+created: 2026-06-25+tool_calls_in_session: 7+uses: 0+last_used: null+status: active+---++## When to use this+When someone asks to deploy a service to staging.++## Steps+1. Check if there's an open PR with the changes (use `github:list_prs`)+2. Verify CI is passing on the branch+3. Trigger the `deploy-staging` workflow via `github:trigger_workflow`+4. Monitor the deployment log for 2 minutes+5. Post the staging URL back to the channel++## Known gotchas+- We don't deploy on Fridays (check day of week first)+- Always confirm with the person who asked before triggering+```++---++## Phase Build Plan++### Phase 1 — Reactive channel teammate (target: 2–3 weeks)+- [ ] Project scaffold: Python, Bolt async, pyproject.toml+- [ ] Socket Mode Slack connection+- [ ] Channel router: `(workspace_id, channel_id)` → `AgentSession`+- [ ] Context assembler: CHANNEL.md + MEMORY.md + recent messages with attribution+- [ ] Agent loop: ReAct + tool-use via LiteLLM+- [ ] 3 built-in MCP tools: web search, Python code runner, file reader+- [ ] SQLite + FTS5 session store per channel+- [ ] Multi-user attribution in context window+- [ ] File-based channel config (CHANNEL.md, TOOLS.md, BUDGET.md)+- [ ] Basic token budget enforcement++**Milestone:** `@agent explain the last PR that was deployed` works in a Slack channel, with shared context across all users.++### Phase 2 — Memory + Skills (target: +2 weeks)+- [ ] Letta inner loop: memory curation turn after each response+- [ ] `memory_append` and `memory_replace` agent tools+- [ ] Hermes-style skill auto-creation (≥5 tool calls → write SKILL.md)+- [ ] Skill loader: semantic match skill to incoming task+- [ ] Skill curator (weekly background job)+- [ ] Mem0 integration for semantic recall layer++**Milestone:** Agent remembers team conventions across sessions without being told twice. Skill library grows automatically.++### Phase 3 — Ambient mode (target: +2 weeks)+- [ ] Heartbeat evaluator (APScheduler, per channel)+- [ ] Stale thread detection+- [ ] `schedule_task` tool (agent creates its own crons)+- [ ] Observation dump builder+- [ ] SILENT / post decision logic+- [ ] Temporal integration for durable task orchestration (optional at this stage)++**Milestone:** Agent proactively surfaces a forgotten thread or approaching deadline without being tagged.++### Phase 4 — Governance + Admin UI (target: +2 weeks)+- [ ] Per-channel audit log (who asked what, which tools ran, tokens spent)+- [ ] Hard token budget enforcement (reject request if over limit)+- [ ] Admin web UI: channel config, tool access controls, budget view+- [ ] Microsoft Agent Governance Toolkit integration for RBAC+- [ ] Channel isolation tests (agent A cannot read channel B memory)++**Milestone:** Enterprise admin can configure and audit every channel's agent from a web UI.++### Phase 5 — Multi-platform + ecosystem (ongoing)+- [ ] Discord adapter (same channel router, different event source)+- [ ] Microsoft Teams adapter+- [ ] Contribute Slack adapter improvements to OpenClaw ecosystem+- [ ] MCP server registry UI (browse and enable community MCP servers)+- [ ] Public hosted version (tagopen.ai or similar)++---++## What NOT to Build (at least not yet)++- ❌ Per-user memory (personal assistant mode) — stay focused on channel-native+- ❌ Custom LLM fine-tuning — use existing models, stay model-agnostic+- ❌ Voice/video — Slack only for now+- ❌ Own vector DB — use Mem0 abstraction, don't build RAG infrastructure+- ❌ Custom MCP servers — support the protocol, let community build servers+- ❌ Real-time streaming UI — Slack's threading model is enough for MVP++---++## Key References++- [Claude Tag announcement — Anthropic](https://www.anthropic.com/news/introducing-claude-tag)+- [Claude Tag technical architecture — explainx.ai](https://www.explainx.ai/blog/claude-tag-slack-team-ai-collaboration-guide-2026)+- [OpenClaw docs — agent loop](https://docs.openclaw.ai/concepts/agent-loop)+- [OpenClaw docs — multi-agent routing](https://docs.openclaw.ai/concepts/multi-agent)+- [OpenClaw gateway deep dive](https://practiceoverflow.substack.com/p/deep-dive-into-the-openclaw-gateway)+- [Hermes Agent 5-pillar architecture](https://www.mindstudio.ai/blog/hermes-agent-5-pillar-architecture-memory-skills-soul-crons)+- [Hermes Agent self-improving loop](https://mranand.substack.com/p/inside-hermes-agent-how-a-self-improving)+- [Letta agent loop rearchitecture](https://www.letta.com/blog/letta-v1-agent)+- [Ambient agents — Temporal](https://temporal.io/blog/orchestrating-ambient-agents-with-temporal)+- [Heartbeat pattern for proactive agents](https://www.mindstudio.ai/blog/agentic-os-heartbeat-pattern-proactive-ai-agent)+- [Mem0 vs Zep vs Letta comparison](https://dev.to/agdex_ai/ai-agent-memory-in-2026-mem0-vs-zep-vs-letta-vs-cognee-a-practical-guide-cfa)+- [Slack as agentic OS + MCP](https://aiautomationglobal.com/blog/slack-ai-agentic-os-mcp-30-features-2026)+- [Agent Governance Toolkit — Microsoft](https://opensource.microsoft.com/blog/2026/04/02/introducing-the-agent-governance-toolkit-open-source-runtime-security-for-ai-agents/)++---++## Open Questions (decide before building)++1. **Name** — TagOpen? Channelmate? Copal? Teammate? Needs a GitHub repo name.+2. **Python vs Node** — Python chosen for ML ecosystem alignment, but OpenClaw is Node/TS with way more community. Worth revisiting if community contribution matters early.+3. **Hosting model** — self-host only for MVP, or offer a hosted SaaS version early for distribution?+4. **Thread vs channel** — should ambient posts start new threads or post in main channel? (UX decision)+5. **Memory consent** — should users be able to opt out of having their messages stored in channel memory?+6. **Skill sharing** — should skills be per-channel only, or shareable across channels in the same workspace?diff --git a/README.md b/README.mdindex e47c8b2..4a6ae3b 100644--- a/README.md+++ b/README.md@@ -1,47 +1,157 @@-# Open-Poe-AI+# TagOpen-Open-source, self-hosted alternative to [Poe AI](https://poe.com) — chat with multiple large language models from a single interface, on your own infrastructure.+**Self-hostable, channel-native AI teammate for Slack.**+LLM-agnostic open source alternative to Claude Tag.-Poe (by Quora) is a hosted aggregator that puts GPT, Claude, Gemini, Grok, DeepSeek, Llama, Mistral and image/video models behind one chat UI. **Open-Poe-AI** is the self-hosted version: bring your own API keys, run it on your own server, and keep full control of prompts, conversations, and data.+> One agent per channel, shared by the whole team. Persistent memory. Skill auto-creation. Ambient monitoring. No vendor lock-in.-<p align="center">- <a href="https://github.com/Anil-matcha/awesome-generative-ai-apps">- <img src="https://img.shields.io/badge/Part%20of-Awesome%20Generative%20AI%20Apps-FFD700?style=for-the-badge&logo=github&logoColor=black" alt="Awesome Generative AI Apps">- </a>-</p>+----> 🎨 **[Explore 50+ more open-source AI apps →](https://github.com/Anil-matcha/awesome-generative-ai-apps)**+## What makes this different-## Related Projects+Most Slack AI bots are personal assistants — one context per user, isolated DMs. TagOpen flips this:-- [Open-Pomelli](https://github.com/SamurAIGPT/Open-Pomelli) — Open-source Pomelli alternative — another self-hosted AI assistant-- [open-character-ai](https://github.com/Anil-matcha/open-character-ai) — Open-source Character.AI alternative with custom AI personas+- **Channel-scoped identity** — one agent shared by everyone in `#engineering`. All users see the same context, pick up mid-thread.+- **Multi-user attribution** — every message is tagged `[@alice]` so the agent knows who said what and can follow up with the right person.+- **Agent-curated memory** — after each conversation, the agent decides what to persist to `MEMORY.md`. No noisy append-only logs.+- **Skill auto-creation** — after complex multi-step tasks, the agent writes a `SKILL.md` capturing what it learned. Institutional knowledge accumulates automatically.+- **Ambient heartbeat** — configurable proactive monitoring: the agent surfaces stale threads, approaching deadlines, and unresolved questions without being tagged.+- **File-based config** — each channel is a directory of Markdown files. Version-controllable, no UI required.+- **MCP-native tools** — plug in any MCP server per channel. Admins control exactly what each channel's agent can access.-## Features+----- **Multi-model chat** — unified interface for OpenAI, Anthropic, Google, Mistral, DeepSeek, xAI, Meta Llama, and any OpenAI-compatible endpoint (including local models via Ollama / vLLM / LM Studio).-- **Multi-bot conversations** — query several models in the same thread and compare answers side by side.-- **Custom bots** — build and share bots with their own system prompts, tools, and knowledge bases.-- **Group chat** — multiple users and multiple AI models in one shared conversation.-- **Multimodal** — text, image generation, vision, and audio; pluggable adapters for image/video model providers.-- **Bring your own keys** — no subscription, no rate caps beyond the providers you use.-- **Self-hosted** — Docker Compose for one-command deploy; works on a laptop, VPS, or Kubernetes.-- **Open protocol** — bot server API so anyone can host their own bot and plug it in.+## Quickstart-## Status+```bash+# 1. Clone and install+git clone https://github.com/Anil-matcha/tagopen+cd tagopen+pip install -e ".[dev]"++# 2. Configure+cp .env.example .env+# Fill in SLACK_BOT_TOKEN, SLACK_APP_TOKEN, ANTHROPIC_API_KEY++# 3. Set up your first channel config+mkdir -p data/channels/YOUR_CHANNEL_ID+cp channels/example/CHANNEL.md data/channels/YOUR_CHANNEL_ID/CHANNEL.md+# Edit CHANNEL.md to describe your channel's purpose++# 4. Run+tagopen+```++Then `@tagopen` in your channel.++---++## Channel configuration++Each channel gets a directory under `data/channels/<channel_id>/`:++```+data/channels/C01234ABC/+ CHANNEL.md ← identity, purpose, tone+ MEMORY.md ← agent-maintained facts (do not edit manually)+ tools.toml ← which MCP servers are enabled+ skills/ ← auto-created skill playbooks+ deploy.md+ oncall.md+```++### CHANNEL.md example+```markdown+# Engineering Channel++You are the engineering team's AI teammate.+Be concise, technical, and ask before triggering deploys.++## Team context+- Stack: Python, React, PostgreSQL, AWS+- We do not deploy on Fridays+```++### tools.toml example+```toml+[[mcp_server]]+name = "github"+url = "mcp://localhost:3001"+allowed_tools = ["list_prs", "get_file", "create_comment"]+```-Early work in progress. Contributions welcome.+----## Quick start+## Architecture++```+Slack (Socket Mode)+ ↓+ Bolt Gateway+ ↓+ Channel Router ← (workspace_id, channel_id) → AgentSession+ ↓+ Context Assembler ← CHANNEL.md + MEMORY.md + skills + recent msgs+ ↓+ Agent Loop (ReAct + tool-use via LiteLLM)+ ├── Tool Registry (built-ins + MCP)+ ├── Streaming reply → Slack thread+ ├── Memory curation turn (Letta inner loop)+ └── Skill auto-creation (Hermes pattern)+ ↓+ SQLite + FTS5 ← per-channel message store+ ↓+ Ambient Engine ← heartbeat cron, proactive posts+```++---++## Supported LLMs++Uses [LiteLLM](https://github.com/BerriAI/litellm) — swap provider via `LLM_MODEL` in `.env`:++| Provider | Model string | Key env var |+|---|---|---|+| Anthropic (default) | `claude-sonnet-4-6` | `ANTHROPIC_API_KEY` |+| OpenAI | `gpt-4o` | `OPENAI_API_KEY` |+| Google Gemini | `gemini/gemini-2.0-flash` | `GEMINI_API_KEY` |+| Groq | `groq/llama-3.3-70b-versatile` | `GROQ_API_KEY` |+| Local (Ollama) | `ollama/llama3` | *(none)* |++**Per-channel override** — different channels can use different models. Add to `data/channels/<id>/tools.toml`:+```toml+[llm]+model = "gpt-4o"+```++---++## Development```bash-git clone https://github.com/Anil-matcha/Open-Poe-AI.git-cd Open-Poe-AI-cp .env.example .env # add your provider API keys-docker compose up -d+# Run tests+pytest++# Lint+ruff check .++# Type check+mypy tagopen/```-Then open http://localhost:3000.+---++## Roadmap++- [x] Phase 1 — Channel-native reactive teammate+- [ ] Phase 2 — Mem0 semantic recall + skill curator+- [ ] Phase 3 — Ambient heartbeat + agent-managed crons+- [ ] Phase 4 — Admin web UI + token governance+- [ ] Phase 5 — Discord + Teams adapters++See [PLAN.md](PLAN.md) for full architecture and design decisions.++---## Licensediff --git a/channels/example/BUDGET.md b/channels/example/BUDGET.mdnew file mode 100644index 0000000..7562705--- /dev/null+++ b/channels/example/BUDGET.md@@ -0,0 +1,3 @@+# Token Budget++Managed by tagopen. Do not edit.diff --git a/channels/example/CHANNEL.md b/channels/example/CHANNEL.mdnew file mode 100644index 0000000..cb82762--- /dev/null+++ b/channels/example/CHANNEL.md@@ -0,0 +1,18 @@+# Engineering Channel++You are the engineering team's AI teammate.++## Purpose+Help the team with deployments, code reviews, incident response, and architecture decisions.++## Tone+Technical, direct, concise. Use code blocks liberally.+Ask clarifying questions before taking big actions.+Always confirm before triggering deploys or destructive operations.++## Team context+- Stack: Python backend, React frontend, PostgreSQL, AWS+- CI/CD: GitHub Actions+- Issue tracker: Linear+- On-call: check with the team before assuming who is on-call+- We do not deploy on Fridaysdiff --git a/channels/example/MEMORY.md b/channels/example/MEMORY.mdnew file mode 100644index 0000000..cc9496c--- /dev/null+++ b/channels/example/MEMORY.md@@ -0,0 +1,5 @@+# Channel Memory++This file is maintained by the agent. Do not edit manually unless correcting errors.++<!-- agent will append facts here as they emerge -->diff --git a/channels/example/tools.toml b/channels/example/tools.tomlnew file mode 100644index 0000000..bb1a80e--- /dev/null+++ b/channels/example/tools.toml@@ -0,0 +1,21 @@+# Channel tool + LLM configuration+# Built-in tools (web_search, run_python, search_channel_history) are always available.++# Per-channel LLM override — leave commented to use the global LLM_MODEL+# [llm]+# model = "gpt-4o" # use OpenAI for this channel+# model = "claude-sonnet-4-6" # use Anthropic+# model = "gemini/gemini-2.0-flash" # use Gemini+# model = "groq/llama-3.3-70b-versatile" # use Groq++# Example: GitHub MCP server+# [[mcp_server]]+# name = "github"+# url = "mcp://localhost:3001"+# allowed_tools = ["list_prs", "get_file", "create_comment"]++# Example: Linear MCP server+# [[mcp_server]]+# name = "linear"+# url = "mcp://localhost:3002"+# allowed_tools = ["list_issues", "create_issue", "update_status"]diff --git a/client/.gitignore b/client/.gitignoredeleted file mode 100644index 1fdfd70..0000000--- a/client/.gitignore+++ /dev/null@@ -1,43 +0,0 @@-# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.--# dependencies-/node_modules-/.pnp-.pnp.*-.yarn/*-!.yarn/patches-!.yarn/plugins-!.yarn/releases-!.yarn/versions--# testing-/coverage--# next.js-/.next/-/out/--# production-/build--# misc-.DS_Store-*.pem--# debug-npm-debug.log*-yarn-debug.log*-yarn-error.log*-.pnpm-debug.log*--# env files (can opt-in for committing if needed)-.env*--# vercel-.vercel--# typescript-*.tsbuildinfo-next-env.d.ts-package-lock.json-diff --git a/client/app/agents/[agent_id]/[conversation_id]/page.js b/client/app/agents/[agent_id]/[conversation_id]/page.jsdeleted file mode 100644index 8bdceff..0000000--- a/client/app/agents/[agent_id]/[conversation_id]/page.js+++ /dev/null@@ -1,19 +0,0 @@-import { cookies } from "next/headers";-import { fetchAgentData, fetchHistoryData } from "@/context/fetchAgentData";-import AgentClientWrapper from "@/components/AgentClientWrapper";--export default async function Page({ params }) {- const { agent_id, conversation_id } = await params;- const cookieStore = await cookies();- const cookieStr = cookieStore.toString();-- // Fetch agent and history in parallel- const [agentDetails, initialHistory] = await Promise.all([- fetchAgentData(agent_id, cookieStr, true),- fetchHistoryData(agent_id, conversation_id, cookieStr)- ]);-- return (- <AgentClientWrapper initialAgentDetails={agentDetails} initialHistory={initialHistory} />- );-}diff --git a/client/app/agents/[agent_id]/page.js b/client/app/agents/[agent_id]/page.jsdeleted file mode 100644index 81e1eea..0000000--- a/client/app/agents/[agent_id]/page.js+++ /dev/null@@ -1,14 +0,0 @@-import { cookies } from "next/headers";-import { fetchAgentData } from "@/context/fetchAgentData";-import AgentClientWrapper from "@/components/AgentClientWrapper";--export default async function Page({ params }) {- const { agent_id } = await params;- const cookieStore = await cookies();-- // Fetch agent by slug- const agentDetails = await fetchAgentData(agent_id, cookieStore.toString(), true);- return (- <AgentClientWrapper initialAgentDetails={agentDetails} />- );-}diff --git a/client/app/agents/[agent_id]/profile/page.js b/client/app/agents/[agent_id]/profile/page.jsdeleted file mode 100644index ae09d50..0000000--- a/client/app/agents/[agent_id]/profile/page.js+++ /dev/null@@ -1,25 +0,0 @@-"use client";--import { AgentProfile } from "ai-agent";-import "ai-agent/dist/tailwind.css";-import { useParams } from "next/navigation";--// Mock user context to pass into components-const mockUseUser = () => ({- user: {- name: "Tester",- username: "dev_user",- profile_photo: "",- }-});--export default function AgentProfileRoute() {- const params = useParams();- const agent_id = params.agent_id;-- return (- <div className="w-full h-dvh bg-white">- <AgentProfile agent_id={agent_id} useUser={mockUseUser} usedIn="muapiapp" />- </div>- );-}diff --git a/client/app/agents/create/page.js b/client/app/agents/create/page.jsdeleted file mode 100644index fcc8b84..0000000--- a/client/app/agents/create/page.js+++ /dev/null@@ -1,21 +0,0 @@-"use client";--import { CreateAgentPage } from "ai-agent";-import "ai-agent/dist/tailwind.css";--// Mock user context to pass into components-const mockUseUser = () => ({- user: {- name: "Tester",- username: "dev_user",- profile_photo: "",- }-});--export default function CreateAgentRoute() {- return (- <div className="w-full h-dvh bg-white">- <CreateAgentPage useUser={mockUseUser} usedIn="muapiapp" />- </div>- );-}diff --git a/client/app/agents/edit/[id]/page.js b/client/app/agents/edit/[id]/page.jsdeleted file mode 100644index 4a0438c..0000000--- a/client/app/agents/edit/[id]/page.js+++ /dev/null@@ -1,25 +0,0 @@-"use client";--import { EditAgentPage } from "ai-agent";-import "ai-agent/dist/tailwind.css";-import { useParams } from "next/navigation";--// Mock user context to pass into components-const mockUseUser = () => ({- user: {- name: "Tester",- username: "dev_user",- profile_photo: "",- }-});--export default function EditAgentRoute() {- const params = useParams();- const id = params.id;-- return (- <div className="h-dvh bg-white">- <EditAgentPage id={id} useUser={mockUseUser} usedIn="muapiapp" />- </div>- );-}diff --git a/client/app/agents/loading.js b/client/app/agents/loading.jsdeleted file mode 100644index 1ed0dee..0000000--- a/client/app/agents/loading.js+++ /dev/null@@ -1,8 +0,0 @@-export default function Loading() {- return (- <div className="flex flex-col items-center justify-center min-h-[60vh] gap-4">- <div className="w-10 h-10 border-2 border-slate-200 border-t-blue-500 rounded-full animate-spin" />- <p className="text-slate-400 text-sm font-bold uppercase tracking-widest animate-pulse">Syncing Library...</p>- </div>- );-}diff --git a/client/app/agents/page.js b/client/app/agents/page.jsdeleted file mode 100644index bd97537..0000000--- a/client/app/agents/page.js+++ /dev/null@@ -1,275 +0,0 @@-"use client";--import { useState, useEffect, useCallback } from "react";-import Link from "next/link";-import axios from "axios";-import {- RiRobot2Fill,- RiUser3Line,- RiLayoutGridLine,- RiStarLine,- RiSearchLine,- RiArrowRightUpLine,- RiAddLine,- RiInformationLine-} from "react-icons/ri";--const AgentCard = ({ agent, category }) => (- <Link- href={`/agents/${agent.agent_id}`}- className="group flex flex-col bg-white border border-slate-200 rounded-2xl p-2 hover:bg-slate-50 hover:border-slate-300 transition-all duration-200 shadow-sm hover:shadow-md"- >- {/* Large Image Top (muapiapp style) */}- <div className="relative aspect-square w-full rounded-xl overflow-hidden bg-slate-100 border border-slate-200 flex items-center justify-center mb-4">- {agent.icon_url ? (- <img- src={agent.icon_url}- alt={agent.name}- className="object-cover w-full h-full transition-transform duration-500 group-hover:scale-105"- />- ) : (- <RiRobot2Fill className="w-12 h-12 text-slate-300" />- )}- <div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity">- <div className="p-1.5 bg-white/80 backdrop-blur-md rounded-lg border border-slate-200 shadow-sm">- <RiArrowRightUpLine className="w-3.5 h-3.5 text-slate-600" />- </div>- </div>- </div>-- {/* Content Bottom */}- <div className="px-2 pb-2">- <div className="flex items-center justify-between gap-2 mb-1">- <h3 className="text-sm font-bold text-slate-900 truncate group-hover:text-blue-600 transition-colors">- {agent.name}- </h3>- <span className="text-[9px] font-black text-blue-500 uppercase tracking-widest shrink-0">- {category}- </span>- </div>-- <p className="text-[11px] text-slate-500 line-clamp-2 leading-relaxed h-8 mb-4 font-medium">- {agent.description || "Specialized AI Intelligence Unit for complex workflows."}- </p>-- <div className="flex items-center justify-between mt-auto pt-3 border-t border-slate-100">- <div className="flex items-center gap-1.5">- <span className="flex h-1 w-1 rounded-full bg-emerald-500 shadow-[0_0_4px_rgba(16,185,129,0.5)]" />- <span className="text-[9px] font-bold text-slate-400 uppercase tracking-wider">Ready</span>- </div>- <div className="text-[9px] font-bold text-slate-200 uppercase tracking-tighter">- ACTIVE HUB- </div>- </div>- </div>- </Link>-);--const CategorySection = ({ title, icon: Icon, agents, categoryLabel }) => {- const items = Array.isArray(agents) ? agents : [];- if (items.length === 0) return null;-- return (- <section className="animate-fade-in-up">- <div className="flex items-center gap-2 mb-6 border-l-2 border-blue-500/30 pl-3">- <Icon className="w-4 h-4 text-slate-400" />- <h2 className="text-lg font-bold text-slate-900 tracking-tight">{title}</h2>- <span className="text-[10px] font-black text-slate-400 bg-slate-100 px-1.5 py-0.5 rounded-md ml-1">{items.length}</span>- </div>- <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">- {items.map(a => (- <AgentCard key={a.id || a.agent_id} agent={a} category={categoryLabel} />- ))}- </div>- </section>- );-};--export default function AgentsLibrary() {- const [agents, setAgents] = useState([]);- const [templates, setTemplates] = useState([]);- const [featured, setFeatured] = useState([]);- const [loading, setLoading] = useState(true);- const [error, setError] = useState(null);- const [searchTerm, setSearchTerm] = useState("");- const [activeTab, setActiveTab] = useState("workforce"); // Removed "all"-- const fetchAllData = useCallback(async () => {- try {- setLoading(true);- setError(null);-- const BASE_URL = "/api/agents";-- const [userRes, templatesRes, featuredRes] = await Promise.all([- axios.get(`${BASE_URL}/user/agents`),- axios.get(`${BASE_URL}/templates/agents`),- axios.get(`${BASE_URL}/featured/agents`)- ]);-- setAgents(Array.isArray(userRes.data) ? userRes.data : []);- setTemplates(Array.isArray(templatesRes.data) ? templatesRes.data : []);- setFeatured(Array.isArray(featuredRes.data) ? featuredRes.data : []);- } catch (err) {- console.error(err);- setError("Synchronizing failed. Check connectivity.");- } finally {- setLoading(false);- }- }, []);-- useEffect(() => {- fetchAllData();- }, [fetchAllData]);-- const filterAgents = (list) => {- const arr = Array.isArray(list) ? list : [];- if (!searchTerm) return arr;- return arr.filter(a =>- (a.name && a.name.toLowerCase().includes(searchTerm.toLowerCase())) ||- (a.description && a.description.toLowerCase().includes(searchTerm.toLowerCase()))- );- };-- const filteredAgents = filterAgents(agents);- const filteredTemplates = filterAgents(templates);- const filteredFeatured = filterAgents(featured);-- const TABS = [- { id: "workforce", label: "My Workforce", icon: RiUser3Line },- { id: "templates", label: "Templates", icon: RiLayoutGridLine },- { id: "featured", label: "Featured", icon: RiStarLine },- ];-- return (- <div className="min-h-screen bg-[#FDFDFD] text-slate-900 selection:bg-blue-500/10 font-sans pb-20">- <div className="fixed top-0 right-0 w-1/3 h-1/3 bg-blue-500/[0.03] rounded-full blur-[100px] pointer-events-none" />- <div className="fixed inset-0 bg-[#00000003] backdrop-noise pointer-events-none" />-- <div className="relative z-10 max-w-[1400px] mx-auto px-6 py-12">-- <header className="flex flex-col md:flex-row md:items-center justify-between gap-6 mb-12 animate-fade-in-up">- <div className="space-y-1">- <h1 className="text-3xl font-bold tracking-tight text-slate-900 flex items-center gap-2">- <RiRobot2Fill className="text-blue-600 w-8 h-8" />- Agent Library- </h1>- <p className="text-slate-400 text-sm font-medium uppercase tracking-widest text-[10px]">Manage Intelligence Workflow</p>- </div>-- <div className="flex flex-col sm:flex-row items-center gap-3">- <div className="relative min-w-[280px]">- <RiSearchLine className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />- <input- type="text"- placeholder="Filter intelligence..."- value={searchTerm}- onChange={(e) => setSearchTerm(e.target.value)}- className="w-full bg-white border border-slate-200 rounded-xl pl-9 pr-4 py-2 text-sm outline-none focus:border-blue-500/40 focus:ring-4 focus:ring-blue-500/5 transition-all font-medium text-slate-900监测:text-slate-400"- />- </div>- <Link- href="/agents/create"- className="flex items-center justify-center gap-1.5 px-5 py-2 bg-slate-900 text-white text-sm font-bold rounded-xl hover:bg-slate-800 transition-all shrink-0 shadow-sm"- >- <RiAddLine className="w-4 h-4" />- Create- </Link>- </div>- </header>-- {/* Tab Strip */}- <nav className="flex items-center gap-1 bg-slate-100/50 border border-slate-200/60 p-1 rounded-2xl mb-12 w-fit animate-fade-in-up shadow-sm" style={{ animationDelay: '0.1s' }}>- {TABS.map(tab => (- <button- key={tab.id}- onClick={() => setActiveTab(tab.id)}- className={`flex items-center gap-2 px-5 py-2.5 text-[12px] font-bold rounded-xl transition-all ${- activeTab === tab.id- ? "bg-white text-slate-900 shadow-sm border border-slate-200/50"- : "text-slate-500 hover:text-slate-900 hover:bg-white/50"- }`}- >- <tab.icon className={`w-3.5 h-3.5 ${activeTab === tab.id ? "text-blue-600" : "text-slate-400"}`} />- {tab.label}- </button>- ))}- </nav>-- {loading ? (- <div className="flex flex-col items-center justify-center py-32 gap-4">- <div className="w-8 h-8 border-2 border-slate-200 border-t-blue-500 rounded-full animate-spin" />- <p className="text-slate-400 text-[10px] font-bold uppercase tracking-widest animate-pulse">Syncing Library...</p>- </div>- ) : error ? (- <div className="flex flex-col items-center justify-center py-20 p-8 border border-slate-200 bg-white rounded-3xl text-center max-w-md mx-auto shadow-sm">- <RiInformationLine className="w-8 h-8 text-red-500/50 mb-4" />- <h2 className="text-lg font-bold mb-1 text-slate-900">Connection Error</h2>- <p className="text-slate-500 text-xs mb-6 leading-relaxed">{error}</p>- <button- onClick={fetchAllData}- className="px-6 py-2 bg-slate-900 text-white rounded-xl text-xs font-bold hover:bg-slate-800 transition-all shadow-sm"- >- Reconnect- </button>- </div>- ) : (- <div className="space-y-4">-- {activeTab === "workforce" && (- <CategorySection- title="My Workforce"- icon={RiUser3Line}- agents={filteredAgents}- categoryLabel="Personal"- />- )}-- {activeTab === "templates" && (- <CategorySection- title="Templates"- icon={RiLayoutGridLine}- agents={filteredTemplates}- categoryLabel="Blueprint"- />- )}-- {activeTab === "featured" && (- <CategorySection- title="Featured"- icon={RiStarLine}- agents={filteredFeatured}- categoryLabel="Verified"- />- )}-- {(activeTab === "workforce" ? filteredAgents : activeTab === "templates" ? filteredTemplates : filteredFeatured).length === 0 && (- <div className="py-32 text-center bg-slate-50/50 rounded-3xl border border-dashed border-slate-200">- <RiSearchLine className="w-10 h-10 text-slate-200 mx-auto mb-4" />- <h3 className="text-lg font-bold text-slate-400 mb-1">No units found</h3>- <p className="text-slate-400 text-[10px] font-medium uppercase tracking-widest">Adjust filters or architect a new unit</p>- </div>- )}-- </div>- )}- </div>-- <style jsx global>{`- @keyframes fade-in-up {- from { opacity: 0; transform: translateY(10px); }- to { opacity: 1; transform: translateY(0); }- }- .animate-fade-in-up {- animation: fade-in-up 0.5s cubic-bezier(0.16, 1, 0.3, 1) forwards;- opacity: 0;- }- .backdrop-noise {- background-image: url('https://grainy-gradients.vercel.app/noise.svg');- opacity: 0.01;- filter: contrast(120%) brightness(120%);- }- `}</style>- </div>- );-}diff --git a/client/app/globals.css b/client/app/globals.cssdeleted file mode 100644index a2dc41e..0000000--- a/client/app/globals.css+++ /dev/null@@ -1,26 +0,0 @@-@import "tailwindcss";--:root {- --background: #ffffff;- --foreground: #171717;-}--@theme inline {- --color-background: var(--background);- --color-foreground: var(--foreground);- --font-sans: var(--font-geist-sans);- --font-mono: var(--font-geist-mono);-}--@media (prefers-color-scheme: dark) {- :root {- --background: #0a0a0a;- --foreground: #ededed;- }-}--body {- background: var(--background);- color: var(--foreground);- font-family: Arial, Helvetica, sans-serif;-}diff --git a/client/app/layout.js b/client/app/layout.jsdeleted file mode 100644index 2db113e..0000000--- a/client/app/layout.js+++ /dev/null@@ -1,29 +0,0 @@-import { Geist, Geist_Mono } from "next/font/google";-import "./globals.css";--const geistSans = Geist({- variable: "--font-geist-sans",- subsets: ["latin"],-});--const geistMono = Geist_Mono({- variable: "--font-geist-mono",- subsets: ["latin"],-});--export const metadata = {- title: "Vibe-Agents Client",- description: "Testing Vibe-Agents proxy and frontend package",-};--export default function RootLayout({ children }) {- return (- <html lang="en">- <body- className={`${geistSans.variable} ${geistMono.variable} antialiased`}- >- {children}- </body>- </html>- );-}diff --git a/client/app/page.js b/client/app/page.jsdeleted file mode 100644index abd2de0..0000000--- a/client/app/page.js+++ /dev/null@@ -1,97 +0,0 @@-"use client";--import React from "react";-import Link from "next/link";-import { RiRobot2Fill, RiTeamLine, RiFlashlightLine, RiNodeTree } from "react-icons/ri";--export default function WelcomePage() {- return (- <div className="relative min-h-screen w-full bg-white text-slate-900 overflow-hidden selection:bg-blue-500/10 font-sans">- {/* Premium Background Effects */}- <div className="fixed top-[-10%] right-[-5%] w-[50%] h-[50%] bg-blue-500/[0.03] rounded-full blur-[120px] pointer-events-none" />- <div className="fixed bottom-[-10%] left-[-5%] w-[50%] h-[50%] bg-purple-500/[0.03] rounded-full blur-[120px] pointer-events-none" style={{ animationDelay: '2s' }} />- <div className="fixed inset-0 bg-[linear-gradient(to_right,#00000005_1px,transparent_1px),linear-gradient(to_bottom,#00000005_1px,transparent_1px)] bg-[size:40px_40px] pointer-events-none" />-- {/* Subtle Noise Texture */}- <div className="fixed inset-0 opacity-[0.01] pointer-events-none bg-[url('https://grainy-gradients.vercel.app/noise.svg')] filter contrast(120%) brightness(120%)" />-- <div className="relative z-10 flex flex-col items-center justify-center px-6 pt-20 pb-32 max-w-7xl mx-auto min-h-screen">- {/* Badge */}- <div className="mb-8 inline-flex items-center gap-2 px-3 py-1 bg-blue-50 border border-blue-100 rounded-full animate-fade-in-up">- <span className="flex h-2 w-2 rounded-full bg-blue-500 animate-pulse" />- <span className="text-xs font-bold tracking-wide text-blue-600 uppercase">Next Gen AI Engine</span>- </div>-- {/* Hero Title */}- <h1 className="text-6xl md:text-8xl font-black text-center tracking-tighter leading-[0.9] mb-8 bg-gradient-to-b from-slate-900 via-slate-800 to-slate-500 bg-clip-text text-transparent animate-fade-in-up" style={{ animationDelay: '0.1s' }}>- Vibe-Agents <br />- <span className="text-blue-600">Intelligent Workforce</span>- </h1>-- {/* Description */}- <p className="max-w-2xl text-center text-lg md:text-xl text-slate-500 font-medium leading-relaxed mb-12 animate-fade-in-up" style={{ animationDelay: '0.2s' }}>- Unleash autonomous AI agents that think, collaborate, and execute.- The ultimate platform for architecting specialized intelligence into your workflows.- </p>-- {/* CTA Section */}- <div className="flex flex-col sm:flex-row gap-4 items-center animate-fade-in-up" style={{ animationDelay: '0.3s' }}>- <Link- href="/agents"- className="group relative px-8 py-4 bg-slate-900 text-white font-bold rounded-2xl transition-all hover:scale-[1.02] active:scale-[0.98] shadow-lg shadow-slate-200 hover:shadow-xl hover:shadow-slate-300 overflow-hidden"- >- <div className="absolute inset-0 bg-gradient-to-r from-blue-600 to-blue-500 opacity-0 group-hover:opacity-100 transition-opacity" />- <span className="relative flex items-center gap-2">- Browse Agent Library- <RiRobot2Fill className="w-5 h-5 group-hover:rotate-12 transition-transform" />- </span>- </Link>- <Link- href="/agents/create"- className="px-8 py-4 bg-white border border-slate-200 text-slate-900 font-bold rounded-2xl hover:bg-slate-50 transition-all active:scale-[0.98] shadow-sm"- >- Architect New Agent- </Link>- </div>-- {/* Features Grid */}- <div className="mt-32 grid grid-cols-1 md:grid-cols-3 gap-6 w-full animate-fade-in-up" style={{ animationDelay: '0.4s' }}>- <div className="p-8 rounded-3xl bg-white border border-slate-100 shadow-sm group hover:border-blue-500/30 transition-all">- <div className="w-12 h-12 rounded-2xl bg-blue-50 flex items-center justify-center mb-6 group-hover:scale-110 transition-transform">- <RiTeamLine className="w-6 h-6 text-blue-600" />- </div>- <h3 className="text-xl font-bold mb-3 text-slate-900">Multi-Agent Teams</h3>- <p className="text-slate-500 leading-relaxed font-medium">Build swarms of specialized agents that collaborate on complex tasks through natural language.</p>- </div>-- <div className="p-8 rounded-3xl bg-white border border-slate-100 shadow-sm group hover:border-purple-500/30 transition-all">- <div className="w-12 h-12 rounded-2xl bg-purple-50 flex items-center justify-center mb-6 group-hover:scale-110 transition-transform">- <RiFlashlightLine className="w-6 h-6 text-purple-600" />- </div>- <h3 className="text-xl font-bold mb-3 text-slate-900">Instant Execution</h3>- <p className="text-slate-500 leading-relaxed font-medium">From code generation to visual design, agents execute with unprecedented speed and accuracy.</p>- </div>-- <div className="p-8 rounded-3xl bg-white border border-slate-100 shadow-sm group hover:border-slate-300 transition-all">- <div className="w-12 h-12 rounded-2xl bg-slate-100 flex items-center justify-center mb-6 group-hover:scale-110 transition-transform">- <RiNodeTree className="w-6 h-6 text-slate-600" />- </div>- <h3 className="text-xl font-bold mb-3 text-slate-900">Modular Logic</h3>- <p className="text-slate-500 leading-relaxed font-medium">Deeply integrated with Vibe-Workflow for seamless bridging between human intent and automated logic.</p>- </div>- </div>- </div>-- <style jsx global>{`- @keyframes fade-in-up {- from { opacity: 0; transform: translateY(20px); }- to { opacity: 1; transform: translateY(0); }- }- .animate-fade-in-up {- animation: fade-in-up 0.8s cubic-bezier(0.16, 1, 0.3, 1) forwards;- opacity: 0;- }- `}</style>- </div>- );-}diff --git a/client/components/AgentClientWrapper.js b/client/components/AgentClientWrapper.jsdeleted file mode 100644index 199a0ee..0000000--- a/client/components/AgentClientWrapper.js+++ /dev/null@@ -1,26 +0,0 @@-"use client";--import { AiAgent } from "ai-agent";-import "ai-agent/dist/tailwind.css";--// Mock user context to pass into AiAgent-const mockUseUser = () => ({- user: {- name: "Tester",- username: "dev_user",- profile_photo: "",- }-});--export default function AgentClientWrapper({ initialAgentDetails, initialHistory = null }) {- return (- <div className="h-dvh w-full">- <AiAgent- initialAgentDetails={initialAgentDetails}- initialHistory={initialHistory}- useUser={mockUseUser}- usedIn="muapiapp"- />- </div>- );-}diff --git a/client/context/fetchAgentData.js b/client/context/fetchAgentData.jsdeleted file mode 100644index eeb0f61..0000000--- a/client/context/fetchAgentData.js+++ /dev/null@@ -1,26 +0,0 @@-export async function fetchAgentData(id, cookieHeader, byName = false) {- const endpoint = `http://127.0.0.1:8000/api/agents/by-slug/${id}`;- const res = await fetch(endpoint, {- cache: 'no-store',- headers: {- 'Cookie': cookieHeader || '',- },- });-- if (!res.ok) return null;-- return await res.json();-}--export async function fetchHistoryData(agentSlug, conversationId, cookieHeader) {- const endpoint = `http://127.0.0.1:8000/api/agents/by-slug/${agentSlug}/${conversationId}`;- const res = await fetch(endpoint, {- cache: 'no-store',- headers: {- 'Cookie': cookieHeader || '',- },- });-- if (!res.ok) return null;- return await res.json();-}diff --git a/client/jsconfig.json b/client/jsconfig.jsondeleted file mode 100644index ba70235..0000000--- a/client/jsconfig.json+++ /dev/null@@ -1,10 +0,0 @@-{- "compilerOptions": {- "baseUrl": ".",- "paths": {- "@/*": [- "./*"- ]- }- }-}\ No newline at end of filediff --git a/client/next.config.mjs b/client/next.config.mjsdeleted file mode 100644index 3f45a4b..0000000--- a/client/next.config.mjs+++ /dev/null@@ -1,24 +0,0 @@-/** @type {import('next').NextConfig} */-const nextConfig = {- transpilePackages: ['ai-agent'],- images: {- remotePatterns: [- {- protocol: 'https',- hostname: 'cdn.muapi.ai',- port: '',- pathname: '/**',- },- ],- },- async rewrites() {- return [- {- source: '/api/:path*',- destination: 'http://localhost:8000/api/:path*',- },- ];- },-};--export default nextConfig;diff --git a/client/package.json b/client/package.jsondeleted file mode 100644index 08a8c79..0000000--- a/client/package.json+++ /dev/null@@ -1,27 +0,0 @@-{- "name": "vibe-agents-client",- "version": "0.1.0",- "private": true,- "scripts": {- "dev": "next dev",- "build": "next build",- "start": "next start",- "lint": "eslint"- },- "dependencies": {- "axios": "^1.13.2",- "next": "16.1.1",- "react": "19.2.3",- "react-dom": "19.2.3",- "react-icons": "^5.5.0",- "react-hot-toast": "^2.4.1",- "reactflow": "^11.11.4",- "ai-agent": "*"- },- "devDependencies": {- "@tailwindcss/postcss": "^4",- "eslint": "^9",- "eslint-config-next": "16.1.1",- "tailwindcss": "^4"- }-}diff --git a/client/postcss.config.mjs b/client/postcss.config.mjsdeleted file mode 100644index 61e3684..0000000--- a/client/postcss.config.mjs+++ /dev/null@@ -1,7 +0,0 @@-const config = {- plugins: {- "@tailwindcss/postcss": {},- },-};--export default config;diff --git a/package.json b/package.jsondeleted file mode 100644index 8925dc2..0000000--- a/package.json+++ /dev/null@@ -1,16 +0,0 @@-{- "name": "vibe-agents-monorepo",- "version": "1.0.0",- "private": true,- "workspaces": [- "packages/*",- "client",- "server"- ],- "scripts": {- "dev:app": "npm run dev -w client",- "build:app": "npm run build -w client",- "build:lib": "npm run build -w packages/agents",- "install:all": "npm install"- }-}diff --git a/packages/agents/.gitignore b/packages/agents/.gitignoredeleted file mode 100644index 897cb9f..0000000--- a/packages/agents/.gitignore+++ /dev/null@@ -1,3 +0,0 @@-node_modules-package-lock.json-dist\ No newline at end of filediff --git a/packages/agents/README.md b/packages/agents/README.mddeleted file mode 100644index a9ead09..0000000--- a/packages/agents/README.md+++ /dev/null@@ -1,53 +0,0 @@-# AI Agent--A premium React component for AI interactions.--## Installation--To use this component in another project, run:--```bash-npm install git+https://github.com/jaiprasad04/ai-agent.git-```--## Usage--### 1. Import the Component--```javascript-import { AiAgent } from 'ai-agent';-```--### 2. Import the Styles--You must import the CSS file for the component to look correct:--```javascript-import 'ai-agent/dist/tailwind.css';-```--### 3. Example--```jsx-import React from 'react';-import { AiAgent } from 'ai-agent';-import 'ai-agent/dist/tailwind.css';--function App() {- return (- <div className="App">- <AiAgent />- </div>- );-}--export default App;-```--## Development--If you want to modify the component:--1. Clone the repo-2. Run `npm install`-3. Run `npm run build` to update the `dist/` folderdiff --git a/packages/agents/THEME_SETUP.md b/packages/agents/THEME_SETUP.mddeleted file mode 100644index af9319d..0000000--- a/packages/agents/THEME_SETUP.md+++ /dev/null@@ -1,52 +0,0 @@-# Theme Setup Guide--This library uses `next-themes` to manage light and dark modes. For the theme switching buttons to work correctly, you must wrap your application with the provided `AgentThemeProvider`.--## 1. Wrap your Application-In your root layout or `App` component, import and use `AgentThemeProvider`.--### Next.js (App Router)-In your `layout.js`:--```jsx-import { AgentThemeProvider } from 'ai-agent';--export default function RootLayout({ children }) {- return (- <html lang="en" suppressHydrationWarning>- <body>- <AgentThemeProvider>- {children}- </AgentThemeProvider>- </body>- </html>- )-}-```-> [!IMPORTANT]-> Adding `suppressHydrationWarning` to the `<html>` tag is required by `next-themes` to avoid hydration mismatch errors.--### Other React Apps-Wrap your main component:-```jsx-import { AgentThemeProvider } from 'ai-agent';--ReactDOM.render(- <AgentThemeProvider>- <App />- </AgentThemeProvider>,- document.getElementById('root')-);-```--## 2. Tailwind Configuration-Ensure your `tailwind.config.js` in the **consuming project** includes `darkMode: 'class'`:-```javascript-module.exports = {- darkMode: 'class',- // ... rest of your config-}-```--## 3. Usage-Once the provider is in place, the theme switching logic inside `HomepageNavbar` (and other components) will work automatically, toggling the `.dark` class on the `<html>` element.diff --git a/packages/agents/babel.config.json b/packages/agents/babel.config.jsondeleted file mode 100644index 08d007e..0000000--- a/packages/agents/babel.config.json+++ /dev/null@@ -1,6 +0,0 @@-{- "presets": [- "@babel/preset-env",- ["@babel/preset-react", { "runtime": "automatic" }]- ]-}diff --git a/packages/agents/package.json b/packages/agents/package.jsondeleted file mode 100644index a524500..0000000--- a/packages/agents/package.json+++ /dev/null@@ -1,37 +0,0 @@-{- "name": "ai-agent",- "version": "1.0.0",- "description": "AI Agent",- "main": "dist/index.js",- "module": "dist/index.js",- "files": [- "dist"- ],- "scripts": {- "build:css": "tailwindcss -i ./src/tailwind.css -o ./dist/tailwind.css --minify",- "build": "npm run build:css && babel src --out-dir dist --extensions .js,.jsx"- },- "license": "MIT",- "dependencies": {- "axios": "^1.7.0",- "next-themes": "^0.4.6",- "react-hot-toast": "^2.5.2",- "react-icons": "^5.0.1",- "react-markdown": "^9.0.0",- "react-toastify": "^11.0.5",- "reactflow": "^11.11.4",- "remark-gfm": "^4.0.0"- },- "peerDependencies": {- "react": ">=18.0.0",- "react-dom": ">=18.0.0"- },- "devDependencies": {- "@babel/cli": "^7.28.3",- "@babel/preset-env": "^7.28.5",- "@babel/preset-react": "^7.28.5",- "autoprefixer": "^10.4.14",- "postcss": "^8.4.24",- "tailwindcss": "^3.3.3"- }-}diff --git a/packages/agents/postcss.config.js b/packages/agents/postcss.config.jsdeleted file mode 100644index 33ad091..0000000--- a/packages/agents/postcss.config.js+++ /dev/null@@ -1,6 +0,0 @@-module.exports = {- plugins: {- tailwindcss: {},- autoprefixer: {},- },-}diff --git a/packages/agents/src/AgentProfile.jsx b/packages/agents/src/AgentProfile.jsxdeleted file mode 100644index 679333b..0000000--- a/packages/agents/src/AgentProfile.jsx+++ /dev/null@@ -1,17 +0,0 @@-"use client";--import { Toaster } from "react-hot-toast";-import ProfileAgent from "./components/ProfileAgent";--const AgentProfile = ({ useUser, usedIn = "muapiapp" }) => {- return (- <div className="h-screen w-full flex flex-col bg-blue-50/50 transition-all duration-300 ease-in-out">- <Toaster position="top-center" reverseOrder={false} />- <main className="flex flex-col items-center gap-2 w-full h-full overflow-y-auto pt-8">- <ProfileAgent useUser={useUser} usedIn={usedIn} />- </main>- </div>- );-};--export default AgentProfile;diff --git a/packages/agents/src/AiAgent.jsx b/packages/agents/src/AiAgent.jsxdeleted file mode 100644index e11d1d5..0000000--- a/packages/agents/src/AiAgent.jsx+++ /dev/null@@ -1,1529 +0,0 @@-"use client";--import React, { useState, useEffect, useRef } from "react";-import { useParams, useRouter, useSearchParams } from "next/navigation";-import axios from "axios";-import ReactMarkdown from "react-markdown";-import remarkGfm from "remark-gfm";-import { IoSend, IoChevronBack, IoColorPalette, IoAdd, IoHeart, IoHeartOutline, IoChatbubbleEllipsesSharp } from "react-icons/io5";-import { HiLightBulb } from "react-icons/hi2";-import { MdTerminal, MdPerson, MdClose, MdEdit, MdContentCopy, MdCheck, MdFullscreen, MdFileDownload, MdImage } from "react-icons/md";-import { RiRobot2Fill } from "react-icons/ri";-import { HiOutlinePencilAlt } from "react-icons/hi";-import { BiLoaderAlt } from "react-icons/bi";-import { VscDebugAlt } from "react-icons/vsc";-import { themes } from "./components/themes";-import { FaAngleRight } from "react-icons/fa6";--const BASE_URL = "/api/agents"; // "https://api.muapi.ai/agents";--const formatMessageTime = (date) => {- if (!date) return "";- return new Intl.DateTimeFormat("en-US", {- hour: "numeric",- minute: "2-digit",- hour12: true,- }).format(new Date(date));-};--const getDateHeader = (date) => {- const d = new Date(date);- const now = new Date();- const yesterday = new Date(now);- yesterday.setDate(now.getDate() - 1);-- if (d.toDateString() === now.toDateString()) return "Today";- if (d.toDateString() === yesterday.toDateString()) return "Yesterday";-- return d.toLocaleDateString("en-US", {- month: "short",- day: "numeric",- year: d.getFullYear() !== now.getFullYear() ? "numeric" : undefined,- });-};--const parseMessageContent = (text) => {- if (!text) return [];- const urlRegex = /(https?:\/\/[^\s]+)/g;- const parts = [];- let lastIndex = 0;- let match;-- while ((match = urlRegex.exec(text)) !== null) {- const start = match.index;- const end = start + match[0].length;- const url = match[0];-- if (start > lastIndex) {- parts.push({ type: "text", content: text.substring(lastIndex, start) });- }-- const cleanUrl = url.split("?")[0].toLowerCase();- const isImage = /\.(jpg|jpeg|png|gif|webp|svg)$/i.test(cleanUrl);- const isVideo = /\.(mp4|webm|mov|ogg)$/i.test(cleanUrl);- const isAudio = /\.(mp3|wav|mpeg)$/i.test(cleanUrl);-- if (isImage) {- parts.push({ type: "image", url });- } else if (isVideo) {- parts.push({ type: "video", url });- } else if (isAudio) {- parts.push({ type: "audio", url });- } else {- parts.push({ type: "text", content: url });- }-- lastIndex = end;- }-- if (lastIndex < text.length) {- parts.push({ type: "text", content: text.substring(lastIndex) });- }-- return parts;-};--const CopyButton = ({ text }) => {- const [copied, setCopied] = useState(false);-- const handleCopy = async () => {- try {- await navigator.clipboard.writeText(text);- setCopied(true);- setTimeout(() => setCopied(false), 2000);- } catch (err) {- console.error("Failed to copy text: ", err);- }- };-- return (- <button- onClick={handleCopy}- className="p-1.5 rounded-lg border transition-all group relative border-[var(--border-color)] text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--component-hover)]"- title="Copy to clipboard"- type="button"- >- {copied ? (- <MdCheck className="w-3.5 h-3.5 text-green-400" />- ) : (- <MdContentCopy className="w-3.5 h-3.5" />- )}- <span- className={`absolute -top-8 left-1/2 -translate-x-1/2 px-2 py-1 bg-slate-800 text-white text-[10px] rounded pointer-events-none transition-opacity duration-200 ${copied ? "opacity-100" : "opacity-0"- }`}- >- Copied!- </span>- </button>- );-};--const ChatPage = ({- initialAgentDetails,- useUser,- usedIn = "muapiapp",- useSidebar,- searchQuery = "",- setSearchQuery = () => {},- getSearchItems = () => {},- initialHistory = null,-}) => {- const { id: routeAgentId, agent_id, agent_name, conversation_id: routeConversationId } = useParams();- const effectiveAgentId = agent_id || agent_name || routeAgentId;- const lowerAgentSlug = effectiveAgentId?.toLowerCase();-- const effectiveConversationId = routeConversationId;- const router = useRouter();-- const userContext = useUser ? useUser() : {};- let userName = "User";- let userProfile = null;-- if (usedIn === "vadoo") {- const { serverDetails } = userContext;- userName = serverDetails?.user_details?.name || "User";- userProfile = serverDetails?.user_details?.profile;- } else if (usedIn === "muapiapp") {- // muapiapp- const { user } = userContext;- userName = user?.username || user?.name || "User";- userProfile = user?.profile_photo;- }-- const [messages, setMessages] = useState(() => {- if (initialHistory && initialHistory.history) {- return initialHistory.history.map((msg, i) => {- let ts = msg.timestamp || initialHistory.created_at || new Date();- if (typeof ts === 'string' && ts.includes('T') && !ts.endsWith('Z') && !ts.includes('+')) {- ts += 'Z';- }- return {- ...msg,- id: msg.id || `${msg.role}_${Date.now()}_${i}`,- timestamp: ts- };- });- }- return [];- });- const [input, setInput] = useState("");- const [isStreaming, setIsStreaming] = useState(() => {- if (typeof window !== 'undefined' && effectiveConversationId) {- return !!sessionStorage.getItem('pending_first_msg');- }- return false;- });- const [agentDetails, setAgentDetails] = useState(initialAgentDetails || null);- const [error, setError] = useState(null);- const [debugLogs, setDebugLogs] = useState([]);- const [showDebug, setShowDebug] = useState(false);- const conversationIdRef = useRef(null);- const [showDropdown, setShowDropdown] = useState(false);- const [showThemeDropdown, setShowThemeDropdown] = useState(false);- const [selectedMedia, setSelectedMedia] = useState(null);- const [downloadingUrl, setDownloadingUrl] = useState(null);- const [currentTheme, setCurrentTheme] = useState(() => {- const themeData = initialAgentDetails?.theme;- if (typeof themeData === 'string' && themes[themeData]) {- return themes[themeData];- }- if (themeData && typeof themeData === 'object' && themeData.colors) {- return themeData;- }- return themes.cosmic;- });- const textareaRef = useRef(null);- const scrollRef = useRef(null);- const [attachments, setAttachments] = useState([]);- const [isUploading, setIsUploading] = useState(false);- const [uploadProgress, setUploadProgress] = useState(0);- const [isDragging, setIsDragging] = useState(false);- const fileInputRef = useRef(null);- const currentAssistantMsgRef = useRef({- content: "",- thoughts: "",- status: [],- suggestions: [],- });- const [showCustomColorPanel, setShowCustomColorPanel] = useState(false);- const [isMounted, setIsMounted] = useState(false);- const [liked, setLiked] = useState(agentDetails ? agentDetails?.has_liked : false);- const [likeCount, setLikeCount] = useState(agentDetails ? agentDetails?.like_count : 0);-- useEffect(() => {- setIsMounted(true);- }, []);-- useEffect(() => {- const fetchHistory = async () => {- if (messages.length > 0) {- conversationIdRef.current = effectiveConversationId;- return;- }-- if (effectiveConversationId && lowerAgentSlug) {- const pending = sessionStorage.getItem('pending_first_msg');- if (pending) {- try {- const { convId } = JSON.parse(pending);- if (convId === effectiveConversationId) {- return;- }- } catch (e) {}- }-- try {- let endpoint = `${BASE_URL}/by-slug/${lowerAgentSlug}/${effectiveConversationId}`;- const res = await axios.get(endpoint);- if (res.data && res.data.history) {- const hydratedMessages = res.data.history.map((msg, i) => {- let ts = msg.timestamp || res.data.created_at || new Date();- if (typeof ts === 'string' && ts.includes('T') && !ts.endsWith('Z') && !ts.includes('+')) {- ts += 'Z';- }- return {- ...msg,- id: msg.id || `${msg.role}_${Date.now()}_${i}`,- timestamp: ts- };- });-- if (hydratedMessages.length > 0) {- setMessages(hydratedMessages);- }- conversationIdRef.current = effectiveConversationId;- }- } catch (err) {- console.error("Failed to fetch conversation history:", err);- }- }- };- fetchHistory();- }, [effectiveConversationId, lowerAgentSlug]);-- const handleCustomColorChange = (part, color) => {- const updatedTheme = {- ...currentTheme,- id: 'custom',- name: 'Custom Theme',- colors: {- ...currentTheme.colors,- [part]: color- }- };- setCurrentTheme(updatedTheme);- };-- const handleThemeSync = async (theme) => {- try {- await axios.put(`${BASE_URL}/by-slug/${lowerAgentSlug}`, { theme: theme });- } catch (err) {- console.error("Failed to save theme:", err);- }- setShowCustomColorPanel(false);- };-- const generateCssVariables = (theme) => {- const c = theme?.colors || themes.cosmic.colors;- return {- "--bg-primary": c.background,- "--text-primary": c.foreground,- "--text-secondary": c.muted,- "--border-color": c.border,- "--component-bg": c.componentBg,- "--component-hover": c.componentHover,- "--header-bg": c.headerBg,- "--user-bubble": c.userBubble,- "--user-text": c.userText,- "--agent-bubble": c.agentBubble,- "--agent-text": c.agentText,- "--input-bg": c.inputBg,- "--accent": c.accent,- "--accent-text": c.accentText,- "--font-family": "'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",- };- };-- const handleDownloadFile = async (file_url, filename = "download") => {- if (!file_url) {- toast.error("File URL not found");- return;- }-- setDownloadingUrl(file_url);- try {- const response = await axios.post("/api/workflow/cloudfront-signed-url",- {- url: file_url- }- );-- const signed_url = response.data.signed_url;- const fetchResponse = await fetch(signed_url, { mode: "cors" });- const blob = await fetchResponse.blob();- const url = window.URL.createObjectURL(blob);-- const link = document.createElement("a");- link.href = url;- link.download = filename;- document.body.appendChild(link);- link.click();- document.body.removeChild(link);-- window.URL.revokeObjectURL(url);- } catch (err) {- console.error("Download failed:", err);- toast.error(`Download failed: ${err.message}`);- } finally {- setDownloadingUrl(null);- }- };-- useEffect(() => {- if (agentDetails?.theme && themes[agentDetails.theme]) {- setCurrentTheme(themes[agentDetails.theme]);- }- }, [agentDetails]);-- useEffect(() => {- if (initialAgentDetails) {- setAgentDetails(initialAgentDetails);- } else {- // fetchAgentDetails();- }- }, [lowerAgentSlug, initialAgentDetails]);-- useEffect(() => {- const checkPendingMessage = async () => {- if (effectiveConversationId) {- const pending = sessionStorage.getItem('pending_first_msg');- if (pending) {- try {- const { convId, text, attachments: pendingAttachments } = JSON.parse(pending);- if (convId === effectiveConversationId) {- sessionStorage.removeItem('pending_first_msg');- setTimeout(() => {- handleSendMessage(null, text, pendingAttachments);- }, 100);- }- } catch (e) {- console.error("Failed to parse pending message", e);- }- }- }- };- checkPendingMessage();- }, [effectiveConversationId]);-- useEffect(() => {- if (textareaRef.current) {- textareaRef.current.style.height = 'auto';- textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`;- }- }, [input]);-- useEffect(() => {- if (scrollRef.current) {- scrollRef.current.scrollTo({- top: scrollRef.current.scrollHeight,- behavior: "smooth",- });- }- }, [messages]);-- const fetchAgentDetails = async () => {- try {- const endpoint = `${BASE_URL}/by-slug/${lowerAgentSlug}`;- const response = await axios.get(endpoint);- setAgentDetails(response.data);- } catch (err) {- setAgentDetails({- name: "Autonomous Agent",- description: "MuAPI Powered Intelligence.",- });- }- };-- const uploadFile = async (file) => {- if (!file) return;-- if (file.size > 10 * 1024 * 1024) {- setError("File size too large (max 10MB)");- return;- }-- try {- setUploadProgress(0);- setIsUploading(true);-- const response = await axios.get("/api/app/get_file_upload_url", {- params: { filename: file.name }- });- const { url, fields } = response.data;-- const formData = new FormData();- Object.entries(fields).forEach(([key, value]) => {- formData.append(key, value);- });- formData.append("file", file);-- await axios.post(url, formData, {- headers: { "Content-Type": "multipart/form-data" },- onUploadProgress: (progressEvent) => {- const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);- setUploadProgress(percent);- }- });- const prefix = "https://cdn.muapi.ai/";- const uploadedUrl = prefix + fields.key;- setAttachments(prev => [...prev, uploadedUrl]);- } catch (err) {- console.error("Upload failed", err);- setError("Failed to upload image.");- } finally {- setIsUploading(false);- setUploadProgress(0);- if (fileInputRef.current) fileInputRef.current.value = "";- }- };-- const handleFileUpload = (e) => {- const file = e.target.files[0];- uploadFile(file);- };-- const handleDragOver = (e) => {- e.preventDefault();- setIsDragging(true);- };-- const handleDragLeave = (e) => {- e.preventDefault();- setIsDragging(false);- };-- const handleDrop = (e) => {- e.preventDefault();- setIsDragging(false);-- const file = e.dataTransfer.files[0];- if (file && file.type.startsWith("image/")) {- uploadFile(file);- } else if (file) {- setError("Please only upload image files.");- }- };-- const removeAttachment = (url) => {- setAttachments(prev => prev.filter(item => item !== url));- };-- const handleThemeChange = async (theme) => {- setCurrentTheme(theme);- handleThemeSync(theme);- };-- const handleLike = async () => {- const newLiked = !liked;- const prevLikeCount = likeCount;-- // Optimistic update- setLiked(newLiked);- setLikeCount(prev => newLiked ? prev + 1 : prev - 1);-- try {- const res = await axios.post(`/api/agents/by-slug/${lowerAgentSlug}/like?is_like=${newLiked}`);- setLiked(res.data.has_liked);- setLikeCount(res.data.like_count);- } catch (err) {- console.error("Failed to sync like:", err);- // Rollback- setLiked(!newLiked);- setLikeCount(prevLikeCount);- }- };-- const handleNewChat = () => {- if (lowerAgentSlug) {- router.push(`/agents/${lowerAgentSlug}`);- }- };-- const handleSendMessage = async (e, overrideText = null, overrideAttachments = null) => {- if (e) e.preventDefault();-- const userText = overrideText || input;- const currentAttachments = overrideAttachments || (overrideText ? [] : attachments);-- if (!userText.trim()) return;- if (isStreaming && !overrideText) return;-- if (overrideText) setIsStreaming(false);-- const userMessage = {- role: "user",- content: userText,- attachments: [...currentAttachments],- timestamp: new Date(),- };- setMessages((prev) => [...prev, userMessage]);-- if (!overrideText) {- setAttachments([]);- setInput("");- }-- setIsStreaming(true);- setError(null);- setDebugLogs([]);-- const assistantMsgId = `asst_${Date.now()}`;- currentAssistantMsgRef.current = {- id: assistantMsgId,- role: "assistant",- content: "",- thoughts: "",- status: [],- suggestions: [],- timestamp: new Date(),- };-- setMessages((prev) => [...prev, { ...currentAssistantMsgRef.current }]);-- try {- let currentConvId = conversationIdRef.current || effectiveConversationId;-- if (!currentConvId && !overrideText) {- const newConvId = crypto.randomUUID();- conversationIdRef.current = newConvId;-- sessionStorage.setItem('pending_first_msg', JSON.stringify({- convId: newConvId,- text: userText,- attachments: currentAttachments,- timestamp: new Date().toISOString()- }));-- if (lowerAgentSlug) {- router.replace(`/agents/${lowerAgentSlug}/${newConvId}`);- }-- return;- }-- const initialRes = await axios.post(- `${BASE_URL}/by-slug/${lowerAgentSlug}/chat`,- {- message: userText,- stream: false,- conversation_id: currentConvId,- attachments: userMessage.attachments,- }- );-- const { request_id } = initialRes.data;- if (!request_id) throw new Error("No Request ID returned from agent");-- const pollInterval = 1000;- let isComplete = false;- let errors = 0;-- while (!isComplete && errors < 5) {- try {- const pollRes = await axios.get(`/api/api/v1/predictions/${request_id}/result`);- const data = pollRes.data;-- // data format from backend execute_agent_chat_background:- // {- // conversation_id,- // messages: [{role, content...}, {type:'pulse'...}],- // status_text,- // is_complete,- // suggestions,- // error- // }-- if (data.conversation_id) conversationIdRef.current = data.conversation_id;-- const incomingMessages = data.messages || [];-- let newContent = "";- let newThoughts = "";- let newStatus = [];-- incomingMessages.forEach(msg => {- if (msg.role === "assistant" && msg.content) {- newContent = msg.content;- }- if (msg.type === "pulse" && msg.content) {- newStatus.push(msg.content);- }- if (msg.role === "assistant" && msg.thoughts) {- newThoughts = msg.thoughts;- }- });-- currentAssistantMsgRef.current.content = newContent;- currentAssistantMsgRef.current.status = newStatus;- currentAssistantMsgRef.current.suggestions = data.suggestions || [];- setMessages((prev) => {- const index = prev.findIndex((m) => m.id === assistantMsgId);- if (index !== -1) {- const newMessages = [...prev];- newMessages[index] = {- ...newMessages[index],- content: newContent,- status: newStatus,- suggestions: data.suggestions || [],- };- return newMessages;- }- return prev;- });-- if (data.status === "failed") {- throw new Error(data.error || "Agent execution failed");- }-- if (data.status === "completed" || data.status === "succeeded" || data.is_complete) {- isComplete = true;- } else {- await new Promise(r => setTimeout(r, pollInterval));- }-- } catch (pollErr) {- console.error("Polling error", pollErr);- errors++;- await new Promise(r => setTimeout(r, 2000));- }- }-- if (errors >= 5) throw new Error("Lost connection to agent process");-- } catch (err) {- console.log("Agent error:", err);- let errorMessage = err.message || "Something went wrong. Check browser console";- if (err.response) {- const { status, data } = err.response;- errorMessage = data?.error || "Not enough credits";- } else {- errorMessage = err.message;- }- setError(errorMessage);- if (!currentAssistantMsgRef.current.content) {- setMessages((prev) => prev.filter((m) => m.id !== assistantMsgId));- }- } finally {- setIsStreaming(false);- }- };-- return (- <main- className="h-dvh flex flex-col selection:bg-blue-500/30 relative"- style={{- ...generateCssVariables(currentTheme),- background: "var(--bg-primary)",- color: "var(--text-primary)",- fontFamily: "var(--font-family)",- }}- >- {isMounted && (- <style dangerouslySetInnerHTML={{ __html: `- @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');-- main {- font-family: var(--font-family) !important;- }-- .prose, .prose p, .prose h1, .prose h2, .prose h3, .prose h4, .prose li {- font-family: var(--font-family) !important;- }- ` }} />- )}- <header className="flex-shrink-0 border-b backdrop-blur-2xl px-6 py-4 flex items-center justify-center z-10 shadow-lg transition-colors duration-300 bg-[var(--header-bg)] border-[var(--border-color)]">- <div className="flex items-center justify-between gap-4 w-full lg:max-w-[80%]">- <div className="flex items-center gap-4">- <button- onClick={() => window.history.back()}- className="flex items-center justify-center transition-all group"- >- <IoChevronBack className="w-5 h-5 text-[var(--text-secondary)] group-hover:text-[var(--text-primary)] transition-colors" />- </button>- <div className="flex items-center gap-3">- {agentDetails?.icon_url ? (- <img- src={agentDetails.icon_url}- alt={agentDetails.name}- className="w-9 h-9 rounded-lg object-cover border border-[var(--border-color)]"- />- ) : (- <div className="w-9 h-9 rounded-lg flex items-center justify-center" style={{ background: 'var(--accent)', color: 'var(--accent-text)' }}>- <RiRobot2Fill className="w-5 h-5" />- </div>- )}- <div className="relative">- <button- onClick={() => setShowDropdown(!showDropdown)}- className="flex items-center gap-2 px-2 py-1 rounded-lg transition-all hover:bg-[var(--component-hover)]"- >- <div className="flex flex-col items-start leading-tight">- <h1 className="text-base font-semibold text-[var(--text-primary)] truncate">- {agentDetails?.name || "Loading..."}- </h1>- {agentDetails && !agentDetails.is_owner && (agentDetails.owner_username || agentDetails.owner_email) && (- <span className="text-[10px] text-[var(--text-secondary)] font-medium">- by {agentDetails.owner_username || agentDetails.owner_email?.split('@')[0]}- </span>- )}- </div>- <IoChevronBack- className={`w-4 h-4 text-[var(--text-secondary)] transition-transform ${showDropdown ? "rotate-90" : "-rotate-180"- }`}- />- </button>- {showDropdown && (- <div className="absolute top-10 left-0 border rounded-lg shadow-xl z-50 animate-in fade-in slide-in-from-top-2 duration-200 min-w-[200px] bg-[var(--header-bg)] border-[var(--border-color)]">- <button- onClick={() => {- setShowDropdown(false);- router.push(`/agents/${lowerAgentSlug}/profile`);- }}- type="button"- className="w-full flex items-center gap-3 px-3 py-2 transition-all hover:bg-[var(--component-hover)] rounded-t-lg"- >- <RiRobot2Fill size={16} className="text-[var(--text-secondary)]" />- <span className="text-sm text-[var(--text-primary)]">View Profile</span>- </button>- {agentDetails?.is_owner && (- <>- <button- onClick={() => {- setShowDropdown(false);- router.push(`/agents/edit/${agent_id}`);- }}- type="button"- className="w-full flex items-center gap-3 px-3 py-2 transition-all hover:bg-[var(--component-hover)] border-t border-[var(--border-color)]"- >- <MdEdit size={16} className="text-[var(--text-secondary)]" />- <span className="text-sm text-[var(--text-primary)]">Edit agent</span>- </button>- <div className="relative group/submenu">- <button- onMouseEnter={() => setShowThemeDropdown(true)}- onClick={() => setShowThemeDropdown(!showThemeDropdown)}- type="button"- className={`w-full flex items-center gap-3 px-3 py-2 transition-all hover:bg-[var(--component-hover)] border-t border-[var(--border-color)] rounded-b-lg ${showThemeDropdown ? 'bg-[var(--component-hover)]' : ''}`}- >- <IoColorPalette size={16} className="text-[var(--text-secondary)]" />- <span className="text-sm text-[var(--text-primary)]">Themes</span>- <FaAngleRight size={14} className="ml-auto text-[var(--text-secondary)]" />- </button>- {showThemeDropdown && (- <div- className="md:absolute relative md:left-full left-0 md:top-0 top-0 md:ml-1 ml-0 md:border border-none md:rounded-xl rounded-none md:shadow-2xl shadow-none overflow-hidden z-[60] animate-in fade-in md:slide-in-from-left-2 slide-in-from-top-2 duration-200 min-w-[200px] bg-[var(--header-bg)] md:border-[var(--border-color)] p-2"- onMouseEnter={() => setShowThemeDropdown(true)}- onMouseLeave={() => setShowThemeDropdown(false)}- >- <div className="text-[10px] font-bold text-[var(--text-secondary)] mb-2 px-2 uppercase tracking-[0.2em]">Select Theme</div>- <div className="space-y-1 max-h-80 overflow-y-auto custom-scrollbar pr-1">- {Object.values(themes).map((theme) => (- <button- key={theme.id}- onClick={() => {- handleThemeChange(theme);- setShowThemeDropdown(false);- setShowDropdown(false);- }}- type="button"- className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm transition-all group/theme ${currentTheme.id === theme.id- ? "bg-[var(--accent)] text-[var(--accent-text)] shadow-md"- : "text-[var(--text-secondary)] hover:bg-[var(--component-hover)]"- }`}- >- <div- className="w-4 h-4 rounded-full border border-white/20 shadow-inner flex-shrink-0"- style={{ background: theme.colors.background }}- ></div>- <span className="font-medium">{theme.name}</span>- {currentTheme.id === theme.id && (- <MdCheck className="ml-auto w-4 h-4" />- )}- </button>- ))}- <button- onClick={() => {- setShowCustomColorPanel(true);- setShowThemeDropdown(false);- setShowDropdown(false);- }}- type="button"- className="w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm text-[var(--text-secondary)] hover:bg-[var(--component-hover)] border-t border-[var(--border-color)] mt-1"- >- <MdEdit className="w-4 h-4" />- <span className="font-medium">Customize Colors</span>- </button>- </div>- </div>- )}- </div>- </>- )}- </div>- )}- </div>- </div>- </div>- <div className="flex items-center gap-2">- <button- type="button"- onClick={handleLike}- className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg transition-all border border-[var(--border-color)] text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--component-hover)]"- title={liked ? "Unlike agent" : "Like agent"}- >- {liked ? (- <IoHeart className="w-4 h-4 text-red-500" />- ) : (- <IoHeartOutline className="w-4 h-4" />- )}- <span className="text-xs font-semibold">{likeCount || 0}</span>- </button>-- {effectiveConversationId && (- <button- type="button"- onClick={handleNewChat}- className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg transition-all border border-[var(--border-color)] text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--component-hover)]"- title="Start new chat"- >- <HiOutlinePencilAlt className="w-4 h-4" />- <span className="text-xs hidden md:flex font-semibold">New Chat</span>- </button>- )}- </div>- </div>- </header>- <div className="flex-1 flex overflow-y-auto">- <div- ref={scrollRef}- className="flex-1 overflow-y-auto px-4 py-8 custom-scrollbar"- >- <div className="max-w-3xl mx-auto space-y-6">- {messages.length === 0 && agentDetails && (- <div className="space-y-6">- <div className="flex justify-center">- <div className="px-4 py-1.5 rounded-full border text-[10px] uppercase tracking-widest font-bold bg-[var(--component-bg)] border-[var(--border-color)] text-[var(--text-secondary)]">- Today- </div>- </div>- <div className="flex flex-col items-start animate-in fade-in slide-in-from-bottom-2 duration-300">- <div className="flex items-center gap-2 mb-1 ml-11">- <div className="text-xs font-bold text-[var(--text-primary)]">- {agentDetails?.name}- </div>- </div>-- <div className="flex gap-3 items-end max-w-[85%] group/msg">- {agentDetails?.icon_url ? (- <img- src={agentDetails.icon_url}- alt={agentDetails.name}- className="w-8 h-8 rounded-full object-cover border flex-shrink-0 border-[var(--border-color)] transition-all duration-500 ease-in-out"- />- ) : (- <div className="w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 transition-all duration-500 ease-in-out" style={{ background: 'var(--accent)', color: 'var(--accent-text)' }}>- <RiRobot2Fill className="w-4 h-4" />- </div>- )}- <div className="flex-1 space-y-3">- <div className="flex items-end gap-2">- <div- className="backdrop-blur-sm rounded-2xl rounded-tl-md px-4 py-3 shadow-xl border inline-block"- style={{- background: 'var(--agent-bubble)',- color: 'var(--agent-text)',- borderColor: 'var(--border-color)'- }}- >- <div className="prose prose-sm max-w-none" style={{ color: 'var(--agent-text)' }}>- <p>- {agentDetails.welcome_message ||- `Hello! I am ${agentDetails.name}. ${agentDetails.description ||- "How can I assist you today?"- }`}- </p>- </div>- </div>- <div className="opacity-0 group-hover/msg:opacity-100 transition-opacity">- <CopyButton text={agentDetails?.welcome_message || `Hello! I am ${agentDetails.name}. ${agentDetails.description || "How can I assist you today?"}`} />- </div>- </div>- {agentDetails.initial_suggestions?.length > 0 && (- <div className="flex flex-wrap gap-2 pt-2">- {agentDetails.initial_suggestions.map((sug, i) => (- <button- key={i}- type="button"- onClick={() => {- setInput(sug.prompt);- if (textareaRef.current) {- textareaRef.current.focus();- }- }}- className="flex items-center gap-2 text-xs font-medium border px-3 py-2 rounded-lg transition-all group hover:opacity-80"- style={{- background: 'var(--component-bg)',- borderColor: 'var(--border-color)',- color: 'var(--text-primary)'- }}- >- <HiLightBulb className="w-3.5 h-3.5 text-yellow-500 group-hover:scale-110 transition-transform" />- {sug.label}- </button>- ))}- </div>- )}- </div>- </div>- </div>- </div>- )}- {messages.map((msg, idx) => {- const prevMsg = messages[idx - 1];- const showDateHeader =- !prevMsg ||- new Date(msg.timestamp).toDateString() !==- new Date(prevMsg.timestamp).toDateString();-- return (- <div key={idx} className="space-y-6">- {showDateHeader && msg.timestamp && (- <div className="flex justify-center">- <div className="px-4 py-1.5 rounded-full border text-[10px] uppercase tracking-widest font-bold bg-[var(--component-bg)] border-[var(--border-color)] text-[var(--text-secondary)]">- {getDateHeader(msg.timestamp)}- </div>- </div>- )}- <div- className={`flex ${msg.role === "user" ? "justify-end" : "justify-start"- } animate-in fade-in slide-in-from-bottom-2 duration-300`}- >- {msg.role === "user" ? (- <div className="flex flex-col items-end max-w-[80%] group/msg">- <div className="flex items-center gap-2 mb-1 mr-11">- {msg.timestamp && (- <div className="text-[10px] font-medium text-[var(--text-secondary)]">- {formatMessageTime(msg.timestamp)}- </div>- )}- <div className="text-xs font-bold text-[var(--text-primary)]">- {userName}- </div>- </div>-- <div className="flex gap-3 items-end w-full justify-end">- <div className="flex-1 space-y-1 text-right">- <div className="flex items-end justify-end gap-2">- <div className="opacity-0 group-hover/msg:opacity-100 transition-opacity">- <CopyButton text={msg.content} />- </div>- <div- className="px-4 py-3 rounded-2xl rounded-tr-md shadow-xl inline-block text-left"- style={{- background: 'var(--user-bubble)',- color: 'var(--user-text)',- }}- >- {msg.attachments?.length > 0 && (- <div className="mb-3 flex flex-wrap justify-end gap-2">- {msg.attachments.map((url, i) => (- <div key={i} className="relative group/user-att">- <img- src={url}- alt="Uploaded Attachment"- className="w-24 h-24 sm:w-32 sm:h-32 rounded-xl object-cover border border-white/20 shadow-md cursor-pointer hover:scale-[1.02] transition-transform"- onClick={() => setSelectedMedia({ type: "image", url })}- />- </div>- ))}- </div>- )}- <p className="text-sm leading-relaxed font-medium whitespace-pre-wrap">- {msg.content}- </p>- </div>- </div>- </div>- {userProfile ? (- <img- src={userProfile}- alt={userName}- className="w-8 h-8 rounded-full object-cover border flex-shrink-0 border-[var(--border-color)] transition-all duration-500 ease-in-out"- />- ) : (- <div className="w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 transition-all duration-500 ease-in-out" style={{ background: 'var(--accent)', color: 'var(--accent-text)' }}>- <MdPerson className="w-4 h-4" />- </div>- )}- </div>- </div>- ) : (- <div className="flex flex-col items-start max-w-[85%] group/msg">- <div className="flex items-center gap-2 mb-1 ml-11">- <div className="text-xs font-bold text-[var(--text-primary)]">- {agentDetails?.name}- </div>- {msg.timestamp && (- <div className="text-[10px] font-medium text-[var(--text-secondary)]">- {formatMessageTime(msg.timestamp)}- </div>- )}- </div>-- <div className="flex gap-3 items-end w-full">- {agentDetails?.icon_url ? (- <img- src={agentDetails.icon_url}- alt={agentDetails.name}- className="w-8 h-8 rounded-full object-cover border flex-shrink-0 border-[var(--border-color)] transition-all duration-500 ease-in-out"- />- ) : (- <div className="w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 transition-all duration-500 ease-in-out" style={{ background: 'var(--accent)', color: 'var(--accent-text)' }}>- <RiRobot2Fill className="w-4 h-4" />- </div>- )}-- <div className="flex-1 space-y-3">- {msg.status?.length > 0 && (- <div className="flex flex-wrap gap-2">- {msg.status.map((st, i) => (- <div- key={i}- className="flex items-center gap-1.5 text-xs px-3 py-1 rounded-full border"- style={{- background: 'var(--component-bg)',- borderColor: 'var(--border-color)',- color: 'var(--accent)'- }}- >- <MdTerminal className="w-3 h-3" />- <span>{st}</span>- </div>- ))}- </div>- )}-- {msg.thoughts && (- <div className="border rounded-xl p-4 space-y-2 bg-[var(--component-bg)] border-[var(--border-color)]">- <div className="flex items-center gap-2 text-xs font-medium text-[var(--text-secondary)]">- <RiRobot2Fill className="w-3.5 h-3.5" />- <span>Thinking process</span>- </div>- <p className="text-xs leading-relaxed italic text-[var(--text-secondary)]">- {msg.thoughts}- </p>- </div>- )}-- {(msg.content || (isStreaming && idx === messages.length - 1)) && (- <div className="flex items-end gap-2">- <div- className="backdrop-blur-sm rounded-2xl rounded-tl-md px-4 py-3 shadow-xl border inline-block"- style={{- background: 'var(--agent-bubble)',- color: 'var(--agent-text)',- borderColor: 'var(--border-color)',- }}- >- <div className="prose prose-sm max-w-none" style={{ color: 'var(--agent-text)' }}>- {parseMessageContent(msg.content || " ").map((part, i) => (- <div key={i}>- {part.type === "text" && (- <ReactMarkdown remarkPlugins={[remarkGfm]}>- {part.content}- </ReactMarkdown>- )}- {part.type === "image" && (- <div className="my-3 rounded-xl overflow-hidden border shadow-lg relative w-fit group/media bg-[var(--component-bg)] border-[var(--border-color)]">- <img- src={part.url}- alt="Generated Media"- className="w-full h-auto max-h-[300px] object-contain transition-transform duration-500 group-hover/media:scale-[1.02]"- loading="lazy"- />- <div className="absolute inset-0 bg-black/40 opacity-0 group-hover/media:opacity-100 transition-opacity duration-300 flex items-center justify-center gap-4">- <button- onClick={() => setSelectedMedia({ type: "image", url: part.url })}- type="button"- className="p-3 rounded-full bg-white/10 hover:bg-white/20 text-white backdrop-blur-md border border-white/20 transition-all hover:scale-110"- title="View Full Screen"- >- <MdFullscreen className="w-6 h-6" />- </button>- <button- onClick={() => handleDownloadFile(part.url, `image-${Date.now()}.png`)}- type="button"- className="p-3 rounded-full bg-white/10 hover:bg-white/20 text-white backdrop-blur-md border border-white/20 transition-all hover:scale-110 disabled:opacity-50"- title="Download"- disabled={downloadingUrl === part.url}- >- {downloadingUrl === part.url ? (- <BiLoaderAlt className="w-6 h-6 animate-spin" />- ) : (- <MdFileDownload className="w-6 h-6" />- )}- </button>- </div>- </div>- )}- {part.type === "video" && (- <div className="my-3 rounded-xl overflow-hidden border shadow-lg relative w-fit group/media bg-[var(--component-bg)] border-[var(--border-color)]">- <video- src={part.url}- className="w-full h-auto max-h-[300px] transition-transform duration-500 group-hover/media:scale-[1.02]"- />- <div className="absolute top-4 right-4 flex flex-col gap-2 opacity-0 group-hover/media:opacity-100 transition-opacity duration-300 z-10">- <button- onClick={() => setSelectedMedia({ type: "video", url: part.url })}- className="p-2 rounded-lg bg-black/60 hover:bg-black/80 text-white backdrop-blur-md border border-white/20 transition-all hover:scale-105"- title="View Full Screen"- >- <MdFullscreen className="w-5 h-5" />- </button>- <button- onClick={() => handleDownloadFile(part.url, `video-${Date.now()}.mp4`)}- className="p-2 rounded-lg bg-black/60 hover:bg-black/80 text-white backdrop-blur-md border border-white/20 transition-all hover:scale-105 disabled:opacity-50"- title="Download"- disabled={downloadingUrl === part.url}- >- {downloadingUrl === part.url ? (- <BiLoaderAlt className="w-5 h-5 animate-spin" />- ) : (- <MdFileDownload className="w-5 h-5" />- )}- </button>- </div>- </div>- )}- {part.type === "audio" && (- <div className="my-3 flex items-center gap-3 p-3 rounded-xl border backdrop-blur-sm bg-[var(--component-bg)] border-[var(--border-color)]">- <div- className="w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0"- style={{ background: 'var(--component-hover)', color: 'var(--accent)' }}- >- <svg- xmlns="http://www.w3.org/2000/svg"- fill="none"- viewBox="0 0 24 24"- strokeWidth={1.5}- stroke="currentColor"- className="w-5 h-5"- >- <path- strokeLinecap="round"- strokeLinejoin="round"- d="M19.114 5.636a9 9 0 0 1 0 12.728M16.463 8.288a5.25 5.25 0 0 1 0 7.424M6.75 8.25l4.72-4.72a.75.75 0 0 1 1.28.53v15.88a.75.75 0 0 1-1.28.53l-4.72-4.72H4.51c-.88 0-1.704-.507-1.938-1.354A9.01 9.01 0 0 1 2.25 12c0-.83.112-1.633.322-2.396C2.806 8.756 3.63 8.25 4.51 8.25H6.75Z"- />- </svg>- </div>- <audio src={part.url} controls className="w-full h-8" />- </div>- )}- </div>- ))}- </div>- {isStreaming && idx === messages.length - 1 && (- <div className="flex gap-1 mt-2">- <div- className="w-2 h-2 rounded-full animate-bounce"- style={{ background: 'var(--accent)', animationDelay: "0ms" }}- ></div>- <div- className="w-2 h-2 rounded-full animate-bounce"- style={{ background: 'var(--accent)', animationDelay: "150ms" }}- ></div>- <div- className="w-2 h-2 rounded-full animate-bounce"- style={{ background: 'var(--accent)', animationDelay: "300ms" }}- ></div>- </div>- )}- </div>- <div className="opacity-0 group-hover/msg:opacity-100 transition-opacity">- <CopyButton text={msg.content} />- </div>- </div>- )}-- {msg.suggestions?.length > 0 && (- <div className="flex flex-wrap gap-2">- {msg.suggestions.map((sug, i) => (- <button- key={i}- onClick={() => setInput(sug.prompt)}- className="flex items-center gap-2 text-xs font-medium border px-3 py-2 rounded-lg transition-all hover:opacity-80"- style={{- background: 'var(--component-bg)',- borderColor: 'var(--border-color)',- color: 'var(--text-primary)'- }}- >- <HiLightBulb className="w-3.5 h-3.5 text-yellow-500" />- {sug.label}- </button>- ))}- </div>- )}- </div>- </div>- </div>- )}- </div>- </div>- );- })}- </div>- </div>- {/* {showDebug && (- <div className="w-80 border-l backdrop-blur-xl overflow-y-auto p-4 custom-scrollbar animate-in slide-in-from-right duration-300 bg-[var(--header-bg)] border-[var(--border-color)]">- <div className="flex items-center justify-between mb-4 pb-3 border-b border-[var(--border-color)]">- <h3 className="text-xs font-semibold uppercase tracking-wider text-[var(--text-secondary)]">- Debug Logs- </h3>- <button- type="button"- onClick={() => setShowDebug(false)}- className="text-[var(--text-secondary)] hover:text-[var(--text-primary)]"- >- <MdClose className="w-4 h-4" />- </button>- </div>- <div className="space-y-2">- {debugLogs.length === 0 && (- <p className="text-xs italic text-[var(--text-secondary)]">- No logs yet...- </p>- )}- {debugLogs.map((log, i) => (- <div- key={i}- className={`p-2 rounded-lg border text-xs font-mono ${log.type === "error"- ? "bg-red-500/10 border-red-500/20 text-red-400"- : log.type === "warn"- ? "bg-yellow-500/10 border-yellow-500/20 text-yellow-400"- : "bg-[var(--component-bg)] border-[var(--border-color)] text-[var(--text-secondary)]"- }`}- >- <span className="text-[10px] opacity-50 mr-2">- [{log.time}]- </span>- {log.msg}- </div>- ))}- </div>- </div>- )} */}- </div>- <footer className="flex-shrink-0 p-4">- <div className="max-w-3xl mx-auto">- {error && (- <div className="mb-3 p-3 bg-red-500/10 border border-red-500/20 rounded-xl flex items-center justify-between">- <span className="text-xs text-red-400 font-medium">- Error: {error}- </span>- <button- onClick={() => setError(null)}- className="text-red-400 hover:text-red-300"- >- <MdClose className="w-4 h-4" />- </button>- </div>- )}- <form- onSubmit={handleSendMessage}- onDragOver={handleDragOver}- onDragLeave={handleDragLeave}- onDrop={handleDrop}- className={`relative border rounded-2xl flex items-end gap-2 p-2 transition-all shadow-inner focus-within:border-[var(--accent)] ${- isDragging ? "ring-2 ring-[var(--accent)] border-[var(--accent)] bg-[var(--accent)]/5" : ""- }`}- style={{- background: 'var(--input-bg)',- borderColor: 'var(--border-color)'- }}- >- {isDragging && (- <div className="absolute inset-0 z-50 flex items-center justify-center bg-[var(--accent)]/10 backdrop-blur-[2px] rounded-2xl pointer-events-none border-2 border-dashed border-[var(--accent)] animate-in fade-in duration-200">- <div className="flex items-center justify-center gap-2 text-[var(--accent)]">- <IoAdd className="w-8 h-8 animate-bounce" />- <span className="text-sm font-bold uppercase tracking-wider">Drop image to upload</span>- </div>- </div>- )}- {attachments.length > 0 && (- <div className="absolute bottom-full left-0 right-0 mb-2 flex flex-wrap gap-2 animate-in slide-in-from-bottom-2">- {attachments.map((url, i) => (- <div key={i} className="relative group/att">- <img- src={url}- className="w-16 h-16 rounded-xl object-cover border-2 border-[var(--border-color)] shadow-lg"- alt="Attachment Preview"- />- <button- onClick={() => removeAttachment(url)}- type="button"- className="absolute -top-1.5 -right-1.5 p-1 bg-red-500 text-white rounded-full shadow-lg opacity-0 group-hover/att:opacity-100 transition-opacity"- >- <MdClose className="w-3 h-3" />- </button>- </div>- ))}- </div>- )}- <input- type="file"- ref={fileInputRef}- onChange={handleFileUpload}- className="hidden"- accept="image/*"- />- <button- onClick={() => fileInputRef.current?.click()}- type="button"- disabled={isUploading || isStreaming}- className="flex-shrink-0 w-9 h-9 rounded-xl flex items-center justify-center transition-all bg-[var(--component-hover)] text-[var(--text-secondary)] hover:text-[var(--text-primary)] disabled:opacity-50 shadow-sm relative overflow-hidden"- title="Upload Image"- >- {isUploading ? (- <>- <BiLoaderAlt className="w-4 h-4 animate-spin opacity-20" />- <span className="absolute inset-0 flex items-center justify-center text-[10px] font-bold text-[var(--accent)]">- {uploadProgress}%- </span>- </>- ) : (- <IoAdd className="w-5 h-5" />- )}- </button>- <textarea- ref={textareaRef}- value={input}- onChange={(e) => setInput(e.target.value)}- onKeyDown={(e) => {- if (e.key === "Enter" && !e.shiftKey) {- e.preventDefault();- handleSendMessage();- }- }}- disabled={isStreaming}- placeholder={isStreaming ? "Agent is thinking..." : "Type here or drop an image..."}- className="flex-1 bg-transparent px-3 py-2.5 text-sm focus:outline-none resize-none max-h-32 placeholder:text-gray-500 custom-scrollbar text-[var(--text-primary)]"- rows={1}- />- <button- type="submit"- disabled={!input.trim() || isStreaming}- className="flex-shrink-0 w-9 h-9 rounded-xl flex items-center justify-center transition-all disabled:opacity-50 disabled:cursor-not-allowed shadow-lg"- style={{- background: 'var(--accent)',- color: 'var(--accent-text)'- }}- >- {isStreaming ? (- <BiLoaderAlt className="w-4 h-4 animate-spin" />- ) : (- <IoSend className="w-4 h-4" />- )}- </button>- </form>- </div>- </footer>- {selectedMedia && (- <div- className="fixed inset-0 z-[100] flex items-center justify-center bg-black/95 backdrop-blur-sm animate-in fade-in duration-300"- onClick={() => setSelectedMedia(null)}- >- <button- type="button"- className="absolute top-6 right-6 p-2 rounded-full bg-white/5 hover:bg-white/10 text-white transition-all border border-white/10 z-[110]"- onClick={() => setSelectedMedia(null)}- >- <MdClose className="w-6 h-6" />- </button>- <div- className="max-w-[90vw] max-h-[90vh] relative animate-in zoom-in-95 duration-300"- onClick={(e) => e.stopPropagation()}- >- {selectedMedia.type === "image" ? (- <img- src={selectedMedia.url}- alt="Full Screen"- className="w-full h-auto max-h-[90vh] object-contain rounded-lg shadow-2xl border border-white/10"- />- ) : (- <video- src={selectedMedia.url}- controls- autoPlay- className="w-full h-auto max-h-[90vh] rounded-lg shadow-2xl border border-white/10"- />- )}- <div className="flex justify-center">- <button- onClick={() =>- handleDownloadFile(- selectedMedia.url,- `${selectedMedia.type}-${Date.now()}.${selectedMedia.type === "image" ? "png" : "mp4"- }`- )- }- type="button"- className="flex items-center gap-2 px-6 py-2.5 rounded-full bg-blue-600 hover:bg-blue-700 text-white font-medium transition-all shadow-lg shadow-blue-500/20 disabled:opacity-50"- disabled={downloadingUrl === selectedMedia.url}- >- {downloadingUrl === selectedMedia.url ? (- <>- <BiLoaderAlt className="w-5 h-5 animate-spin" />- Preparing...- </>- ) : (- <>- <MdFileDownload className="w-5 h-5" />- Download- </>- )}- </button>- </div>- </div>- </div>- )}- {showCustomColorPanel && (- <div className="absolute inset-0 z-[100] flex items-center justify-center p-4">- <div- className="absolute inset-0 bg-black/10 backdrop-blur-sm transition-opacity"- onClick={() => setShowCustomColorPanel(false)}- />- <div className="relative w-full max-w-md bg-[var(--header-bg)] border border-[var(--border-color)] rounded-2xl shadow-2xl overflow-hidden animate-in fade-in zoom-in-95 duration-200">- <div className="flex items-center justify-between px-6 py-4 border-b border-[var(--border-color)]">- <div className="flex items-center gap-2">- <IoColorPalette className="w-5 h-5 text-[var(--accent)]" />- <h3 className="font-bold text-[var(--text-primary)]">Customize Theme</h3>- </div>- <button- onClick={() => setShowCustomColorPanel(false)}- className="p-1 rounded-lg hover:bg-[var(--component-hover)] text-[var(--text-secondary)] transition-colors"- >- <MdClose className="w-6 h-6" />- </button>- </div>-- <div className="p-6 max-h-[70vh] overflow-y-auto custom-scrollbar space-y-4">- {[- { label: 'Background', key: 'background' },- { label: 'Text Primary', key: 'foreground' },- { label: 'Text Secondary', key: 'muted' },- { label: 'Border Color', key: 'border' },- { label: 'Panel Background', key: 'componentBg' },- { label: 'Header Background', key: 'headerBg' },- { label: 'User Bubble', key: 'userBubble' },- { label: 'User Text', key: 'userText' },- { label: 'Agent Bubble', key: 'agentBubble' },- { label: 'Agent Text', key: 'agentText' },- { label: 'Input Background', key: 'inputBg' },- { label: 'Accent Color', key: 'accent' },- { label: 'Accent Text', key: 'accentText' },- ].map((item) => (- <div key={item.key} className="flex items-center justify-between p-3 rounded-xl border border-[var(--border-color)] bg-[var(--component-bg)]/50">- <span className="text-sm font-medium text-[var(--text-primary)]">{item.label}</span>- <div className="flex items-center gap-3">- <span className="text-[10px] font-mono text-[var(--text-secondary)] uppercase">- {currentTheme.colors[item.key]}- </span>- <input- type="color"- value={currentTheme.colors[item.key]?.startsWith('#') ? currentTheme.colors[item.key] : '#000000'}- onChange={(e) => handleCustomColorChange(item.key, e.target.value)}- className="w-10 h-10 rounded-lg cursor-pointer border-none bg-transparent"- />- </div>- </div>- ))}- </div>-- <div className="p-4 bg-[var(--component-bg)]/50 border-t border-[var(--border-color)]">- <button- onClick={() => handleThemeSync(currentTheme)}- className="w-full py-3 rounded-xl font-bold transition-all shadow-lg active:scale-95"- style={{ background: 'var(--accent)', color: 'var(--accent-text)' }}- >- Apply Changes- </button>- </div>- </div>- </div>- )}- </main>- );-};--export default ChatPage;diff --git a/packages/agents/src/CreatePage.jsx b/packages/agents/src/CreatePage.jsxdeleted file mode 100644index ff30229..0000000--- a/packages/agents/src/CreatePage.jsx+++ /dev/null@@ -1,17 +0,0 @@-"use client";--import CreateAgent from "./components/CreateAgent";-import { Toaster } from "react-hot-toast";--const CreateAgentPage = ({ useUser, usedIn = "muapiapp" }) => {- return (- <div className="h-screen w-full flex flex-col bg-gray-100 transition-all duration-300 ease-in-out">- <main className="flex flex-col items-center gap-2 w-full h-full overflow-y-auto pt-8">- <CreateAgent useUser={useUser} usedIn={usedIn} />- </main>- <Toaster position="top-center" reverseOrder={false} />- </div>- );-};--export default CreateAgentPage;diff --git a/packages/agents/src/EditPage.jsx b/packages/agents/src/EditPage.jsxdeleted file mode 100644index 45a082d..0000000--- a/packages/agents/src/EditPage.jsx+++ /dev/null@@ -1,17 +0,0 @@-"use client";--import EditAgent from "./components/EditAgent";-import { Toaster } from "react-hot-toast";--const EditAgentPage = ({ useUser, usedIn = "muapiapp" }) => {- return (- <div className="h-dvh w-full flex flex-col bg-blue-50/50 transition-all duration-300 ease-in-out">- <Toaster position="top-center" reverseOrder={false} />- <main className="flex flex-col items-center gap-2 w-full h-full overflow-y-auto pt-8">- <EditAgent useUser={useUser} usedIn={usedIn} />- </main>- </div>- );-};--export default EditAgentPage;diff --git a/packages/agents/src/components/AgentThemeProvider.jsx b/packages/agents/src/components/AgentThemeProvider.jsxdeleted file mode 100644index 7066794..0000000--- a/packages/agents/src/components/AgentThemeProvider.jsx+++ /dev/null@@ -1,19 +0,0 @@-'use client'--import React from 'react'-import { ThemeProvider } from 'next-themes'--export const AgentThemeProvider = ({ children }) => {- return (- <ThemeProvider- attribute="class"- defaultTheme="system"- enableSystem- disableTransitionOnChange- >- {children}- </ThemeProvider>- )-}--export default AgentThemeProviderdiff --git a/packages/agents/src/components/CreateAgent.jsx b/packages/agents/src/components/CreateAgent.jsxdeleted file mode 100644index a8cce6a..0000000--- a/packages/agents/src/components/CreateAgent.jsx+++ /dev/null@@ -1,152 +0,0 @@-import React, { useEffect, useState } from "react";-import Link from "next/link";-import axios from "axios";-import { BiLoaderAlt } from "react-icons/bi";-import { RiRobot2Fill } from "react-icons/ri";-import { IoArrowBackOutline } from "react-icons/io5";-import { useRouter } from "next/navigation";--const BASE_URL = "/api/agents";--const CreateAgent = ({ useUser, usedIn }) => {- const userContext = useUser ? useUser() : {};- let user = null;-- if (usedIn === "vadoo") {- const { serverDetails } = userContext;- user = serverDetails?.user_details- ? { email: serverDetails.user_details.email, name: serverDetails.user_details.name }- : null;- } else {- // muapiapp- user = userContext.user || null;- }- const router = useRouter();- const [prompt, setPrompt] = useState("");- const [loading, setLoading] = useState(false);- const [error, setError] = useState(null);-- const handleArchitectAgent = async (e) => {- e.preventDefault();- if (!prompt.trim()) return;-- try {- setLoading(true);- setError(null);-- const suggestResponse = await axios.post(`${BASE_URL}/suggest`, {- prompt,- });- const suggestion = suggestResponse.data;- const createPayload = {- name: suggestion.name || "Unnamed Agent",- description: suggestion.description || "",- system_prompt: suggestion.system_prompt || "",- skill_ids: suggestion.recommended_skill_ids || [],- welcome_message: suggestion.welcome_message || "",- initial_suggestions: suggestion.initial_suggestions || [],- is_published: false,- is_template: false,- };-- const createResponse = await axios.post(`${BASE_URL}`, createPayload);- if (createResponse.status === 200 || createResponse.status === 201) {- const createdAgent = createResponse.data;- router.push(`/agents/edit/${createdAgent.agent_id}`);- }- } catch (err) {- console.error("Agent creation failed:", err);- setError(- err.response?.data?.message ||- err.response?.data?.detail ||- err.message ||- "Failed to architect agent. Please try again.",- );- } finally {- setLoading(false);- }- };-- return (- <div className="flex-1 flex flex-col gap-8 items-center w-full max-w-[95%] sm:max-w-[90%] lg:max-w-[80%] relative pb-12">- <div className="flex items-start gap-2 w-full">- <Link- href="/agents"- className="p-2 hover:bg-gray-100 dark:hover:bg-secondary-bg rounded-full transition-colors group"- >- <IoArrowBackOutline className="w-4 h-4 text-gray-800 dark:text-primary-text group-hover:scale-110 transition-transform" />- </Link>- <div className="flex flex-col gap-2 w-full">- <h1 className="text-2xl font-bold text-black dark:text-white">- Prompt Any Assistant- </h1>- <p className="text-gray-500 dark:text-secondary-text text-sm font-medium">- Use this to prompt up an assistant to help you with any topic!- </p>- </div>- </div>- <form onSubmit={handleArchitectAgent} className="space-y-8 w-full">- <div className="space-y-4">- <label className="text-lg font-semibold text-black dark:text-white block">- What should your assistant be able to do and be knowledgeable in?- </label>- <div className="relative">- <textarea- value={prompt}- autoFocus- onChange={(e) => setPrompt(e.target.value)}- placeholder="Ex: A helpful travel agent that finds the best destinations in Italy..."- className="w-full bg-white dark:bg-secondary-bg border border-gray-200 dark:border-divider rounded-xl p-4 text-gray-900 dark:text-primary-text text-sm focus:outline-none focus:ring-2 focus:ring-black/10 dark:focus:ring-primary/10 focus:border-gray-400 dark:focus:border-primary transition-all resize-none min-h-[140px] shadow-sm"- disabled={loading}- />- </div>- </div>-- <div className="flex items-center gap-6">- </div>-- <div className="flex flex-col gap-4">- <button- type="submit"- disabled={loading || !prompt.trim()}- className="w-full py-3 bg-blue-500 dark:bg-primary hover:bg-blue-600 dark:hover:bg-primary/90 disabled:bg-gray-200 dark:disabled:bg-divider disabled:text-gray-400 dark:disabled:text-secondary-text disabled:cursor-not-allowed text-white text-base font-semibold rounded-xl transition-all flex items-center justify-center gap-3 active:scale-[0.98]"- >- {loading ? (- <>- <BiLoaderAlt className="w-6 h-6 animate-spin" />- <span>Creating agent...</span>- </>- ) : (- "Create agent"- )}- </button>- {loading && (- <p className="text-center text-gray-400 dark:text-secondary-text text-sm animate-pulse">- Analyzing prompt and building capabilities...- </p>- )}- {error && (- <div className="p-4 bg-red-50 dark:bg-red-900/10 border border-red-100 dark:border-red-900/30 rounded-xl text-red-600 dark:text-red-400 text-sm flex items-center gap-3 animate-in fade-in duration-300">- <svg- className="w-5 h-5 flex-shrink-0"- fill="none"- stroke="currentColor"- viewBox="0 0 24 24"- >- <path- strokeLinecap="round"- strokeLinejoin="round"- strokeWidth="2"- d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"- />- </svg>- {error}- </div>- )}- </div>- </form>- </div>- )-};--export default CreateAgent;diff --git a/packages/agents/src/components/EditAgent.jsx b/packages/agents/src/components/EditAgent.jsxdeleted file mode 100644index c7cb5e0..0000000--- a/packages/agents/src/components/EditAgent.jsx+++ /dev/null@@ -1,896 +0,0 @@-import React, { useState, useEffect, useRef } from "react";-import { useParams, useRouter } from "next/navigation";-import Link from "next/link";-import axios from "axios";-import { IoChevronBack, IoPencilOutline, IoShareOutline, IoTrashOutline, IoCloseOutline, IoImageOutline, IoSparklesOutline, IoChatbubblesOutline } from "react-icons/io5";-import { BiLoaderAlt } from "react-icons/bi";-import { RiRobot2Fill } from "react-icons/ri";-import toast from "react-hot-toast";-import { FaRegTrashCan } from "react-icons/fa6";-import { MdClose } from "react-icons/md";-import { themes } from "./themes";--const BASE_URL = "/api/agents";--const EditAgent = ({ useUser, usedIn }) => {- // Project-specific user detail extraction- const userContext = useUser ? useUser() : {};- let user = null;-- if (usedIn === "vadoo") {- const { serverDetails } = userContext;- user = serverDetails?.user_details- ? { email: serverDetails.user_details.email, name: serverDetails.user_details.name }- : null;- } else {- // muapiapp- user = userContext.user || null;- }- const { id } = useParams();- const router = useRouter();- const fileInputRef = useRef(null);-- const [formData, setFormData] = useState({- name: "",- description: "",- system_prompt: "",- icon_url: "",- skill_ids: [],- theme: "cosmic",- is_published: false,- is_template: false,- });-- const [availableSkills, setAvailableSkills] = useState([]);- const [loading, setLoading] = useState(true);- const [saving, setSaving] = useState(false);- const [uploading, setUploading] = useState(false);- const [uploadProgress, setUploadProgress] = useState(0);- const [searchTerm, setSearchTerm] = useState("");- const [error, setError] = useState(null);- const [success, setSuccess] = useState(false);- const [initialSkills, setInitialSkills] = useState([]);- const [realignedPrompt, setRealignedPrompt] = useState("");- const [isRealigning, setIsRealigning] = useState(false);- const [showRealignModal, setShowRealignModal] = useState(false);- const [generatingIcon, setGeneratingIcon] = useState(false);- const [showIconPromptModal, setShowIconPromptModal] = useState(false);- const [showIconSelectionModal, setShowIconSelectionModal] = useState(false);- const [iconPrompt, setIconPrompt] = useState("");-- useEffect(() => {- if (id) {- fetchData();- }- }, [id]);-- const fetchData = async () => {- try {- setLoading(true);- setError(null);-- const [agentRes, skillsRes] = await Promise.all([- axios.get(`${BASE_URL}/by-slug/${id}`),- axios.get(`${BASE_URL}/skills`)- ]);-- const agent = agentRes.data;- if (!agent.is_owner) {- setError("You are not authorized to edit this agent.");- setLoading(false);- return;- }- setFormData({- name: agent.name,- description: agent.description || "",- system_prompt: agent.system_prompt,- icon_url: agent.icon_url || "",- skill_ids: agent.skills.map(s => s.id),- theme: agent.theme || "cosmic",- is_published: agent.is_published || false,- is_template: agent.is_template || false,- });- setInitialSkills(agent.skills.map(s => s.id));- setAvailableSkills(skillsRes.data);- } catch (err) {- console.error("Error fetching data:", err);- setError(- err.response?.data?.message ||- err.response?.data?.detail ||- "Failed to load agent details."- );- } finally {- setLoading(false);- }- };-- const handleInputChange = (e) => {- const { name, value } = e.target;- setFormData(prev => ({ ...prev, [name]: value }));- };-- const handleSkillToggle = (skillId) => {- setFormData(prev => {- const isSelected = prev.skill_ids.includes(skillId);- if (isSelected) {- return { ...prev, skill_ids: prev.skill_ids.filter(id => id !== skillId) };- } else {- return { ...prev, skill_ids: [...prev.skill_ids, skillId] };- }- });- };-- const handleDelete = async () => {- if (!window.confirm("Are you sure you want to delete this agent? This action cannot be undone.")) {- return;- }-- try {- setSaving(true);- await axios.delete(`${BASE_URL}/by-slug/${id}`);- toast.success("Agent deleted successfully");- router.push("/agents");- } catch (err) {- console.error("Delete error:", err);- toast.error("Failed to delete agent");- setError(err.response?.data?.detail || "Delete failed");- } finally {- setSaving(false);- }- };-- const handleShare = () => {- const url = `${window.location.origin}/agents/${id}`;- navigator.clipboard.writeText(url);- toast.success("Chat link copied to clipboard!");- };-- const handleFileUpload = async (e) => {- const file = e.target.files?.[0];- if (!file) return;-- if (!file.type.startsWith("image/")) {- toast.error("Please upload an image file");- return;- }-- try {- setUploading(true);- setUploadProgress(0);- const { data: uploadParams } = await axios.get("/api/app/get_file_upload_url", {- params: { filename: file.name }- });-- const { url, fields } = uploadParams;- const uploadData = new FormData();- Object.entries(fields).forEach(([key, value]) => {- uploadData.append(key, value);- });- uploadData.append("file", file);-- await axios.post(url, uploadData, {- headers: { "Content-Type": "multipart/form-data" },- onUploadProgress: (progressEvent) => {- const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);- setUploadProgress(percent);- }- });- const prefix = usedIn === "vadoo" ? "https://d3adwkbyhxyrtq.cloudfront.net/": "https://cdn.muapi.ai/";- const uploadedUrl = `${prefix}${fields.key}`;- setFormData(prev => ({ ...prev, icon_url: uploadedUrl }));- toast.success("Profile image updated");- } catch (err) {- console.error("Upload failed:", err);- toast.error("Failed to upload image");- } finally {- setUploading(false);- setUploadProgress(0);- }- };-- const handleGenerateIcon = async (customPrompt) => {- if (!formData.name && !customPrompt) {- toast.error("Please enter an agent name first");- return;- }-- try {- setGeneratingIcon(true);- const prompt = customPrompt || `A professional, clean profile icon for an AI agent named "${formData.name}". Description: ${formData.description || "An AI assistant"}. Minimalist, high-quality, circular composition.`;-- const response = await axios.post("/api/api/v1/flux-schnell-image", {- prompt,- width: 1024,- height: 1024,- num_images: 1,- sync: true- });-- if (response.data && response.data.outputs && response.data.outputs.length > 0) {- const generatedUrl = response.data.outputs[0];- setFormData(prev => ({ ...prev, icon_url: generatedUrl }));- setShowIconPromptModal(false);- toast.success("AI icon generated!");- } else {- throw new Error("No image generated");- }- } catch (err) {- console.error("Icon generation failed:", err);- toast.error(err.response?.data?.detail || "Failed to generate AI icon");- } finally {- setGeneratingIcon(false);- }- };-- const handleRealign = async () => {- try {- setIsRealigning(true);- const res = await axios.post(`${BASE_URL}/by-slug/${id}/preview-realign`, {- current_prompt: formData.system_prompt,- new_skill_ids: formData.skill_ids- });- setRealignedPrompt(res.data.proposed_prompt);- setShowRealignModal(true);- toast.success("Prompt realigned! Please review.");- } catch (err) {- console.error("Realign failed:", err);- toast.error("Failed to realign prompt");- } finally {- setIsRealigning(false);- }- };-- const applyRealignedPrompt = () => {- setFormData(prev => ({ ...prev, system_prompt: realignedPrompt }));- setShowRealignModal(false);- toast.success("New instructions applied!");- };-- const handleSubmit = async (e) => {- e.preventDefault();- try {- setSaving(true);- setError(null);- setSuccess(false);-- await axios.put(`${BASE_URL}/by-slug/${id}`, formData);-- setSuccess(true);- toast.success("Agent profile updated successfully!");- setTimeout(() => {- router.push("/agents");- }, 1500);- } catch (err) {- console.error("Error updating agent:", err);- setError(- err.response?.data?.message ||- err.response?.data?.detail ||- "Failed to update agent."- );- toast.error("Failed to save changes");- } finally {- setSaving(false);- }- };-- if (loading) {- return (- <main className="flex-1 flex items-center justify-center">- <div className="flex flex-col items-center gap-2">- <BiLoaderAlt className="w-12 h-12 text-blue-600 animate-spin" />- <p className="text-gray-500 font-medium animate-pulse">Loading Identity Data...</p>- </div>- </main>- );- }-- if (error) {- return (- <main className="flex-1 flex flex-col items-center justify-center h-full gap-4 text-center p-8">- <div className="w-16 h-16 bg-red-100 dark:bg-red-900/30 rounded-full flex items-center justify-center mb-2">- <IoCloseOutline className="w-10 h-10 text-red-500 dark:text-red-400" />- </div>- <h2 className="text-2xl font-bold text-gray-900 dark:text-white">Access Denied</h2>- <p className="text-gray-600 dark:text-secondary-text max-w-md font-medium">- {error}- </p>- <Link- href="/agents"- className="mt-4 px-8 py-3 bg-gray-900 dark:bg-primary text-white font-bold rounded-xl hover:bg-gray-800 dark:hover:bg-primary/90 transition-all shadow-lg active:scale-95"- >- Return to My Agents- </Link>- </main>- );- }-- return (- <div className="flex-1 flex flex-col gap-8 items-center w-full max-w-[95%] sm:max-w-[90%] lg:max-w-[80%] relative">- <div className="flex items-center justify-between pb-2 border-b border-gray-50 dark:border-divider w-full">- <Link- href="/agents"- className="flex items-center gap-2 text-gray-500 hover:text-gray-900 dark:text-secondary-text dark:hover:text-primary-text transition-colors text-sm font-medium"- >- <IoChevronBack className="w-4 h-4" />- Back- </Link>- <div className="flex items-center gap-3">- <Link- href={`${window.location.origin}/agents/${id}`}- className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 rounded-xl text-sm font-bold text-white transition-all active:scale-95 shadow-sm"- >- <IoChatbubblesOutline className="w-4 h-4" />- Chat- </Link>- <button- type="button"- onClick={handleShare}- className="flex items-center gap-2 px-4 py-2 border border-gray-100 dark:border-divider rounded-xl text-sm font-bold text-gray-600 dark:text-primary-text hover:bg-gray-50 dark:hover:bg-secondary-bg transition-all active:scale-95"- >- <IoShareOutline className="w-4 h-4" />- </button>- <button- type="button"- onClick={handleDelete}- disabled={saving}- className="flex items-center gap-2 px-4 py-2 border border-red-50 dark:border-red-900/30 rounded-xl text-sm font-bold text-red-500 hover:bg-red-50 dark:hover:bg-red-900/10 transition-all active:scale-95 disabled:opacity-50"- >- <IoTrashOutline className="w-4 h-4" />- </button>- <Link- href="/docs/agents"- target="_blank"- className="flex items-center gap-2 px-3 py-1.5 bg-gray-50 dark:bg-secondary-bg border border-gray-100 dark:border-divider rounded-lg text-xs font-bold text-blue-600 dark:text-primary hover:bg-blue-50 dark:hover:bg-primary-bg transition-all active:scale-95 shadow-sm"- >- Docs- </Link>- </div>- </div>- <div className="flex flex-col items-center gap-2 w-full">- <form id="edit-agent-form" onSubmit={handleSubmit} className="flex flex-col gap-12 w-full">- <div className="flex flex-col md:flex-row md:items-center gap-8 w-full">- <div className="flex items-center gap-8 w-full">- <div className="relative">- <div- onClick={() => setShowIconSelectionModal(true)}- className="w-28 h-28 rounded-full bg-gray-100 dark:bg-secondary-bg overflow-hidden ring-4 ring-white dark:ring-primary-bg shadow-sm border border-gray-100 dark:border-divider cursor-pointer group transition-all hover:ring-blue-500/30"- >- {formData.icon_url ? (- <img src={formData.icon_url} alt="Profile" className="w-full h-full object-cover transition-transform group-hover:scale-110" />- ) : (- <div className="w-full h-full flex items-center justify-center bg-gray-50 dark:bg-primary-bg transition-colors group-hover:bg-gray-100 dark:group-hover:bg-secondary-bg">- <RiRobot2Fill className="w-12 h-12 text-gray-300 dark:text-divider group-hover:text-blue-500 transition-colors" />- </div>- )}- <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 flex items-center justify-center transition-opacity rounded-full">- <IoPencilOutline className="w-6 h-6 text-white" />- </div>- {uploading && (- <div className="absolute inset-0 bg-white/95 dark:bg-primary-bg/95 flex items-center justify-center rounded-full z-10 backdrop-blur-[1px]">- <div className="relative w-16 h-16">- <svg className="w-full h-full -rotate-90" viewBox="0 0 36 36">- <circle- cx="18"- cy="18"- r="16"- fill="none"- className="stroke-gray-100 dark:stroke-divider"- strokeWidth="3.5"- />- <circle- cx="18"- cy="18"- r="16"- fill="none"- className="stroke-black dark:stroke-primary transition-all duration-500 ease-out"- strokeWidth="3.5"- strokeDasharray="100.53"- strokeDashoffset={100.53 * (1 - uploadProgress / 100)}- strokeLinecap="round"- />- </svg>- <div className="absolute inset-0 flex items-center justify-center">- <span className="text-xs font-bold text-gray-900 dark:text-white">- {uploadProgress}%- </span>- </div>- </div>- </div>- )}- </div>- <input type="file" ref={fileInputRef} onChange={handleFileUpload} className="hidden" accept="image/*" />- </div>- <div className="flex flex-col gap-2 w-full">- <div className="flex items-center gap-2 group/title w-full">- <input- type="text"- name="name"- value={formData.name}- onChange={handleInputChange}- className="text-3xl font-bold text-gray-900 dark:text-white leading-tight tracking-tight truncate bg-transparent border-none p-0 focus:ring-0 w-full"- placeholder="Unnamed Agent"- required- />- <IoPencilOutline className="w-5 h-5 text-gray-300 dark:text-divider opacity-0 group-hover/title:opacity-100 transition-opacity" />- </div>- <div className="flex items-center gap-3 mt-1 mr-auto">- {/* Toggles moved to better location */}- </div>- </div>- </div>- <div className="flex flex-col gap-4">- <button- type="submit"- form="edit-agent-form"- disabled={saving}- className="px-6 py-3 whitespace-nowrap bg-black dark:bg-primary hover:bg-gray-800 dark:hover:bg-primary/90 disabled:opacity-50 text-white font-bold rounded-xl transition-all shadow-lg text-sm active:scale-95"- >- {saving ? "Saving..." : "Save Changes"}- </button>- <div className="flex items-center gap-1.5 p-1 bg-gray-100 dark:bg-secondary-bg rounded-2xl border border-gray-200 dark:border-divider w-fit">- <div- onClick={() => setFormData(prev => ({ ...prev, is_published: !prev.is_published }))}- className={`flex items-center gap-2 px-4 py-2.5 rounded-xl cursor-pointer transition-all duration-300 ${- formData.is_published- ? "bg-white dark:bg-primary-bg shadow-sm text-blue-600 dark:text-primary"- : "text-gray-400 hover:text-gray-600 dark:text-secondary-text dark:hover:text-primary-text"- }`}- >- <div className={`w-2 h-2 rounded-full transition-all duration-500 ${formData.is_published ? "bg-blue-500 shadow-[0_0_8px_rgba(59,130,246,0.5)]" : "bg-gray-300 dark:bg-gray-600"}`} />- <span className="text-xs font-bold tracking-wider">Publish</span>- </div>- </div>- </div>- </div>- <div className="flex flex-col gap-12">- <div className="flex flex-col gap-6">- <div className="flex flex-col gap-2">- <h2 className="text-xl font-bold text-gray-900 dark:text-white">Behavior & Identity</h2>- <p className="text-sm text-gray-500 dark:text-secondary-text font-medium">- Shape how your agent thinks, responds, and describes itself- </p>- </div>- <div className="flex flex-col gap-6">- <div className="flex flex-col gap-2">- <div className="flex items-center justify-between border-l-4 border-black dark:border-primary pl-3 ml-1 mb-1">- <label className="text-base font-bold text-gray-900 dark:text-white">Instructions</label>- <button- type="button"- onClick={handleRealign}- disabled={isRealigning || JSON.stringify(formData.skill_ids.sort()) === JSON.stringify(initialSkills.sort())}- className="flex items-center gap-2 px-3 py-1.5 bg-violet-600 hover:bg-violet-700 disabled:bg-gray-100 disabled:text-gray-400 text-white text-xs font-bold rounded-lg transition-all active:scale-95 shadow-sm"- title={JSON.stringify(formData.skill_ids.sort()) === JSON.stringify(initialSkills.sort()) ? "No changes to skills" : "Sync instructions with current skills"}- >- {isRealigning ? <BiLoaderAlt className="animate-spin" /> : "✨ Realign with Skills"}- </button>- </div>- <div className="relative group">- <textarea- name="system_prompt"- value={formData.system_prompt}- onChange={handleInputChange}- className="w-full bg-white dark:bg-secondary-bg border border-gray-100 dark:border-divider rounded-2xl px-6 py-6 text-gray-800 dark:text-primary-text text-sm focus:ring-4 focus:ring-black/5 dark:focus:ring-primary/5 focus:border-black dark:focus:border-primary transition-all outline-none min-h-[200px] leading-relaxed shadow-sm font-medium"- placeholder="Define how your agent thinks and communicates..."- required- />- <p className="text-xs text-gray-400 dark:text-secondary-text font-medium ml-1">- Define how your agent thinks and communicates. Start with "You are..." and include specific examples.- </p>- </div>- </div>- <div className="flex flex-col gap-2">- <label className="text-base font-bold text-gray-900 dark:text-white border-l-4 border-black dark:border-primary pl-3 ml-1">Description</label>- <textarea- name="description"- value={formData.description}- onChange={handleInputChange}- className="w-full bg-white dark:bg-secondary-bg border border-gray-100 dark:border-divider rounded-2xl px-6 py-4 text-gray-800 dark:text-primary-text text-sm focus:ring-4 focus:ring-black/5 dark:focus:ring-primary/5 focus:border-black dark:focus:border-primary transition-all outline-none min-h-[100px] leading-relaxed shadow-sm font-medium"- placeholder="Add a description that describes your agent to others..."- />- <p className="text-xs text-gray-400 dark:text-secondary-text font-medium ml-1">- This will be visible to users when they discover your agent.- </p>- </div>- </div>- </div>- <div className="flex flex-col gap-6 border-t border-gray-50 dark:border-divider pt-12">- <div className="flex flex-col gap-2">- <h2 className="text-base font-bold text-gray-900 dark:text-white border-l-4 border-black dark:border-primary pl-3 ml-1">Theme & Appearance</h2>- <p className="text-sm text-gray-500 dark:text-secondary-text font-medium ml-1">- Customize how your agent looks in the chat interface- </p>- </div>-- <div className="bg-white dark:bg-secondary-bg shadow-lg rounded-3xl p-8 border border-gray-100 dark:border-divider flex flex-col lg:flex-row gap-8">- {/* Theme Selection */}- <div className="flex-1 flex flex-col gap-4">- <h4 className="text-xs text-gray-400 dark:text-secondary-text font-bold uppercase tracking-wider ml-1">Select Theme</h4>- <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">- {Object.values(themes || {}).map((theme) => (- <button- key={theme.id}- type="button"- onClick={() => setFormData(prev => ({ ...prev, theme: theme.id }))}- className={`group relative flex flex-col items-center gap-2 p-3 rounded-2xl border-2 transition-all ${- formData.theme === theme.id- ? "border-black dark:border-primary bg-gray-50 dark:bg-primary-bg shadow-md scale-[1.02]"- : "border-gray-100 dark:border-divider hover:border-gray-200 dark:hover:border-primary bg-white dark:bg-primary-bg/50"- }`}- >- <div- className="w-full aspect-video rounded-xl shadow-inner border border-black/5 flex items-center justify-center relative overflow-hidden"- style={{ background: theme.colors.background }}- >- <div className="flex flex-col gap-1 w-[60%]">- <div className="h-1.5 w-[80%] rounded-full opacity-40" style={{ background: theme.colors.foreground }}></div>- <div className="h-1.5 w-[50%] rounded-full opacity-40 ml-auto" style={{ background: theme.colors.userBubble }}></div>- </div>- </div>- <span className={`text-xs font-bold transition-colors ${- formData.theme === theme.id ? "text-black dark:text-white" : "text-gray-500 dark:text-secondary-text group-hover:text-gray-700 dark:group-hover:text-primary-text"- }`}>- {theme.name}- </span>- {formData.theme === theme.id && (- <div className="absolute -top-2 -right-2 w-5 h-5 bg-black dark:bg-primary text-white rounded-full flex items-center justify-center shadow-lg">- <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="3" d="M5 13l4 4L19 7" />- </svg>- </div>- )}- </button>- ))}- </div>- </div>- <div className="flex-1 flex flex-col gap-4">- <h4 className="text-xs text-gray-400 dark:text-secondary-text font-bold uppercase tracking-wider ml-1">Chat Preview</h4>- <div- className="w-full h-[300px] rounded-3xl overflow-hidden shadow-2xl border border-gray-100 dark:border-divider relative"- style={{- background: (themes[formData.theme] || themes.cosmic)?.colors.background,- color: (themes[formData.theme] || themes.cosmic)?.colors.foreground- }}- >- <div- className="px-4 py-3 flex items-center gap-2 border-b"- style={{- background: (themes[formData.theme] || themes.cosmic)?.colors.headerBg,- borderColor: (themes[formData.theme] || themes.cosmic)?.colors.border- }}- >- <div className="w-8 h-8 rounded-full bg-gray-400 overflow-hidden">- {formData.icon_url ? (- <img src={formData.icon_url} className="w-full h-full object-cover" />- ) : (- <RiRobot2Fill className="w-full h-full p-1.5 text-white/50" />- )}- </div>- <div className="flex flex-col">- <span className="text-xs font-bold truncate">{formData.name || "Agent Name"}</span>- <span className="text-[10px] opacity-60">Online</span>- </div>- </div>- <div className="p-4 flex flex-col gap-4 h-[180px] overflow-y-auto">- <div className="flex flex-col items-end gap-1 max-w-[85%] ml-auto">- <div- className="px-3 py-2 rounded-2xl text-xs font-medium shadow-sm"- style={{- background: (themes[formData.theme] || themes.cosmic)?.colors.userBubble,- color: (themes[formData.theme] || themes.cosmic)?.colors.userText- }}- >- Hi! How can you help me today?- </div>- </div>- <div className="flex flex-col items-start gap-1 max-w-[85%]">- <div- className="px-3 py-2 rounded-2xl text-xs font-medium border shadow-sm"- style={{- background: (themes[formData.theme] || themes.cosmic)?.colors.agentBubble,- color: (themes[formData.theme] || themes.cosmic)?.colors.agentText,- borderColor: (themes[formData.theme] || themes.cosmic)?.colors.border- }}- >- I can help you with tasks, answer questions, and much more using {formData.skill_ids.length} configured skills!- </div>- </div>- </div>- <div className="absolute bottom-0 w-full p-4">- <div- className="h-10 rounded-xl flex items-center px-4 gap-2 border shadow-inner"- style={{- background: (themes[formData.theme] || themes.cosmic)?.colors.inputBg,- borderColor: (themes[formData.theme] || themes.cosmic)?.colors.border- }}- >- <span className="text-xs opacity-30 flex-1">Type a message...</span>- <div- className="w-6 h-6 rounded-lg flex items-center justify-center"- style={{ background: (themes[formData.theme] || themes.cosmic)?.colors.accent }}- >- <div className="w-1.5 h-1.5 rounded-full" style={{ background: (themes[formData.theme] || themes.cosmic)?.colors.accentText }}></div>- </div>- </div>- </div>- </div>- </div>- </div>- <p className="text-xs text-gray-400 dark:text-secondary-text font-medium ml-1">- This theme will be automatically applied to the chat interface for all users.- </p>- </div>-- <div className="flex flex-col gap-6 border-t border-gray-50 dark:border-divider pt-12">- <h2 className="text-base font-bold text-gray-900 dark:text-white border-l-4 border-black dark:border-primary pl-3 ml-1">Capabilities</h2>- <div className="bg-white dark:bg-secondary-bg shadow-lg rounded-3xl p-8 border border-gray-100 dark:border-divider flex flex-col gap-4">- <div className="relative">- <input- type="text"- placeholder="Type to search and add skills (e.g. image generation, web search)..."- value={searchTerm}- onChange={(e) => setSearchTerm(e.target.value)}- className="w-full bg-white dark:bg-primary-bg border border-gray-100 dark:border-divider rounded-xl px-5 py-3.5 text-sm dark:text-white focus:ring-4 focus:ring-black/5 dark:focus:ring-primary/5 focus:border-black dark:focus:border-primary transition-all outline-none shadow-sm"- />- </div>- <div className="flex flex-col gap-4">- <h4 className="text-xs text-gray-400 dark:text-secondary-text ml-1">- Active Agent Skills ({formData.skill_ids.length})- </h4>- <div className="grid grid-cols-1 md:grid-cols-2 gap-3">- {formData.skill_ids.length > 0 ? (- formData.skill_ids.map((id) => {- const skill = availableSkills.find(s => s.id === id);- if (!skill) return null;- return (- <button- key={skill.id}- type="button"- onClick={() => handleSkillToggle(skill.id)}- className="relative p-4 flex items-center justify-between rounded-2xl bg-white dark:bg-primary-bg border border-gray-100 dark:border-divider shadow-sm transition-all hover:border-black dark:hover:border-primary group"- >- <div className="flex flex-col text-left">- <span title={skill.name} className="text-base font-bold text-gray-900 dark:text-white line-clamp-1">- {skill.name}- </span>- <span title={skill.description} className="text-xs text-gray-400 dark:text-secondary-text line-clamp-2">- {skill.description}- </span>- </div>- <FaRegTrashCan size={18} className="absolute right-4 opacity-0 group-hover:opacity-100 transition-all duration-300 ease-in-out bg-white dark:bg-primary-bg text-red-500" />- </button>- );- })- ) : (- <div className="col-span-full p-12 rounded-2xl border border-dashed border-gray-200 dark:border-divider text-center bg-white/50 dark:bg-primary-bg/50">- <p className="text-sm text-gray-400 dark:text-secondary-text">No skills configured yet</p>- </div>- )}- </div>- <div className="border-t border-gray-200/50 dark:border-divider pt-4">- <h4 className="text-xs text-gray-400 dark:text-secondary-text ml-1 mb-2">- Available in Registry- </h4>- <div className="grid grid-cols-1 md:grid-cols-2 gap-3 max-h-[400px] overflow-y-auto pr-2 custom-scrollbar">- {availableSkills- .filter(skill =>- !formData.skill_ids.includes(skill.id) &&- (skill.name.toLowerCase().includes(searchTerm.toLowerCase()) ||- skill.id.toLowerCase().includes(searchTerm.toLowerCase()))- )- .map((skill) => (- <button- key={skill.id}- type="button"- onClick={() => {- handleSkillToggle(skill.id);- setSearchTerm("");- }}- className="p-4 flex items-center justify-between rounded-2xl border border-gray-100 dark:border-divider bg-white dark:bg-primary-bg hover:border-black dark:hover:border-primary transition-all shadow-sm hover:shadow-md group"- >- <div className="flex flex-col text-left">- <span title={skill.name} className="text-base font-bold text-gray-900 dark:text-white line-clamp-1">- {skill.name}- </span>- <span title={skill.description} className="text-xs text-gray-400 dark:text-secondary-text line-clamp-2">- {skill.description}- </span>- </div>- <span className="text-lg text-white bg-black dark:bg-primary rounded-full p-0.5 w-5 h-5 flex items-center justify-center flex-shrink-0">+</span>- </button>- ))- }- </div>- </div>- </div>- </div>- <p className="text-xs text-gray-400 dark:text-secondary-text font-medium ml-1">- Manage tools and skills your agent can use to perform tasks- </p>- </div>- </div>- {error && (- <div className="p-4 bg-red-50 dark:bg-red-900/10 border border-red-100 dark:border-red-900/30 rounded-xl text-red-600 dark:text-red-400 text-sm flex items-center gap-3 animate-shake">- <svg className="w-5 h-5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />- </svg>- <span className="font-medium">{error}</span>- </div>- )}- </form>- </div>- {showRealignModal && (- <div className="fixed inset-0 bg-black/60 backdrop-blur-sm z-[100] flex items-center justify-center p-4 animate-in fade-in duration-200">- <div className="bg-white dark:bg-secondary-bg rounded-3xl w-full max-w-4xl max-h-[90vh] overflow-hidden shadow-2xl flex flex-col animate-in zoom-in-95 duration-200">- <div className="px-8 py-6 border-b border-gray-100 dark:border-divider flex items-center justify-between bg-violet-50/50 dark:bg-violet-900/10">- <div className="flex items-center gap-3">- <div className="w-10 h-10 rounded-xl bg-violet-600 flex items-center justify-center text-white shadow-lg shadow-violet-200 dark:shadow-none">- <RiRobot2Fill className="w-6 h-6" />- </div>- <div>- <h3 className="text-xl font-bold text-gray-900 dark:text-white">Review Brain Realignment</h3>- <p className="text-xs text-gray-500 dark:text-secondary-text font-medium">The AI has refactored your instructions to match your new skills.</p>- </div>- </div>- <button- onClick={() => setShowRealignModal(false)}- className="p-2 hover:bg-white dark:hover:bg-primary-bg rounded-full transition-colors text-gray-400 dark:text-secondary-text hover:text-gray-900 dark:hover:text-white"- >- <MdClose className="w-6 h-6" />- </button>- </div>-- <div className="flex-1 overflow-y-auto p-8 flex flex-col md:flex-row gap-6 custom-scrollbar">- <div className="flex-1 flex flex-col gap-3">- <label className="text-xs font-bold text-gray-400 dark:text-secondary-text uppercase tracking-wider ml-1">Current Instructions</label>- <div className="flex-1 p-5 bg-gray-50 dark:bg-primary-bg border border-gray-100 dark:border-divider rounded-2xl text-sm text-gray-600 dark:text-secondary-text font-medium whitespace-pre-wrap overflow-y-auto max-h-[400px]">- {formData.system_prompt}- </div>- </div>- <div className="hidden md:flex items-center justify-center text-violet-300 dark:text-violet-500">- <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 5l7 7-7 7M5 5l7 7-7 7" />- </svg>- </div>- <div className="flex-1 flex flex-col gap-3">- <label className="text-xs font-bold text-violet-600 dark:text-violet-400 uppercase tracking-wider ml-1">Proposed Instructions</label>- <textarea- value={realignedPrompt}- onChange={(e) => setRealignedPrompt(e.target.value)}- className="flex-1 p-5 bg-violet-50/30 dark:bg-violet-900/10 border-2 border-violet-100 dark:border-violet-800/50 rounded-2xl text-sm text-gray-800 dark:text-primary-text font-medium leading-relaxed focus:ring-4 focus:ring-violet-500/10 focus:border-violet-500 outline-none transition-all resize-none min-h-[400px]"- />- </div>- </div>-- <div className="px-8 py-6 bg-gray-50 dark:bg-primary-bg border-t border-gray-100 dark:border-divider flex items-center justify-end gap-3">- <button- onClick={() => setShowRealignModal(false)}- className="px-6 py-2.5 text-sm font-bold text-gray-600 dark:text-secondary-text hover:text-gray-900 dark:hover:text-white transition-colors"- >- Discard Changes- </button>- <button- onClick={applyRealignedPrompt}- className="px-8 py-2.5 bg-violet-600 hover:bg-violet-700 text-white text-sm font-bold rounded-xl transition-all shadow-lg shadow-violet-200 dark:shadow-none active:scale-95"- >- Accept & Apply- </button>- </div>- </div>- </div>- )}- {showIconPromptModal && (- <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm animate-in fade-in duration-200">- <div className="bg-white dark:bg-secondary-bg w-full max-w-lg rounded-3xl shadow-2xl border border-gray-100 dark:border-divider overflow-hidden transform animate-in zoom-in-95 duration-200">- <div className="p-6 border-b border-gray-100 dark:border-divider flex items-center justify-between bg-gray-50/50 dark:bg-primary-bg/50">- <h3 className="text-xl font-bold dark:text-white flex items-center gap-2">- <span className="text-2xl">✨</span> Customize AI Icon Prompt- </h3>- <button- onClick={() => setShowIconPromptModal(false)}- className="p-2 hover:bg-white dark:hover:bg-secondary-bg rounded-full transition-colors text-gray-400 hover:text-gray-600 dark:hover:text-primary-text"- >- <IoCloseOutline className="w-6 h-6" />- </button>- </div>-- <div className="p-8">- <p className="text-sm text-gray-500 dark:text-secondary-text mb-6">- Tell the AI what kind of icon you want. You can describe style, colors, and specific elements.- </p>-- <div className="space-y-4">- <textarea- value={iconPrompt}- onChange={(e) => setIconPrompt(e.target.value)}- placeholder="Describe your agent's icon..."- className="w-full h-40 p-5 bg-gray-50 dark:bg-primary-bg border border-gray-200 dark:border-divider rounded-2xl text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all resize-none dark:text-white placeholder:text-gray-400"- />-- <div className="flex gap-3 pt-4">- <button- onClick={() => setShowIconPromptModal(false)}- className="flex-1 px-6 py-4 border border-gray-200 dark:border-divider rounded-2xl text-sm font-bold text-gray-600 dark:text-primary-text hover:bg-gray-50 dark:hover:bg-primary-bg transition-all active:scale-[0.98]"- >- Cancel- </button>- <button- onClick={() => handleGenerateIcon(iconPrompt)}- disabled={generatingIcon || !iconPrompt.trim()}- className="flex-[2] px-6 py-4 bg-blue-600 hover:bg-blue-700 disabled:opacity-50 text-white font-bold rounded-2xl transition-all shadow-lg shadow-blue-500/20 active:scale-[0.98] flex items-center justify-center gap-2"- >- {generatingIcon ? (- <>- <BiLoaderAlt className="w-5 h-5 animate-spin" />- Generating...- </>- ) : (- <>- <span className="text-lg">✨</span>- Generate Icon- </>- )}- </button>- </div>- </div>- </div>- </div>- </div>- )}- {showIconSelectionModal && (- <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm animate-in fade-in duration-200">- <div className="bg-white dark:bg-secondary-bg w-full max-w-md rounded-[2.5rem] shadow-2xl border border-gray-100 dark:border-divider overflow-hidden transform animate-in zoom-in-95 duration-200">- <div className="p-8 border-b border-gray-50 dark:border-divider flex items-center justify-between">- <div>- <h3 className="text-2xl font-black dark:text-white leading-tight">Profile Icon</h3>- <p className="text-sm text-gray-500 dark:text-secondary-text mt-1 font-medium">Choose how to update your agent's look</p>- </div>- <button- onClick={() => setShowIconSelectionModal(false)}- className="w-10 h-10 flex items-center justify-center bg-gray-50 dark:bg-primary-bg rounded-full text-gray-400 hover:text-black dark:hover:text-white transition-colors"- >- <IoCloseOutline className="w-6 h-6" />- </button>- </div>-- <div className="p-8 grid grid-cols-1 gap-4">- <button- onClick={() => {- setShowIconSelectionModal(false);- fileInputRef.current?.click();- }}- className="group flex flex-col items-center gap-4 p-8 bg-gray-50 dark:bg-primary-bg rounded-[2rem] border border-gray-100 dark:border-divider hover:border-blue-500/50 hover:bg-white dark:hover:bg-secondary-bg transition-all duration-300 hover:shadow-xl hover:shadow-blue-500/5 active:scale-[0.98]"- >- <div className="w-16 h-16 rounded-2xl bg-white dark:bg-secondary-bg shadow-sm flex items-center justify-center text-gray-400 group-hover:text-blue-500 transition-colors duration-300">- <IoImageOutline className="w-8 h-8" />- </div>- <div className="text-center">- <h4 className="font-bold text-gray-900 dark:text-white text-lg">Upload Photo</h4>- <p className="text-sm text-gray-500 dark:text-secondary-text mt-1">Pick a file from your device</p>- </div>- </button>-- <button- onClick={() => {- setShowIconSelectionModal(false);- setIconPrompt(`A professional, clean profile icon for an AI agent named "${formData.name}". Description: ${formData.description || "An AI assistant"}. Minimalist, high-quality, circular composition.`);- setShowIconPromptModal(true);- }}- className="group flex flex-col items-center gap-4 p-8 bg-blue-50/30 dark:bg-blue-500/5 rounded-[2rem] border border-blue-100/50 dark:border-blue-500/20 hover:border-blue-500 hover:bg-white dark:hover:bg-secondary-bg transition-all duration-300 hover:shadow-xl hover:shadow-blue-500/10 active:scale-[0.98]"- >- <div className="w-16 h-16 rounded-2xl bg-blue-600 shadow-lg shadow-blue-500/30 flex items-center justify-center text-white transform transition-transform duration-500 group-hover:rotate-12 group-hover:scale-110">- <IoSparklesOutline className="w-8 h-8" />- </div>- <div className="text-center">- <h4 className="font-bold text-blue-600 dark:text-primary text-lg">Generate with AI</h4>- <p className="text-sm text-blue-500/70 dark:text-primary/70 mt-1">Create unique icon from prompt</p>- </div>- </button>- </div>- </div>- </div>- )}- </div>- );-}--export default EditAgentdiff --git a/packages/agents/src/components/ProfileAgent.jsx b/packages/agents/src/components/ProfileAgent.jsxdeleted file mode 100644index fa0e253..0000000--- a/packages/agents/src/components/ProfileAgent.jsx+++ /dev/null@@ -1,345 +0,0 @@-"use client";--import React, { useState, useEffect, useCallback } from "react";-import Image from "next/image";-import Link from "next/link";-import axios from "axios";-import { RiRobot2Fill } from "react-icons/ri";-import { BiLoaderAlt } from "react-icons/bi";-import {- IoChatbubbleEllipsesSharp,- IoShareOutline,- IoHeartOutline,- IoHeart,-} from "react-icons/io5";-import { FiClock, FiZap } from "react-icons/fi";-import { MdOutlineVerified } from "react-icons/md";-import { HiPlus } from "react-icons/hi2";-import { useParams } from "next/navigation";--const BASE_URL = "/api/agents";--function timeAgo(dateStr) {- if (!dateStr) return "";- const utcStr =- dateStr.endsWith("Z") || dateStr.includes("+") ? dateStr : dateStr + "Z";- const now = new Date();- const d = new Date(utcStr);- const diff = Math.floor((now - d) / 1000);- if (diff < 60) return "just now";- if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;- if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;- if (diff < 604800) return `${Math.floor(diff / 86400)}d ago`;- const months = Math.floor(diff / 2592000);- if (months < 12) return `${months} mo. ago`;- return `${Math.floor(months / 12)} yr. ago`;-}--function formatCount(n) {- if (!n && n !== 0) return "–";- if (n >= 1000000) return (n / 1000000).toFixed(1) + "M";- if (n >= 1000) return (n / 1000).toFixed(1) + "K";- return n.toLocaleString();-}--/**- * ProfileAgent — Agent profile content component.- * Supports light (muapiapp default) and dark (vadoo / dark-mode) themes via- * Tailwind's `dark:` prefix + CSS variables set by the host app.- *- * Props:- * useUser {function} — hook to get the current logged-in user- * usedIn {string} — "muapiapp" | "vadoo"- */-export default function ProfileAgent({ useUser, usedIn = "muapiapp" }) {- const { agent_id } = useParams();-- const [profile, setProfile] = useState(null);- const [loading, setLoading] = useState(true);- const [error, setError] = useState(null);- const [liked, setLiked] = useState(false);- const [copied, setCopied] = useState(false);-- const fetchProfile = useCallback(async () => {- try {- setLoading(true);- const res = await axios.get(`${BASE_URL}/${agent_id}/profile`);- setProfile(res.data);- if (res.data?.agent) {- setLiked(res.data.agent.has_liked || false);- }- setError(null);- } catch (err) {- setError(- err.response?.data?.detail || err.message || "Failed to load agent profile"- );- } finally {- setLoading(false);- }- }, [agent_id]);-- useEffect(() => {- if (agent_id) fetchProfile();- }, [agent_id, fetchProfile]);-- const handleShare = () => {- const url = window.location.href;- navigator.clipboard.writeText(url).then(() => {- setCopied(true);- setTimeout(() => setCopied(false), 2000);- });- };-- const handleLike = async () => {- const newLiked = !liked;- setLiked(newLiked);- try {- const res = await axios.post(`/api/agents/by-slug/${agent.agent_id || agent.id}/like?is_like=${newLiked}`);-- // Update the local state properly to trigger re-render- if (profile) {- setProfile({- ...profile,- agent: {- ...profile.agent,- like_count: res.data.like_count,- has_liked: res.data.has_liked- }- });- // Also ensure the 'liked' state is in sync with the real source of truth- setLiked(res.data.has_liked);- }- } catch (err) {- console.error("Failed to sync like:", err);- // Rollback on error- setLiked(!newLiked);- }- };-- if (loading) {- return (- <div className="flex flex-col items-center justify-center py-32 gap-3 w-full">- <BiLoaderAlt className="w-8 h-8 text-gray-400 dark:text-secondary-text animate-spin" />- <p className="text-gray-400 dark:text-secondary-text text-sm">Loading agent profile...</p>- </div>- );- }-- if (error || !profile) {- return (- <div className="flex flex-col items-center justify-center py-32 gap-2 w-full">- <RiRobot2Fill className="w-12 h-12 text-gray-300 dark:text-secondary-text mx-auto" />- <p className="text-gray-800 dark:text-primary-text font-bold">Agent not found</p>- <p className="text-gray-500 dark:text-secondary-text text-sm">{error}</p>- </div>- );- }-- const { agent, total_messages, total_chats, recent_chats } = profile;-- const chatUrl = agent.agent_id- ? `/agents/${agent.agent_id}`- : `/agents/${agent.id}`;-- return (- <div className="w-full max-w-5xl mx-auto px-4 sm:px-6 pb-16">- <div className="border-b border-gray-200 dark:border-divider py-6">- <div className="flex flex-col md:flex-row md:items-start gap-5">- <div className="flex items-center gap-5">- <div className="relative w-16 h-16 rounded-full overflow-hidden bg-gray-100 dark:bg-secondary-bg border-2 border-gray-200 dark:border-divider shrink-0">- {agent.icon_url ? (- <Image src={agent.icon_url} alt={agent.name} fill className="object-cover" />- ) : (- <div className="w-full h-full flex items-center justify-center">- <RiRobot2Fill className="w-8 h-8 text-gray-400 dark:text-secondary-text" />- </div>- )}- </div>- <div className="flex-1 min-w-0">- <div className="flex items-center gap-2 flex-wrap">- <h1 className="text-2xl font-bold text-black dark:text-white">- {agent.name}- </h1>- {agent.is_published && (- <span className="flex items-center gap-1 text-xs font-bold px-2 py-0.5 rounded-full bg-blue-50 dark:bg-white/10 text-blue-600 dark:text-gray-300 border border-blue-100 dark:border-white/10">- <MdOutlineVerified className="w-3 h-3" /> Public- </span>- )}- </div>- {agent.description && (- <p className="text-gray-500 dark:text-secondary-text text-sm mt-1 leading-relaxed max-w-xl">- {agent.description}- </p>- )}- { (agent.owner_username || agent.owner_email) && (- <p className="text-xs text-gray-400 dark:text-secondary-text mt-1.5">- by{" "}- <span className="text-gray-600 dark:text-gray-300 font-medium">- {agent.owner_username || agent.owner_email.split("@")[0]}- </span>- </p>- )}- </div>- </div>- <div className="flex items-center gap-2 shrink-0">- <button- type="button"- onClick={handleLike}- className="flex items-center gap-2 px-3 py-2 rounded-lg bg-gray-100 dark:bg-secondary-bg hover:bg-gray-200 dark:hover:bg-white/10 border border-gray-200 dark:border-divider text-sm transition-all"- >- {liked ? (- <IoHeart className="w-4 h-4 text-red-500" />- ) : (- <IoHeartOutline className="w-4 h-4 text-gray-500 dark:text-secondary-text" />- )}- <span className="font-medium text-gray-700 dark:text-gray-300">- {agent.like_count || 0}- </span>- </button>- <button- onClick={handleShare}- title={copied ? "Copied!" : "Share link"}- className="flex items-center gap-1.5 px-3 py-2 rounded-lg bg-gray-100 dark:bg-secondary-bg hover:bg-gray-200 dark:hover:bg-white/10 border border-gray-200 dark:border-divider text-sm transition-all"- >- <IoShareOutline className="w-4 h-4 text-gray-500 dark:text-secondary-text" />- {copied && <span className="text-xs text-green-500 dark:text-green-400">Copied!</span>}- </button>- <Link- href={chatUrl}- className="flex items-center gap-2 px-4 py-2 bg-violet-600 hover:bg-violet-500 text-white text-sm font-bold rounded-lg transition-all shadow-sm"- >- <IoChatbubbleEllipsesSharp className="w-4 h-4" />- Chat- </Link>- </div>- </div>- </div>- <div className="grid grid-cols-1 lg:grid-cols-[1fr_280px] gap-8 mt-8">- <div className="space-y-8">- {agent.skills && agent.skills.length > 0 && (- <section>- <p className="text-[11px] font-bold text-gray-400 dark:text-secondary-text uppercase tracking-widest mb-3">- Workflows- </p>- <div className="flex flex-wrap gap-2">- {agent.skills.map((skill) => (- <span- key={skill.id}- className="flex items-center gap-1.5 px-3 py-1.5 bg-gray-100 dark:bg-secondary-bg border border-gray-200 dark:border-divider rounded-lg text-xs text-gray-600 dark:text-gray-300 font-medium hover:bg-gray-200 dark:hover:bg-white/10 transition-colors"- >- <FiZap className="w-3 h-3 text-violet-500 dark:text-violet-400" />- {skill.name}- </span>- ))}- </div>- </section>- )}- {agent.description && (- <section>- <p className="text-[11px] font-bold text-gray-400 dark:text-secondary-text uppercase tracking-widest mb-3">- About {agent.name}- </p>- <p className="text-gray-700 dark:text-gray-300 text-sm leading-relaxed">- {agent.description}- </p>- </section>- )}- {agent.welcome_message && (- <section className="bg-gray-50 dark:bg-secondary-bg border border-gray-200 dark:border-divider rounded-xl p-4">- <p className="text-[11px] font-bold text-gray-400 dark:text-secondary-text uppercase tracking-widest mb-2">- Greeting- </p>- <p className="text-gray-600 dark:text-gray-300 text-sm italic leading-relaxed">- "{agent.welcome_message}"- </p>- </section>- )}- <section>- <p className="text-[11px] font-bold text-gray-400 dark:text-secondary-text uppercase tracking-widest mb-3">- Details- </p>- <div className="space-y-2.5">- <DetailRow label="Messages" value={formatCount(total_messages)} />- <DetailRow label="Chats" value={formatCount(total_chats)} />- <DetailRow label="Created" value={timeAgo(agent.created_at)} />- {agent.skills && agent.skills.length > 0 && (- <DetailRow label="Skills" value={agent.skills.length.toString()} />- )}- </div>- </section>- </div>- <div className="space-y-4">- {recent_chats && recent_chats.length > 0 && (- <div className="bg-gray-50 dark:bg-secondary-bg border border-gray-200 dark:border-divider rounded-2xl p-4">- <div className="flex items-center gap-2 mb-4">- <FiClock className="w-3.5 h-3.5 text-gray-400 dark:text-secondary-text" />- <p className="text-[11px] font-bold text-gray-400 dark:text-secondary-text uppercase tracking-widest">- Recent chats with this agent- </p>- </div>- <div className="space-y-1">- {recent_chats.map((chat) => (- <Link- key={chat.id}- href={- chat.agent_slug- ? `/agents/${chat.agent_slug}/${chat.id}`- : `/agents/${chat.agent_id}/${chat.id}`- }- className="flex items-center gap-3 p-2.5 rounded-xl hover:bg-gray-100 dark:hover:bg-white/5 transition-colors group"- >- <div className="w-8 h-8 rounded-lg bg-gray-200 dark:bg-gray-700 flex items-center justify-center shrink-0">- <IoChatbubbleEllipsesSharp className="w-4 h-4 text-gray-500 dark:text-gray-400 group-hover:text-gray-800 dark:group-hover:text-white transition-colors" />- </div>- <div className="flex-1 min-w-0">- <p className="text-sm font-medium text-gray-800 dark:text-gray-200 truncate group-hover:text-black dark:group-hover:text-white transition-colors">- {chat.title || "New Chat"}- </p>- <p className="text-[11px] text-gray-400 dark:text-secondary-text">- {chat.message_count} msg{chat.message_count !== 1 ? "s" : ""} · {timeAgo(chat.updated_at)}- </p>- </div>- </Link>- ))}- </div>- <Link- href={chatUrl}- className="mt-3 flex items-center justify-center gap-2 w-full py-2.5 rounded-xl bg-gray-100 dark:bg-white/5 hover:bg-gray-200 dark:hover:bg-white/10 border border-gray-200 dark:border-divider text-sm text-gray-600 dark:text-gray-300 hover:text-black dark:hover:text-white transition-all font-medium"- >- <HiPlus className="w-4 h-4" />- New chat- </Link>- </div>- )}- {agent.initial_suggestions && agent.initial_suggestions.length > 0 && (- <div className="bg-gray-50 dark:bg-secondary-bg border border-gray-200 dark:border-divider rounded-2xl p-4">- <p className="text-[11px] font-bold text-gray-400 dark:text-secondary-text uppercase tracking-widest mb-3">- Try asking- </p>- <div className="space-y-2">- {agent.initial_suggestions.slice(0, 4).map((s, i) => (- <Link- key={i}- href={`${chatUrl}?prompt=${encodeURIComponent(s.prompt || s.label || "")}`}- className="block text-sm text-gray-600 dark:text-gray-300 hover:text-black dark:hover:text-white bg-white dark:bg-white/5 hover:bg-gray-100 dark:hover:bg-white/10 border border-gray-200 dark:border-divider rounded-xl px-3 py-2 transition-all truncate"- >- {s.label || s.prompt}- </Link>- ))}- </div>- </div>- )}- </div>- </div>- </div>- );-}--function DetailRow({ label, value }) {- return (- <div className="flex items-center gap-4">- <span className="text-sm text-gray-400 dark:text-secondary-text w-24 shrink-0">{label}</span>- <span className="text-sm text-gray-800 dark:text-primary-text font-medium">{value}</span>- </div>- );-}diff --git a/packages/agents/src/components/themes.jsx b/packages/agents/src/components/themes.jsxdeleted file mode 100644index e9ee74d..0000000--- a/packages/agents/src/components/themes.jsx+++ /dev/null@@ -1,263 +0,0 @@--export const themes = {- cosmic: {- id: 'cosmic',- name: 'Cosmic',- colors: {- background: 'radial-gradient(circle at 50% -20%, #1e293b 0%, #0b0f1a 80%)',- foreground: '#ffffff',- muted: '#94a3b8',- border: 'rgba(255, 255, 255, 0.1)',- componentBg: 'rgba(255, 255, 255, 0.05)',- componentHover: 'rgba(255, 255, 255, 0.1)',- headerBg: 'rgba(19, 24, 38, 0.8)',- userBubble: 'linear-gradient(135deg, #2563eb 0%, #4338ca 100%)',- userText: '#ffffff',- agentBubble: 'rgba(30, 41, 59, 0.6)',- agentText: '#cbd5e1',- inputBg: 'rgba(30, 41, 59, 0.5)',- accent: '#3b82f6',- accentText: '#ffffff',- }- },- midnight: {- id: 'midnight',- name: 'Midnight',- colors: {- background: '#000000',- foreground: '#ededed',- muted: '#737373',- border: '#262626',- componentBg: '#171717',- componentHover: '#262626',- headerBg: 'rgba(0, 0, 0, 0.8)',- userBubble: '#262626',- userText: '#ffffff',- agentBubble: '#0a0a0a',- agentText: '#d4d4d4',- inputBg: '#0a0a0a',- accent: '#ffffff',- accentText: '#000000',- }- },- light: {- id: 'light',- name: 'Clean Light',- colors: {- background: 'linear-gradient(to bottom, #f8fafc, #ffffff)',- foreground: '#1e293b',- muted: '#64748b',- border: '#e2e8f0',- componentBg: '#f1f5f9',- componentHover: '#e2e8f0',- headerBg: 'rgba(255, 255, 255, 0.8)',- userBubble: '#1e293b',- userText: '#ffffff',- agentBubble: '#ffffff',- agentText: '#334155',- inputBg: '#ffffff',- accent: '#475569',- accentText: '#ffffff',- }- },- cyberpunk: {- id: 'cyberpunk',- name: 'Cyberpunk',- colors: {- background: 'linear-gradient(45deg, #050505 0%, #12031c 100%)',- foreground: '#00ff41',- muted: '#d300c5',- border: '#00ff41',- componentBg: 'rgba(255, 0, 187, 0.1)',- componentHover: 'rgba(0, 255, 65, 0.1)',- headerBg: 'rgba(5, 5, 5, 0.9)',- userBubble: 'linear-gradient(90deg, #ff00ea, #5500ff)',- userText: '#ffffff',- agentBubble: '#000000',- agentText: '#00ff41',- inputBg: '#050505',- accent: '#d300c5',- accentText: '#ffffff',- }- },- glossy: {- id: 'glossy',- name: 'Glossy',- colors: {- background: 'linear-gradient(120deg, #e0c3fc 0%, #8ec5fc 100%)',- foreground: '#2d3748',- muted: '#64748b',- border: 'rgba(255, 255, 255, 0.4)',- componentBg: 'rgba(255, 255, 255, 0.3)',- componentHover: 'rgba(255, 255, 255, 0.5)',- headerBg: 'rgba(255, 255, 255, 0.2)',- userBubble: 'rgba(255, 255, 255, 0.8)',- userText: '#2d3748',- agentBubble: 'rgba(255, 255, 255, 0.4)',- agentText: '#2d3748',- inputBg: 'rgba(255, 255, 255, 0.5)',- accent: '#63b3ed',- accentText: '#ffffff',- }- },- ocean: {- id: 'ocean',- name: 'Ocean Depth',- colors: {- background: 'linear-gradient(to bottom, #0f172a, #082f49)',- foreground: '#e0f2fe',- muted: '#7dd3fc',- border: '#0c4a6e',- componentBg: '#0c4a6e',- componentHover: '#075985',- headerBg: 'rgba(12, 74, 110, 0.8)',- userBubble: '#0ea5e9',- userText: '#ffffff',- agentBubble: '#164e63',- agentText: '#e0f2fe',- inputBg: '#082f49',- accent: '#38bdf8',- accentText: '#082f49',- }- },- forest: {- id: 'forest',- name: 'Dark Forest',- colors: {- background: '#052e16',- foreground: '#dcfce7',- muted: '#86efac',- border: '#14532d',- componentBg: '#14532d',- componentHover: '#166534',- headerBg: 'rgba(5, 46, 22, 0.9)',- userBubble: '#22c55e',- userText: '#064e3b',- agentBubble: '#064e3b',- agentText: '#dcfce7',- inputBg: '#064e3b',- accent: '#4ade80',- accentText: '#064e3b',- }- },- sunset: {- id: 'sunset',- name: 'Sunset',- colors: {- background: 'linear-gradient(to top right, #4a1d1d, #7c2d12)',- foreground: '#ffedd5',- muted: '#fdba74',- border: '#9a3412',- componentBg: '#7c2d12',- componentHover: '#9a3412',- headerBg: 'rgba(124, 45, 18, 0.8)',- userBubble: 'linear-gradient(90deg, #f97316, #ea580c)',- userText: '#ffffff',- agentBubble: '#431407',- agentText: '#ffedd5',- inputBg: '#431407',- accent: '#fb923c',- accentText: '#431407',- }- },- dracula: {- id: 'dracula',- name: 'Vampire',- colors: {- background: '#282a36',- foreground: '#f8f8f2',- muted: '#6272a4',- border: '#44475a',- componentBg: '#44475a',- componentHover: '#6272a4',- headerBg: '#282a36',- userBubble: '#ff79c6',- userText: '#282a36',- agentBubble: '#44475a',- agentText: '#f8f8f2',- inputBg: '#44475a',- accent: '#bd93f9',- accentText: '#282a36',- }- },- coffee: {- id: 'coffee',- name: 'Coffee Shop',- colors: {- background: '#2e2622',- foreground: '#d6ccc2',- muted: '#b0a695',- border: '#4a3b32',- componentBg: '#3d322b',- componentHover: '#4a3b32',- headerBg: 'rgba(46, 38, 34, 0.9)',- userBubble: '#c3a185',- userText: '#2e2622',- agentBubble: '#1f1a17',- agentText: '#d6ccc2',- inputBg: '#1f1a17',- accent: '#d4a373',- accentText: '#2e2622',- }- },- terminal: {- id: 'terminal',- name: 'Hacker Terminal',- colors: {- background: '#0d1117',- foreground: '#00ff00',- muted: '#2ea043', // Lighter green for better visibility- border: '#30363d', // Subtle border- componentBg: '#161b22',- componentHover: '#21262d',- headerBg: '#0d1117',- userBubble: '#238636', // GitHub-like green button- userText: '#ffffff',- agentBubble: '#161b22',- agentText: '#00ff00',- inputBg: '#0d1117',- accent: '#2f81f7', // Blue accent for variety or keep green #2ea043- accentText: '#ffffff',- }- },- royal: {- id: 'royal',- name: 'Royal',- colors: {- background: '#1a0b2e',- foreground: '#e9d5ff',- muted: '#a855f7',- border: '#4c1d95',- componentBg: '#2e1065',- componentHover: '#4c1d95',- headerBg: 'rgba(26, 11, 46, 0.9)',- userBubble: 'linear-gradient(to right, #7e22ce, #6b21a8)',- userText: '#ffffff',- agentBubble: '#3b0764',- agentText: '#e9d5ff',- inputBg: '#3b0764',- accent: '#d8b4fe',- accentText: '#3b0764',- }- },- custom: {- id: 'custom',- name: 'Custom Theme',- colors: {- background: '#ffffff',- foreground: '#1e293b',- muted: '#64748b',- border: '#e2e8f0',- componentBg: '#f1f5f9',- componentHover: '#e2e8f0',- headerBg: 'rgba(255, 255, 255, 0.8)',- userBubble: '#1e293b',- userText: '#ffffff',- agentBubble: '#ffffff',- agentText: '#334155',- inputBg: '#ffffff',- accent: '#475569',- accentText: '#ffffff',- }- }-};diff --git a/packages/agents/src/index.js b/packages/agents/src/index.jsdeleted file mode 100644index b23ea93..0000000--- a/packages/agents/src/index.js+++ /dev/null@@ -1,8 +0,0 @@-export { default as AiAgent } from "./AiAgent";-export { getAgentDetails } from "./utils/server";-export { themes } from "./components/themes";-export { default as CreateAgentPage } from "./CreatePage";-export { default as EditAgentPage } from "./EditPage";-export { default as AgentThemeProvider } from "./components/AgentThemeProvider";-export { default as AgentProfile } from "./AgentProfile";-diff --git a/packages/agents/src/tailwind.css b/packages/agents/src/tailwind.cssdeleted file mode 100644index e67956d..0000000--- a/packages/agents/src/tailwind.css+++ /dev/null@@ -1,92 +0,0 @@-@tailwind base;-@tailwind components;-@tailwind utilities;--@layer components {- .premium-bg {- @apply bg-white dark:bg-[#09090b];- background-image: radial-gradient(circle at 0% 0%, rgba(79, 70, 229, 0.03) 0%, transparent 25%),- radial-gradient(circle at 100% 100%, rgba(59, 130, 246, 0.03) 0%, transparent 25%);- }-- .premium-sidebar-blur {- @apply backdrop-blur-xl bg-white/80 dark:bg-[#09090b]/80;- }-- .premium-glass {- @apply backdrop-blur-md bg-white/70 dark:bg-zinc-900/60 border border-black/5 dark:border-white/10;- }-- .scrollbar-hide::-webkit-scrollbar {- display: none;- }-- .scrollbar-hide {- -ms-overflow-style: none;- scrollbar-width: none;- }-}--.skeleton {- background: linear-gradient(- 90deg,- #2a2a2a 25%,- #3a3a3a 50%,- #2a2a2a 75%- );- background-size: 200% 100%;- animation: wave 1.5s ease-in-out infinite;-}--@keyframes wave {- 0% {- background-position: 200% 0;- }- 100% {- background-position: -200% 0;- }-}--/* Basic Markdown Spacing Fixes */-.prose p {- margin-bottom: 1rem;-}-.prose p:last-child {- margin-bottom: 0;-}-.prose ul {- list-style-type: disc;- margin-left: 1.5rem;- margin-bottom: 1rem;-}-.prose ol {- list-style-type: decimal;- margin-left: 1.5rem;- margin-bottom: 1rem;-}-.prose li {- margin-bottom: 0.25rem;-}-.prose h1, .prose h2, .prose h3, .prose h4 {- font-weight: 600;- margin-top: 1.5rem;- margin-bottom: 0.75rem;- color: white;-}-.prose h1 { font-size: 1.5rem; }-.prose h2 { font-size: 1.25rem; }-.prose h3 { font-size: 1.125rem; }--.custom-scrollbar::-webkit-scrollbar {- width: 6px;-}-.custom-scrollbar::-webkit-scrollbar-track {- background: transparent;-}-.custom-scrollbar::-webkit-scrollbar-thumb {- background: rgba(255, 255, 255, 0.1);- border-radius: 10px;-}-.custom-scrollbar:hover::-webkit-scrollbar-thumb {- background: rgba(255, 255, 255, 0.15);-}diff --git a/packages/agents/src/utils/server.js b/packages/agents/src/utils/server.jsdeleted file mode 100644index cbb296d..0000000--- a/packages/agents/src/utils/server.js+++ /dev/null@@ -1,28 +0,0 @@-export const getAgentDetails = async (agentId, options = {}) => {- const {- baseUrl = "http://127.0.0.1:8000/agents", // Default relative URL for internal API, or provide full URL- fetchOptions = {}- } = options;-- if (!agentId) {- throw new Error("Agent ID is required");- }-- const url = `${baseUrl}/${agentId}`;-- try {- const response = await fetch(url, {- ...fetchOptions,- cache: fetchOptions.cache || 'no-store',- });-- if (!response.ok) {- throw new Error(`Failed to fetch agent details: ${response.status} ${response.statusText}`);- }-- return await response.json();- } catch (error) {- console.error("Error fetching agent details:", error);- throw error;- }-};diff --git a/packages/agents/tailwind.config.js b/packages/agents/tailwind.config.jsdeleted file mode 100644index e944ab8..0000000--- a/packages/agents/tailwind.config.js+++ /dev/null@@ -1,19 +0,0 @@-/** @type {import('tailwindcss').Config} */-module.exports = {- darkMode: 'class',- content: ["./src/**/*.{js,jsx}"],- theme: {- extend: {- colors: {- 'primary': '#3898ec',- 'primary-bg': '#121212',- 'secondary-bg': '#1E1E1E',- 'primary-text': '#E0E0E0',- 'secondary-text': '#B0B0B0',- 'divider': '#333333',- },- },- },- plugins: [],-}-diff --git a/pyproject.toml b/pyproject.tomlnew file mode 100644index 0000000..f36fbde--- /dev/null+++ b/pyproject.toml@@ -0,0 +1,52 @@+[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[project]+name = "tagopen"+version = "0.1.0"+description = "Self-hostable channel-native AI teammate for Slack"+readme = "README.md"+requires-python = ">=3.11"+dependencies = [+ "slack-bolt>=1.21.0",+ "litellm>=1.45.0",+ "mem0ai>=0.1.0",+ "mcp>=1.0.0",+ "aiosqlite>=0.20.0",+ "apscheduler>=3.10.0",+ "pydantic>=2.7.0",+ "pydantic-settings>=2.3.0",+ "toml>=0.10.2",+ "httpx>=0.27.0",+ "tenacity>=8.3.0",+ "structlog>=24.2.0",+]++[project.optional-dependencies]+dev = [+ "pytest>=8.2.0",+ "pytest-asyncio>=0.23.0",+ "pytest-mock>=3.14.0",+ "ruff>=0.4.0",+ "mypy>=1.10.0",+]++[project.scripts]+tagopen = "tagopen.cli:main"++[tool.ruff]+line-length = 100+target-version = "py311"++[tool.ruff.lint]+select = ["E", "F", "I", "UP"]++[tool.pytest.ini_options]+asyncio_mode = "auto"+testpaths = ["tests"]++[tool.mypy]+python_version = "3.11"+strict = false+ignore_missing_imports = truediff --git a/server/.env b/server/.envdeleted file mode 100644index 275f1f9..0000000--- a/server/.env+++ /dev/null@@ -1,2 +0,0 @@-MUAPI_BASE_URL=https://api.muapi.ai-MU_API_KEY=your_api_keydiff --git a/server/.gitignore b/server/.gitignoredeleted file mode 100644index 6c595b3..0000000--- a/server/.gitignore+++ /dev/null@@ -1,15 +0,0 @@-__pycache__/-*.py[cod]-*$py.class-*.so-.Python-env/-venv/-ENV/-.venv-*.egg-info/-dist/-build/-.pytest_cache/-.coverage-htmlcov/diff --git a/server/app/main.py b/server/app/main.pydeleted file mode 100644index 6c30768..0000000--- a/server/app/main.py+++ /dev/null@@ -1,31 +0,0 @@-import os-from dotenv import load_dotenv--env_path = os.path.join(os.path.dirname(__file__), '..', '.env')-load_dotenv(env_path)--from fastapi import FastAPI-from fastapi.middleware.cors import CORSMiddleware-from .routers import agent_proxy--app = FastAPI(title="Vibe-Agents API", version="1.0.0")--# Configure CORS-app.add_middleware(- CORSMiddleware,- allow_origins=["http://localhost:3000"],- allow_credentials=True,- allow_methods=["*"],- allow_headers=["*"],-)--# Include routers-app.include_router(agent_proxy.router, prefix="/api", tags=["proxy"])-[email protected]("/")-async def root():- return {"message": "Welcome to Vibe-Agents API"}-[email protected]("/api/health")-async def health_check():- return {"status": "healthy"}diff --git a/server/app/routers/__init__.py b/server/app/routers/__init__.pydeleted file mode 100644index c94c902..0000000--- a/server/app/routers/__init__.py+++ /dev/null@@ -1 +0,0 @@-from . import agent_proxydiff --git a/server/app/routers/agent_proxy.py b/server/app/routers/agent_proxy.pydeleted file mode 100644index c24aab5..0000000--- a/server/app/routers/agent_proxy.py+++ /dev/null@@ -1,91 +0,0 @@-from fastapi import APIRouter, Request, HTTPException-from app.utils.agent_helper import proxy_request-from typing import Optional-import os--router = APIRouter()-MUAPI_BASE_URL = os.getenv("MUAPI_BASE_URL", "https://api.muapi.ai")-# --- Agent Library Endpoints ----[email protected]("/agents/user/agents")-async def get_user_agents():- return await proxy_request("GET", "/agents/user/agents")-[email protected]("/agents/templates/agents")-async def get_template_agents():- return await proxy_request("GET", "/agents/templates/agents")-[email protected]("/agents/featured/agents")-async def get_featured_agents():- return await proxy_request("GET", "/agents/featured/agents")-[email protected]("/agents/suggest")-async def get_suggested_agents(request: Request):- payload = await request.json()- return await proxy_request("POST", "/agents/suggest", payload=payload)-[email protected]("/agents")-async def create_agent(request: Request):- payload = await request.json()- return await proxy_request("POST", "/agents", payload=payload)--# --- Agent Detail & Chat Endpoints ---[email protected]("/agents/skills")-async def get_agent_skills():- return await proxy_request("GET", f"/agents/skills")-[email protected]("/agents/by-slug/{slug}")-async def get_agent_by_slug(slug: str):- return await proxy_request("GET", f"/agents/by-slug/{slug}")-[email protected]("/agents/{slug}/profile")-async def get_agent_profile(slug: str):- return await proxy_request("GET", f"/agents/{slug}/profile")-[email protected]("/agents/by-slug/{slug}")-async def update_agent_by_slug(slug: str, request: Request):- payload = await request.json()- return await proxy_request("PUT", f"/agents/by-slug/{slug}", payload=payload)-[email protected]("/agents/by-slug/{slug}/chat")-async def agent_chat(slug: str, request: Request):- payload = await request.json()- return await proxy_request("POST", f"/agents/by-slug/{slug}/chat", payload=payload)-[email protected]("/agents/by-slug/{slug}/like")-async def like_agent(slug: str, request: Request):- params = dict(request.query_params)- return await proxy_request("POST", f"/agents/by-slug/{slug}/like", params=params)-[email protected]("/agents/by-slug/{slug}/{conv_id}")-async def get_conversation_history(slug: str, conv_id: str):- return await proxy_request("GET", f"/agents/by-slug/{slug}/{conv_id}")-[email protected]("/agents/by-slug/{slug}/preview-realign")-async def get_agent_preview(slug: str, request: Request):- payload = await request.json()- return await proxy_request("POST", f"/agents/by-slug/{slug}/preview-realign", payload=payload)--# --- Prediction & Image Gen Endpoints ----[email protected]("/api/v1/predictions/{request_id}/result")-async def get_prediction_result(request_id: str):- return await proxy_request("GET", f"/api/v1/predictions/{request_id}/result")-[email protected]("/api/v1/flux-schnell-image")-async def generate_flux_image(request: Request):- payload = await request.json()- return await proxy_request("POST", "/api/v1/flux-schnell-image", payload=payload)--# --- App & Workflow Utilities ----[email protected]("/app/get_file_upload_url")-async def get_upload_url(request: Request):- params = dict(request.query_params)- return await proxy_request("GET", "/app/get_file_upload_url", params=params)-[email protected]("/workflow/cloudfront-signed-url")-async def get_signed_url(request: Request):- payload = await request.json()- return await proxy_request("POST", "/workflow/cloudfront-signed-url", payload=payload)-diff --git a/server/app/utils/agent_helper.py b/server/app/utils/agent_helper.pydeleted file mode 100644index 9ef0100..0000000--- a/server/app/utils/agent_helper.py+++ /dev/null@@ -1,50 +0,0 @@-import os-import httpx-import logging-from fastapi import HTTPException-from typing import Optional--logging.basicConfig(level=logging.INFO)-logger = logging.getLogger(__name__)--MUAPI_BASE_URL = os.getenv("MUAPI_BASE_URL", "https://api.muapi.ai")--async def get_api_key():- api_key = os.getenv("MU_API_KEY")- if not api_key:- raise HTTPException(status_code=400, detail="Setup MU_API_KEY in .env to be able to use the agent library")- return api_key--async def proxy_request(method: str, path: str, payload: Optional[dict] = None, params: Optional[dict] = None):- api_key = await get_api_key()- url = f"{MUAPI_BASE_URL}/{path.lstrip('/')}"-- headers = {- "Content-Type": "application/json",- "x-api-key": api_key,- }-- async with httpx.AsyncClient() as client:- try:- response = await client.request(- method=method,- url=url,- json=payload,- params=params,- headers=headers,- timeout=60.0- )-- # For JSON responses, return the parsed data- if "application/json" in response.headers.get("content-type", ""):- return response.json()- else:- # Fallback for other content types- return response.content-- except httpx.RequestError as e:- logger.error(f"Request error: {e}")- raise HTTPException(status_code=500, detail=f"Error contacting MuAPI: {e}")- except Exception as e:- logger.error(f"Unexpected error: {e}")- raise HTTPException(status_code=500, detail=str(e))diff --git a/server/requirements.txt b/server/requirements.txtdeleted file mode 100644index 013d333..0000000--- a/server/requirements.txt+++ /dev/null@@ -1,7 +0,0 @@-fastapi-uvicorn-sqlalchemy-asyncpg-httpx-python-dotenv-ruffdiff --git a/tagopen/__init__.py b/tagopen/__init__.pynew file mode 100644index 0000000..3a8bb00--- /dev/null+++ b/tagopen/__init__.py@@ -0,0 +1,3 @@+"""TagOpen — open source channel-native AI teammate."""++__version__ = "0.1.0"diff --git a/tagopen/agent/__init__.py b/tagopen/agent/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/tagopen/agent/context.py b/tagopen/agent/context.pynew file mode 100644index 0000000..cedae13--- /dev/null+++ b/tagopen/agent/context.py@@ -0,0 +1,94 @@+"""Context assembler — builds the system prompt and message list for the LLM."""++from __future__ import annotations++import logging+from pathlib import Path++from tagopen.config import settings+from tagopen.memory.store import MessageStore++logger = logging.getLogger(__name__)++_DEFAULT_CHANNEL_MD = """\+# Channel Agent++You are a helpful AI teammate in this Slack channel.+Be concise, direct, and technical. Ask clarifying questions before taking big actions.+"""+++def _read_channel_file(channel_id: str, filename: str, default: str = "") -> str:+ path = settings.channels_dir / channel_id / filename+ if path.exists():+ return path.read_text()+ return default+++def build_system_prompt(channel_id: str, user_map: dict[str, str]) -> str:+ """Assemble the system prompt from CHANNEL.md + MEMORY.md + active skills."""+ channel_md = _read_channel_file(channel_id, "CHANNEL.md", _DEFAULT_CHANNEL_MD)+ memory_md = _read_channel_file(channel_id, "MEMORY.md", "")+ skills = _load_skills(channel_id)++ parts = [channel_md.strip()]++ if memory_md.strip():+ parts.append(f"## What I know about this channel\n\n{memory_md.strip()}")++ if skills:+ skill_block = "\n\n".join(f"### Skill: {name}\n{content}" for name, content in skills)+ parts.append(f"## Available skills\n\n{skill_block}")++ parts.append(+ "## Multi-user context\n"+ "Messages are prefixed with [timestamp @username]. "+ "You are a shared teammate — anyone in the channel can see this conversation. "+ "When following up, address the relevant person by @username."+ )++ parts.append(+ "## Memory tools\n"+ "After responding you may call `memory_append` or `memory_replace` to persist "+ "important facts, decisions, or conventions to MEMORY.md. Only save what future "+ "sessions would genuinely benefit from knowing."+ )++ return "\n\n---\n\n".join(parts)+++def _load_skills(channel_id: str) -> list[tuple[str, str]]:+ skills_dir = settings.channels_dir / channel_id / "skills"+ if not skills_dir.exists():+ return []+ results = []+ for path in sorted(skills_dir.glob("*.md")):+ content = path.read_text()+ # Skip archived skills+ if "status: archived" in content:+ continue+ results.append((path.stem, content))+ return results+++async def build_messages(+ channel_id: str,+ user_id: str,+ display_name: str,+ text: str,+ thread_ts: str,+ store: MessageStore,+) -> list[dict]:+ """Build the messages list: recent channel history + current message."""+ recent = await store.get_recent_messages(limit=settings.context_window_messages)++ messages: list[dict] = []+ for row in recent:+ ts_str = row["ts"][:16].replace("T", " ") # trim to minute+ prefix = f"[{ts_str} @{row['display_name']}]"+ role = "assistant" if row["role"] == "assistant" else "user"+ messages.append({"role": role, "content": f"{prefix} {row['content']}"})++ # Append current user message+ messages.append({"role": "user", "content": f"[@{display_name}] {text}"})+ return messagesdiff --git a/tagopen/agent/loop.py b/tagopen/agent/loop.pynew file mode 100644index 0000000..18002d0--- /dev/null+++ b/tagopen/agent/loop.py@@ -0,0 +1,146 @@+"""Agent loop — ReAct-style: think → tool call → observe → repeat → reply → memory curation."""++from __future__ import annotations++import json+import logging+from typing import TYPE_CHECKING, Any++from tagopen.agent.context import build_messages, build_system_prompt+from tagopen.agent.skills import maybe_create_skill+from tagopen.config import settings+from tagopen.llm import acompletion+from tagopen.memory.store import MessageStore+from tagopen.memory.writer import run_memory_curation+from tagopen.tools.registry import get_channel_tools, dispatch_tool++if TYPE_CHECKING:+ from slack_bolt.async_app import AsyncApp++logger = logging.getLogger(__name__)++MAX_TOOL_ROUNDS = 10 # prevent runaway loops+++async def run_agent_loop(+ app: "AsyncApp",+ workspace_id: str,+ channel_id: str,+ user_id: str,+ display_name: str,+ text: str,+ thread_ts: str,+ event_ts: str,+ store: MessageStore,+) -> None:+ # Persist the incoming user message+ await store.add_message(+ ts=event_ts,+ role="user",+ user_id=user_id,+ display_name=display_name,+ content=text,+ thread_ts=thread_ts,+ )++ # Fetch Slack user map for attribution (best-effort)+ try:+ members = await app.client.conversations_members(channel=channel_id)+ user_map: dict[str, str] = {}+ for uid in (members.get("members") or [])[:50]:+ info = await app.client.users_info(user=uid)+ profile = info["user"].get("profile", {})+ user_map[uid] = profile.get("display_name") or info["user"].get("real_name") or uid+ except Exception:+ user_map = {user_id: display_name}++ system_prompt = build_system_prompt(channel_id, user_map)+ messages = await build_messages(channel_id, user_id, display_name, text, thread_ts, store)+ tools = get_channel_tools(channel_id)++ tool_call_count = 0+ final_text = ""++ for _round in range(MAX_TOOL_ROUNDS):+ response = await acompletion(+ channel_id=channel_id,+ messages=[{"role": "system", "content": system_prompt}] + messages,+ tools=tools or None,+ tool_choice="auto" if tools else None,+ )++ choice = response.choices[0]+ msg = choice.message++ # Pure text response — we're done+ if not msg.tool_calls:+ final_text = msg.content or ""+ break++ # Execute each tool call+ messages.append(msg.model_dump(exclude_none=True))+ for tc in msg.tool_calls:+ tool_call_count += 1+ fn_name = tc.function.name+ fn_args = json.loads(tc.function.arguments or "{}")++ logger.info("Tool call: %s(%s) in channel=%s", fn_name, fn_args, channel_id)+ result = await dispatch_tool(fn_name, fn_args, channel_id=channel_id)++ # Handle memory write tools inline+ if fn_name in ("memory_append", "memory_replace"):+ _handle_memory_tool(channel_id, fn_name, fn_args)+ result = "Memory updated."++ messages.append({+ "role": "tool",+ "tool_call_id": tc.id,+ "content": str(result),+ })+ else:+ final_text = "I reached my tool call limit. Here's what I found so far."++ if not final_text:+ final_text = "Done."++ # Post reply to Slack+ await app.client.chat_postMessage(+ channel=channel_id,+ text=final_text,+ thread_ts=thread_ts,+ )++ # Persist assistant reply+ await store.add_message(+ ts=str(__import__("time").time()),+ role="assistant",+ user_id="agent",+ display_name="agent",+ content=final_text,+ thread_ts=thread_ts,+ )++ # Inner loop: memory curation turn (Letta-inspired)+ # Agent decides what's worth persisting to MEMORY.md+ await run_memory_curation(channel_id, system_prompt, messages, final_text)++ # Skill auto-creation if task was complex (Hermes-inspired)+ if tool_call_count >= 5:+ await maybe_create_skill(channel_id, messages, final_text, tool_call_count)+++def _handle_memory_tool(channel_id: str, fn_name: str, args: dict[str, Any]) -> None:+ memory_path = settings.channels_dir / channel_id / "MEMORY.md"+ memory_path.parent.mkdir(parents=True, exist_ok=True)++ current = memory_path.read_text() if memory_path.exists() else ""++ if fn_name == "memory_append":+ entry = args.get("content", "").strip()+ if entry:+ memory_path.write_text(current.rstrip() + f"\n- {entry}\n")++ elif fn_name == "memory_replace":+ old = args.get("old", "")+ new = args.get("new", "")+ memory_path.write_text(current.replace(old, new))diff --git a/tagopen/agent/skills.py b/tagopen/agent/skills.pynew file mode 100644index 0000000..2a9387f--- /dev/null+++ b/tagopen/agent/skills.py@@ -0,0 +1,99 @@+"""Skill auto-creation after complex tasks (Hermes-inspired)."""++from __future__ import annotations++import logging+from datetime import date++from tagopen.config import settings+from tagopen.llm import acompletion++logger = logging.getLogger(__name__)++_SKILL_CREATION_PROMPT = """\+The agent just completed a complex multi-step task. Review the conversation below and decide+whether it reveals a reusable procedure worth saving as a skill.++A skill is worth saving if:+- The task involved a non-obvious sequence of steps+- The same task is likely to come up again in this channel+- The agent made useful discoveries (gotchas, correct tool order, edge cases)++If yes, write a SKILL.md with this exact format:++---+name: <short-kebab-slug>+description: <one sentence — what task this skill handles>+created: {today}+tool_calls_in_session: {tool_calls}+uses: 0+last_used: null+status: active+---++## When to use this+<1-2 sentences>++## Steps+<numbered list>++## Known gotchas+<bullet list, or "None">++If no skill is worth saving, respond with exactly: SKIP+"""+++async def maybe_create_skill(+ channel_id: str,+ messages: list[dict],+ final_reply: str,+ tool_call_count: int,+) -> None:+ skills_dir = settings.channels_dir / channel_id / "skills"+ skills_dir.mkdir(parents=True, exist_ok=True)++ conversation_summary = _summarize_messages(messages[-20:]) # last 20 to keep prompt tight+ prompt = _SKILL_CREATION_PROMPT.format(today=date.today(), tool_calls=tool_call_count)++ try:+ response = await acompletion(+ channel_id=channel_id,+ messages=[+ {"role": "system", "content": prompt},+ {"role": "user", "content": f"Conversation:\n{conversation_summary}\n\nFinal reply:\n{final_reply}"},+ ],+ )+ content = response.choices[0].message.content or ""+ if content.strip() == "SKIP":+ return++ # Extract the name from the frontmatter+ name = "unnamed"+ for line in content.splitlines():+ if line.startswith("name:"):+ name = line.split(":", 1)[1].strip()+ break++ skill_path = skills_dir / f"{name}.md"+ # Don't overwrite existing skills+ if skill_path.exists():+ skill_path = skills_dir / f"{name}-{int(__import__('time').time())}.md"++ skill_path.write_text(content)+ logger.info("Skill created: %s in channel=%s", skill_path.name, channel_id)++ except Exception:+ logger.exception("Skill creation failed for channel=%s", channel_id)+++def _summarize_messages(messages: list[dict]) -> str:+ lines = []+ for m in messages:+ role = m.get("role", "")+ content = m.get("content") or ""+ if isinstance(content, list):+ content = " ".join(c.get("text", "") for c in content if isinstance(c, dict))+ if role in ("user", "assistant") and content:+ lines.append(f"{role.upper()}: {content[:300]}")+ return "\n".join(lines)diff --git a/tagopen/ambient/__init__.py b/tagopen/ambient/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/tagopen/ambient/heartbeat.py b/tagopen/ambient/heartbeat.pynew file mode 100644index 0000000..6f8d079--- /dev/null+++ b/tagopen/ambient/heartbeat.py@@ -0,0 +1,61 @@+"""Ambient heartbeat — proactive channel monitoring (Phase 3 stub).++The scheduler calls run_heartbeat(channel_id) on a per-channel cron.+It assembles an observation dump and asks the LLM: "anything worth surfacing?"+If yes, it posts to the channel. If no, it stays silent (SILENT sentinel).+"""++from __future__ import annotations++import logging++import litellm++from tagopen.config import settings+from tagopen.memory.store import get_store++logger = logging.getLogger(__name__)++_HEARTBEAT_PROMPT = """\+You are monitoring a Slack channel as a proactive AI teammate.+Below is a summary of recent activity.++Your job: decide if anything is worth surfacing proactively.+Only post if there's genuine value — a stale thread needing follow-up,+a deadline approaching, an unresolved question, or a risk you spotted.++If nothing is worth surfacing, respond with exactly: SILENT+Otherwise, write the message you would post to the channel (concise, actionable).+"""+++async def run_heartbeat(+ app,+ workspace_id: str,+ channel_id: str,+) -> None:+ store = await get_store(workspace_id, channel_id)+ recent = await store.get_recent_messages(limit=30)++ if not recent:+ return++ summary_lines = []+ for row in recent:+ summary_lines.append(f"[{row['display_name']}]: {row['content'][:200]}")+ summary = "\n".join(summary_lines)++ try:+ response = await litellm.acompletion(+ model=settings.llm_model,+ messages=[+ {"role": "system", "content": _HEARTBEAT_PROMPT},+ {"role": "user", "content": f"Recent messages:\n{summary}"},+ ],+ )+ text = (response.choices[0].message.content or "").strip()+ if text and text != "SILENT":+ await app.client.chat_postMessage(channel=channel_id, text=text)+ logger.info("Heartbeat posted to channel=%s", channel_id)+ except Exception:+ logger.exception("Heartbeat failed for channel=%s", channel_id)diff --git a/tagopen/cli.py b/tagopen/cli.pynew file mode 100644index 0000000..ea59b1c--- /dev/null+++ b/tagopen/cli.py@@ -0,0 +1,28 @@+"""CLI entry point."""++import asyncio+import logging++import structlog+++def main() -> None:+ structlog.configure(+ processors=[+ structlog.stdlib.add_log_level,+ structlog.stdlib.PositionalArgumentsFormatter(),+ structlog.dev.ConsoleRenderer(),+ ],+ wrapper_class=structlog.make_filtering_bound_logger(logging.INFO),+ logger_factory=structlog.PrintLoggerFactory(),+ )++ from tagopen.llm import configure+ from tagopen.gateway.app import start++ configure()+ asyncio.run(start())+++if __name__ == "__main__":+ main()diff --git a/tagopen/config.py b/tagopen/config.pynew file mode 100644index 0000000..7ae7466--- /dev/null+++ b/tagopen/config.py@@ -0,0 +1,39 @@+"""Global settings loaded from environment / .env file."""++from pathlib import Path++from pydantic_settings import BaseSettings, SettingsConfigDict+++class Settings(BaseSettings):+ model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")++ # Slack+ slack_bot_token: str+ slack_app_token: str++ # LLM — LiteLLM model string, e.g. "gpt-4o", "claude-sonnet-4-6", "gemini/gemini-2.0-flash"+ llm_model: str = "claude-sonnet-4-6"+ anthropic_api_key: str = ""+ openai_api_key: str = ""+ gemini_api_key: str = ""+ groq_api_key: str = ""++ # Storage+ data_dir: Path = Path("./data")++ # Limits+ default_max_tokens_per_request: int = 50_000+ default_max_tokens_per_day: int = 500_000+ context_window_messages: int = 50++ @property+ def channels_dir(self) -> Path:+ return self.data_dir / "channels"++ @property+ def db_path(self) -> Path:+ return self.data_dir / "tagopen.db"+++settings = Settings() # type: ignore[call-arg]diff --git a/tagopen/gateway/__init__.py b/tagopen/gateway/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/tagopen/gateway/app.py b/tagopen/gateway/app.pynew file mode 100644index 0000000..0140c80--- /dev/null+++ b/tagopen/gateway/app.py@@ -0,0 +1,58 @@+"""Slack Bolt gateway — entry point for all Slack events."""++import asyncio+import logging++from slack_bolt.async_app import AsyncApp+from slack_bolt.adapter.socket_mode.async_handler import AsyncSocketModeHandler++from tagopen.config import settings+from tagopen.gateway.router import route_message++logger = logging.getLogger(__name__)++app = AsyncApp(token=settings.slack_bot_token)++[email protected]("app_mention")+async def handle_mention(event: dict, say, client) -> None:+ """Handle @tagopen mentions in channels."""+ channel_id = event["channel"]+ workspace_id = (await client.auth_test())["team_id"]+ user_id = event["user"]+ text = event["text"]+ thread_ts = event.get("thread_ts") or event["ts"]++ # Acknowledge quickly with a reaction so the user knows we're working+ await client.reactions_add(channel=channel_id, timestamp=event["ts"], name="thinking_face")++ try:+ await route_message(+ app=app,+ workspace_id=workspace_id,+ channel_id=channel_id,+ user_id=user_id,+ text=text,+ thread_ts=thread_ts,+ event_ts=event["ts"],+ )+ except Exception:+ logger.exception("Error handling mention in %s", channel_id)+ await say(+ text="Sorry, I ran into an error processing that. Check the logs.",+ thread_ts=thread_ts,+ )+ finally:+ await client.reactions_remove(channel=channel_id, timestamp=event["ts"], name="thinking_face")++[email protected]("message")+async def handle_message(event: dict, client) -> None:+ """Ignore regular messages — only respond to @mentions."""+ pass+++async def start() -> None:+ handler = AsyncSocketModeHandler(app, settings.slack_app_token)+ logger.info("TagOpen gateway starting (Socket Mode)…")+ await handler.start_async()diff --git a/tagopen/gateway/router.py b/tagopen/gateway/router.pynew file mode 100644index 0000000..a062bb5--- /dev/null+++ b/tagopen/gateway/router.py@@ -0,0 +1,76 @@+"""Channel router — maps (workspace_id, channel_id) to an AgentSession and runs the loop."""++import logging+from dataclasses import dataclass, field+from typing import TYPE_CHECKING++from tagopen.agent.loop import run_agent_loop+from tagopen.memory.store import get_store++if TYPE_CHECKING:+ from slack_bolt.async_app import AsyncApp++logger = logging.getLogger(__name__)++# In-memory session registry: (workspace_id, channel_id) → AgentSession+# The key insight vs OpenClaw: session key includes channel_id, NOT user_id.+# All users in a channel share the same session.+_sessions: dict[tuple[str, str], "AgentSession"] = {}+++@dataclass+class AgentSession:+ workspace_id: str+ channel_id: str+ # Shared lock so concurrent @mentions in the same channel are serialized+ # preventing context corruption from parallel writes.+ _lock: asyncio.Lock = field(default_factory=lambda: __import__("asyncio").Lock())+++import asyncio # noqa: E402 — needed for Lock reference above+++def get_or_create_session(workspace_id: str, channel_id: str) -> AgentSession:+ key = (workspace_id, channel_id)+ if key not in _sessions:+ _sessions[key] = AgentSession(workspace_id=workspace_id, channel_id=channel_id)+ logger.info("New session: workspace=%s channel=%s", workspace_id, channel_id)+ return _sessions[key]+++async def route_message(+ app: "AsyncApp",+ workspace_id: str,+ channel_id: str,+ user_id: str,+ text: str,+ thread_ts: str,+ event_ts: str,+) -> None:+ session = get_or_create_session(workspace_id, channel_id)+ store = await get_store(workspace_id, channel_id)++ # Fetch user display name for attribution in context+ try:+ user_info = await app.client.users_info(user=user_id)+ display_name = (+ user_info["user"].get("profile", {}).get("display_name")+ or user_info["user"].get("real_name")+ or user_id+ )+ except Exception:+ display_name = user_id++ # Serialize per-channel — prevents race conditions on shared context+ async with session._lock:+ await run_agent_loop(+ app=app,+ workspace_id=workspace_id,+ channel_id=channel_id,+ user_id=user_id,+ display_name=display_name,+ text=text,+ thread_ts=thread_ts,+ event_ts=event_ts,+ store=store,+ )diff --git a/tagopen/llm.py b/tagopen/llm.pynew file mode 100644index 0000000..1717da0--- /dev/null+++ b/tagopen/llm.py@@ -0,0 +1,90 @@+"""LiteLLM helpers — key injection, model resolution, per-channel overrides.++LiteLLM reads provider keys from os.environ, not from arbitrary Python objects.+Call configure() once at startup to sync settings → os.environ.++Per-channel model override: add a line to CHANNEL.md frontmatter:+ llm_model: gpt-4o+or set LLM_MODEL per channel in tools.toml:+ [llm]+ model = "gpt-4o"+"""++from __future__ import annotations++import logging+import os+from pathlib import Path++import litellm+import toml++from tagopen.config import settings++logger = logging.getLogger(__name__)++# Suppress LiteLLM's verbose success logs+litellm.suppress_debug_info = True+++def configure() -> None:+ """Sync API keys from settings → os.environ so LiteLLM can pick them up."""+ _set_if_nonempty("ANTHROPIC_API_KEY", settings.anthropic_api_key)+ _set_if_nonempty("OPENAI_API_KEY", settings.openai_api_key)+ _set_if_nonempty("GEMINI_API_KEY", settings.gemini_api_key)+ _set_if_nonempty("GROQ_API_KEY", settings.groq_api_key)++ logger.info("LLM configured — default model: %s", settings.llm_model)+ _log_available_providers()+++def _set_if_nonempty(env_var: str, value: str) -> None:+ if value and not os.environ.get(env_var):+ os.environ[env_var] = value+++def _log_available_providers() -> None:+ providers = []+ if os.environ.get("ANTHROPIC_API_KEY"):+ providers.append("Anthropic")+ if os.environ.get("OPENAI_API_KEY"):+ providers.append("OpenAI")+ if os.environ.get("GEMINI_API_KEY"):+ providers.append("Gemini")+ if os.environ.get("GROQ_API_KEY"):+ providers.append("Groq")+ if providers:+ logger.info("Available LLM providers: %s", ", ".join(providers))+ else:+ logger.warning("No LLM provider API keys found — set at least one in .env")+++def resolve_model(channel_id: str | None = None) -> str:+ """Return the model to use, respecting per-channel overrides.++ Override order (highest wins):+ 1. tools.toml [llm] model = "..." in channel dir+ 2. LLM_MODEL env var / settings.llm_model+ """+ if channel_id:+ override = _channel_model_override(channel_id)+ if override:+ return override+ return settings.llm_model+++def _channel_model_override(channel_id: str) -> str | None:+ tools_toml = settings.channels_dir / channel_id / "tools.toml"+ if not tools_toml.exists():+ return None+ try:+ config = toml.loads(tools_toml.read_text())+ return config.get("llm", {}).get("model") or None+ except Exception:+ return None+++async def acompletion(channel_id: str | None = None, **kwargs):+ """Thin wrapper around litellm.acompletion that injects the resolved model."""+ kwargs.setdefault("model", resolve_model(channel_id))+ return await litellm.acompletion(**kwargs)diff --git a/tagopen/memory/__init__.py b/tagopen/memory/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/tagopen/memory/store.py b/tagopen/memory/store.pynew file mode 100644index 0000000..d930bdc--- /dev/null+++ b/tagopen/memory/store.py@@ -0,0 +1,127 @@+"""SQLite + FTS5 message store — one DB per workspace, one table per channel."""++from __future__ import annotations++import logging+from functools import lru_cache+from pathlib import Path++import aiosqlite++from tagopen.config import settings++logger = logging.getLogger(__name__)++_CREATE_MESSAGES = """+CREATE TABLE IF NOT EXISTS messages (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ ts TEXT NOT NULL,+ thread_ts TEXT,+ channel_id TEXT NOT NULL,+ role TEXT NOT NULL, -- 'user' | 'assistant'+ user_id TEXT NOT NULL,+ display_name TEXT NOT NULL,+ content TEXT NOT NULL,+ tool_calls INTEGER DEFAULT 0,+ created_at REAL NOT NULL DEFAULT (unixepoch('now', 'subsec'))+);+"""++_CREATE_FTS = """+CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(+ content,+ display_name,+ content='messages',+ content_rowid='id'+);+"""++_CREATE_TRIGGERS = """+CREATE TRIGGER IF NOT EXISTS messages_ai AFTER INSERT ON messages BEGIN+ INSERT INTO messages_fts(rowid, content, display_name)+ VALUES (new.id, new.content, new.display_name);+END;++CREATE TRIGGER IF NOT EXISTS messages_ad AFTER DELETE ON messages BEGIN+ INSERT INTO messages_fts(messages_fts, rowid, content, display_name)+ VALUES ('delete', old.id, old.content, old.display_name);+END;+"""+++class MessageStore:+ def __init__(self, db_path: Path, channel_id: str) -> None:+ self._db_path = db_path+ self._channel_id = channel_id+ self._db: aiosqlite.Connection | None = None++ async def open(self) -> None:+ self._db_path.parent.mkdir(parents=True, exist_ok=True)+ self._db = await aiosqlite.connect(self._db_path)+ self._db.row_factory = aiosqlite.Row+ await self._db.execute("PRAGMA journal_mode=WAL")+ await self._db.execute("PRAGMA foreign_keys=ON")+ await self._db.executescript(_CREATE_MESSAGES + _CREATE_FTS + _CREATE_TRIGGERS)+ await self._db.commit()++ async def add_message(+ self,+ ts: str,+ role: str,+ user_id: str,+ display_name: str,+ content: str,+ thread_ts: str | None = None,+ tool_calls: int = 0,+ ) -> None:+ assert self._db+ await self._db.execute(+ """INSERT INTO messages (ts, thread_ts, channel_id, role, user_id, display_name, content, tool_calls)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",+ (ts, thread_ts, self._channel_id, role, user_id, display_name, content, tool_calls),+ )+ await self._db.commit()++ async def get_recent_messages(self, limit: int = 50) -> list[aiosqlite.Row]:+ assert self._db+ async with self._db.execute(+ """SELECT ts, role, user_id, display_name, content+ FROM messages+ WHERE channel_id = ?+ ORDER BY created_at DESC+ LIMIT ?""",+ (self._channel_id, limit),+ ) as cursor:+ rows = await cursor.fetchall()+ return list(reversed(rows)) # return chronologically++ async def search(self, query: str, limit: int = 10) -> list[aiosqlite.Row]:+ """Full-text search across channel messages."""+ assert self._db+ async with self._db.execute(+ """SELECT m.ts, m.role, m.display_name, m.content+ FROM messages_fts f+ JOIN messages m ON m.id = f.rowid+ WHERE messages_fts MATCH ? AND m.channel_id = ?+ ORDER BY rank+ LIMIT ?""",+ (query, self._channel_id, limit),+ ) as cursor:+ return await cursor.fetchall()++ async def close(self) -> None:+ if self._db:+ await self._db.close()+++_stores: dict[tuple[str, str], MessageStore] = {}+++async def get_store(workspace_id: str, channel_id: str) -> MessageStore:+ key = (workspace_id, channel_id)+ if key not in _stores:+ db_path = settings.data_dir / "workspaces" / workspace_id / "messages.db"+ store = MessageStore(db_path=db_path, channel_id=channel_id)+ await store.open()+ _stores[key] = store+ return _stores[key]diff --git a/tagopen/memory/writer.py b/tagopen/memory/writer.pynew file mode 100644index 0000000..0791c3c--- /dev/null+++ b/tagopen/memory/writer.py@@ -0,0 +1,102 @@+"""Memory curation turn — inner loop (Letta-inspired).++After the agent replies, it gets one more LLM call to decide what+(if anything) to write to MEMORY.md. This keeps memory clean and+agent-curated rather than a noisy append-only log.+"""++from __future__ import annotations++import logging++from tagopen.llm import acompletion++logger = logging.getLogger(__name__)++_CURATION_PROMPT = """\+You just responded to a message in a Slack channel. Review the exchange below.++Your job: decide if anything should be persisted to the channel's long-term memory (MEMORY.md).+Only save facts that future sessions would genuinely benefit from knowing:+- Team conventions or preferences that came up+- Decisions made ("we decided to use X")+- Important context about the team or project+- Corrections to things you got wrong++Do NOT save:+- Transient task results (code output, search results)+- Things already in MEMORY.md+- Obvious facts that can be looked up++If something is worth saving, call memory_append or memory_replace.+If nothing is worth saving, do nothing — respond with an empty message.+"""++_MEMORY_TOOLS = [+ {+ "type": "function",+ "function": {+ "name": "memory_append",+ "description": "Append a new fact or decision to MEMORY.md",+ "parameters": {+ "type": "object",+ "properties": {+ "content": {"type": "string", "description": "The fact to persist (one concise bullet)"},+ },+ "required": ["content"],+ },+ },+ },+ {+ "type": "function",+ "function": {+ "name": "memory_replace",+ "description": "Replace an outdated fact in MEMORY.md with an updated one",+ "parameters": {+ "type": "object",+ "properties": {+ "old": {"type": "string", "description": "The exact text to replace"},+ "new": {"type": "string", "description": "The replacement text"},+ },+ "required": ["old", "new"],+ },+ },+ },+]+++async def run_memory_curation(+ channel_id: str,+ system_prompt: str,+ messages: list[dict],+ final_reply: str,+) -> None:+ try:+ response = await acompletion(+ channel_id=channel_id,+ messages=[+ {"role": "system", "content": _CURATION_PROMPT},+ # Provide the last few turns as context+ *messages[-6:],+ {"role": "assistant", "content": final_reply},+ ],+ tools=_MEMORY_TOOLS,+ tool_choice="auto",+ )++ msg = response.choices[0].message+ if not msg.tool_calls:+ return++ import json+ from tagopen.agent.loop import _handle_memory_tool++ for tc in msg.tool_calls:+ fn_name = tc.function.name+ fn_args = json.loads(tc.function.arguments or "{}")+ if fn_name in ("memory_append", "memory_replace"):+ _handle_memory_tool(channel_id, fn_name, fn_args)+ logger.info("Memory updated via curation: %s in channel=%s", fn_name, channel_id)++ except Exception:+ logger.exception("Memory curation failed for channel=%s", channel_id)diff --git a/tagopen/tools/__init__.py b/tagopen/tools/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/tagopen/tools/builtins.py b/tagopen/tools/builtins.pynew file mode 100644index 0000000..4f5d4c7--- /dev/null+++ b/tagopen/tools/builtins.py@@ -0,0 +1,147 @@+"""Built-in tools always available to the agent: web search, Python runner, channel search."""++from __future__ import annotations++import asyncio+import logging+import sys+from io import StringIO+from typing import Any++import httpx++logger = logging.getLogger(__name__)++# LiteLLM-compatible tool schemas+BUILTIN_TOOLS: list[dict] = [+ {+ "type": "function",+ "function": {+ "name": "web_search",+ "description": "Search the web for up-to-date information",+ "parameters": {+ "type": "object",+ "properties": {+ "query": {"type": "string", "description": "Search query"},+ },+ "required": ["query"],+ },+ },+ },+ {+ "type": "function",+ "function": {+ "name": "run_python",+ "description": "Execute a Python snippet and return stdout. Use for calculations, data processing, and quick scripts.",+ "parameters": {+ "type": "object",+ "properties": {+ "code": {"type": "string", "description": "Python code to execute"},+ },+ "required": ["code"],+ },+ },+ },+ {+ "type": "function",+ "function": {+ "name": "search_channel_history",+ "description": "Full-text search across this channel's message history",+ "parameters": {+ "type": "object",+ "properties": {+ "query": {"type": "string", "description": "Keywords to search for"},+ },+ "required": ["query"],+ },+ },+ },+ {+ "type": "function",+ "function": {+ "name": "memory_append",+ "description": "Append a new fact or decision to channel long-term memory (MEMORY.md)",+ "parameters": {+ "type": "object",+ "properties": {+ "content": {"type": "string", "description": "The fact to persist (one concise bullet)"},+ },+ "required": ["content"],+ },+ },+ },+ {+ "type": "function",+ "function": {+ "name": "memory_replace",+ "description": "Replace an outdated fact in channel memory with an updated version",+ "parameters": {+ "type": "object",+ "properties": {+ "old": {"type": "string"},+ "new": {"type": "string"},+ },+ "required": ["old", "new"],+ },+ },+ },+]+++async def dispatch_builtin(fn_name: str, args: dict[str, Any]) -> Any:+ if fn_name == "web_search":+ return await _web_search(args["query"])+ if fn_name == "run_python":+ return _run_python(args["code"])+ if fn_name == "search_channel_history":+ # Actual search happens in dispatch_tool after store lookup; return placeholder+ return args # passed through to registry for store-aware dispatch+ return f"Unknown built-in: {fn_name}"+++async def _web_search(query: str) -> str:+ # Uses DuckDuckGo instant answer API — no key required+ try:+ async with httpx.AsyncClient(timeout=10) as client:+ resp = await client.get(+ "https://api.duckduckgo.com/",+ params={"q": query, "format": "json", "no_html": "1", "skip_disambig": "1"},+ )+ data = resp.json()+ abstract = data.get("AbstractText", "")+ related = [r.get("Text", "") for r in data.get("RelatedTopics", [])[:3] if r.get("Text")]+ if abstract:+ return abstract + ("\n\nRelated:\n" + "\n".join(f"- {r}" for r in related) if related else "")+ if related:+ return "\n".join(f"- {r}" for r in related)+ return "No results found."+ except Exception as e:+ logger.warning("Web search failed: %s", e)+ return f"Search failed: {e}"+++def _run_python(code: str) -> str:+ # Sandboxed Python execution — stdout captured, dangerous builtins removed+ safe_globals: dict[str, Any] = {+ "__builtins__": {+ k: v for k, v in __builtins__.items() # type: ignore[union-attr]+ if k not in ("open", "exec", "eval", "__import__", "compile")+ }+ if isinstance(__builtins__, dict)+ else {},+ "print": print,+ }+ # Allow common safe stdlib+ import math, json, re, datetime+ safe_globals.update({"math": math, "json": json, "re": re, "datetime": datetime})++ old_stdout = sys.stdout+ sys.stdout = buffer = StringIO()+ try:+ exec(code, safe_globals) # noqa: S102+ output = buffer.getvalue()+ return output.strip() or "(no output)"+ except Exception as e:+ return f"Error: {e}"+ finally:+ sys.stdout = old_stdoutdiff --git a/tagopen/tools/registry.py b/tagopen/tools/registry.pynew file mode 100644index 0000000..7665e33--- /dev/null+++ b/tagopen/tools/registry.py@@ -0,0 +1,52 @@+"""Tool registry — loads allowed tools per channel from TOOLS.md / tools.toml.++All tools are exposed as MCP-compatible function schemas so the agent can call them.+Built-in tools are always available. Channel admins can add MCP servers via TOOLS.md.+"""++from __future__ import annotations++import logging+from pathlib import Path+from typing import Any++import toml++from tagopen.config import settings+from tagopen.tools.builtins import BUILTIN_TOOLS, dispatch_builtin++logger = logging.getLogger(__name__)++# Cache parsed tool configs per channel+_tool_configs: dict[str, list[dict]] = {}+++def get_channel_tools(channel_id: str) -> list[dict]:+ """Return LiteLLM-compatible tool schemas for this channel."""+ tools = list(BUILTIN_TOOLS) # always include built-ins++ tools_toml_path = settings.channels_dir / channel_id / "tools.toml"+ if tools_toml_path.exists():+ try:+ config = toml.loads(tools_toml_path.read_text())+ for server in config.get("mcp_server", []):+ # For now, MCP servers are registered but called via HTTP+ # Full MCP client implementation in Phase 2+ logger.debug("MCP server registered: %s for channel=%s", server.get("name"), channel_id)+ except Exception:+ logger.exception("Failed to parse tools.toml for channel=%s", channel_id)++ return tools+++async def dispatch_tool(fn_name: str, args: dict[str, Any], channel_id: str) -> Any:+ """Dispatch a tool call to built-ins or MCP servers."""+ if fn_name in {t["function"]["name"] for t in BUILTIN_TOOLS}:+ return await dispatch_builtin(fn_name, args)++ # Memory tools are handled directly in the agent loop+ if fn_name in ("memory_append", "memory_replace"):+ return None++ logger.warning("Unknown tool: %s in channel=%s", fn_name, channel_id)+ return f"Tool '{fn_name}' not found."diff --git a/tests/__init__.py b/tests/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/tests/unit/__init__.py b/tests/unit/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/tests/unit/test_memory_store.py b/tests/unit/test_memory_store.pynew file mode 100644index 0000000..b084920--- /dev/null+++ b/tests/unit/test_memory_store.py@@ -0,0 +1,74 @@+"""Tests for SQLite message store."""++import pytest+from pathlib import Path+from tagopen.memory.store import MessageStore+++async def store(tmp_path):+ db_path = tmp_path / "test.db"+ s = MessageStore(db_path=db_path, channel_id="C001")+ await s.open()+ yield s+ await s.close()+++async def test_add_and_retrieve_message(store):+ await store.add_message(+ ts="1234567890.000001",+ role="user",+ user_id="U001",+ display_name="alice",+ content="hello world",+ )+ rows = await store.get_recent_messages(limit=10)+ assert len(rows) == 1+ assert rows[0]["content"] == "hello world"+ assert rows[0]["display_name"] == "alice"+++async def test_message_ordering(store):+ for i in range(5):+ await store.add_message(+ ts=f"100000000{i}.000000",+ role="user",+ user_id="U001",+ display_name="alice",+ content=f"message {i}",+ )+ rows = await store.get_recent_messages(limit=10)+ contents = [r["content"] for r in rows]+ assert contents == [f"message {i}" for i in range(5)]+++async def test_fts_search(store):+ await store.add_message(+ ts="1.0", role="user", user_id="U1", display_name="bob", content="deploy the staging server"+ )+ await store.add_message(+ ts="2.0", role="user", user_id="U1", display_name="bob", content="update the README docs"+ )+ results = await store.search("staging")+ assert len(results) == 1+ assert "staging" in results[0]["content"]+++async def test_channel_isolation(tmp_path):+ db_path = tmp_path / "shared.db"+ store_a = MessageStore(db_path=db_path, channel_id="C001")+ store_b = MessageStore(db_path=db_path, channel_id="C002")+ await store_a.open()+ await store_b.open()++ await store_a.add_message(ts="1.0", role="user", user_id="U1", display_name="a", content="channel A msg")+ await store_b.add_message(ts="2.0", role="user", user_id="U1", display_name="b", content="channel B msg")++ rows_a = await store_a.get_recent_messages()+ rows_b = await store_b.get_recent_messages()++ assert len(rows_a) == 1 and rows_a[0]["content"] == "channel A msg"+ assert len(rows_b) == 1 and rows_b[0]["content"] == "channel B msg"++ await store_a.close()+ await store_b.close()diff --git a/tests/unit/test_router.py b/tests/unit/test_router.pynew file mode 100644index 0000000..4b56f95--- /dev/null+++ b/tests/unit/test_router.py@@ -0,0 +1,32 @@+"""Tests for channel router — verifies channel-scoped session isolation."""++import pytest+from tagopen.gateway.router import get_or_create_session, _sessions+++def setup_function():+ _sessions.clear()+++def test_same_channel_returns_same_session():+ s1 = get_or_create_session("W001", "C001")+ s2 = get_or_create_session("W001", "C001")+ assert s1 is s2+++def test_different_channels_return_different_sessions():+ s1 = get_or_create_session("W001", "C001")+ s2 = get_or_create_session("W001", "C002")+ assert s1 is not s2+++def test_different_workspaces_return_different_sessions():+ s1 = get_or_create_session("W001", "C001")+ s2 = get_or_create_session("W002", "C001")+ assert s1 is not s2+++def test_session_has_channel_scoped_identity():+ s = get_or_create_session("W001", "C001")+ assert s.workspace_id == "W001"+ assert s.channel_id == "C001"