Skip to content
Docs menu

Embed the harness in a Next.js app

Build a Next.js 16 app that streams a venom agent's answer to the browser, then move the sessions to a venom serve worker and answer the agent's approvals from the page.

View .md

Two versions of the same small app. The first runs the agent inside the Next.js server process: good for an internal tool on one machine. The second keeps Next.js thin and runs sessions in venom serve, which survives long runs and lets a person approve the agent's commands from the page. Both use the App Router of Next.js 16 and its Node.js runtime; the harness spawns processes and reads files, so it never runs in an edge runtime.

You need Node 22.19 or newer, a model endpoint (local or cloud) and the harness tarballs (install).

Set up the project

npx create-next-app@latest agent-app --ts --app --eslint --use-npm
cd agent-app
npm install /path/to/venom-harness-<version>.tgz /path/to/venom-harness-server-<version>.tgz

Keep the libraries out of the bundler, and turn on skipLibCheck (pi's declaration files do not type-check under NodeNext):

// next.config.ts
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  serverExternalPackages: ["@venom/harness", "@venom/harness-server"],
};
export default nextConfig;
{ "compilerOptions": { "skipLibCheck": true } }

The model endpoint comes from the server's environment, as for the CLI:

# .env.local
VENOM_BASE_URL=http://localhost:8787/v1
VENOM_API_KEY=…

Version 1: the agent in a route handler

The route handler starts a session, forwards the assistant's text as it is generated plus a line per tool call, and stops the run when the browser goes away. Embedding has a variant that forwards the raw harness events instead.

// app/api/agent/route.ts
import { createVenomSession, provider } from "@venom/harness";
import { currentUserId } from "@/lib/auth";      // your own auth

export const runtime = "nodejs";
export const maxDuration = 300;                    // seconds, where the platform honours it

