npm package: @kognitivedev/next
Description: Next.js integration for Kognitive — auto-registration plugin and middleware
Latest version: 0.2.22

# @kognitivedev/next

Next.js integration for [Kognitive](https://kognitive.dev): **automatic cloud registration**, **runtime API endpoints**, and a **singleton** `Kognitive` instance on the server.

## What it provides

| Mechanism | When it runs | Purpose |
|-----------|----------------|---------|
| **`withKognitive`** | Build time | Adds `transpilePackages` and `instrumentationHook` to Next.js config |
| **`register`** | Server startup (`instrumentation.ts`) | Syncs metadata to cloud, stores instance on `globalThis` |
| **API handler** | On each request to `/api/kognitive/*` | Exposes agent/workflow/tool endpoints for the dashboard Studio |
| **`createKognitiveMiddleware`** | On each matched request | Alternative: request-triggered sync for serverless |

## Installation

```bash
bun add @kognitivedev/next @kognitivedev/core
```

**Peer dependency:** `next >= 14.0.0`

## Quick start (3 files)

### 1. `kognitive.config.ts`

```typescript
import { Kognitive } from "@kognitivedev/core";

export default new Kognitive({
  apiKey: process.env.COGNITIVE_API_KEY,
  baseUrl: process.env.COGNITIVE_API_URL,
  agents: { /* assistant: myAgent */ },
  workflows: { /* onboarding: myWorkflow */ },
});
```

### 2. `next.config.ts`

```typescript
import { withKognitive } from "@kognitivedev/next";

export default withKognitive({
  /* your Next.js config */
});
```

### 3. `instrumentation.ts`

```typescript
import { register as registerKognitive } from "@kognitivedev/next/instrumentation";
import kognitive from "./kognitive.config";

export async function register() {
  await registerKognitive(kognitive);
}
```

### 4. `app/api/kognitive/[...path]/route.ts`

```typescript
export { GET, POST, OPTIONS } from "@kognitivedev/next/api-handler";
```

That's it. The dashboard can now execute agents, workflows, and tools via Studio.

### Edge-safe instrumentation

If your config imports Node.js built-in modules (e.g. `crypto`, `fs`), use dynamic imports:

```typescript
export async function register() {
  if (process.env.NEXT_RUNTIME === "nodejs") {
    const { register: registerKognitive } = await import("@kognitivedev/next/instrumentation");
    const { default: kognitive } = await import("./kognitive.config");
    await registerKognitive(kognitive);
  }
}
```

## API handler

The API handler (`@kognitivedev/next/api-handler`) auto-exposes all registered agents, workflows, and tools as REST endpoints:

| Method | Path | Action |
|--------|------|--------|
| GET | `/info` | Runtime info (protocol, version, counts) |
| GET | `/agents` | List agents |
| GET | `/agents/:name` | Agent metadata |
| POST | `/agents/:name/generate` | Execute agent (JSON) |
| POST | `/agents/:name/stream` | Stream agent (SSE) |
| GET | `/workflows` | List workflows |
| GET | `/workflows/:name` | Workflow metadata |
| POST | `/workflows/:name/execute` | Execute workflow (JSON) |
| POST | `/workflows/:name/stream` | Stream workflow (SSE) |
| POST | `/workflows/:name/resume` | Resume suspended workflow |
| GET | `/tools` | List tools |
| POST | `/tools/:id/execute` | Execute tool |

### Custom handler

```typescript
// app/api/kognitive/[...path]/route.ts
import { createKognitiveApiHandler } from "@kognitivedev/next/api-handler";
import { kognitive } from "@/lib/kognitive";

const { GET, POST, OPTIONS } = createKognitiveApiHandler({
  getKognitive: () => kognitive,
  apiKey: process.env.MY_RUNTIME_KEY, // optional auth override
});
export { GET, POST, OPTIONS };
```

### Custom mount path

If you mount at a different path (e.g. `app/api/runtime/[...path]/route.ts`), tell `register()`:

```typescript
await registerKognitive(kognitive, { basePath: "/api/runtime" });
```

## Security

Runtime endpoints are secured with an **auto-provisioned access token**:

1. During `register()`, the `sync()` call sends metadata to the Kognitive backend
2. The backend generates a `runtimeAccessToken` and returns it
3. The API handler validates incoming `Authorization: Bearer <token>` headers
4. The dashboard automatically uses the token when connecting to the instance

No manual key configuration needed. For manual override, set `RUNTIME_API_KEY` env var or pass `apiKey` to `createKognitiveApiHandler`.

## Middleware (alternative)

For serverless/edge setups where `instrumentation.ts` isn't available:

```typescript
// middleware.ts
import { createKognitiveMiddleware } from "@kognitivedev/next/middleware";
import { kognitive } from "./lib/kognitive";

export const middleware = createKognitiveMiddleware({ kognitive });
export const config = { matcher: "/api/:path*" };
```

## Environment variables

| Variable | Role |
|----------|------|
| `COGNITIVE_API_KEY` | Kognitive project API key |
| `COGNITIVE_API_URL` | API base URL (often `http://localhost:3001` in dev) |
| `COGNITIVE_SERVE_URL` | Optional; full public URL including base path (e.g. `https://myapp.com/api/kognitive`) |
| `RUNTIME_API_KEY` | Optional; manual auth key override for runtime endpoints |

### Serve URL

If `COGNITIVE_SERVE_URL` is not set, `register()` auto-detects the host and appends the `basePath` (default `/api/kognitive`):

1. `VERCEL_URL` → `https://{VERCEL_URL}/api/kognitive`
2. `PORT` → `http://localhost:{PORT}/api/kognitive`
3. Fallback → `http://localhost:3000/api/kognitive`

When `COGNITIVE_SERVE_URL` is set, it's used as-is — include the full base path yourself.

## Package exports

| Import | Description |
|--------|-------------|
| `@kognitivedev/next` | `withKognitive`, `createKognitiveMiddleware`, `createKognitiveApiHandler`, `getKognitive`, `setKognitive`, `hasKognitive` |
| `@kognitivedev/next/middleware` | `createKognitiveMiddleware` |
| `@kognitivedev/next/instrumentation` | `register(kognitive, options?)` |
| `@kognitivedev/next/api-handler` | `GET`, `POST`, `OPTIONS`, `createKognitiveApiHandler` |

## API overview

| Symbol | Description |
|--------|-------------|
| `withKognitive(nextConfig?)` | Adds `transpilePackages` and `instrumentationHook` |
| `register(kognitive, options?)` | Syncs to cloud, stores on `globalThis`; `options.basePath` defaults to `/api/kognitive` |
| `createKognitiveApiHandler(options?)` | Factory for custom route handlers |
| `GET` / `POST` / `OPTIONS` | Pre-built handlers using the global instance |
| `createKognitiveMiddleware({ kognitive })` | Request-triggered sync middleware |
| `getKognitive()` / `setKognitive()` / `hasKognitive()` | Global instance store |

## License

MIT