# @mzhub/plexus

AI-Native Fullstack Framework for React. Build agent-powered applications with file-based routing and security-first architecture.

## Quick Start

```bash
npx plexus init           # Create project
npm install               # Install dependencies
cp .env.example .env      # Configure API keys
npm run dev               # Start dev servers
```

### Serverless Deployment (Vercel/Netlify)

```bash
npx plexus init --serverless  # Create project with serverless config
npm install
vercel --prod                 # Deploy to Vercel
```

## Project Structure

```
my-app/
  src/
    hub/                      # Framework-managed (auto-discovered)
      route/
        home/page.jsx         # / (homepage)
        dashboard/page.jsx    # /dashboard
        users/[id]/page.jsx   # /users/:id (dynamic)
      agent/
        global.js             # All routes
        dashboard/_agent.js   # /dashboard + children
      tools/
        global.js             # All agents
        dashboard.js          # Dashboard agent only
      api/
        users.js              # /_api/users
    main.jsx                  # Entry point
    styles.css                # Global styles
  public/                     # Static assets
  index.html
  vite.config.js              # Uses plexusViteConfig()
```

## Entry Point

```jsx
// src/main.jsx - generated by init
import { createApp } from "@mzhub/plexus";
import "./styles.css";

createApp(); // Auto-loads routes, mounts to #root
```

With custom layout:

```jsx
import { createApp } from "@mzhub/plexus";
import Layout from "@/components/Layout";

createApp({ Layout });
```

## Vite Config

```javascript
// vite.config.js - generated by init
import { plexusViteConfig } from "@mzhub/plexus/bundler";

export default plexusViteConfig();
```

With overrides:

```javascript
export default plexusViteConfig({
  port: 3000,
  serverPort: 3001,
  alias: { "@components": "./src/components" },
});
```

## Routing

### File-Based Routes

| File                            | Route        |
| ------------------------------- | ------------ |
| `hub/route/home/page.jsx`       | `/`          |
| `hub/route/about/page.jsx`      | `/about`     |
| `hub/route/users/[id]/page.jsx` | `/users/:id` |

### Dynamic Routes

```jsx
// src/hub/route/users/[id]/page.jsx
import { useParams } from "react-router-dom";

export default function UserPage() {
  const { id } = useParams();
  return <h1>User: {id}</h1>;
}
```

### Agent Inheritance

```
hub/agent/
  global.js               # All routes
  dashboard/_agent.js     # /dashboard + children
```

### Tool Scoping

```
hub/tools/
  global.js       # All agents
  dashboard.js    # Only dashboard agent
```

## API Reference

### Client (`@mzhub/plexus`)

| Export               | Description             |
| -------------------- | ----------------------- |
| `createApp()`        | One-liner app setup     |
| `Router`             | Manual router component |
| `createAgentProxy()` | RPC client for agent    |
| `useAgentRPC()`      | Streaming chat hook     |
| `compressDOM()`      | DOM compression         |

### Bundler (`@mzhub/plexus/bundler`)

| Export                 | Description                |
| ---------------------- | -------------------------- |
| `plexusViteConfig()`   | Pre-configured Vite config |
| `plexusRouterPlugin()` | Auto-routing Vite plugin   |

### AI (`@mzhub/plexus/ai`)

| Export                   | Description                 |
| ------------------------ | --------------------------- |
| `defineAgent()`          | Create agent with defaults  |
| `agentLoop()`            | Execute agent with tools    |
| `defineTool()`           | Create tool with Zod schema |
| `createOpenAIProvider()` | OpenAI/Groq/Cerebras        |
| `createGroqProvider()`   | Groq (fast inference)       |
| `createGeminiProvider()` | Google Gemini               |

### Runtime (`@mzhub/plexus/runtime`)

| Export                      | Description                     |
| --------------------------- | ------------------------------- |
| `createPlexusServer()`      | WebSocket server factory        |
| `createPlexusHttpHandler()` | HTTP/SSE handler for serverless |
| `registerAgent()`           | Explicit agent registration     |
| `discoverRoutes()`          | File discovery                  |
| `startServer()`             | Start production server         |
| `GlobalAIDefaults`          | Type for config cascade         |

## Serverless Deployment

Deploy to Vercel, Netlify, or Cloudflare Workers using HTTP/SSE transport.

### Client Configuration

```javascript
import { createAgentProxy, PortalClient } from "@mzhub/plexus";

// Agent proxy with HTTP transport
const agent = createAgentProxy({
  agentId: "global",
  transport: "http", // WebSocket remains default
});

// Portal client with HTTP transport
const portal = new PortalClient({
  serverUrl: "https://your-app.vercel.app",
  transport: "http",
});
```

### Server (Vercel API Route)

