---
title: Sessions, events and cost
description: Every HarnessOptions and CreateSessionOptions field, the event stream a session emits, saved sessions and how to read a session's cost.
section: harness
order: 20
audience: [builder, agent]
sources: [packages/harness/src/session.ts, packages/harness/src/harness.ts, packages/harness/src/types.ts, packages/harness/src/sessions.ts, packages/harness/AGENTS.md]
features: [harness.cost]
---

A harness (`createHarness(options)`) holds the policy and state for one workspace; a session (`harness.createSession(options)`) is one conversation with the model on top of it. One harness can create many sessions. This page is the reference for both.

## The objects {#objects}

```ts
const harness = createHarness(options);          // VenomHarness
const session = await harness.createSession(o);  // VenomSession

session.prompt(text): Promise<string>            // runs the agent; resolves with the final assistant text
session.events(): AsyncIterableIterator<VenomSessionEvent>  // session + harness events; ends on dispose
session.subscribe(listener): () => void          // the same events, push style; returns an unsubscribe
session.session                                  // pi's AgentSession: models, steering, the message list
session.dispose()

harness.mode / harness.setMode(mode)             // a mode the organisation policy forbids is capped
harness.evaluate(req): Verdict                   // pure policy check, no hooks, no approval
harness.addSessionRule("bash(npm test:*)")       // an allow rule for this harness's lifetime
harness.on((e: HarnessEvent) => …)               // harness events only
harness.checkpoints                              // undo / redo / restore of the agent's file changes
harness.close()                                  // stop the egress proxy, sandbox namespace, language servers
```

`session.session` is the escape hatch for anything the wrapper does not cover: switching models, steering a running prompt, aborting (`session.session.abort()`), reading messages.

## HarnessOptions {#options}

Every field is optional.

