Skip to content
ZHIVEXDocs

Agents, tools, and sessions

Build a tool-using agent, add durable multi-turn sessions, and introduce approval boundaries.

TypeScriptStable
Current release guide · reviewed Sep 18, 2026

Use Agent when the model should choose whether to call tools or delegate work. Wrap it in Runner + SessionService when the experience belongs to a user-facing, multi-turn product.

Create an agent

import { Agent, tool } from "@zhivex-ai/sdk";
import { createOpenAI } from "@zhivex-ai/openai";
import { z } from "zod";

const openai = createOpenAI({ apiKey: process.env.OPENAI_API_KEY });

const agent = new Agent({
  model: openai("gpt-6-astra"),
  instructions: "Answer with verified account facts and keep replies short.",
  maxSteps: 3,
  tools: {
    lookupAccount: tool({
      name: "lookupAccount",
      schema: z.object({ accountId: z.string() }),
      execute: async ({ accountId }) => loadAccount(accountId)
    })
  }
});

const result = await agent.run({
  prompt: "Check account acct_123."
});

console.log(result.outputText);
console.log(result.state);

Every run returns serializable state with messages, steps, tool results, approvals, usage, status, schema version, and revision. Persist that state or attach an SDK run store when a process restart must not lose the run.

Add multi-turn sessions

import {
  createFileSessionService,
  createRunner
} from "@zhivex-ai/sdk";

const runner = createRunner({
  appName: "support-copilot",
  agent,
  sessionService: createFileSessionService({
    directory: ".zhivex/sessions"
  })
});

const first = await runner.run({
  userId: "user_123",
  sessionId: "demo",
  prompt: "Remember that I prefer short answers."
});

const second = await runner.run({
  userId: "user_123",
  sessionId: first.session.sessionId,
  prompt: "Summarize the account status."
});

File-backed sessions are useful for local development. Use Postgres for shared or serverless production deployments.

Pause before a side effect

Local tools can interrupt the run and wait for an application-owned approval decision:

const deploy = tool({
  name: "deploy",
  schema: z.object({ target: z.string() }),
  requiresApproval: true,
  approvalMode: "interrupt",
  approvalVersion: "2026-07-29",
  execute: async ({ target }, context) =>
    deployRelease(target, {
      signal: context?.abortSignal,
      idempotencyKey: context?.idempotencyKey
    })
});

The SDK can bind and persist approval state, but your application still owns identity, role checks, queue-token validation, expiration, audit records, and one-time consumption.

For a governed application boundary, TypeScript 1.5 exposes the Stable @zhivex-ai/agents/control-plane entrypoint. It composes capsules, tool policy, approval queues, ledgers, capability routing, inspectable runs, and durable single-consumer approval resume. This is a library contract, not a hosted control plane: the application still owns IAM, tenancy, secrets, storage, network policy, and the approval UI.

Observe execution without exposing full state

streamAgent() now emits additive agent-run-update events carrying AgentRunView: status, hierarchy, steps, token usage, tool counts and configured limits. Child runs carry their own run ID and parentRunId. Existing terminal events remain unchanged. These summaries omit prompts, tool arguments, scope and full state.

Use the React agent panel for a bounded live view and an authenticated run store for history. runAgentGroup() is not a streaming API; its results need an application-owned projection or coordinator to feed live summaries.

Agent or workflow?

  • Use an agent when the model chooses the next action.
  • Use a workflow when the application already knows the sequence.
  • Use subagents when the model should decide whether to delegate.
  • Use a parallel workflow group when application code always fans out.

For a product UI and server route, continue with the Next.js integration.

For model-directed delegation, continue with subagents. If application code already knows the order, use a workflow instead.

For low-latency audio or text sessions, use the Stable shared realtime lifecycle and streamLiveAgent() described in multimodal and realtime. Provider model IDs and preview availability remain provider-scoped even though the shared SDK contract is Stable.

Reconcile external effects

status: "completed" means the agent loop finished. The optional taskOutcome field on state and output distinguishes resolved, denied, failed, in_progress, and needs_reconciliation. Historical states may omit it. resolved means no unresolved journal entries remain; validate the application’s business result separately. An ordinary tool error does not automatically mean an external effect is indeterminate.

For an effect confirmed by an external system, the Beta reconcileAgentToolExecution API accepts application-verified evidence:

import { reconcileAgentToolExecution } from "@zhivex-ai/sdk";

const state = await reconcileAgentToolExecution({
  store,
  evidence,
  verifyEvidence: async (candidate, journal) =>
    externalLedger.verifyConfirmedEffect(candidate, journal)
});
const result = await runAgent(agent, { state, maxSteps: state.currentStep + 2 });

Here store, evidence, and externalLedger are application-owned. Evidence must bind the operation ID, run, scope, tool call, exact input, confirmed output, source and proof. The verifier must authenticate the external receipt and tenant, not unconditionally return true. The API currently supports FileAgentRunStore and InMemoryAgentRunStore; SQL stores reject it until they implement equivalent fencing.

Reconciliation records its decision and previous outcome/output in the journal before updating state with compare-and-swap. Repeating identical evidence recovers a crash between those writes and is idempotent. An active worker or conflicting or rejected evidence keeps the operation blocked. Successful reconciliation queues the state; continuation is still required. Do not manually edit journal entries or replay an uncertain mutation. Use a new operation ID for a new intentional effect.

See the versioned reconciliation contract.

Zhivex AI SDKsPortable by default. Native when needed.
Copied