```javascript
// api/plexus/[...path].js
import { createPlexusHttpHandler } from "@mzhub/plexus/server";

const handler = createPlexusHttpHandler({
  corsOrigins: ["https://your-app.vercel.app"],
});

export default handler;
```

### HTTP Endpoints

| Endpoint                     | Method | Purpose                          |
| ---------------------------- | ------ | -------------------------------- |
| `/_plexus/session`           | POST   | Create session                   |
| `/_plexus/agent/chat`        | POST   | Agent conversation (returns SSE) |
| `/_plexus/portal/message`    | POST   | DOM snapshots                    |
| `/_plexus/portal/events/:id` | GET    | SSE stream for commands          |

## Defining Tools

```javascript
import { defineTool } from "@mzhub/plexus/ai";
import { z } from "zod";

export const searchProducts = defineTool({
  name: "search_products",
  description: "Search for products",
  schema: z.object({ query: z.string() }),
  execute: async ({ query }) => {
    const results = await db.products.search(query);
    return { success: true, data: results };
  },
});
```

## React Usage

```jsx
import { createAgentProxy, useAgentRPC } from "@mzhub/plexus";

const agent = createAgentProxy({ agentId: "global" });

function Chat() {
  const { messages, sendMessage, status } = useAgentRPC(agent);

  return (
    <div>
      {messages.map((m, i) => (
        <div key={i}>{m.content}</div>
      ))}
      <button onClick={() => sendMessage("Hello")}>
        {status === "thinking" ? "..." : "Send"}
      </button>
    </div>
  );
}
```

## Config Cascade

Agents inherit defaults from server config:

```javascript
const server = await createPlexusServer({
  hubDir: "./src/hub",
  ai: {
    maxIterations: 15,
    maxCost: 0.30,
    costPerToken: 0.00002,
  }
});

// Agents inherit these defaults, can override selectively
// hub/agent/support.js
export default {
  provider: createGroqProvider({ ... }),
  maxCost: 0.10,  // Override just this
};
```

## Environment Variables

```bash
GROQ_API_KEY=gsk_...
AI_MODEL=llama-3.3-70b-versatile
PORT=3000
```

## CLI Commands

| Command        | Description                               |
| -------------- | ----------------------------------------- |
| `plexus init`  | Create new project (src/public structure) |
| `plexus dev`   | Run dev servers (Vite + WebSocket)        |
| `plexus build` | Build for production                      |
| `plexus start` | Run production server                     |

## Error Handling

The framework provides typed error classes for common failure scenarios:

```javascript
import {
  AgentBudgetError, // Token/cost limit exceeded
  AgentIterationError, // Max iterations reached
  ToolPermissionError, // RBAC check failed
} from "@mzhub/plexus/ai";
```

### Error Types

| Error                 | Cause                          | Resolution                           |
| --------------------- | ------------------------------ | ------------------------------------ |
| `AgentBudgetError`    | Cost exceeded `maxCost`        | Increase limit or optimize prompts   |
| `AgentIterationError` | Loops exceeded `maxIterations` | Check for tool loops, increase limit |
| `ToolPermissionError` | User lacks `requiredRole`      | Verify user role in session          |

### Handling in Components

```jsx
function Chat() {
  const { error, status } = useAgentRPC(agent);

  if (error?.name === "AgentBudgetError") {
    return <div>Session limit reached. Please try again later.</div>;
  }

  // ... rest of component
}
```

### Tool Error Responses

Tools should return structured error responses:

```javascript
execute: async ({ id }) => {
  const item = await db.find(id);
  if (!item) {
    return { success: false, error: "Item not found" };
  }
  return { success: true, data: item };
};
```

## Troubleshooting

### Common Issues

**WebSocket connection fails**

```bash
# Check server is running on correct port
curl http://localhost:3001/_plexus/health

# Verify proxy config in vite.config.js
serverPort: 3001  # Must match server port
```

**Routes not loading**

```bash
# Verify hub directory structure
ls -la src/hub/route/

# Check for page.jsx files (not index.jsx)
find src/hub/route -name "page.jsx"
```

**Agent not responding**

```bash
# Check API key is set
echo $GROQ_API_KEY

# Verify agent file exports default object
cat src/hub/agent/global.js
```

**Tools not available to agent**

```bash
# Tools must be in hub/tools/ directory
# Global tools: hub/tools/global.js
# Scoped tools: hub/tools/{agent-name}.js
```

### Debug Mode

Enable verbose logging:

```javascript
// vite.config.js
export default plexusViteConfig({
  // ... other config
});

// Start with debug
DEBUG=plexus:* npm run dev
```

### Testing Agents Locally

```bash
# Run the test-agent script
npm run test:agent

# Or test a specific agent
npx tsx scripts/test-agent.ts --agent=dashboard
```

## License

MIT