| Option | Default | What it does |
|---|---|---|
| `cwd` | `process.cwd()` | the workspace root |
| `home`, `venomHome`, `agentDir` | `os.homedir()`, `~/.venom`, `~/.venom/agent` | state locations ([where state goes](/docs/harness/embedding.md#state)) |
| `mode` | config, then Claude's `defaultMode`, then `default` | initial permission mode: `plan`, `default`, `accept-edits`, `auto`, `yolo` |
| `rules` | none | `{ allow, ask, deny }` rule strings from your app, treated as trusted ([rules](/docs/harness/permissions.md#rules)) |
| `approve` | `denyApprover` | your approval callback ([approvals](/docs/harness/tools-and-approvals.md#approver)) |
| `trust` | do not trust | called when a project ships hooks, MCP servers or allow rules; answer `true`, `false`, `undefined` (decide later) or `"parent"` |
| `projectTrusted` | pi's trust store plus venom's content record | force trust on or off |
| `onEvent` | none | a listener for every `HarnessEvent` |
| `audit` | `<venomHome>/audit.jsonl` | an `AuditSink`, or `false` |
| `policy` | `/etc/venom/policy.json`, else `VENOM_POLICY_FILE` | an `OrgPolicy` you loaded, or `null` for none. An invalid file throws `PolicyError` |
| `provider` | `http://localhost:8787/v1`, no key | `VenomProviderOptions`, or `false` ([Model provider](/docs/harness/providers.md)) |
| `compat` | all on | `false`, or `{ memory, skills, commands, agents, mcp, settings, hooks, plugins, user }` |
| `contextFiles` | `true` | load memory files (`AGENTS.md`, `CLAUDE.md`) |
| `sandbox` | `"auto"` (on in `yolo`) | OS sandbox for bash: `true`, `false`, `"auto"` |
| `sandboxNetwork` | permission files, else the default allowlist | `true` (any host), `false` (none) or `{ allow: string[], defaults?: boolean }` |
| `sandboxAvailable` | detected | force whether an OS sandbox exists (tests, a container that is itself the boundary) |
| `subagents` | on: concurrency 4, 6000-character reports, 25 turns | `false` or `{ concurrency, maxReportChars, defaultModel, maxTurns }` |
| `models` | `fast` = `venom-fast`, `smart` = `venom-smart` when listed, else the session's model | `{ main?, fast?, smart? }` model tiers ([subagents](/docs/harness/subagents.md#tiers)) |
| `escalation` | `{ max: 1, to: "smart" }` | re-run a failed fast-tier subagent once on a stronger tier, or `false` |
| `agentModels` | none | a model per agent name |
| `workspaces` | none | a git worktree per writing subagent ([subagents](/docs/harness/subagents.md#worktrees)) |
| `runtime` | `RUNTIME_DEFAULTS` | process quotas (`quotas.maxProcs`, `maxTokens`, `maxCost`) and scheduler pools |
| `kernel` | its own | a `RuntimeKernel` shared with other harnesses, so their agents are scheduled fairly together |
| `guards` | repeat 3, re-reads 6, 200 calls per run, turns unbounded, bash 120 s | `{ repeatThreshold, maxRereads, maxToolCalls, maxTurns, maxSeconds, maxCost, wrapupTurns, bashTimeout, overthink }`; 0 turns one off |
| `thinking` | `venom-fast` off, `venom-default` medium | `{ byModel: { "<model>": "off" \| "minimal" \| "low" \| "medium" \| "high" \| "xhigh" } }` |
| `planning` | on | plan mode and the `todo` tool |
| `network` | `"online"` | `"offline"` removes the web tools and disables remote MCP servers |
| `web` | on | `false`, or `{ searchUrl, search, orchestrator, rerank, maxBytes, timeoutMs, maxRedirects }` for `web_fetch` and `web_search` |
| `searchScope` | `"default"` | `"self-hosted"`: `web_search` uses SearxNG only |
| `browser` | off | `true` or `{ mode: "launch" \| "attach" \| "extension", headless, … }`: the browser tools |
| `injection` | all on | `false` or `{ guidance, spotlight, detect }` prompt-injection defences |
| `checkpoints` | on when git is installed | `false`, or `{ maxFileBytes, maxTotalBytes, maxFiles, exclude, retention, dir }` |
| `compaction` | on | `false`, or `{ triggerRatio: 0.55, keepTurns: 10, minMaskChars: 600, summaryModel: "venom-fast" }` |
| `format` | on | `false`, or `{ timeoutMs: 3000, formatters }`: run the project's own formatter after edits |
| `lsp` | on | `false`, or `{ servers, timeoutMs: 1500, severity, maxServers: 4, … }`: language-server diagnostics after edits |
| `editTool` | `"auto"` | `"edit"`, `"apply_patch"`, `"both"` or `"auto"` (per model) |
| `exec` | on for main agents, 4 sessions | `false` or `{ maxSessions }`: long-lived command sessions |
| `plugins` | discovered | `false`, or `{ dev, builtin }` |
| `fileSystem` | the disk | `{ readTextFile?, writeTextFile? }`: an editor's view of files, unsaved buffers included |
| `autoClassifier`, `autoDecider` | a fast-tier completion; the `venom-decide` alias | `auto` mode's classifier and advisory decider |
| `visionModel`, `visionDescriber` | `venom-vision` | describes images for a text-only model |
| `promptHookEvaluator` | a `venom-fast` completion | evaluates `type: "prompt"` hooks |
| `compactionDecider` | none | a relevance pass before each compaction summary |
| `summaries` | on, local only | session summaries in `<venomHome>/sessions/summaries/`; `false` for none |
| `outcomes`, `orgMemory`, `library` | none | Venom Cloud `{ url, key }` for outcome reports, org memory and the team library |
| `routeProfile`, `gear`, `experiment` | none | sent as `x-venom-profile`, `x-venom-gear`, `x-venom-experiment` on model requests |
| `explicitModel` | `false` | the host picked the model: Claude settings' `model` is not applied |
| `modeShortcut`, `sudoShortcut` | `alt+m`, `alt+s` | terminal keys, for hosts with a TUI |

## CreateSessionOptions {#session-options}

| Option | Default | What it does |
|---|---|---|
| `model` | the provider's `defaultModel` | model id or alias for this session |
| `modelProvider` | `venom` | pi provider name |
| `persist` | `false` | write pi's JSONL transcript under `<agentDir>/sessions/--<cwd>--/` |
| `sessionFile` | none | reopen that saved session and append to it (implies `persist`) |
| `tools` | venom's set | restrict the tool list |
| `systemPrompt`, `appendSystemPrompt` | venom's | replace or extend the system prompt |
| `thinkingLevel` | `off` | `off` to `xhigh` |
| `extensions` | none | your own pi extensions (`InlineExtension[]`), loaded after venom's ([tools](/docs/harness/tools-and-approvals.md)) |
| `loadPlugins` | `true` | load plugins discovery allows |
| `loadUserExtensions` | `false` | load the user's own pi extensions |

Keep the system prompt stable across turns: venom builds it once per session so the model server's prompt cache keeps hitting. Put per-turn data in the prompt text, not in `appendSystemPrompt`.

## Events {#events}

`session.events()` yields `{ source: "session", event }` for pi's own events (`message_update`, `tool_execution_start`, `tool_execution_end`, `turn_end`, …) and `{ source: "harness", event }` for the harness's. Harness events are the exported `HarnessEvent` union, discriminated by `type`:

| `type` | When |
|---|---|
| `permission` | every gated tool call; `record` is the audit record (tool, summary, verdict, outcome, `via`, reason, rule) |
| `mode` | the permission mode changed |
| `todos` | the agent updated its checklist |
| `subagents` | subagents started, progressed or finished |
| `compaction` | context was compacted (`tokensBefore`, `tokensAfter`, `masked`, `trigger`) |
| `egress` | the sandbox denied a network connection (`host`, `port`, `hint`) |
| `lsp` | diagnostics after an edit (`errors`, and `dependents` when files depending on it were checked) |
| `format` | the project's formatter ran after an edit |
| `edit-tool` | which file-editing tools the model got |
| `test-edit` | advisory: an edit changed only a test's expected values |
| `checkpoint` | a snapshot, undo, redo or restore |
| `guard` | a runaway guard fired (`repeat`, `reread`, `tool-limit`, `turn-limit`, `overthink`) |
| `injection` | advisory: a tool result looked like a prompt injection |
| `hook` | a hook ran |
| `diagnostic`, `notice` | warnings, and slash-command output in a session without a UI |
| `agent`, `span`, `memory` | the agent runtime's process table, trace spans and the context memory layer |

```ts
for await (const e of session.events()) {
  if (e.source === "session" && e.event.type === "tool_execution_start") console.log(`[tool] ${e.event.toolName}`);
  else if (e.source === "harness" && e.event.type === "permission")
    console.log(`[perm] ${e.event.record.outcome} ${e.event.record.summary}`);
}
```

Over HTTP the same events have schemas (`HarnessEvent` in the harness server's OpenAPI document), with one rename: the `injection` event's `source` is sent as `origin`.

## Cost {#cost}

Each assistant message carries its token usage. `@venom/harness/cost` prices it at the bundled list price of the model that served it (an orchestrator alias at its cloud target, local models at 0):

```ts
import { cost } from "@venom/harness";

await session.prompt("…");
const est = cost.estimateSessionCost(session.session.messages);
console.log(cost.formatLocalCost(est));
```

`cost.contextBreakdown({ systemPrompt, tools, messages, contextWindow })` returns what fills the context window by category (system prompt, tools, memory files, messages), calibrated against the server's reported prompt tokens; the CLI's `/context` prints it with `formatContextBreakdown`. With `provider.adminToken` (`VENOM_ADMIN_TOKEN`), `/cost` reads the orchestrator's own figures for the session instead of estimating. To cap spend, set `guards.maxCost` or `runtime.quotas.maxCost`.

## Saved sessions {#saved}

With `persist: true`, pi writes the transcript as JSONL. These work without opening a session:

| Function | Returns |
|---|---|
| `listPersistedSessions({ agentDir?, cwd? })` | `PersistedSession[]` (`id`, `path`, `cwd`, `name`, `created`, `modified`, `messageCount`, `firstMessage`), newest first; every workspace when `cwd` is omitted |
| `findPersistedSession(id, { agentDir?, cwd? })` | one session by id |
| `resolveSessionRef(ref, { agentDir?, cwd? })` | a `.jsonl` path, `latest`, an id or a unique prefix, to `{ path, id? }` or `{ error }` |
| `sessionDirFor(agentDir, cwd)` | the directory a workspace's sessions are saved in |

Reopen one with `createSession({ sessionFile: path })`. Session handoff between machines (`exportSession`, `importSession`, leases) and replay (`runReplay`) are exported from the root entry too; the CLI side is in [the automation section](/docs/automation.md).

## Related {#related}

- [Embed the harness](/docs/harness/embedding.md)
- [The permission engine](/docs/harness/permissions.md)
- [Entry points](/docs/harness/entry-points.md)
