---
title: Embed the harness
description: 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.
section: harness
order: 10
audience: [builder, agent]
sources: [packages/harness/src/session.ts, packages/harness/examples/headless-fix.ts, packages/harness/examples/parallel-sessions.ts, docs/build-an-agent-app.md]
features: [harness.core]
---

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

## A first session {#first}

```ts
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](/docs/harness/tools-and-approvals.md) 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 {#parallel}

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.

```ts
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 {#state}

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](/docs/security.md).

## Untrusted workspaces {#untrusted}

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](/docs/harness/claude-code-compat.md).

## In a Next.js route handler {#nextjs}

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:

```ts
// 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:

```ts
// 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](/docs/server-api.md)).

## In a background worker {#worker}

A queue consumer is the simplest home for unattended runs:

```ts
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](/docs/harness/sessions.md#options).

## Troubleshooting {#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 |

## Related {#related}

- [Sessions, events and cost](/docs/harness/sessions.md)
- [Your own tools and approvals](/docs/harness/tools-and-approvals.md)
- [Model provider](/docs/harness/providers.md)
- [Server API section](/docs/server-api.md)
