Skip to contentSkip to page list

Docs

npx langwatch

Trace any coding agent · Setup guide →

TypeScript Connected Agent Reference

API reference for connectAgent from langwatch/agent, the wrapper that makes a Node handler a LangWatch simulation target, with its options, turn fields, parameter definitions and reply types.

On this page

connectAgent()

Registers a handler as a simulation target. The SDK opens one outbound connection per process, registers the agent with its name, its environment and its declared parameters, and calls the handler once per conversation turn.

example.tsTypeScript
import { z } from "zod";import { connectAgent } from "langwatch/agent";​export const supportAgent = connectAgent(  {    name: "support-agent",    environment: process.env.APP_ENV ?? "development",    parameters: z.object({      model: z.enum(["gpt-6-sol", "gpt-6-luna"]).default("gpt-6-luna"),      plan: z.string().default("free").describe("Customer plan"),      maxTools: z.number().int().default(5),    }),  },  async ({ messages, params }) => {    // params is typed: { model: "gpt-6-sol" | "gpt-6-luna"; plan: string; maxTools: number }    return await runMyAgent(messages, { model: params.model });  },);

The entry point is Node only, and zod declares the run parameters, so a project installs langwatch zod. connectAgent returns the handler, so supportAgent({ messages }) calls it directly and a unit test needs no connection. The returned function also exposes .disconnect(), which closes the connection and drops the agent from the presence list.

The process connects only with an API key. The SDK reads LANGWATCH_API_KEY from the environment, logs one line when it is absent, and lets the process run.

ConnectAgentOptions

OptionTypeDefaultEffect
namestringrequiredThe agent's name, and the first half of a connected:<name>@<environment> target.
environmentstringresolved, see belowThe environment row this process registers under.
descriptionstringnoneOne line about the agent, shown on the agents page.
parameterszod schema, definition map or JSON SchemanoneWhat the agent accepts from a run.
enabledbooleantrue, false when CI is setWhether this process connects.
instanceLabelstringnoneA name for this instance in the instances table.
timeoutMsnumber120000Milliseconds one call may take. The ceiling is 300000.
concurrencynumber10Calls this instance takes at the same time.
stickybooleanfalseKeep every turn of one conversation on one instance.
apiKeystringLANGWATCH_API_KEYThe key the connection authenticates with.
endpointstringLANGWATCH_ENDPOINTThe LangWatch instance to connect to.
projectIdstringnoneThe project, for a key that covers more than one.
transport"websocket" | "http"websocketSee Transport.

Environment resolution

environment, then LANGWATCH_AGENT_ENVIRONMENT, then APP_ENV, ENVIRONMENT and NODE_ENV, then development.

development makes the agent personal: it belongs to the API key's owner when the key is personal, and to the machine, identified by its hostname, when the key is a project key. Every other name is shared by the project. See Environments and personal agents.

The handler argument

The handler receives one object.

FieldTypeValue
messagesMessage[]The whole conversation so far, as OpenAI-style messages
newMessagesMessage[]The messages added since the previous turn
threadIdstringThe platform's conversation id, the same on every turn of one run
sessionunknownWhat the handler returned as session on the previous turn, null on the first
stateRecord<string, unknown> | nullThe scenario's state: what the setup hook returned, as the latest turn updated it, null without one
paramstyped from parametersThe run's values for the declared parameters
traceIdstringThe id of the turn's trace

parameters

Three forms, all of which reach the platform as the same declaration.

A zod schema, the form the example above uses. params is typed from it:

example.tsTypeScript
parameters: z.object({  model: z.enum(["gpt-6-sol", "gpt-6-luna"]).default("gpt-6-luna"),  plan: z.string().default("free").describe("Customer plan"),  maxTools: z.number().int().default(5),})
In the schemaEffect
z.enum([...])A closed list of allowed values, up to 50. A value outside it is refused.
.default(value)The default the run dialog prefills
.describe(text)Shown beside the field in the run dialog
z.string(), z.number(), z.boolean()The parameter's type

Give every property a default, or the run must supply a value for it. Keep the schema flat and scalar: nested objects and arrays are not run parameters.

Pass the schema object itself, never schema["~standard"].jsonSchema and never a validator instance. The SDK reads the JSON Schema converter the object carries under "~standard", so valibot, arktype and any other Standard Schema library work the same way, and the SDK imports none of them.

A definition map, for a project with no schema library:

example.tsTypeScript
parameters: {  model: { options: ["gpt-6-sol", "gpt-6-luna"], default: "gpt-6-luna" },  plan: { default: "free", description: "Customer plan" },  maxTools: { type: "number", default: 5 },}
FieldTypeEffect
type"string" | "number" | "boolean"The parameter's type. Read from default when absent.
defaultscalarThe default the run dialog prefills
optionsscalar arrayA closed list of allowed values, up to 50
descriptionstringShown beside the field in the run dialog

A plain JSON Schema object, { type: "object", properties: { ... } }.

Values arrive validated against the declaration. A value the declaration refuses fails the call with agent_parameter_invalid before the handler runs. A parameter the run did not supply arrives as its default; one with no default that the run did not supply fails the call with the name in the message.

Return values

ReturnMeaning
stringThe reply text
MessageOne message
Message[]Several messages
{ output, session, state }A reply, plus the session value for the next turn and an update to the scenario's state. session and state are optional.

session is an opaque JSON value the platform echoes on the next turn of the same conversation, up to 64 kilobytes.

agent.scenario.setup() and agent.scenario.teardown()

The object connectAgent returns has a scenario property that declares the hooks LangWatch calls around a scenario run. See Setup and teardown hooks for when they run and how they fail.

example.tsTypeScript
agent.scenario.setup(async (run, params) => {  return { customerId: "cus_123" }; // the state the run starts with});​agent.scenario.teardown(async (run, state, params) => {  return { deleted: state?.customerId }; // shown on the run});
ArgumentTypeValue
runScenarioRunscenarioRunId, scenarioName and batchRunId of the run, each optional
stateRecord<string, unknown> | nullTeardown only: the latest state
paramstyped from parametersThe run's values for the parameters declared in connectAgent

Each hook returns a JSON object, up to 64 kilobytes, or no value. Declared before the process yields, the hooks are part of the first registration. Declared later, the SDK registers the agent again.

Lifecycle

The connection starts on the next tick after the first connectAgent call, once per process, and one connection carries every agent the process declares. It uses the global WebSocket when the runtime has one and the ws package otherwise. An open WebSocket keeps the event loop alive while it is connected.

The HTTP fallback waits between empty polls on an unreferenced timer, and so does the reconnect backoff, so a script that only declares an agent needs its own keep-alive, for example setInterval(() => {}, 1 << 30).

SIGINT, SIGTERM and normal exit send a deregistration, so the agent reads Offline at once. A dropped connection is retried with a growing wait, from 1 second to 30 seconds.

Transport

The connection is an outbound WebSocket by default. On a network that blocks WebSockets, the same frames travel over HTTP long polling: the SDK posts the registration, waits on a request for the next turn, and posts each answer, through the global fetch of Node 20 or later. Pass transport: "http" or set LANGWATCH_AGENT_TRANSPORT=http to use it from the start.

With the default transport, a proxy that answers the WebSocket upgrade with an HTTP status makes the SDK switch to HTTP on its own, with one warning line that names the status. The ws package is what reports that status; the global WebSocket cannot, so on a runtime without ws set the transport explicitly.

Environment variables

VariableEffect
LANGWATCH_API_KEYThe project key. Without it, the process does not connect.
LANGWATCH_ENDPOINTThe LangWatch instance, for a self-hosted deployment.
LANGWATCH_PROJECT_IDThe project, for a key that covers more than one.
LANGWATCH_AGENT_ENVIRONMENTThe environment to register under.
LANGWATCH_AGENT_CONNECT0 or false stops this process from connecting.
LANGWATCH_AGENT_INSTANCE_LABELThe instance name shown in the instances table.
LANGWATCH_AGENT_TRANSPORThttp uses HTTP long polling instead of the WebSocket.

Errors

A failing call answers with a typed code rather than a stack trace. agent_offline, agent_owner_only, agent_call_timeout, agent_call_failed, agent_disconnected, agent_instance_lost, agent_busy, agent_parameter_invalid, agent_register_refused, agent_payload_too_large, hook_not_declared.

Next steps

Connect your agent

The three-step guide, with the session and parameter recipes

TypeScript SDK reference

Setup, tracing, spans and prompt management

Documentation