export async function POST(req: Request) {
  const userId = await currentUserId(req);
  const { prompt } = (await req.json()) as { prompt: string };
  const session = await createVenomSession({
    cwd: `/srv/agent-app/workspaces/${userId}`,    // a directory only this user's runs see
    venomHome: `/srv/agent-app/venom/${userId}`,
    mode: "plan",                                  // read-only: no edits, no commands
    compat: false, plugins: false, audit: false,
    provider: provider.providerOptionsFromEnv(process.env),
  });

  const enc = new TextEncoder();
  const stream = new ReadableStream<Uint8Array>({
    async start(controller) {
      const send = (event: string, data: unknown) => {
        try { controller.enqueue(enc.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`)); } catch { /* closed */ }
      };
      const stop = () => void session.session.abort();
      req.signal.addEventListener("abort", stop, { once: true });
      const off = session.subscribe((e) => {
        if (e.source !== "session") return;
        const ev = e.event;
        if (ev.type === "message_update" && ev.assistantMessageEvent.type === "text_delta")
          send("delta", { text: ev.assistantMessageEvent.delta });
        else if (ev.type === "tool_execution_start") send("tool", { name: ev.toolName });
      });
      try {
        send("done", { text: await session.prompt(prompt) });
      } catch (err) {
        send("error", { message: String(err) });
      } finally {
        off();
        req.signal.removeEventListener("abort", stop);
        session.dispose();
        await session.harness.close();
        try { controller.close(); } catch { /* already closed */ }
      }
    },
  });
  return new Response(stream, { headers: { "content-type": "text/event-stream", "cache-control": "no-store" } });
}

The page posts the prompt and reads the stream with fetch (an EventSource can only send GET):

// app/page.tsx
"use client";
import { useState } from "react";

export default function Page() {
  const [prompt, setPrompt] = useState("");
  const [answer, setAnswer] = useState("");
  const [tools, setTools] = useState<string[]>([]);
  const [busy, setBusy] = useState(false);

  async function run() {
    setBusy(true); setAnswer(""); setTools([]);
    const res = await fetch("/api/agent", {
      method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ prompt }),
    });
    const reader = res.body!.pipeThrough(new TextDecoderStream()).getReader();
    let buf = "";
    for (;;) {
      const { value, done } = await reader.read();
      if (done) break;
      buf += value;
      for (let i = buf.indexOf("\n\n"); i >= 0; i = buf.indexOf("\n\n")) {
        const block = buf.slice(0, i);
        buf = buf.slice(i + 2);
        const event = /^event: (.*)$/m.exec(block)?.[1];
        const data = JSON.parse(/^data: (.*)$/m.exec(block)?.[1] ?? "null");
        if (event === "delta") setAnswer((a) => a + data.text);
        else if (event === "tool") setTools((t) => [...t, data.name]);
        else if (event === "error") setAnswer((a) => `${a}\n\n[error] ${data.message}`);
      }
    }
    setBusy(false);
  }

  return (
    <main>
      <textarea value={prompt} onChange={(e) => setPrompt(e.target.value)} />
      <button onClick={run} disabled={busy || !prompt}>Ask</button>
      <p>{tools.map((t, i) => <code key={i}>{t} </code>)}</p>
      <pre>{answer}</pre>
    </main>
  );
}

Run npm run dev, open http://localhost:3000, and ask "What does this project do?" with a checkout in the user's workspace directory.

Limits of this version: a run lives as long as the request, plan mode means the agent never edits or runs commands, and no one can approve anything because there is no approver. A host with short function limits cuts long runs off. Version 2 removes all three.

Version 2: sessions in a venom serve worker

Start the worker on a machine you control (the same one in development):

export VENOM_SERVER_TOKEN=$(openssl rand -hex 32)
export VENOM_BASE_URL=http://localhost:8787/v1 VENOM_API_KEY=…
venom serve --root /srv/agent-app/workspaces --approval-timeout 300

It listens on 127.0.0.1:8790. Give the Next.js server the same token (VENOM_SERVER_TOKEN in .env.local) and one client:

// lib/venom.ts
import { HarnessClient } from "@venom/harness-server/client";

export const venom = new HarnessClient({
  baseUrl: "http://127.0.0.1:8790",
  token: process.env.VENOM_SERVER_TOKEN!,
});

Three route handlers: start a run, follow its events, answer an approval. Check in each that the session belongs to the signed-in user (keep the mapping in your database); the token gives full access to the worker.

// app/api/runs/route.ts
import { venom } from "@/lib/venom";
import { currentUserId } from "@/lib/auth";

export async function POST(req: Request) {
  const userId = await currentUserId(req);
  const { prompt } = (await req.json()) as { prompt: string };
  const s = await venom.createSession({
    cwd: `/srv/agent-app/workspaces/${userId}`,
    mode: "default",            // edits and commands ask
    compat: false,
    approvalTimeoutMs: 300_000, // a person has five minutes to answer
  });
  await venom.prompt(s.id, prompt);
  return Response.json({ id: s.id });
}
// app/api/runs/[id]/events/route.ts
import { venom } from "@/lib/venom";

export async function GET(req: Request, ctx: { params: Promise<{ id: string }> }) {
  const { id } = await ctx.params;
  const enc = new TextEncoder();
  const stream = new ReadableStream<Uint8Array>({
    async start(controller) {
      try {
        for await (const e of venom.events(id, { after: 0, signal: req.signal })) {
          controller.enqueue(enc.encode(`data: ${JSON.stringify(e)}\n\n`));
          if (e.type === "prompt_end") break;
        }
        await venom.closeSession(id);
      } catch { /* the browser left, or the session closed */ }
      try { controller.close(); } catch { /* already closed */ }
    },
  });
  return new Response(stream, { headers: { "content-type": "text/event-stream", "cache-control": "no-store" } });
}
// app/api/runs/[id]/approvals/[approvalId]/route.ts
import { venom } from "@/lib/venom";

export async function POST(req: Request, ctx: { params: Promise<{ id: string; approvalId: string }> }) {
  const { id, approvalId } = await ctx.params;
  const { action, feedback } = (await req.json()) as { action: "allow-once" | "deny"; feedback?: string };
  return Response.json(await venom.decide(id, approvalId, { action, ...(feedback ? { feedback } : {}) }));
}

The page opens an EventSource on the events route and shows each approval_request with two buttons:

// app/runs/page.tsx
"use client";
import { useState } from "react";

type Ask = { approvalId: string; summary: string; reason: string };

export default function Runs() {
  const [run, setRun] = useState<string>();
  const [answer, setAnswer] = useState("");
  const [asks, setAsks] = useState<Ask[]>([]);

  async function start(prompt: string) {
    const { id } = await (await fetch("/api/runs", {
      method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ prompt }),
    })).json();
    setRun(id); setAnswer(""); setAsks([]);
    const es = new EventSource(`/api/runs/${id}/events`);
    es.onmessage = (m) => {
      const e = JSON.parse(m.data);
      if (e.type === "message_update" && e.assistantMessageEvent?.type === "text_delta")
        setAnswer((a) => a + e.assistantMessageEvent.delta);
      else if (e.type === "approval_request") setAsks((q) => [...q, e]);
      else if (e.type === "approval_resolved") setAsks((q) => q.filter((a) => a.approvalId !== e.approvalId));
      else if (e.type === "prompt_end") es.close();
    };
  }

  const decide = (a: Ask, action: "allow-once" | "deny") =>
    fetch(`/api/runs/${run}/approvals/${a.approvalId}`, {
      method: "POST", headers: { "content-type": "application/json" },
      body: JSON.stringify(action === "deny" ? { action, feedback: "Not approved by the user." } : { action }),
    });

  return (
    <main>
      <button onClick={() => start("Run the tests and fix the first failure.")}>Fix the first failing test</button>
      {asks.map((a) => (
        <div key={a.approvalId}>
          <code>{a.summary}</code> <small>{a.reason}</small>
          <button onClick={() => decide(a, "allow-once")}>Allow</button>
          <button onClick={() => decide(a, "deny")}>Deny</button>
        </div>
      ))}
      <pre>{answer}</pre>
    </main>
  );
}

Events from venom serve carry seq, source and type, with pi's session events flattened into them, so a text delta is {type: "message_update", assistantMessageEvent: {type: "text_delta", delta}}. An unanswered approval is denied when approvalTimeoutMs runs out (the server caps it at 10 minutes unless started with a longer --approval-timeout). To reconnect after a dropped stream, pass after with the last seq you saw.

Production notes

  • Where the worker runs. On your own server or container next to the workspaces it edits, never on the edge. The Next.js app can be anywhere that reaches it; keep port 8790 on a private network.
  • Approvals that wait hours do not fit a timeout. Let the agent write a proposal your own UI acts on, as in the SaaS design.
  • Cost. Each session's usage is in its events and in the worker's transcript; for limits per user, give each user a key with a budget on the orchestrator (keys and budgets).
  • Lock the policy down with rules and tools on createSession (permissions).

Troubleshooting

Symptom Cause and fix
Module not found for a pi package, or errors from bundling node:child_process serverExternalPackages is missing one of the two packages
TS1543 or type errors inside @earendil-works/* Set "skipLibCheck": true
The first prompt fails naming VENOM_BASE_URL The model endpoint did not answer GET /models within 3 s; check the URL includes /v1
401 from the worker VENOM_SERVER_TOKEN differs between venom serve and the app
403 root_not_allowed creating a session cwd is outside the worker's --root directories
Every command is denied in version 2 No one answered in time; check the page receives approval_request events