Skip to content
Docs menu

Embed the harness

Run a first venom session from Node, from a Next.js route handler and from a background worker, with state kept where your app wants it.

View .md

This page gets a session running inside your own program. It assumes the package is installed (install) and a model server is reachable: by default the harness talks to http://localhost:8787/v1, a local venom orchestrator.

A first session

import { createVenomSession, provider } from "@venom/harness";

const session = await createVenomSession({
  cwd: "/srv/work/repo",                                 // the workspace the agent works in
  mode: "accept-edits",                                  // edits in the workspace go ahead; commands ask
  provider: provider.providerOptionsFromEnv(process.env), // VENOM_BASE_URL, VENOM_API_KEY, VENOM_MODEL
  audit: false,                                          // don't write ~/.venom/audit.jsonl
  compat: false,                                         // ignore CLAUDE.md, .claude/ and .mcp.json in the workspace
});
try {
  const answer = await session.prompt("Run the tests and fix the first failure.");
  console.log(answer);                                   // the final assistant text
} finally {
  session.dispose();
}

createVenomSession is createHarness(options).createSession(options) in one call. prompt resolves when the agent's run ends. No approver is set here, so any call the policy would ask about (a shell command in accept-edits) is denied with a reason the model reads. Your own tools and approvals shows how to answer those asks.

Nothing is read from the environment unless you pass it: providerOptionsFromEnv(process.env) is an explicit choice. Without provider, the session uses http://localhost:8787/v1, no key and the model venom-default.

Several sessions in one process

A harness holds a workspace, a mode, rules, an audit sink and the trust state. Create one per tenant, job or workspace; they share nothing.

import { createHarness, MemoryAuditSink, provider } from "@venom/harness";

const providerOpts = { ...provider.providerOptionsFromEnv(process.env), discover: false };
const reviewer = createHarness({ cwd: reviewDir, mode: "plan", audit: new MemoryAuditSink(), compat: false, provider: providerOpts });
const writer = createHarness({ cwd: writeDir, mode: "accept-edits", audit: new MemoryAuditSink(), compat: false, provider: providerOpts });

const [r, w] = await Promise.all([reviewer.createSession(), writer.createSession()]);
const [review, edit] = await Promise.all([
  r.prompt("Review util.js for bugs. Do not change anything."),
  w.prompt("Append a line to NOTES.md."),
]);
r.dispose(); w.dispose();
await Promise.all([reviewer.close(), writer.close()]);

discover: false skips the background GET /v1/models model discovery, which is useful when you already know the model. harness.close() stops the egress proxy, the sandbox's network namespace on Linux, and language servers the sessions started.

Where state goes

By default the harness keeps state where the CLI does. For a service, give each tenant or job its own directories.

Option Default What lives there
home os.homedir() the home directory used to find user-level config (~/.claude, ~/.venom)
venomHome ~/.venom audit.jsonl, the model list cache, spill files for masked tool output, file checkpoints, language server caches, the code index, inbox and task files
agentDir ~/.venom/agent pi's saved sessions, when persist: true
audit JSONL at <venomHome>/audit.jsonl any AuditSink, or false
checkpoints on when git is installed false turns off the shadow git store of file checkpoints

An organisation policy file (/etc/venom/policy.json, or VENOM_POLICY_FILE) is read by every harness unless you pass policy: null or your own loaded OrgPolicy; its audit path cannot be turned off. See the security section.

Untrusted workspaces

A session loads the Claude Code files it finds in the workspace (CLAUDE.md, .claude/settings.json, skills, commands, agents, .mcp.json, plugins). A project's hooks, MCP servers and allow rules apply only once the project is trusted, which an app grants with projectTrusted: true or a trust callback; nothing asks on its own. For code you did not write (a customer upload, a CI checkout of a fork), pass compat: false to turn all of it off. Details: Claude Code compatibility.

In a Next.js route handler

The harness spawns processes, reads the file system and keeps long-lived objects, so it runs in the Node.js runtime of a server you control, not in an edge runtime. Keep it out of the bundler:

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

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

A route handler that runs one prompt and streams the harness's events to the browser as Server-Sent Events:

// app/api/agent/route.ts
import { createVenomSession, provider } from "@venom/harness";

export const runtime = "nodejs";

export async function POST(req: Request) {
  const { prompt, workspace } = (await req.json()) as { prompt: string; workspace: string };
  // Authenticate the caller and resolve `workspace` to a directory this tenant owns before this line.
  const session = await createVenomSession({
    cwd: workspace,
    mode: "plan",                       // read-only for this endpoint
    compat: false,
    audit: false,
    venomHome: `/var/lib/myapp/venom/${encodeURIComponent(workspace)}`,
    provider: provider.providerOptionsFromEnv(process.env),
  });
  const enc = new TextEncoder();
  const stream = new ReadableStream({
    async start(controller) {
      const off = session.subscribe((e) => {
        if (e.source === "harness") controller.enqueue(enc.encode(`data: ${JSON.stringify(e.event)}\n\n`));
      });
      try {
        const text = await session.prompt(prompt);
        controller.enqueue(enc.encode(`event: done\ndata: ${JSON.stringify({ text })}\n\n`));
      } catch (err) {
        controller.enqueue(enc.encode(`event: error\ndata: ${JSON.stringify({ message: String(err) })}\n\n`));
      } finally {
        off();
        session.dispose();
        await session.harness.close();
        controller.close();
      }
    },
  });
  return new Response(stream, { headers: { "content-type": "text/event-stream", "cache-control": "no-store" } });
}

Agent runs take minutes, and an approval can wait on a person. On a serverless platform with short function limits, run sessions in a long-lived worker instead and let the web app talk to it: embed createHarnessServer from @venom/harness-server in that worker, or run venom serve, and call it from the route handler. That also gives you approvals answered from another request (server API section).

In a background worker

A queue consumer is the simplest home for unattended runs:

import { createVenomSession, MemoryAuditSink, provider } from "@venom/harness";

export async function handleJob(job: { id: string; workspace: string; goal: string }) {
  const audit = new MemoryAuditSink();
  const session = await createVenomSession({
    cwd: job.workspace,
    mode: "accept-edits",
    audit,
    compat: false,
    venomHome: `/var/lib/myapp/jobs/${job.id}`,
    provider: provider.providerOptionsFromEnv(process.env),
    guards: { maxToolCalls: 150, maxSeconds: 900 },   // stop runaway loops
  });
  try {
    return { text: await session.prompt(job.goal), decisions: audit.records };
  } finally {
    session.dispose();
    await session.harness.close();
  }
}

guards caps a run (repeated calls, re-reads, tool calls, turns, seconds, cost); the full table is in Sessions, events and cost.

Troubleshooting

Symptom Cause and fix
The server at http://localhost:8787/v1 rejected the API key. Set VENOM_API_KEY to a key it accepts Pass apiKey in provider, or set VENOM_API_KEY and use providerOptionsFromEnv
The first prompt fails at once naming VENOM_BASE_URL The model server did not answer GET /models within 3 s (preflightTimeoutMs). Check baseUrl includes /v1
A 404 naming the model, with a list of served models The server does not serve venom-default. Set defaultModel, or aliasMap / VENOM_ALIAS_MAP=venom-default=<model>
TS1543 or errors inside pi's .d.ts files Set "skipLibCheck": true
Every shell command is denied No approve callback and the mode asks for commands. Add an approver, rules.allow, or a mode that allows them
PolicyError thrown by createHarness The organisation policy file on that machine is invalid. Fix it, or pass policy: null only where no policy should apply