langwatch 1.16.0 → 1.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/agent/index.js +21 -2
  2. package/dist/agent/index.js.map +1 -1
  3. package/dist/agent/index.mjs +21 -2
  4. package/dist/agent/index.mjs.map +1 -1
  5. package/dist/{chunk-XC6AXWVR.mjs → chunk-HY2N6TO5.mjs} +2 -2
  6. package/dist/{chunk-6SSJPQAW.js → chunk-JJASOJOK.js} +2 -2
  7. package/dist/{chunk-6SSJPQAW.js.map → chunk-JJASOJOK.js.map} +1 -1
  8. package/dist/{chunk-NZP72HTX.mjs → chunk-MVQJMRM6.mjs} +2 -2
  9. package/dist/{chunk-NZP72HTX.mjs.map → chunk-MVQJMRM6.mjs.map} +1 -1
  10. package/dist/{chunk-FUDF46YW.js → chunk-UEJSGC3P.js} +12 -12
  11. package/dist/{chunk-FUDF46YW.js.map → chunk-UEJSGC3P.js.map} +1 -1
  12. package/dist/cli/bundle.js +260 -253
  13. package/dist/{implementation-Dlxw5hlM.d.ts → implementation-BvX-7vox.d.ts} +1 -1
  14. package/dist/{implementation-BvHTdJLg.d.mts → implementation-CQ__V0Vc.d.mts} +1 -1
  15. package/dist/index.d.mts +2 -2
  16. package/dist/index.d.ts +2 -2
  17. package/dist/index.js +33 -33
  18. package/dist/index.js.map +1 -1
  19. package/dist/index.mjs +2 -2
  20. package/dist/index.mjs.map +1 -1
  21. package/dist/observability-sdk/index.d.mts +3 -3
  22. package/dist/observability-sdk/index.d.ts +3 -3
  23. package/dist/observability-sdk/index.js +2 -2
  24. package/dist/observability-sdk/index.mjs +1 -1
  25. package/dist/observability-sdk/instrumentation/langchain/index.d.mts +1 -1
  26. package/dist/observability-sdk/instrumentation/langchain/index.d.ts +1 -1
  27. package/dist/observability-sdk/setup/node/index.js +3 -3
  28. package/dist/observability-sdk/setup/node/index.mjs +2 -2
  29. package/dist/{types-CzElA_6o.d.ts → types-CNEUr6Hm.d.ts} +345 -36
  30. package/dist/{types-Dd2d9hCy.d.mts → types-DfPAHmAh.d.mts} +345 -36
  31. package/package.json +1 -1
  32. /package/dist/{chunk-XC6AXWVR.mjs.map → chunk-HY2N6TO5.mjs.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/agent/index.ts","../../src/logger/index.ts","../../src/agent/client.ts","../../src/agent/identity.ts","../../package.json","../../src/internal/constants.ts","../../src/internal/endpoint.ts","../../src/agent/protocol.ts","../../src/agent/schema.ts","../../src/agent/transport.ts","../../src/internal/http/langwatchFetch.ts","../../src/agent/reconnect.ts","../../src/agent/define.ts"],"sourcesContent":["/**\n * `langwatch/agent`: connect the function that runs an agent to LangWatch\n * so simulations run against it with no public URL.\n *\n * Node only, and outbound only. The default transport is a WebSocket that\n * carries the API key in its request headers. It falls back to HTTP long\n * polling when a proxy refuses the upgrade, and\n * `LANGWATCH_AGENT_TRANSPORT=http` selects HTTP long polling from the start.\n *\n * @see dev/docs/adr/128-connected-agents.md\n */\n\nexport { connectAgent, normalizeReply, DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS } from \"./define\";\nexport type {\n AgentCall,\n AgentHandler,\n AgentOutput,\n AgentReply,\n AgentResult,\n ConnectAgentOptions,\n ConnectedAgent,\n DirectAgentCall,\n InferParameters,\n} from \"./define\";\nexport { AgentParameterError, toParameterSchema, parameterSpecsFromSchema } from \"./schema\";\nexport type {\n ParameterDefinition,\n ParameterDefinitions,\n ParameterInput,\n ParameterSpec,\n ParameterType,\n StandardJsonSchema,\n} from \"./schema\";\nexport { PROTOCOL_VERSION } from \"./protocol\";\nexport type { AgentMessage, AgentParameterValue, JsonSchemaObject } from \"./protocol\";\nexport { resolveEnvironment, sanitizeEnvironment, resolveConnectUrl, resolveHttpConnectUrl } from \"./identity\";\nexport { resolveTransport, AGENT_TRANSPORTS } from \"./transport\";\nexport type { AgentTransport } from \"./transport\";\n","// Logger utility for SDKs\n//\n// Usage:\n// - If you pass your own Logger implementation, the SDK will use it as-is (no log level filtering or prefixing applied).\n// - If you use ConsoleLogger, you can specify log level and prefix options.\n// - NoOpLogger disables all logging.\n//\n// Example:\n// const logger = new ConsoleLogger({ level: \"warn\", prefix: \"SDK\" });\n// logger.info(\"This will not show\");\n// logger.warn(\"This will show with prefix\");\n//\n// // If you pass your own logger, SDK will not filter logs:\n// const customLogger: Logger = { ... };\n// // SDK uses customLogger as-is\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nconst logLevelOrder: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n} as const;\n\nexport interface Logger {\n debug: (message: string, ...args: unknown[]) => void;\n info: (message: string, ...args: unknown[]) => void;\n warn: (message: string, ...args: unknown[]) => void;\n error: (message: string, ...args: unknown[]) => void;\n}\n\nexport class NoOpLogger implements Logger {\n debug: () => void = () => { /* noop */ }\n info: () => void = () => { /* noop */ }\n warn: () => void = () => { /* noop */ }\n error: () => void = () => { /* noop */ }\n}\n\ninterface ConsoleLoggerOptions {\n level: LogLevel;\n prefix?: string;\n}\n\n/**\n * ConsoleLogger applies log level filtering and optional prefixing.\n * If you pass your own Logger, the SDK will not apply log level filtering or prefixing.\n */\nexport class ConsoleLogger implements Logger {\n private level: LogLevel;\n private prefix?: string;\n\n constructor(options: ConsoleLoggerOptions = { level: \"warn\" }) {\n this.level = options.level;\n this.prefix = options.prefix;\n }\n\n private shouldLog(level: LogLevel): boolean {\n return logLevelOrder[level] >= logLevelOrder[this.level];\n }\n\n private format(message: string): string {\n return this.prefix ? `[${this.prefix}] ${message}` : message;\n }\n\n debug: (message: string, ...args: unknown[]) => void = (message: string, ...args: unknown[]): void => {\n if (this.shouldLog(\"debug\")) console.debug(this.format(message), ...args);\n };\n info: (message: string, ...args: unknown[]) => void = (message: string, ...args: unknown[]): void => {\n if (this.shouldLog(\"info\")) console.info(this.format(message), ...args);\n };\n warn: (message: string, ...args: unknown[]) => void = (message: string, ...args: unknown[]): void => {\n if (this.shouldLog(\"warn\")) console.warn(this.format(message), ...args);\n }\n error: (message: string, ...args: unknown[]) => void = (message: string, ...args: unknown[]): void => {\n if (this.shouldLog(\"error\")) console.error(this.format(message), ...args);\n }\n}\n","/**\n * One shared connection per process to `/api/v1/agents/connect`.\n *\n * The client holds every agent the process defined, registers them all on\n * one socket, answers `call` frames by running the agent's function, and\n * reconnects with backoff when the platform goes away. Nothing in here throws\n * into customer code: every frame is handled under a catch that logs, and a\n * failure on the LangWatch side produces one warning that names the fix and\n * leaves the application running as if the wrapper were absent.\n *\n * @see dev/docs/adr/128-connected-agents.md\n */\n\nimport { context, propagation, trace } from \"@opentelemetry/api\";\nimport type { Logger } from \"../logger\";\nimport type { AgentCall, AgentResult } from \"./define\";\nimport {\n buildConnectHeaders,\n buildInstance,\n resolveConnectUrl,\n resolveHttpConnectUrl,\n SDK_IDENTITY,\n} from \"./identity\";\nimport {\n parseServerFrame,\n PROTOCOL_VERSION,\n serializeFrame,\n traceIdFromTraceparent,\n type AgentParameterValue,\n type CallFrame,\n type ClientFrame,\n type RefusedFrame,\n type RegisterAgent,\n type RegisterInstance,\n type RegisteredFrame,\n} from \"./protocol\";\nimport { AgentParameterError, type ParameterReader } from \"./schema\";\nimport {\n describeError,\n NoWebSocketError,\n openTransportSocket,\n RECONNECT_BASE_MS,\n RECONNECT_MAX_MS,\n reconnectDelayMs,\n watchdogDelayMs,\n} from \"./reconnect\";\nimport {\n type AgentTransport,\n defaultSocketFactory,\n resolveTransport,\n type SocketFactory,\n type SocketLike,\n} from \"./transport\";\n\n/** One defined agent as the client runs it. */\nexport interface AgentRuntime {\n name: string;\n environment: string;\n register: RegisterAgent;\n /** Defaults, coercion and the schema's own validation, before every call. */\n readParams: ParameterReader;\n concurrency: number;\n timeoutMs: number;\n run: (call: AgentCall<Record<string, AgentParameterValue>>) => Promise<AgentResult>;\n}\n\nexport interface AgentClientConfig {\n apiKey: string;\n endpoint?: string;\n projectId?: string;\n instanceLabel?: string;\n /** `websocket` (default) or `http`; also `LANGWATCH_AGENT_TRANSPORT`. */\n transport?: AgentTransport;\n logger: Logger;\n socketFactory?: SocketFactory;\n /** Reconnect delays, for tests. Defaults to 1 s doubling up to 30 s. */\n backoff?: { baseMs: number; maxMs: number };\n /** How often the same unreachable-endpoint warning may repeat, for tests. */\n failureNoticeIntervalMs?: number;\n}\n\n/** The unreachable-endpoint warning repeats at most this often. */\nexport const FAILURE_NOTICE_INTERVAL_MS = 5 * 60_000;\n\nconst NOT_CONNECTED = \"not connected to LangWatch\";\n\n/** The one line a refusal produces: what went wrong and what fixes it. */\nexport function refusalAdvice(frame: RefusedFrame): string {\n switch (frame.code) {\n case \"project_required\": {\n const projects = Array.isArray(frame.meta?.projects) ? frame.meta.projects : [];\n const listed = projects\n .map((project) => {\n const entry = project as { id?: unknown; name?: unknown };\n const id = typeof entry.id === \"string\" ? entry.id : \"\";\n const name = typeof entry.name === \"string\" ? entry.name : \"\";\n return name && id ? `${name} (${id})` : id || name;\n })\n .filter((line) => line !== \"\");\n return `the API key reaches more than one project. Set LANGWATCH_PROJECT_ID to one of: ${listed.length > 0 ? listed.join(\", \") : \"the projects the key reaches\"}.`;\n }\n case \"api_key_invalid\":\n return \"the API key is not valid. Set LANGWATCH_API_KEY to a key from the project settings.\";\n case \"key_type_not_allowed\":\n return \"this key type cannot connect agents. Set LANGWATCH_API_KEY to a personal or project API key.\";\n case \"permission_denied\":\n return \"the API key cannot manage scenarios. Use a key with the scenarios:manage permission.\";\n case \"protocol_invalid\":\n return `${frame.message} Update the langwatch package to a version that speaks protocol ${PROTOCOL_VERSION} or later.`;\n case \"replica_count_unsupported\":\n return `${frame.message} Connected agents on a LangWatch deployment without Redis need one app replica.`;\n case \"parameters_invalid\":\n case \"environment_invalid\":\n return frame.message;\n default:\n return `${frame.message} (${frame.code})`;\n }\n}\n\ninterface InFlightCall {\n runtime: AgentRuntime;\n /** True once the call was cancelled or timed out: a late result is dropped. */\n cancelled: boolean;\n /** The timer that ends the call on its deadline, cleared when the call ends. */\n timer: NodeJS.Timeout | null;\n}\n\nconst SHUTDOWN_SIGNALS = [\"SIGINT\", \"SIGTERM\"] as const;\ntype ShutdownSignal = (typeof SHUTDOWN_SIGNALS)[number];\n\nconst CLOSE_GRACE_MS = 500;\n\nexport class AgentClient {\n private readonly agents: AgentRuntime[] = [];\n private readonly byId = new Map<string, AgentRuntime>();\n private readonly inFlight = new Map<string, InFlightCall>();\n private readonly instance: RegisterInstance;\n private readonly url: string;\n private readonly httpUrl: string;\n private readonly headers: Record<string, string>;\n /** The transport in use: the configured one, or HTTP after a refused upgrade. */\n private activeTransport: AgentTransport;\n private upgradeStatus: number | null = null;\n private transportAnnounced = false;\n private readonly logger: Logger;\n private readonly openSocket: SocketFactory;\n private readonly backoff: { baseMs: number; maxMs: number };\n private readonly failureNoticeIntervalMs: number;\n\n private socket: SocketLike | null = null;\n private registered = false;\n private stopped = false;\n /** True while a socket is closed on purpose to register the full agent list again. */\n private restarting = false;\n private attempt = 0;\n private connectTimer: NodeJS.Timeout | null = null;\n private watchdog: NodeJS.Timeout | null = null;\n private heartbeatIntervalMs = 10_000;\n private closeWaiters: Array<() => void> = [];\n private lastError: string | null = null;\n private failureNoticeAt: number | null = null;\n private gaveUp = false;\n\n constructor(config: AgentClientConfig) {\n this.instance = buildInstance({ label: config.instanceLabel });\n this.url = resolveConnectUrl(config.endpoint);\n this.httpUrl = resolveHttpConnectUrl(config.endpoint);\n this.activeTransport = resolveTransport({ explicit: config.transport });\n this.headers = buildConnectHeaders({ apiKey: config.apiKey, projectId: config.projectId });\n this.logger = config.logger;\n this.openSocket = config.socketFactory ?? defaultSocketFactory;\n this.backoff = config.backoff ?? { baseMs: RECONNECT_BASE_MS, maxMs: RECONNECT_MAX_MS };\n this.failureNoticeIntervalMs = config.failureNoticeIntervalMs ?? FAILURE_NOTICE_INTERVAL_MS;\n }\n\n get instanceId(): string {\n return this.instance.id;\n }\n\n /** The transport the client speaks now. */\n get transport(): AgentTransport {\n return this.activeTransport;\n }\n\n get isRegistered(): boolean {\n return this.registered;\n }\n\n /** True once the client gave up: refused, or no socket implementation. No timer is left behind. */\n get isStopped(): boolean {\n return this.stopped;\n }\n\n /** True while a reconnect is scheduled with a timer that keeps the process up. */\n get hasPendingConnect(): boolean {\n return this.connectTimer?.hasRef() ?? false;\n }\n\n /** True while the client is between attempts or inside one, with the process kept up. */\n get isRetrying(): boolean {\n if (this.stopped) return false;\n return this.connectTimer ? this.connectTimer.hasRef() : this.socket !== null;\n }\n\n /** Adds an agent and connects on the next tick, or reconnects when a socket is already open. */\n addAgent(runtime: AgentRuntime): void {\n this.agents.push(runtime);\n if (this.gaveUp) {\n this.logger.debug(`agent \"${runtime.name}\" ${NOT_CONNECTED}: the connection gave up earlier in this process`);\n return;\n }\n this.stopped = false;\n if (this.socket) {\n // The platform ignores a second register on an open socket, whether the\n // first one is still on its way or already answered. A fresh socket\n // carries the complete list.\n this.restartSocket();\n return;\n }\n this.scheduleConnect(0);\n }\n\n /** Closes the socket and connects again at once, keeping the reconnect loop. */\n private restartSocket(): void {\n const socket = this.socket;\n if (!socket) return;\n this.restarting = true;\n try {\n socket.close(1000, \"agents changed\");\n } catch {\n this.restarting = false;\n this.socket = null;\n this.scheduleConnect(0);\n }\n }\n\n /** Removes an agent; the last one leaving deregisters and closes the socket. */\n async removeAgent(runtime: AgentRuntime): Promise<void> {\n const index = this.agents.indexOf(runtime);\n if (index !== -1) this.agents.splice(index, 1);\n for (const [id, agent] of this.byId) if (agent === runtime) this.byId.delete(id);\n if (this.agents.length === 0) {\n await this.disconnect();\n return;\n }\n // The open socket registered the agent that just left, and the platform\n // ignores a second register on it. A fresh socket carries the list as it\n // stands now.\n this.restartSocket();\n }\n\n /** Sends deregister, closes the socket and stops reconnecting. */\n async disconnect(): Promise<void> {\n this.stopped = true;\n this.clearTimers();\n const socket = this.socket;\n if (!socket) return;\n if (this.registered) this.send({ type: \"deregister\", protocol: PROTOCOL_VERSION });\n const closed = new Promise<void>((resolve) => this.closeWaiters.push(resolve));\n try {\n socket.close(1000, \"deregister\");\n } catch {\n // The socket is already gone.\n }\n const grace = new Promise<void>((resolve) => {\n const timer = setTimeout(() => {\n try {\n socket.terminate();\n } catch {\n // Already gone.\n }\n resolve();\n }, CLOSE_GRACE_MS);\n timer.unref();\n });\n await Promise.race([closed, grace]);\n }\n\n /** Deregister with no wait, for a process that is already exiting. */\n shutdownNow(): void {\n this.stopped = true;\n this.clearTimers();\n if (!this.socket) return;\n try {\n if (this.registered) this.send({ type: \"deregister\", protocol: PROTOCOL_VERSION });\n this.socket.close(1000, \"deregister\");\n } catch {\n // The socket is already gone.\n }\n }\n\n private agentNames(): string {\n return this.agents.map((agent) => `\"${agent.name}\"`).join(\", \") || \"the agent\";\n }\n\n /**\n * The reconnect timer keeps its ref on purpose: a script whose only job is\n * the agent must stay up while it retries. Giving up clears every timer.\n */\n private scheduleConnect(delayMs: number): void {\n if (this.stopped || this.connectTimer || this.socket) return;\n this.connectTimer = setTimeout(() => {\n this.connectTimer = null;\n this.connect();\n }, delayMs);\n }\n\n private clearTimers(): void {\n if (this.connectTimer) {\n clearTimeout(this.connectTimer);\n this.connectTimer = null;\n }\n if (this.watchdog) {\n clearTimeout(this.watchdog);\n this.watchdog = null;\n }\n }\n\n private giveUp(reason: string): void {\n this.stopped = true;\n this.gaveUp = true;\n this.clearTimers();\n this.logger.warn(`agent ${this.agentNames()} ${NOT_CONNECTED}: ${reason}`);\n }\n\n private connect(): void {\n if (this.stopped || this.socket) return;\n let socket: SocketLike;\n try {\n socket = openTransportSocket({\n transport: this.activeTransport,\n websocketUrl: this.url,\n httpUrl: this.httpUrl,\n headers: this.headers,\n socketFactory: this.openSocket,\n });\n } catch (error) {\n if (error instanceof NoWebSocketError) {\n this.giveUp(\n \"the ws package is not installed. Run npm install ws; the platform reads the API key from a request header, and only ws can send it.\",\n );\n return;\n }\n this.lastError = describeError(error);\n this.onClosed();\n return;\n }\n this.socket = socket;\n socket.onOpen(() => this.guard(() => this.send(this.registerFrame())));\n socket.onMessage((data) => this.guard(() => this.onMessage(data)));\n socket.onError((error) => {\n this.lastError = describeError(error);\n });\n socket.onPing(() => this.armWatchdog());\n socket.onUpgradeRefused?.((status) => {\n this.upgradeStatus = status;\n });\n socket.onClose((code) => this.guard(() => this.onClosed(code)));\n }\n\n private onClosed(code?: number): void {\n const wasRegistered = this.registered;\n const restarting = this.restarting;\n this.restarting = false;\n this.socket = null;\n this.registered = false;\n if (this.watchdog) {\n clearTimeout(this.watchdog);\n this.watchdog = null;\n }\n for (const waiter of this.closeWaiters.splice(0)) waiter();\n if (this.stopped) return;\n if (this.upgradeStatus !== null && this.activeTransport === \"websocket\") {\n // A proxy answered the upgrade with a status: the socket can never\n // open here, and the same frames travel over plain HTTP.\n const status = this.upgradeStatus;\n this.upgradeStatus = null;\n this.activeTransport = \"http\";\n this.logger.warn(\n `the WebSocket upgrade to ${this.url} was answered with HTTP ${status}; using the HTTP transport at ${this.httpUrl} instead`,\n );\n this.scheduleConnect(0);\n return;\n }\n if (restarting) {\n this.scheduleConnect(0);\n return;\n }\n const delay = reconnectDelayMs({ attempt: this.attempt, ...this.backoff });\n this.attempt += 1;\n this.noteDisconnected({ wasRegistered, code });\n this.scheduleConnect(delay);\n }\n\n /**\n * One warning when the platform cannot be reached, one when a live\n * connection is lost, and silence while the retries run: the same notice\n * repeats only after the notice interval, and a reconnect resets it.\n */\n private noteDisconnected({ wasRegistered, code }: { wasRegistered: boolean; code?: number }): void {\n const now = Date.now();\n if (wasRegistered) {\n this.logger.warn(\n `lost the connection to LangWatch${code === undefined ? \"\" : ` (${code})`}, reconnecting with backoff`,\n );\n this.failureNoticeAt = now;\n return;\n }\n const stale =\n this.failureNoticeAt === null || now - this.failureNoticeAt >= this.failureNoticeIntervalMs;\n if (!stale) return;\n this.failureNoticeAt = now;\n const cause = this.lastError ? ` (${this.lastError})` : \"\";\n this.logger.warn(\n `agent ${this.agentNames()} ${NOT_CONNECTED}: could not reach ${this.url}${cause}. Check LANGWATCH_ENDPOINT and the network; retrying with backoff.`,\n );\n }\n\n private armWatchdog(): void {\n if (this.watchdog) clearTimeout(this.watchdog);\n const socket = this.socket;\n if (!socket) return;\n this.watchdog = setTimeout(() => {\n this.watchdog = null;\n this.logger.warn(\"no heartbeat from LangWatch, reconnecting\");\n try {\n socket.terminate();\n } catch {\n // The close event follows either way.\n }\n }, watchdogDelayMs(this.heartbeatIntervalMs));\n }\n\n private registerFrame(): ClientFrame {\n return {\n type: \"register\",\n protocol: PROTOCOL_VERSION,\n sdk: SDK_IDENTITY,\n instance: { ...this.instance, inFlightCallIds: [...this.inFlight.keys()] },\n agents: this.agents.map((agent) => agent.register),\n };\n }\n\n private send(frame: ClientFrame): void {\n const socket = this.socket;\n if (!socket) return;\n try {\n socket.send(serializeFrame(frame));\n } catch (error) {\n this.logger.debug(`could not send ${frame.type}: ${describeError(error)}`);\n }\n }\n\n private onMessage(data: string): void {\n const frame = parseServerFrame(data);\n if (!frame) {\n this.logger.debug(\"dropped a frame the SDK does not know\");\n return;\n }\n this.armWatchdog();\n switch (frame.type) {\n case \"registered\":\n this.onRegistered(frame);\n return;\n case \"refused\":\n this.onRefused(frame);\n return;\n case \"call\":\n void this.onCall(frame);\n return;\n case \"cancel\": {\n const call = this.inFlight.get(frame.callId);\n if (!call) return;\n call.cancelled = true;\n // The handler may run for as long as it wants; the slot it held is\n // free at once, so the next call is not refused as busy.\n this.releaseCall({ callId: frame.callId, entry: call });\n return;\n }\n }\n }\n\n private onRefused(frame: RefusedFrame): void {\n this.giveUp(refusalAdvice(frame));\n try {\n this.socket?.close(1000, frame.code);\n } catch {\n // The platform closes after refused either way.\n }\n }\n\n private onRegistered(frame: RegisteredFrame): void {\n this.registered = true;\n this.attempt = 0;\n if (this.failureNoticeAt !== null) {\n this.logger.info(\"connected to LangWatch\");\n this.failureNoticeAt = null;\n }\n if (this.activeTransport === \"http\" && !this.transportAnnounced) {\n this.transportAnnounced = true;\n this.logger.info(`connected to LangWatch over HTTP long polling at ${this.httpUrl}`);\n }\n this.heartbeatIntervalMs = frame.heartbeatIntervalMs;\n if (frame.instanceId && frame.instanceId !== this.instance.id) this.instance.id = frame.instanceId;\n this.byId.clear();\n for (const entry of frame.agents) {\n const runtime = this.agents.find(\n (agent) => agent.name === entry.name && agent.environment === entry.environment,\n );\n if (!runtime) continue;\n this.byId.set(entry.id, runtime);\n this.logger.info(\n `agent \"${entry.name}\" (${entry.environment}) is online${entry.url ? `: ${entry.url}` : \"\"}`,\n );\n for (const note of entry.parameterNotes) this.logger.warn(`agent \"${entry.name}\": ${note}`);\n }\n this.armWatchdog();\n }\n\n private async onCall(frame: CallFrame): Promise<void> {\n const runtime = this.byId.get(frame.agentId);\n if (!runtime) {\n this.sendError({\n callId: frame.callId,\n code: \"agent_call_failed\",\n message: `no agent registered as ${frame.agentId}`,\n });\n return;\n }\n const busy = [...this.inFlight.values()].filter((call) => call.runtime === runtime).length;\n if (busy >= runtime.concurrency) {\n this.sendError({\n callId: frame.callId,\n code: \"agent_busy\",\n message: `agent \"${runtime.name}\" has ${busy} call${busy === 1 ? \"\" : \"s\"} in flight, its limit`,\n });\n return;\n }\n if (frame.deadlineAt !== null && frame.deadlineAt <= Date.now()) {\n this.sendError({\n callId: frame.callId,\n code: \"agent_call_timeout\",\n message: \"the call deadline passed before it started\",\n });\n return;\n }\n\n // The slot is taken before the first await. Reading the parameters is\n // asynchronous, and a second call arriving inside that window would pass\n // the concurrency check above if the entry were written after it.\n const entry: InFlightCall = { runtime, cancelled: false, timer: null };\n this.inFlight.set(frame.callId, entry);\n\n let params: Record<string, AgentParameterValue>;\n try {\n params = await runtime.readParams(frame.params);\n } catch (error) {\n this.releaseCall({ callId: frame.callId, entry });\n this.sendError({\n callId: frame.callId,\n code: \"agent_parameter_invalid\",\n message: describeError(error),\n });\n return;\n }\n if (entry.cancelled) {\n this.releaseCall({ callId: frame.callId, entry });\n return;\n }\n\n // The ack means the function started: before it the platform may hand the\n // call to another instance, so it stays after the parameters are read.\n this.send({ type: \"ack\", protocol: PROTOCOL_VERSION, callId: frame.callId });\n this.armCallDeadline({ frame, entry, runtime });\n\n const parent = frame.traceparent\n ? propagation.extract(context.active(), { traceparent: frame.traceparent })\n : context.active();\n const traceId =\n trace.getSpanContext(parent)?.traceId ?? traceIdFromTraceparent(frame.traceparent) ?? \"\";\n\n const call: AgentCall<Record<string, AgentParameterValue>> = {\n messages: frame.messages,\n newMessages: frame.newMessages,\n threadId: frame.threadId,\n session: frame.session,\n params,\n traceId,\n };\n\n try {\n const result = await context.with(parent, () => runtime.run(call));\n if (entry.cancelled) return;\n // The handler answered, so its deadline is over. Disarming it before\n // the export matters: an export slower than what is left of the limit\n // would otherwise let the timer answer the call, and this branch would\n // then answer it a second time.\n this.releaseCall({ callId: frame.callId, entry });\n await this.flushSpans();\n this.send({\n type: \"result\",\n protocol: PROTOCOL_VERSION,\n callId: frame.callId,\n output: result.output,\n ...(result.session === undefined ? {} : { session: result.session }),\n });\n } catch (error) {\n if (entry.cancelled) return;\n const code = error instanceof AgentParameterError ? error.code : \"agent_call_failed\";\n const message = describeError(error);\n this.logger.warn(`agent \"${runtime.name}\" call ${frame.callId} failed: ${message}`);\n this.releaseCall({ callId: frame.callId, entry });\n await this.flushSpans();\n this.sendError({ callId: frame.callId, code, message });\n } finally {\n this.releaseCall({ callId: frame.callId, entry });\n }\n }\n\n /**\n * Exports the spans of the call now instead of at the exporter's next\n * schedule. The judge reads the agent's spans right after the last turn,\n * and a batch exporter would otherwise hold them for seconds, which is what\n * made the judge report the spans missing.\n *\n * The call awaits this before it sends its result or its error: the frame is\n * what tells the platform the turn is over, so a frame that goes out first\n * lets the judge read the call while its spans are still in the exporter.\n */\n private async flushSpans(): Promise<void> {\n const provider = trace.getTracerProvider() as { getDelegate?: () => unknown };\n const delegate =\n typeof provider.getDelegate === \"function\" ? provider.getDelegate() : provider;\n const flush = (delegate as { forceFlush?: () => Promise<void> } | null)?.forceFlush;\n if (typeof flush !== \"function\") return;\n try {\n await flush.call(delegate);\n } catch (error) {\n this.logger.debug(`span flush after a call failed: ${describeError(error)}`);\n }\n }\n\n /** Frees the slot the call holds and drops its deadline timer. */\n private releaseCall({ callId, entry }: { callId: string; entry: InFlightCall }): void {\n if (entry.timer) {\n clearTimeout(entry.timer);\n entry.timer = null;\n }\n if (this.inFlight.get(callId) === entry) this.inFlight.delete(callId);\n }\n\n /**\n * The call ends on its deadline: one timeout result, and the slot is free\n * from that moment. A handler that never returns then costs one call, not\n * every call after it.\n */\n private armCallDeadline({\n frame,\n entry,\n runtime,\n }: {\n frame: CallFrame;\n entry: InFlightCall;\n runtime: AgentRuntime;\n }): void {\n const fromDeadline = frame.deadlineAt === null ? Infinity : frame.deadlineAt - Date.now();\n const limit = Math.min(fromDeadline, runtime.timeoutMs);\n if (!Number.isFinite(limit)) return;\n const timer = setTimeout(() => {\n entry.timer = null;\n if (entry.cancelled) return;\n // The handler keeps running: a function cannot be stopped from here.\n // Its late result is dropped, because the platform has an answer.\n entry.cancelled = true;\n this.releaseCall({ callId: frame.callId, entry });\n this.logger.warn(\n `agent \"${runtime.name}\" call ${frame.callId} passed its ${limit} ms limit`,\n );\n this.sendError({\n callId: frame.callId,\n code: \"agent_call_timeout\",\n message: `the call passed the ${limit} ms limit of agent \"${runtime.name}\"`,\n });\n }, Math.max(0, limit));\n timer.unref();\n entry.timer = timer;\n }\n\n private sendError({ callId, code, message }: { callId: string; code: string; message: string }): void {\n this.send({ type: \"result\", protocol: PROTOCOL_VERSION, callId, error: { code, message } });\n }\n\n private guard(action: () => void): void {\n try {\n action();\n } catch (error) {\n this.logger.error(`agent client error: ${describeError(error)}`);\n }\n }\n}\n\nlet shared: AgentClient | null = null;\nlet sharedKey: string | null = null;\nlet hooksInstalled = false;\nconst noticesGiven = new Set<string>();\nlet testOverrides: Partial<AgentClientConfig> = {};\n\nconst signalHandlers = new Map<ShutdownSignal, () => void>();\n\nconst onShutdownSignal = (signal: ShutdownSignal): void => {\n const client = shared;\n const finish = () => {\n const handler = signalHandlers.get(signal);\n if (handler) process.removeListener(signal, handler);\n if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);\n };\n if (!client) {\n finish();\n return;\n }\n void client.disconnect().finally(finish);\n};\n\nconst onBeforeExit = (): void => {\n shared?.shutdownNow();\n};\n\nconst installShutdownHooks = (): void => {\n if (hooksInstalled) return;\n hooksInstalled = true;\n for (const signal of SHUTDOWN_SIGNALS) {\n const handler = () => onShutdownSignal(signal);\n signalHandlers.set(signal, handler);\n process.on(signal, handler);\n }\n process.on(\"beforeExit\", onBeforeExit);\n};\n\nconst removeShutdownHooks = (): void => {\n if (!hooksInstalled) return;\n hooksInstalled = false;\n for (const [signal, handler] of signalHandlers) process.removeListener(signal, handler);\n signalHandlers.clear();\n process.removeListener(\"beforeExit\", onBeforeExit);\n};\n\n/** One warning per process for a condition every agent definition would repeat. */\nexport function warnOnce({ logger, key, message }: { logger: Logger; key: string; message: string }): void {\n if (noticesGiven.has(key)) {\n logger.debug(message);\n return;\n }\n noticesGiven.add(key);\n logger.warn(message);\n}\n\n/**\n * The one client of this process. The first agent's credentials and endpoint\n * are the ones used; a later agent that names different ones is told so and\n * shares the socket anyway.\n */\nexport function getSharedClient(config: AgentClientConfig): AgentClient {\n const key = `${config.endpoint ?? \"\"}|${config.projectId ?? \"\"}|${config.apiKey}`;\n if (shared) {\n if (sharedKey !== key) {\n warnOnce({\n logger: config.logger,\n key: \"credentials-differ\",\n message:\n \"connectAgent: this process already has an agent connection with other credentials or endpoint; the first ones are used\",\n });\n }\n return shared;\n }\n shared = new AgentClient({ ...config, ...testOverrides });\n sharedKey = key;\n installShutdownHooks();\n return shared;\n}\n\n/** Settings the next shared client is built with, on top of what the agent gave. For tests. */\nexport function overrideSharedClientForTests(overrides: Partial<AgentClientConfig>): void {\n testOverrides = overrides;\n}\n\n/** Drops the shared client so the next definition starts a new one. For tests. */\nexport async function resetSharedClient(): Promise<void> {\n const client = shared;\n shared = null;\n sharedKey = null;\n noticesGiven.clear();\n testOverrides = {};\n removeShutdownHooks();\n if (client) await client.disconnect();\n}\n\n/** The client the process shares right now, so a test can read its state. */\nexport function sharedClientForTests(): AgentClient | null {\n return shared;\n}\n\n/** The shutdown handlers as installed, so a test can drive a signal without raising it. */\nexport const shutdownForTests = { onShutdownSignal, onBeforeExit };\n","/**\n * Who and where a connected agent is: its environment, its instance identity\n * and the endpoint it connects to. Every read of the machine is defensive, so\n * a locked-down sandbox with no hostname or no passwd entry still connects.\n */\n\nimport * as os from \"node:os\";\nimport { randomUUID } from \"node:crypto\";\nimport { LANGWATCH_SDK_VERSION } from \"../internal/constants\";\nimport { resolveEndpoint } from \"../internal/endpoint\";\nimport type { RegisterInstance, RegisterSdk } from \"./protocol\";\n\nexport const DEFAULT_ENVIRONMENT = \"development\";\nconst ENVIRONMENT_MAX_LENGTH = 32;\n\n/** The environment variables read in order after the explicit option. */\nconst ENVIRONMENT_VARIABLES = [\n \"LANGWATCH_AGENT_ENVIRONMENT\",\n \"APP_ENV\",\n \"ENVIRONMENT\",\n \"NODE_ENV\",\n] as const;\n\nconst isSet = (value: string | undefined): value is string =>\n typeof value === \"string\" && value.trim() !== \"\";\n\n/**\n * An environment name as the platform stores it: lowercase, `[a-z0-9_-]`\n * only, at most 32 characters. Anything else collapses to a dash, and an\n * empty result is the default environment.\n */\nexport function sanitizeEnvironment(name: string): string {\n const cleaned = name\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, ENVIRONMENT_MAX_LENGTH)\n .replace(/-+$/g, \"\");\n return cleaned === \"\" ? DEFAULT_ENVIRONMENT : cleaned;\n}\n\n/**\n * The environment an agent registers under: the explicit option, then\n * `LANGWATCH_AGENT_ENVIRONMENT`, `APP_ENV`, `ENVIRONMENT`, `NODE_ENV`, else\n * `development`.\n */\nexport function resolveEnvironment({\n explicit,\n env = process.env,\n}: {\n explicit?: string;\n env?: NodeJS.ProcessEnv;\n}): string {\n if (isSet(explicit)) return sanitizeEnvironment(explicit);\n for (const name of ENVIRONMENT_VARIABLES) {\n const value = env[name];\n if (isSet(value)) return sanitizeEnvironment(value);\n }\n return DEFAULT_ENVIRONMENT;\n}\n\nconst isTruthy = (value: string | undefined): boolean => {\n if (!isSet(value)) return false;\n const lowered = value.trim().toLowerCase();\n return lowered !== \"0\" && lowered !== \"false\" && lowered !== \"no\" && lowered !== \"off\";\n};\n\n/**\n * Whether the agent connects at all. `LANGWATCH_AGENT_CONNECT=0` (or false)\n * always disables it; the explicit option wins next; otherwise the connection\n * is on, except when `CI` is truthy.\n */\nexport function resolveEnabled({\n explicit,\n env = process.env,\n}: {\n explicit?: boolean;\n env?: NodeJS.ProcessEnv;\n}): boolean {\n const flag = env.LANGWATCH_AGENT_CONNECT;\n if (isSet(flag) && !isTruthy(flag)) return false;\n if (explicit !== undefined) return explicit;\n return !isTruthy(env.CI);\n}\n\n/** The instance label: the option, then `LANGWATCH_AGENT_INSTANCE_LABEL`. */\nexport function resolveInstanceLabel({\n explicit,\n env = process.env,\n}: {\n explicit?: string;\n env?: NodeJS.ProcessEnv;\n}): string | undefined {\n if (isSet(explicit)) return explicit.trim();\n const fromEnv = env.LANGWATCH_AGENT_INSTANCE_LABEL;\n return isSet(fromEnv) ? fromEnv.trim() : undefined;\n}\n\n/** The two reads of the machine, replaceable so a test can make them fail. */\nexport interface MachineReader {\n hostname: () => string;\n userInfo: () => { username: string };\n}\n\nconst HOST_LABEL_MAX_LENGTH = 24;\n\n/**\n * A short label for this machine: lowercase, `[a-z0-9-]`, 24 characters.\n *\n * The platform scopes a development agent connected with a project key to\n * this label, and the Python SDK sends the same shape, so one machine reads\n * the same whichever SDK connected it.\n */\nexport function hostLabel(hostname: string): string {\n return hostname\n .toLowerCase()\n .replace(/\\.(local|lan|home|localdomain)$/i, \"\")\n .replace(/[^a-z0-9-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, HOST_LABEL_MAX_LENGTH);\n}\n\nconst readHostname = (machine: MachineReader): string => {\n try {\n return hostLabel(machine.hostname());\n } catch {\n return \"\";\n }\n};\n\nconst readUsername = (machine: MachineReader): string => {\n try {\n return machine.userInfo().username;\n } catch {\n return \"\";\n }\n};\n\n/** The identity one process announces in `register`, built once. */\nexport function buildInstance({\n label,\n machine = os,\n}: {\n label?: string;\n machine?: MachineReader;\n}): RegisterInstance {\n return {\n id: `inst_${randomUUID().replace(/-/g, \"\")}`,\n hostname: readHostname(machine),\n username: readUsername(machine),\n pid: process.pid,\n startedAt: new Date().toISOString(),\n ...(label ? { label } : {}),\n inFlightCallIds: [],\n };\n}\n\n/** The SDK block of `register`. */\nexport const SDK_IDENTITY: RegisterSdk = {\n name: \"langwatch-typescript\",\n version: LANGWATCH_SDK_VERSION,\n language: \"typescript\",\n};\n\nexport const USER_AGENT = `langwatch-typescript/${LANGWATCH_SDK_VERSION}`;\n\nexport const CONNECT_PATH = \"/api/v1/agents/connect\";\n\n/**\n * The socket URL for an endpoint: `https://app.langwatch.ai` becomes\n * `wss://app.langwatch.ai/api/v1/agents/connect`, `http://localhost:5560`\n * becomes `ws://localhost:5560/api/v1/agents/connect`.\n */\nexport function resolveConnectUrl(endpoint?: string | null): string {\n const base = resolveEndpoint(endpoint);\n const socketBase = base.replace(/^http(s?):\\/\\//i, (_match, secure: string) =>\n secure ? \"wss://\" : \"ws://\",\n );\n return `${socketBase}${CONNECT_PATH}`;\n}\n\n/**\n * The base of the HTTP long-poll routes for an endpoint:\n * `https://app.langwatch.ai` becomes `https://app.langwatch.ai/api/v1/agents/connect`.\n */\nexport function resolveHttpConnectUrl(endpoint?: string | null): string {\n return `${resolveEndpoint(endpoint)}${CONNECT_PATH}`;\n}\n\n/** The headers the socket opens with. */\nexport function buildConnectHeaders({\n apiKey,\n projectId,\n}: {\n apiKey: string;\n projectId?: string;\n}): Record<string, string> {\n const headers: Record<string, string> = {\n Authorization: `Bearer ${apiKey}`,\n \"User-Agent\": USER_AGENT,\n };\n if (isSet(projectId)) headers[\"X-Project-Id\"] = projectId;\n return headers;\n}\n","{\n \"name\": \"langwatch\",\n \"version\": \"1.16.0\",\n \"description\": \"LangWatch TypeScript/JavaScript SDK. Interact with the full LangWatch API and use the LangWatch OpenTelemetry SDK to instrument your application. For more information, see https://docs.langwatch.ai/integration/typescript/guide\",\n \"main\": \"dist/index.js\",\n \"module\": \"dist/index.mjs\",\n \"types\": \"dist/index.d.ts\",\n \"author\": \"LangWatch\",\n \"license\": \"MIT\",\n \"engines\": {\n \"node\": \">=20\",\n \"pnpm\": \">=8\"\n },\n \"files\": [\n \"dist\",\n \"!dist/bin\",\n \"!dist/cli/*.map\",\n \"README.md\",\n \"LICENSE\"\n ],\n \"bin\": {\n \"lw\": \"./dist/cli/index.js\",\n \"langwatch\": \"./dist/cli/index.js\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.js\"\n },\n \"./observability\": {\n \"types\": \"./dist/observability-sdk/index.d.ts\",\n \"require\": \"./dist/observability-sdk/index.js\",\n \"import\": \"./dist/observability-sdk/index.mjs\"\n },\n \"./observability/node\": {\n \"types\": \"./dist/observability-sdk/setup/node/index.d.ts\",\n \"require\": \"./dist/observability-sdk/setup/node/index.js\",\n \"import\": \"./dist/observability-sdk/setup/node/index.mjs\"\n },\n \"./observability/instrumentation/langchain\": {\n \"types\": \"./dist/observability-sdk/instrumentation/langchain/index.d.ts\",\n \"require\": \"./dist/observability-sdk/instrumentation/langchain/index.js\",\n \"import\": \"./dist/observability-sdk/instrumentation/langchain/index.mjs\"\n },\n \"./agent\": {\n \"types\": \"./dist/agent/index.d.ts\",\n \"require\": \"./dist/agent/index.js\",\n \"import\": \"./dist/agent/index.mjs\"\n }\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/langwatch/langwatch.git\",\n \"directory\": \"typescript-sdk\"\n },\n \"scripts\": {\n \"generate\": \"pnpm run generate:server-types && pnpm run generate:openapi-types\",\n \"cli\": \"node dist/cli/index.js\",\n \"prelint\": \"pnpm run generate\",\n \"lint\": \"eslint .\",\n \"pretest\": \"pnpm run generate\",\n \"test\": \"vitest\",\n \"test:unit\": \"vitest run --exclude '**/*.integration.test.ts'\",\n \"test:e2e\": \"dotenv -- vitest run -c ./vitest.e2e.config.mts\",\n \"test:governance-e2e\": \"vitest run -c ./vitest.governance-e2e.config.mts\",\n \"test:seed\": \"dotenv -e .env.test -- bash -c 'cd ../../platform/app && pnpm prisma:seed'\",\n \"prebuild\": \"pnpm run generate\",\n \"build\": \"tsc --noEmit && rm -rf dist && tsup\",\n \"postbuild\": \"node -e \\\"const{statSync}=require('node:fs'),{execFileSync}=require('node:child_process');const f='dist/cli/index.js',want=require('./package.json').version;const s=statSync(f);if(process.platform!=='win32'&&!(s.mode&0o111))throw new Error(f+' is not executable');const got=execFileSync(process.execPath,[f,'--version'],{encoding:'utf8',env:{...process.env,LANGWATCH_NO_DAEMON:'1'}}).trim();if(got!==want)throw new Error('version mismatch: '+f+' reports '+got+', package.json says '+want);console.log('postbuild: '+f+' ok ('+got+')')\\\"\",\n \"build:binary\": \"bun run scripts/build-cli-binary.ts\",\n \"tarball\": \"pnpm build && pnpm pack\",\n \"typecheck\": \"tsc --noEmit\",\n \"prepublish\": \"pnpm run build\",\n \"generate:openapi-types\": \"pnpm exec openapi-typescript ../../platform/app/src/app/api/openapiLangWatch.json -o ./src/internal/generated/openapi/api-client.ts && node scripts/patch-generated-openapi.mjs\",\n \"generate:server-types\": \"./copy-types.sh\"\n },\n \"devDependencies\": {\n \"@eslint/js\": \"^9.32.0\",\n \"@langchain/core\": \">=0.3.68 <0.4.0\",\n \"@langchain/langgraph\": \">=0.4.0 <1.0.0\",\n \"@langchain/openai\": \">=0.6.0 <1.0.0\",\n \"@langwatch/langy\": \"workspace:*\",\n \"@opentelemetry/sdk-node\": \"0.221.0\",\n \"@opentelemetry/sdk-trace-node\": \"^2.0.1\",\n \"@opentelemetry/sdk-trace-web\": \">=2.0.1\",\n \"@types/debug\": \"^4.1.12\",\n \"@types/js-yaml\": \"^4.0.9\",\n \"@types/node\": \"^26.2.0\",\n \"@types/prompts\": \"^2.4.9\",\n \"@types/ws\": \"^8.18.1\",\n \"@vercel/otel\": \"^1.13.0\",\n \"@vitest/coverage-v8\": \"^4.1.0\",\n \"dotenv-cli\": \"^11.0.0\",\n \"esbuild\": \"^0.28.1\",\n \"eslint\": \"^9.32.0\",\n \"fets\": \"^0.8.5\",\n \"fishery\": \"^2.3.1\",\n \"langchain\": \">=0.3.0 <2.0.0\",\n \"msw\": \"^2.10.4\",\n \"nock\": \"^14.0.8\",\n \"openapi-msw\": \"^1.2.0\",\n \"openapi-typescript\": \"7.13.0\",\n \"tsup\": \"^8.5.0\",\n \"typescript\": \"^6.0.3\",\n \"typescript-eslint\": \"^8.38.0\",\n \"vitest\": \"^4.1.0\",\n \"vitest-mock-extended\": \"^5.1.1\",\n \"yaml\": \"^2.8.1\"\n },\n \"dependencies\": {\n \"@opentelemetry/api\": \"^1.9.0\",\n \"@opentelemetry/api-logs\": \"0.221.0\",\n \"@opentelemetry/core\": \"^2.0.1\",\n \"@opentelemetry/exporter-logs-otlp-http\": \"0.221.0\",\n \"@opentelemetry/exporter-trace-otlp-http\": \"0.221.0\",\n \"@opentelemetry/instrumentation\": \"0.221.0\",\n \"@opentelemetry/resources\": \"^2.0.1\",\n \"@opentelemetry/sdk-logs\": \"0.221.0\",\n \"@opentelemetry/sdk-metrics\": \"^2.0.1\",\n \"@opentelemetry/sdk-node\": \"^0.221.0\",\n \"@opentelemetry/sdk-trace-base\": \"^2.0.1\",\n \"@opentelemetry/semantic-conventions\": \"^1.36.0\",\n \"chalk\": \"^6.0.0\",\n \"cloudflared\": \"0.7.1\",\n \"commander\": \"^15.0.0\",\n \"dotenv\": \"^17.3.1\",\n \"js-yaml\": \"^5.2.0\",\n \"jsonc-parser\": \"^3.3.1\",\n \"liquidjs\": \"^10.27.0\",\n \"open\": \"^11.0.0\",\n \"openapi-fetch\": \"^0.17.0\",\n \"ora\": \"^9.3.0\",\n \"prompts\": \"^2.4.2\",\n \"ws\": \"^8.21.0\",\n \"xksuid\": \"^0.0.4\",\n \"zod\": \"^4.0.14\"\n },\n \"peerDependencies\": {\n \"@ai-sdk/openai\": \">=2.0.0 <5.0.0\",\n \"@langchain/core\": \">=0.3.0 <2.0.0\",\n \"@langchain/langgraph\": \">=0.4.0 <2.0.0\",\n \"@langchain/openai\": \">=0.6.0 <2.0.0\",\n \"@opentelemetry/context-async-hooks\": \"^2.1.0\",\n \"@opentelemetry/context-zone\": \">=1.19.0 <3.0.0\",\n \"@opentelemetry/sdk-trace-web\": \">=1.19.0 <3.0.0\",\n \"langchain\": \">=0.3.0 <2.0.0\"\n },\n \"peerDependenciesMeta\": {\n \"@ai-sdk/openai\": {\n \"optional\": true\n },\n \"@langchain/core\": {\n \"optional\": true\n },\n \"@langchain/langgraph\": {\n \"optional\": true\n },\n \"@langchain/openai\": {\n \"optional\": true\n },\n \"@opentelemetry/context-async-hooks\": {\n \"optional\": true\n },\n \"@opentelemetry/context-zone\": {\n \"optional\": true\n },\n \"@opentelemetry/sdk-trace-web\": {\n \"optional\": true\n },\n \"langchain\": {\n \"optional\": true\n }\n }\n}\n","import { version } from \"../../package.json\";\nimport { getRuntime } from \"./runtime\";\n\nexport const LANGWATCH_SDK_RUNTIME = getRuntime;\n\nexport const LANGWATCH_SDK_NAME_OBSERVABILITY = \"langwatch-observability-sdk\";\nexport const LANGWATCH_SDK_NAME_CLIENT = \"langwatch-client-sdk\";\nexport const LANGWATCH_SDK_LANGUAGE = \"typescript\";\nexport const LANGWATCH_SDK_VERSION = version;\n\nexport const DEFAULT_ENDPOINT = \"https://app.langwatch.ai\";\nexport const DEFAULT_SERVICE_NAME = \"unknown-service.langwatch\";\n\nexport const TRACES_PATH = \"/api/otel/v1/traces\";\nexport const LOGS_PATH = \"/api/otel/v1/logs\";\nexport const METRICS_PATH = \"/api/otel/v1/metrics\";\n","/**\n * Single place where a configured LangWatch endpoint becomes a usable base URL.\n *\n * Most services build request URLs by concatenation — `${endpoint}/api/...` —\n * and every path already carries its own leading slash. A trailing slash on the\n * endpoint therefore yields `https://app.langwatch.ai//api/experiment/init`,\n * which the router does not match, and the caller gets an opaque\n * `{\"error\":\"Not Found\"}` with nothing pointing at the real cause. Normalizing\n * at the point of resolution keeps every call site free of that concern.\n */\n\nimport { DEFAULT_ENDPOINT } from \"./constants\";\n\nconst isSet = (value: string | null | undefined): value is string =>\n typeof value === \"string\" && value.trim() !== \"\";\n\n/**\n * Trim surrounding whitespace and drop any trailing slashes.\n *\n * Scanned rather than matched with `/\\/+$/`: a repeated character class bound\n * to an anchor backtracks from every start index, which is quadratic on a\n * string of many slashes. The endpoint is configuration rather than attacker\n * input, but a linear scan costs nothing and leaves no such edge to reason\n * about.\n */\nexport const normalizeEndpoint = (endpoint: string): string => {\n const trimmed = endpoint.trim();\n let end = trimmed.length;\n while (end > 0 && trimmed[end - 1] === \"/\") end--;\n return trimmed.slice(0, end);\n};\n\n/**\n * Resolve the endpoint from an explicit value, then `LANGWATCH_ENDPOINT`, then\n * the cloud default. Blank values are treated as unset so that an empty\n * `LANGWATCH_ENDPOINT=` in a `.env` falls through to the default rather than\n * producing relative request URLs.\n */\nexport const resolveEndpoint = (endpoint?: string | null): string => {\n for (const candidate of [endpoint, process.env.LANGWATCH_ENDPOINT]) {\n if (!isSet(candidate)) continue;\n const normalized = normalizeEndpoint(candidate);\n if (normalized !== \"\") return normalized;\n }\n return normalizeEndpoint(DEFAULT_ENDPOINT);\n};\n\n/**\n * The OTLP logs endpoint an environment asks for, per the OTel exporter spec:\n * the signal-specific variable wins and is used verbatim; the generic variable\n * is a base that `/v1/logs` hangs off. Null when neither is set, which means no\n * OTLP transport rather than a default one.\n *\n * It lives here rather than beside either of its callers because both need it\n * and their module graphs must stay apart. The CLI's live event channel loads\n * the OpenTelemetry logs pipeline and the card contract; the session context\n * hook is bundled into a zero-dependency single file that ships inside the\n * agent plugin. Reaching into the event channel for this one pure env read\n * would put the whole telemetry graph in that bundle.\n */\nexport const resolveLogsEndpoint = (\n env: NodeJS.ProcessEnv = process.env,\n): string | null => {\n const signal = env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT?.trim();\n if (signal) return signal;\n\n const generic = env.OTEL_EXPORTER_OTLP_ENDPOINT?.trim();\n if (generic) return `${normalizeEndpoint(generic)}/v1/logs`;\n\n return null;\n};\n","/**\n * The frames the SDK and the platform exchange over the agent socket.\n *\n * Every frame is one JSON text message with a `type` and the protocol\n * version. The shapes here match the contract table in ADR-128 and the\n * platform's own frame module; the validators are small and hand-written\n * because this file is part of the public `langwatch/agent` surface, where no\n * schema library may cross as a value.\n *\n * @see dev/docs/adr/128-connected-agents.md\n */\n\nexport const PROTOCOL_VERSION = 1;\n\n/** One conversation message, OpenAI style. Extra keys are carried as is. */\nexport interface AgentMessage {\n role: string;\n content?: unknown;\n [key: string]: unknown;\n}\n\n/** The value of one run parameter as the platform sends it. */\nexport type AgentParameterValue = string | number | boolean;\n\n/** A JSON Schema object as the SDK sends it in `register`. */\nexport type JsonSchemaObject = Record<string, unknown>;\n\nexport interface RegisterSdk {\n name: string;\n version: string;\n language: string;\n}\n\nexport interface RegisterInstance {\n id: string;\n hostname: string;\n username: string;\n pid: number;\n startedAt: string;\n label?: string;\n inFlightCallIds: string[];\n}\n\nexport interface RegisterAgent {\n name: string;\n environment: string;\n parameters: JsonSchemaObject;\n concurrency?: number;\n timeoutMs?: number;\n sticky?: boolean;\n}\n\nexport interface RegisterFrame {\n type: \"register\";\n protocol: typeof PROTOCOL_VERSION;\n sdk: RegisterSdk;\n instance: RegisterInstance;\n agents: RegisterAgent[];\n}\n\nexport interface AckFrame {\n type: \"ack\";\n protocol: typeof PROTOCOL_VERSION;\n callId: string;\n}\n\nexport interface CallError {\n code: string;\n message: string;\n}\n\nexport type ResultFrame =\n | {\n type: \"result\";\n protocol: typeof PROTOCOL_VERSION;\n callId: string;\n output: unknown;\n session?: unknown;\n }\n | {\n type: \"result\";\n protocol: typeof PROTOCOL_VERSION;\n callId: string;\n error: CallError;\n };\n\nexport interface DeregisterFrame {\n type: \"deregister\";\n protocol: typeof PROTOCOL_VERSION;\n}\n\n/** Everything the SDK sends. */\nexport type ClientFrame = RegisterFrame | AckFrame | ResultFrame | DeregisterFrame;\n\nexport interface RegisteredAgent {\n name: string;\n environment: string;\n id: string;\n url: string;\n parameterNotes: string[];\n}\n\nexport interface RegisteredFrame {\n type: \"registered\";\n protocol: number;\n agents: RegisteredAgent[];\n heartbeatIntervalMs: number;\n instanceId: string;\n}\n\nexport interface RefusedFrame {\n type: \"refused\";\n protocol: number;\n code: string;\n message: string;\n /** Extra data for one code, for example the projects a key reaches under `project_required`. */\n meta?: Record<string, unknown>;\n}\n\nexport interface CallRun {\n scenarioRunId?: string;\n scenarioName?: string;\n batchRunId?: string;\n}\n\nexport interface CallFrame {\n type: \"call\";\n protocol: number;\n callId: string;\n agentId: string;\n threadId: string;\n messages: AgentMessage[];\n newMessages: AgentMessage[];\n params: Record<string, AgentParameterValue>;\n session: unknown;\n traceparent: string | null;\n /** Epoch milliseconds, null when the platform sent none. */\n deadlineAt: number | null;\n run: CallRun;\n}\n\nexport interface CancelFrame {\n type: \"cancel\";\n protocol: number;\n callId: string;\n}\n\n/** Everything the platform sends. */\nexport type ServerFrame = RegisteredFrame | RefusedFrame | CallFrame | CancelFrame;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isString = (value: unknown): value is string => typeof value === \"string\";\n\nconst isMessageList = (value: unknown): value is AgentMessage[] =>\n Array.isArray(value) && value.every((item) => isRecord(item) && isString(item.role));\n\nconst isStringList = (value: unknown): value is string[] =>\n Array.isArray(value) && value.every(isString);\n\nconst readRegistered = (frame: Record<string, unknown>): RegisteredFrame | null => {\n if (!Array.isArray(frame.agents) || !isString(frame.instanceId)) return null;\n const agents: RegisteredAgent[] = [];\n for (const entry of frame.agents) {\n if (!isRecord(entry) || !isString(entry.name)) return null;\n const id = isString(entry.id) ? entry.id : isString(entry.agentId) ? entry.agentId : null;\n if (id === null) return null;\n agents.push({\n name: entry.name,\n environment: isString(entry.environment) ? entry.environment : \"\",\n id,\n url: isString(entry.url) ? entry.url : \"\",\n parameterNotes: isStringList(entry.parameterNotes) ? entry.parameterNotes : [],\n });\n }\n return {\n type: \"registered\",\n protocol: typeof frame.protocol === \"number\" ? frame.protocol : PROTOCOL_VERSION,\n agents,\n heartbeatIntervalMs:\n typeof frame.heartbeatIntervalMs === \"number\" ? frame.heartbeatIntervalMs : 10_000,\n instanceId: frame.instanceId,\n };\n};\n\nconst readRefused = (frame: Record<string, unknown>): RefusedFrame => ({\n type: \"refused\",\n protocol: typeof frame.protocol === \"number\" ? frame.protocol : PROTOCOL_VERSION,\n code: isString(frame.code) ? frame.code : \"agent_register_refused\",\n message: isString(frame.message) ? frame.message : \"The platform refused the registration.\",\n ...(isRecord(frame.meta) ? { meta: frame.meta } : {}),\n});\n\nconst readParams = (value: unknown): Record<string, AgentParameterValue> => {\n if (!isRecord(value)) return {};\n const params: Record<string, AgentParameterValue> = {};\n for (const [name, item] of Object.entries(value)) {\n if (typeof item === \"string\" || typeof item === \"number\" || typeof item === \"boolean\") {\n params[name] = item;\n }\n }\n return params;\n};\n\n/** A deadline as epoch milliseconds, from a number or an ISO string. */\nconst readDeadline = (value: unknown): number | null => {\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (isString(value)) {\n const parsed = Date.parse(value);\n return Number.isNaN(parsed) ? null : parsed;\n }\n return null;\n};\n\nconst readCall = (frame: Record<string, unknown>): CallFrame | null => {\n if (!isString(frame.callId) || !isString(frame.agentId)) return null;\n const messages = isMessageList(frame.messages) ? frame.messages : [];\n const run = isRecord(frame.run) ? frame.run : {};\n return {\n type: \"call\",\n protocol: typeof frame.protocol === \"number\" ? frame.protocol : PROTOCOL_VERSION,\n callId: frame.callId,\n agentId: frame.agentId,\n threadId: isString(frame.threadId) ? frame.threadId : \"\",\n messages,\n newMessages: isMessageList(frame.newMessages) ? frame.newMessages : messages,\n params: readParams(frame.params),\n session: frame.session === undefined ? null : frame.session,\n traceparent: isString(frame.traceparent) ? frame.traceparent : null,\n deadlineAt: readDeadline(frame.deadlineAt),\n run: {\n ...(isString(run.scenarioRunId) ? { scenarioRunId: run.scenarioRunId } : {}),\n ...(isString(run.scenarioName) ? { scenarioName: run.scenarioName } : {}),\n ...(isString(run.batchRunId) ? { batchRunId: run.batchRunId } : {}),\n },\n };\n};\n\n/**\n * Reads one text message from the platform into a typed frame, or null when\n * the message is not a frame this protocol version knows. Unknown types and\n * malformed frames are dropped rather than thrown, so a newer platform never\n * crashes an older SDK.\n */\nexport function parseServerFrame(raw: string): ServerFrame | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return null;\n }\n if (!isRecord(parsed) || !isString(parsed.type)) return null;\n switch (parsed.type) {\n case \"registered\":\n return readRegistered(parsed);\n case \"refused\":\n return readRefused(parsed);\n case \"call\":\n return readCall(parsed);\n case \"cancel\":\n return isString(parsed.callId)\n ? {\n type: \"cancel\",\n protocol: typeof parsed.protocol === \"number\" ? parsed.protocol : PROTOCOL_VERSION,\n callId: parsed.callId,\n }\n : null;\n default:\n return null;\n }\n}\n\n/** One frame as the text the socket carries. */\nexport function serializeFrame(frame: ClientFrame): string {\n return JSON.stringify(frame);\n}\n\n/** The trace id of a W3C traceparent header, or null when it does not parse. */\nexport function traceIdFromTraceparent(traceparent: string | null | undefined): string | null {\n if (!traceparent) return null;\n const parts = traceparent.trim().split(\"-\");\n const traceId = parts[1];\n if (parts.length < 4 || !traceId || !/^[0-9a-f]{32}$/i.test(traceId)) return null;\n return traceId.toLowerCase();\n}\n","/**\n * The run parameters an agent declares, and the values a call supplies.\n *\n * Three forms are accepted: a definition map, any Standard JSON Schema object\n * (read through `\"~standard\".jsonSchema`, so zod 4, valibot and arktype work\n * without this package importing them), or a plain JSON Schema. A schema\n * library instance that offers no JSON Schema converter is refused with the\n * three forms named, because the SDK never takes a zod instance as a value.\n */\n\nimport type { AgentParameterValue, JsonSchemaObject } from \"./protocol\";\n\n/** The scalar types a run parameter may hold. */\nexport type ParameterType = \"string\" | \"number\" | \"boolean\";\n\n/** One entry of the definition map. */\nexport interface ParameterDefinition {\n /** The value type. Read from `options`, then `default`, else string. */\n type?: ParameterType;\n /** A closed list of accepted values. */\n options?: readonly string[];\n /** The value a run takes when it does not supply one. Without it the parameter is required. */\n default?: AgentParameterValue;\n description?: string;\n}\n\n/** Parameters declared by name. */\nexport type ParameterDefinitions = Record<string, ParameterDefinition>;\n\n/**\n * The Standard JSON Schema converter an object exposes under `\"~standard\"`.\n * Method syntax on purpose: a library narrows `target` to its own union, and\n * a method parameter is checked bivariantly, so zod 4, valibot and arktype\n * all fit without the SDK naming any of them.\n */\nexport interface StandardJsonSchemaConverter {\n input?(options: { readonly target: string }): Record<string, unknown>;\n output?(options: { readonly target: string }): Record<string, unknown>;\n}\n\n/** One problem a Standard Schema `validate` reports. */\nexport interface StandardSchemaIssue {\n readonly message: string;\n readonly path?: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }> | undefined;\n}\n\nexport type StandardSchemaResult<O> =\n | { readonly value: O; readonly issues?: undefined }\n | { readonly issues: ReadonlyArray<StandardSchemaIssue> };\n\n/**\n * Any object that implements the Standard JSON Schema interface. When it also\n * implements Standard Schema (`validate`), the values of every call go\n * through it before the handler runs, so a zod 4 schema validates, fills its\n * defaults and types `params` in one place.\n */\nexport interface StandardJsonSchema<O = unknown> {\n readonly \"~standard\": {\n readonly jsonSchema: StandardJsonSchemaConverter;\n validate?(value: unknown): StandardSchemaResult<O> | Promise<StandardSchemaResult<O>>;\n /** Type-only, from Standard Schema: the parsed output type. */\n readonly types?: { readonly input: unknown; readonly output: O } | undefined;\n };\n}\n\n/** The `params` type a Standard Schema object gives the handler: its parsed output. */\nexport type InferStandardOutput<S> = S extends { readonly \"~standard\": { readonly types?: infer T } }\n ? [NonNullable<T>] extends [never]\n ? Record<string, AgentParameterValue>\n : NonNullable<T> extends { readonly output: infer O }\n ? O extends Record<string, unknown>\n ? O\n : Record<string, AgentParameterValue>\n : Record<string, AgentParameterValue>\n : Record<string, AgentParameterValue>;\n\n/** Every form `parameters` accepts. */\nexport type ParameterInput = ParameterDefinitions | StandardJsonSchema | JsonSchemaObject;\n\n/** One parameter as the platform lists it, derived from the schema. */\nexport interface ParameterSpec {\n name: string;\n type: ParameterType;\n options?: string[];\n default?: AgentParameterValue;\n description?: string;\n required?: boolean;\n}\n\n/** The refusal of a parameter definition or of a value a call supplied. */\nexport class AgentParameterError extends Error {\n readonly code = \"agent_parameter_invalid\";\n constructor(message: string) {\n super(message);\n this.name = \"AgentParameterError\";\n }\n}\n\nconst ACCEPTED_FORMS =\n \"parameters must be a definition map ({ model: { options: [...], default: '...' } }), a Standard JSON Schema object (one with \\\"~standard\\\".jsonSchema), or a JSON Schema object ({ type: 'object', properties })\";\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isStandardJsonSchema = (value: unknown): value is StandardJsonSchema => {\n if (!isRecord(value)) return false;\n const standard = value[\"~standard\"];\n return isRecord(standard) && isRecord(standard.jsonSchema);\n};\n\nconst isJsonSchemaObject = (value: unknown): value is JsonSchemaObject =>\n isRecord(value) && value.type === \"object\" && isRecord(value.properties);\n\nconst isDefinitionMap = (value: unknown): value is ParameterDefinitions =>\n isRecord(value) && Object.values(value).every(isRecord);\n\nconst definitionType = (definition: ParameterDefinition): ParameterType => {\n if (definition.type) return definition.type;\n if (definition.options) return \"string\";\n const value = definition.default;\n if (typeof value === \"number\") return \"number\";\n if (typeof value === \"boolean\") return \"boolean\";\n return \"string\";\n};\n\nconst definitionMapToSchema = (definitions: ParameterDefinitions): JsonSchemaObject => {\n const properties: Record<string, Record<string, unknown>> = {};\n const required: string[] = [];\n for (const [name, definition] of Object.entries(definitions)) {\n const property: Record<string, unknown> = { type: definitionType(definition) };\n if (definition.options) property.enum = [...definition.options];\n if (definition.default !== undefined) property.default = definition.default;\n else required.push(name);\n if (definition.description !== undefined) property.description = definition.description;\n properties[name] = property;\n }\n const schema: JsonSchemaObject = { type: \"object\", properties };\n if (required.length > 0) schema.required = required;\n return schema;\n};\n\nconst readStandardJsonSchema = (input: StandardJsonSchema): JsonSchemaObject => {\n const converter = input[\"~standard\"].jsonSchema;\n const options = { target: \"draft-2020-12\" };\n const schema = converter.input?.(options) ?? converter.output?.(options);\n if (schema === undefined) {\n throw new AgentParameterError(`the \"~standard\".jsonSchema converter has no input function; ${ACCEPTED_FORMS}`);\n }\n if (!isRecord(schema)) {\n throw new AgentParameterError(`the \"~standard\".jsonSchema converter returned no object; ${ACCEPTED_FORMS}`);\n }\n return schema;\n};\n\n/**\n * The parameter schema the `register` frame carries, from any accepted form.\n * No parameters is an object schema with no properties.\n */\nexport function toParameterSchema(input: ParameterInput | undefined): JsonSchemaObject {\n if (input === undefined) return { type: \"object\", properties: {} };\n if (isStandardJsonSchema(input)) return readStandardJsonSchema(input);\n if (isJsonSchemaObject(input)) return input;\n if (isDefinitionMap(input)) return definitionMapToSchema(input);\n throw new AgentParameterError(ACCEPTED_FORMS);\n}\n\nconst specType = (property: Record<string, unknown>): ParameterType => {\n const type = Array.isArray(property.type)\n ? property.type.find((item) => item !== \"null\")\n : property.type;\n if (type === \"number\" || type === \"integer\") return \"number\";\n if (type === \"boolean\") return \"boolean\";\n return \"string\";\n};\n\nconst scalar = (value: unknown): AgentParameterValue | undefined =>\n typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\"\n ? value\n : undefined;\n\n/**\n * The parameters a schema declares, one spec per property, the way the\n * platform lists them. Unsupported property types read as text.\n */\nexport function parameterSpecsFromSchema(schema: JsonSchemaObject): ParameterSpec[] {\n const properties = isRecord(schema.properties) ? schema.properties : {};\n const required = new Set(Array.isArray(schema.required) ? schema.required : []);\n const specs: ParameterSpec[] = [];\n for (const [name, raw] of Object.entries(properties)) {\n const property = isRecord(raw) ? raw : {};\n const spec: ParameterSpec = { name, type: specType(property) };\n const options = Array.isArray(property.enum)\n ? property.enum.filter((item): item is string => typeof item === \"string\")\n : undefined;\n if (options && options.length > 0) spec.options = options;\n const fallback = scalar(property.default);\n if (fallback !== undefined) spec.default = fallback;\n if (typeof property.description === \"string\") spec.description = property.description;\n spec.required = fallback === undefined && required.has(name);\n specs.push(spec);\n }\n return specs;\n}\n\nconst coerce = ({\n spec,\n value,\n}: {\n spec: ParameterSpec;\n value: AgentParameterValue;\n}): AgentParameterValue => {\n if (spec.type === \"number\") {\n const asNumber = typeof value === \"number\" ? value : Number(value);\n if (typeof value === \"boolean\" || !Number.isFinite(asNumber) || String(value).trim() === \"\") {\n throw new AgentParameterError(`parameter \"${spec.name}\" must be a number, got ${JSON.stringify(value)}`);\n }\n return asNumber;\n }\n if (spec.type === \"boolean\") {\n if (typeof value === \"boolean\") return value;\n if (value === \"true\") return true;\n if (value === \"false\") return false;\n throw new AgentParameterError(`parameter \"${spec.name}\" must be true or false, got ${JSON.stringify(value)}`);\n }\n const asString = typeof value === \"string\" ? value : String(value);\n if (spec.options && !spec.options.includes(asString)) {\n throw new AgentParameterError(\n `parameter \"${spec.name}\" must be one of ${spec.options.join(\", \")}, got ${JSON.stringify(value)}`,\n );\n }\n return asString;\n};\n\n/**\n * The values the handler receives: every declared parameter, from the call or\n * from its default. A required parameter with no value, or a value of the\n * wrong type or outside the options, is refused with `agent_parameter_invalid`\n * before the handler runs. Names the schema does not declare pass through.\n */\nexport function resolveParameterValues({\n specs,\n supplied,\n}: {\n specs: ParameterSpec[];\n supplied: Record<string, AgentParameterValue> | undefined;\n}): Record<string, AgentParameterValue> {\n const values: Record<string, AgentParameterValue> = { ...(supplied ?? {}) };\n for (const spec of specs) {\n const value = values[spec.name];\n if (value === undefined) {\n if (spec.default !== undefined) {\n values[spec.name] = spec.default;\n continue;\n }\n if (!spec.required) continue;\n throw new AgentParameterError(`parameter \"${spec.name}\" is required and the run did not supply it`);\n }\n values[spec.name] = coerce({ spec, value });\n }\n return values;\n}\n\nconst issuePath = (issue: StandardSchemaIssue): string =>\n (issue.path ?? [])\n .map((segment) =>\n typeof segment === \"object\" && segment !== null ? String(segment.key) : String(segment),\n )\n .join(\".\");\n\n/**\n * The values after the schema's own `validate`: a zod 4 schema refines,\n * fills its defaults and strips what it does not declare. A refusal names\n * every issue with its path. Names the schema does not declare pass through\n * untouched, so a scenario-declared parameter still reaches the handler.\n */\nexport async function validateParameterValues({\n schema,\n values,\n}: {\n schema: StandardJsonSchema;\n values: Record<string, AgentParameterValue>;\n}): Promise<Record<string, AgentParameterValue>> {\n const standard = schema[\"~standard\"];\n const result = await standard.validate?.(values);\n if (result === undefined) return values;\n if (result.issues) {\n const detail = result.issues\n .map((issue) => {\n const path = issuePath(issue);\n return path ? `${path}: ${issue.message}` : issue.message;\n })\n .join(\"; \");\n throw new AgentParameterError(`parameters refused by the schema: ${detail}`);\n }\n const parsed = isRecord(result.value) ? (result.value as Record<string, AgentParameterValue>) : {};\n return { ...values, ...parsed };\n}\n\n/** What every call's parameters go through before the handler runs. */\nexport type ParameterReader = (\n supplied: Record<string, AgentParameterValue> | undefined,\n) => Promise<Record<string, AgentParameterValue>>;\n\n/**\n * The reader of one agent: defaults and coercion from the specs, then the\n * schema's own validation when the input carries one.\n */\nexport function createParameterReader({\n input,\n specs,\n}: {\n input: ParameterInput | undefined;\n specs: ParameterSpec[];\n}): ParameterReader {\n const schema = isStandardJsonSchema(input) ? input : undefined;\n return async (supplied) => {\n const values = resolveParameterValues({ specs, supplied });\n return schema ? validateParameterValues({ schema, values }) : values;\n };\n}\n","/**\n * The connection the client speaks over, behind one small interface so the\n * client never depends on how the frames travel.\n *\n * Two transports carry the same frames. The WebSocket is the default and it\n * needs the `ws` package: the platform authenticates from the request\n * headers of the upgrade, and no global `WebSocket` constructor can send\n * them. HTTP long polling is for a network that blocks WebSockets: one POST\n * registers, a GET waits for the next frames, a POST carries the answers. It\n * speaks through the global `fetch` (Node 20+).\n */\n\nimport { createRequire } from \"node:module\";\nimport type { WebSocket as WsWebSocket } from \"ws\";\nimport { langwatchFetch } from \"../internal/http/langwatchFetch\";\n\nexport const AGENT_TRANSPORTS = [\"websocket\", \"http\"] as const;\nexport type AgentTransport = (typeof AGENT_TRANSPORTS)[number];\n\n/** The header the poll and frames requests carry the instance token in. */\nexport const INSTANCE_TOKEN_HEADER = \"X-Agent-Instance-Token\";\n\nconst isSet = (value: string | undefined): value is string =>\n typeof value === \"string\" && value.trim() !== \"\";\n\n/**\n * The transport to start with: the explicit option, then\n * `LANGWATCH_AGENT_TRANSPORT`, else the WebSocket. Anything that is not\n * `http` is the WebSocket, which falls back to HTTP on its own when the\n * upgrade is refused.\n */\nexport function resolveTransport({\n explicit,\n env = process.env,\n}: {\n explicit?: string;\n env?: NodeJS.ProcessEnv;\n}): AgentTransport {\n const candidate = isSet(explicit) ? explicit : env.LANGWATCH_AGENT_TRANSPORT;\n return isSet(candidate) && candidate.trim().toLowerCase() === \"http\" ? \"http\" : \"websocket\";\n}\n\nexport interface SocketLike {\n send: (data: string) => void;\n close: (code?: number, reason?: string) => void;\n /** Drop the connection without a close handshake. */\n terminate: () => void;\n onOpen: (listener: () => void) => void;\n onMessage: (listener: (data: string) => void) => void;\n onClose: (listener: (code: number) => void) => void;\n onError: (listener: (error: unknown) => void) => void;\n /** The platform pings for liveness; the pong is automatic, this only reports it. */\n onPing: (listener: () => void) => void;\n /**\n * The upgrade was answered with an HTTP status instead of a switch of\n * protocols: a proxy in the way. Only `ws` can tell; the close follows.\n */\n onUpgradeRefused?: (listener: (status: number) => void) => void;\n}\n\nexport type SocketFactory = (args: { url: string; headers: Record<string, string> }) => SocketLike;\n\n/** Thrown when the `ws` package is not installed. */\nexport class NoWebSocketError extends Error {\n constructor() {\n super(\"the ws package is not installed, so no socket can carry the API key header\");\n this.name = \"NoWebSocketError\";\n }\n}\n\nconst textOf = (data: unknown): string => {\n if (typeof data === \"string\") return data;\n if (Buffer.isBuffer(data)) return data.toString(\"utf8\");\n if (Array.isArray(data)) return Buffer.concat(data as Buffer[]).toString(\"utf8\");\n if (data instanceof ArrayBuffer) return Buffer.from(data).toString(\"utf8\");\n return String(data);\n};\n\nconst wrapWs = (socket: WsWebSocket): SocketLike => {\n const closeListeners: Array<(code: number) => void> = [];\n let closed = false;\n const emitClose = (code: number) => {\n if (closed) return;\n closed = true;\n for (const listener of closeListeners) listener(code);\n };\n socket.on(\"close\", (code) => emitClose(code));\n return {\n send: (data) => socket.send(data),\n close: (code, reason) => socket.close(code, reason),\n terminate: () => socket.terminate(),\n onOpen: (listener) => socket.on(\"open\", listener),\n onMessage: (listener) => socket.on(\"message\", (data) => listener(textOf(data))),\n onClose: (listener) => closeListeners.push(listener),\n onError: (listener) => socket.on(\"error\", listener),\n onPing: (listener) => socket.on(\"ping\", listener),\n onUpgradeRefused: (listener) =>\n socket.on(\"unexpected-response\", (request, response) => {\n listener(response.statusCode ?? 0);\n // With a listener attached, `ws` leaves the request open and emits\n // no close of its own; both are finished here.\n response.resume();\n request.destroy();\n emitClose(1006);\n }),\n };\n};\n\ntype WsConstructor = new (\n url: string,\n options: { headers: Record<string, string> },\n) => WsWebSocket;\n\n/**\n * The `ws` constructor, or null when the package cannot be loaded. It is\n * required rather than imported: a runtime or a bundle without `ws` must\n * reach the factory below and get one clear message, never fail while this\n * module loads.\n */\nconst wsConstructor = (): WsConstructor | null => {\n try {\n const loaded = createRequire(__filename)(\"ws\") as { WebSocket?: unknown };\n return typeof loaded.WebSocket === \"function\" ? (loaded.WebSocket as WsConstructor) : null;\n } catch {\n return null;\n }\n};\n\n/**\n * Opens a socket with `ws`. A global `WebSocket` is no substitute: it takes\n * no request headers, the API key never travels in the URL, and the platform\n * would refuse every socket it opened.\n */\nexport const defaultSocketFactory: SocketFactory = ({ url, headers }) => {\n const Ws = wsConstructor();\n if (!Ws) throw new NoWebSocketError();\n return wrapWs(new Ws(url, { headers }));\n};\n\n// ---------------------------------------------------------------------------\n// HTTP long polling\n// ---------------------------------------------------------------------------\n\n/** The close code the client reads as \"register again at once\". */\nexport const SESSION_LOST_CLOSE_CODE = 1012;\n\n/** How a failed post of a frame is retried before the session is dropped. */\nconst POST_RETRY_DELAYS_MS = [250, 500, 1000];\n\n/**\n * The shortest gap between a poll that answered no frames and the next one.\n * The platform holds a poll for its own wait, so this costs nothing there; it\n * bounds a proxy that answers at once, which would otherwise spin.\n */\nconst EMPTY_POLL_FLOOR_MS = 250;\n\n/**\n * How long a close waits for the queued frames to go out before it drops them.\n * A frames request has no deadline of its own, so a proxy that accepts the\n * request and never answers would otherwise keep the socket from ever\n * reporting its close, and the client that is waiting to open a replacement\n * would wait with it.\n */\nconst CLOSE_DEADLINE_MS = 500;\n\nconst describe = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\nconst wait = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms).unref());\n\nexport interface HttpLongPollOptions {\n /** `https://app.langwatch.ai/api/v1/agents/connect`, the base the three routes hang off. */\n url: string;\n headers: Record<string, string>;\n fetch?: typeof fetch;\n}\n\n/**\n * The same frames over three requests. `send` of a register frame posts it\n * and starts the poll loop on the registered answer; `send` of any other\n * frame posts it in order; every frame a poll answers with is a message.\n * A poll that is refused, that fails or that names an unknown session ends\n * the connection the way a dropped socket would, and the client reconnects\n * with its own backoff, registering again.\n */\nexport class HttpLongPollSocket implements SocketLike {\n private readonly url: string;\n private readonly headers: Record<string, string>;\n private readonly fetchImpl: typeof fetch;\n private readonly messageListeners: Array<(data: string) => void> = [];\n private readonly closeListeners: Array<(code: number) => void> = [];\n private readonly errorListeners: Array<(error: unknown) => void> = [];\n private readonly pingListeners: Array<() => void> = [];\n private readonly inFlight = new Set<string>();\n private readonly polls = new AbortController();\n private readonly frames = new AbortController();\n private outbox: Promise<void> = Promise.resolve();\n private token: string | null = null;\n private closed = false;\n private closeEmitted = false;\n /** Settled once the register was answered, so a frame sent before it waits. */\n private readonly registered: Promise<void>;\n private settleRegistered: () => void = () => undefined;\n\n constructor(options: HttpLongPollOptions) {\n this.url = options.url;\n this.headers = options.headers;\n const fetchImpl = options.fetch ?? (typeof globalThis.fetch === \"function\" ? langwatchFetch : undefined);\n if (typeof fetchImpl !== \"function\") {\n throw new Error(\"the HTTP transport needs a global fetch; run on Node 20 or later\");\n }\n this.fetchImpl = fetchImpl;\n this.registered = new Promise<void>((resolve) => {\n this.settleRegistered = resolve;\n });\n }\n\n send(data: string): void {\n let frame: { type?: unknown; callId?: unknown };\n try {\n frame = JSON.parse(data) as { type?: unknown; callId?: unknown };\n } catch {\n return;\n }\n if (frame.type === \"register\") {\n void this.register(data);\n return;\n }\n if (frame.type === \"ack\" && typeof frame.callId === \"string\") this.inFlight.add(frame.callId);\n if (frame.type === \"result\" && typeof frame.callId === \"string\") this.inFlight.delete(frame.callId);\n this.outbox = this.outbox\n .then(() => this.registered)\n .then(() => this.post(data))\n .catch(() => undefined);\n }\n\n /**\n * Stops polling, lets the frames already queued go out, then reports the\n * close. The wait is bounded: on the deadline the frame requests are aborted\n * and the close is reported anyway, so a request that never answers cannot\n * hold the connection open.\n */\n close(code = 1000): void {\n this.closed = true;\n this.polls.abort();\n const deadline = setTimeout(() => {\n this.frames.abort();\n this.emitClose(code);\n }, CLOSE_DEADLINE_MS);\n deadline.unref();\n void this.outbox.finally(() => {\n clearTimeout(deadline);\n this.emitClose(code);\n });\n }\n\n terminate(): void {\n this.closed = true;\n this.polls.abort();\n this.frames.abort();\n this.emitClose(1006);\n }\n\n onOpen(listener: () => void): void {\n // There is nothing to open: the register frame is the first request.\n setTimeout(() => {\n if (!this.closed) listener();\n }, 0);\n }\n\n onMessage(listener: (data: string) => void): void {\n this.messageListeners.push(listener);\n }\n\n onClose(listener: (code: number) => void): void {\n this.closeListeners.push(listener);\n }\n\n onError(listener: (error: unknown) => void): void {\n this.errorListeners.push(listener);\n }\n\n onPing(listener: () => void): void {\n this.pingListeners.push(listener);\n }\n\n private requestHeaders(): Record<string, string> {\n return {\n ...this.headers,\n \"Content-Type\": \"application/json\",\n ...(this.token ? { [INSTANCE_TOKEN_HEADER]: this.token } : {}),\n };\n }\n\n private async register(data: string): Promise<void> {\n let response: Response;\n try {\n response = await this.fetchImpl(`${this.url}/register`, {\n method: \"POST\",\n headers: this.requestHeaders(),\n body: data,\n signal: this.polls.signal,\n });\n } catch (error) {\n if (!this.closed) this.fail(`could not reach ${this.url}/register (${describe(error)})`, 1006);\n return;\n }\n const body = await this.jsonOf(response);\n const frame = body && typeof body.frame === \"object\" && body.frame !== null ? body.frame : null;\n if (!frame) {\n this.fail(`the register request was answered with HTTP ${response.status}`, 1006);\n return;\n }\n if (typeof body?.instanceToken === \"string\") this.token = body.instanceToken;\n this.settleRegistered();\n this.emitMessage(JSON.stringify(frame));\n if ((frame as { type?: unknown }).type !== \"registered\") return;\n if (!this.token) {\n // Registered with no token: no poll can be addressed, so the connection\n // is finished here. The close is what makes the client register again.\n this.fail(\"the register answer carried no instance token\", 1006);\n return;\n }\n void this.pollLoop();\n }\n\n private async pollLoop(): Promise<void> {\n while (!this.closed && this.token) {\n const query = this.inFlight.size > 0 ? `?inFlight=${encodeURIComponent([...this.inFlight].join(\",\"))}` : \"\";\n const startedAt = Date.now();\n let response: Response;\n try {\n response = await this.fetchImpl(`${this.url}/poll${query}`, {\n method: \"GET\",\n headers: this.requestHeaders(),\n signal: this.polls.signal,\n });\n } catch (error) {\n if (!this.closed) this.fail(`the poll failed (${describe(error)})`, 1006);\n return;\n }\n if (this.closed) return;\n if (response.status === 410) {\n this.fail(\"the platform no longer knows this instance, registering again\", SESSION_LOST_CLOSE_CODE);\n return;\n }\n const body = await this.jsonOf(response);\n if (!response.ok) {\n const answered = body && typeof body.frame === \"object\" && body.frame !== null ? body.frame : null;\n if (answered) this.emitMessage(JSON.stringify(answered));\n if ((answered as { type?: unknown } | null)?.type === \"refused\") {\n // The platform refused the credential: the client prints and gives\n // up, and closes the connection itself.\n return;\n }\n this.fail(`the poll was answered with HTTP ${response.status}`, 1006);\n return;\n }\n const frames = Array.isArray(body?.frames) ? (body.frames as unknown[]) : [];\n for (const frame of frames) {\n const entry = frame as { type?: unknown; callId?: unknown };\n if (entry.type === \"cancel\" && typeof entry.callId === \"string\") this.inFlight.delete(entry.callId);\n this.emitMessage(JSON.stringify(frame));\n }\n for (const listener of this.pingListeners) listener();\n if (frames.length === 0) {\n const elapsedMs = Date.now() - startedAt;\n if (elapsedMs < EMPTY_POLL_FLOOR_MS) await wait(EMPTY_POLL_FLOOR_MS - elapsedMs);\n }\n }\n }\n\n private async post(data: string): Promise<void> {\n if (!this.token) return;\n for (let attempt = 0; ; attempt += 1) {\n if (this.frames.signal.aborted) return;\n let response: Response | null = null;\n try {\n response = await this.fetchImpl(`${this.url}/frames`, {\n method: \"POST\",\n headers: this.requestHeaders(),\n body: `{\"frames\":[${data}]}`,\n signal: this.frames.signal,\n });\n } catch {\n if (this.frames.signal.aborted) return;\n response = null;\n }\n if (response?.ok) return;\n if (response?.status === 410) {\n this.fail(\"the platform no longer knows this instance, registering again\", SESSION_LOST_CLOSE_CODE);\n return;\n }\n if (response && response.status < 500) return;\n const delay = POST_RETRY_DELAYS_MS[attempt];\n if (delay === undefined) {\n this.fail(`a frame could not be posted after ${attempt} retries`, 1006);\n return;\n }\n await wait(delay);\n }\n }\n\n private async jsonOf(response: Response): Promise<Record<string, unknown> | null> {\n try {\n const parsed = (await response.json()) as unknown;\n return typeof parsed === \"object\" && parsed !== null ? (parsed as Record<string, unknown>) : null;\n } catch {\n return null;\n }\n }\n\n private fail(message: string, code: number): void {\n for (const listener of this.errorListeners) listener(new Error(message));\n this.closed = true;\n this.polls.abort();\n this.frames.abort();\n this.emitClose(code);\n }\n\n private emitMessage(data: string): void {\n for (const listener of this.messageListeners) listener(data);\n }\n\n private emitClose(code: number): void {\n if (this.closeEmitted) return;\n this.closeEmitted = true;\n // A frame still waiting for the register answer is released; with no\n // token it is dropped, the way a frame on a closed socket is.\n this.settleRegistered();\n for (const listener of this.closeListeners) listener(code);\n }\n}\n","/**\n * The one HTTP client every request to the LangWatch API goes through.\n *\n * A LangWatch endpoint configured as `http://app.langwatch.ai` answers with a\n * redirect to https. The global `fetch` follows it on its own and, for a 301\n * or 302, turns the POST into a GET and drops the body, so the event is lost\n * without an error. This client sends with `redirect: \"manual\"` and applies a\n * rule per method to the 3xx it gets back.\n *\n * GET and HEAD follow a 301, 302, 303, 307 or 308 with the same method, up to\n * five hops. A hop that keeps the origin, or only upgrades http to https on\n * the same host and port, keeps every header; any other hop drops the\n * credential headers first. A hop from https to http and a hop without a\n * Location are refused.\n *\n * Every other method follows exactly one redirect, and only when the target is\n * the same URL with the scheme changed from http to https (same host, port,\n * path and query). The replay uses the same method, headers and body bytes.\n *\n * Every refused redirect throws `LangWatchRedirectError`.\n *\n * This module depends on the SDK logger only, so the CLI boot graph and the\n * `agent` entry can import it without pulling anything else in.\n */\nimport { ConsoleLogger, type Logger } from \"../../logger\";\n\nconst REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);\n\n/** Methods that follow a redirect to any http or https URL. */\nconst FOLLOWING_METHODS = new Set([\"GET\", \"HEAD\"]);\n\n/** The most redirects a GET or HEAD follows before the next one is refused. */\nexport const MAX_FOLLOW_HOPS = 5;\n\n/**\n * Headers dropped when a GET or HEAD hop leaves the origin: the three the Fetch\n * standard strips on a cross-origin redirect, plus the names LangWatch keys on.\n */\nconst CREDENTIAL_HEADERS = [\n \"authorization\",\n \"cookie\",\n \"proxy-authorization\",\n \"x-api-key\",\n \"x-auth-token\",\n \"x-project-id\",\n];\n\nexport class LangWatchRedirectError extends Error {\n readonly url: string;\n readonly location: string | null;\n readonly status: number;\n\n constructor({\n url,\n location,\n status,\n }: {\n url: string;\n location: string | null;\n status: number;\n }) {\n super(\n `LangWatch refused to follow a redirect from ${url} to ${location ?? \"an unknown location\"} (HTTP ${status}). Set the endpoint to the final URL.`,\n );\n this.name = \"LangWatchRedirectError\";\n this.url = url;\n this.location = location;\n this.status = status;\n }\n}\n\nexport type LangWatchFetch = typeof globalThis.fetch;\n\nexport interface CreateLangWatchFetchOptions {\n /** The transport to send with. Defaults to the global `fetch` at call time. */\n fetch?: LangWatchFetch;\n /** Receives the one warning per process about an http endpoint. */\n logger?: Logger;\n}\n\n/** Origins that already produced the http-to-https warning in this process. */\nconst warnedOrigins = new Set<string>();\n\n/** Forgets which origins were warned about. For tests only. */\nexport const resetSchemeUpgradeWarnings = (): void => {\n warnedOrigins.clear();\n};\n\nconst isRedirect = (response: Response): boolean =>\n response.type === \"opaqueredirect\" || REDIRECT_STATUSES.has(response.status);\n\nconst isStream = (body: unknown): boolean =>\n typeof ReadableStream !== \"undefined\" && body instanceof ReadableStream;\n\nconst abortError = (signal: AbortSignal): Error => {\n const reason: unknown = signal.reason;\n if (reason instanceof Error) return reason;\n if (typeof DOMException !== \"undefined\") {\n return new DOMException(\"This operation was aborted\", \"AbortError\");\n }\n return Object.assign(new Error(\"This operation was aborted\"), { name: \"AbortError\" });\n};\n\n/**\n * Releases the unread copy of a request body.\n *\n * `Request.clone` tees the body stream, and a branch nobody reads holds every\n * chunk the other branch consumes in memory. Cancelling the copy the replay\n * never needs keeps a streamed upload from being buffered whole.\n *\n * The cancellation is never awaited: a tee only settles the promise its\n * `cancel` returns once both branches are cancelled, so waiting on the copy\n * while the sent branch is still live would never return.\n */\nconst discard = (spare: Request | null): void => {\n void spare?.body?.cancel().catch(() => undefined);\n};\n\n/**\n * The body bytes to replay, read under the caller's signal.\n *\n * A `Request` built from a stream hands its copy over as a stream too, and\n * reading one that never ends would leave the call pending for good, past an\n * abort the caller already made. The read races the signal and cancels the\n * copy it loses to, so an aborted call settles.\n */\nconst replayBody = async ({\n spare,\n signal,\n}: {\n spare: Request;\n signal: AbortSignal | null | undefined;\n}): Promise<ArrayBuffer> => {\n if (!signal) return spare.arrayBuffer();\n if (signal.aborted) throw abortError(signal);\n\n const aborted = new Promise<never>((_, reject) => {\n signal.addEventListener(\"abort\", () => reject(abortError(signal)), { once: true });\n });\n // An abort that arrives after the read already won still rejects this one,\n // and nothing would be waiting on it by then.\n void aborted.catch(() => undefined);\n try {\n return await Promise.race([spare.arrayBuffer(), aborted]);\n } catch (error) {\n discard(spare);\n throw error;\n }\n};\n\nconst requestUrl = (input: RequestInfo | URL): string => {\n if (typeof input === \"string\") return input;\n if (input instanceof URL) return input.href;\n return input.url;\n};\n\nconst parseHop = ({\n url,\n location,\n}: {\n url: string;\n location: string;\n}): { from: URL; to: URL } | null => {\n try {\n const from = new URL(url);\n return { from, to: new URL(location, from) };\n } catch {\n return null;\n }\n};\n\n/** Same host and port, with the scheme changed from http to https. */\nconst isSchemeUpgrade = ({ from, to }: { from: URL; to: URL }): boolean =>\n from.protocol === \"http:\" &&\n to.protocol === \"https:\" &&\n from.hostname === to.hostname &&\n from.port === to.port;\n\n/**\n * The https URL to replay against when `location` only upgrades the scheme of\n * `url`, and null for any other target. The URL parser drops a default port,\n * so `http://host:80` and `https://host:443` both read as no port.\n */\nexport const schemeUpgradeTarget = ({\n url,\n location,\n}: {\n url: string;\n location: string;\n}): string | null => {\n const hop = parseHop({ url, location });\n if (hop === null || !isSchemeUpgrade(hop)) return null;\n const { from, to } = hop;\n if (from.pathname !== to.pathname) return null;\n if (from.search !== to.search) return null;\n to.hash = \"\";\n return to.href;\n};\n\n/**\n * The URL a GET or HEAD follows to, and null when the hop is refused: a\n * target that is not http or https, or a downgrade from https to http.\n */\nexport const followTarget = ({\n url,\n location,\n}: {\n url: string;\n location: string;\n}): string | null => {\n const hop = parseHop({ url, location });\n if (hop === null) return null;\n const { from, to } = hop;\n if (to.protocol !== \"http:\" && to.protocol !== \"https:\") return null;\n if (from.protocol === \"https:\" && to.protocol === \"http:\") return null;\n to.hash = \"\";\n return to.href;\n};\n\n/** A hop keeps its credential headers on the same origin and on an https upgrade of the same host. */\nconst keepsCredentials = ({ from, to }: { from: URL; to: URL }): boolean =>\n from.origin === to.origin || isSchemeUpgrade({ from, to });\n\nconst withoutCredentials = (headers: Headers): Headers => {\n const stripped = new Headers(headers);\n for (const name of CREDENTIAL_HEADERS) stripped.delete(name);\n return stripped;\n};\n\nconst warnOnce = ({ url, logger }: { url: string; logger: Logger }): void => {\n const { origin, host } = new URL(url);\n if (warnedOrigins.has(origin)) return;\n warnedOrigins.add(origin);\n logger.warn(\n `LangWatch endpoint ${origin} redirected to https. Set the endpoint to https://${host} to skip the extra round trip.`,\n );\n};\n\nconst refusalOf = ({\n url,\n response,\n}: {\n url: string;\n response: Response;\n}): LangWatchRedirectError =>\n new LangWatchRedirectError({\n url,\n location: response.headers.get(\"location\"),\n status: response.status,\n });\n\n/**\n * What `fetch(input, init)` would send, as one request both sends read from.\n * `init` wins over a `Request` input field by field, so reading the raw input\n * for the replay would resend a method, headers or body the caller overrode.\n * A plain URL input stays null: the non-Request path keeps `init` as it is, so\n * a stream body reaches the transport untouched.\n */\nconst effectiveRequest = ({\n input,\n init,\n}: {\n input: RequestInfo | URL;\n init: RequestInit | undefined;\n}): Request | null =>\n typeof Request !== \"undefined\" && input instanceof Request\n ? new Request(input, { ...init, redirect: \"manual\" })\n : null;\n\ninterface Hop {\n send: LangWatchFetch;\n log: Logger;\n effective: Request | null;\n init: RequestInit | undefined;\n url: string;\n first: Response;\n}\n\n/** The GET and HEAD rule: follow with the same method, up to MAX_FOLLOW_HOPS. */\nconst follow = async ({\n send,\n log,\n effective,\n init,\n url,\n method,\n first,\n}: Hop & { method: string }): Promise<Response> => {\n let headers = new Headers(effective?.headers ?? init?.headers);\n const signal = effective?.signal ?? init?.signal;\n let current = url;\n let response = first;\n\n for (let hop = 0; hop < MAX_FOLLOW_HOPS; hop++) {\n const location = response.headers.get(\"location\");\n const target = location === null ? null : followTarget({ url: current, location });\n if (target === null) throw refusalOf({ url: current, response });\n\n const from = new URL(current);\n const to = new URL(target);\n if (!keepsCredentials({ from, to })) headers = withoutCredentials(headers);\n if (isSchemeUpgrade({ from, to })) warnOnce({ url: current, logger: log });\n\n current = target;\n response = effective\n ? await send(new Request(target, { method, headers, signal, redirect: \"manual\" }))\n : await send(target, { ...init, method, headers, body: undefined, redirect: \"manual\" });\n if (!isRedirect(response)) return response;\n }\n\n throw refusalOf({ url: current, response });\n};\n\n/** The rule for every other method: one hop, and only an https upgrade of the same URL. */\nconst upgrade = async ({\n send,\n log,\n effective,\n init,\n url,\n first,\n spare,\n}: Hop & { spare: Request | null }): Promise<Response> => {\n const location = first.headers.get(\"location\");\n const refused = refusalOf({ url, response: first });\n const target = location === null ? null : schemeUpgradeTarget({ url, location });\n if (location === null || first.status === 303 || target === null || isStream(init?.body)) {\n discard(spare);\n throw refused;\n }\n\n warnOnce({ url, logger: log });\n\n const second = effective\n ? await send(\n new Request(target, {\n method: effective.method,\n headers: effective.headers,\n body: spare ? await replayBody({ spare, signal: effective.signal }) : null,\n signal: effective.signal,\n redirect: \"manual\",\n }),\n )\n : await send(target, { ...init, redirect: \"manual\" });\n if (!isRedirect(second)) return second;\n\n throw refusalOf({ url: target, response: second });\n};\n\n/**\n * Builds a `fetch` that applies the redirect rule. Pass `fetch` to send through\n * another transport (a test double, a proxying client) and `logger` to route\n * the http endpoint warning.\n */\nexport const createLangWatchFetch = ({\n fetch: fetchImpl,\n logger,\n}: CreateLangWatchFetchOptions = {}): LangWatchFetch => {\n const send: LangWatchFetch =\n fetchImpl ?? ((input, init) => globalThis.fetch(input, init));\n const log = logger ?? new ConsoleLogger({ level: \"warn\", prefix: \"LangWatch\" });\n\n return async (input, init) => {\n const url = requestUrl(input);\n const effective = effectiveRequest({ input, init });\n const method = (effective?.method ?? init?.method ?? \"GET\").toUpperCase();\n // A Request carries its body as a stream that one send consumes, so a copy\n // is taken before the first send and read only if the replay happens.\n const spare = effective !== null && effective.body !== null ? effective.clone() : null;\n\n const first = effective\n ? await send(effective)\n : await send(input, { ...init, redirect: \"manual\" });\n if (!isRedirect(first)) {\n discard(spare);\n return first;\n }\n\n const hop = { send, log, effective, init, url, first };\n if (!FOLLOWING_METHODS.has(method)) return upgrade({ ...hop, spare });\n\n discard(spare);\n return follow({ ...hop, method });\n };\n};\n\n/** The shared client, bound to the global `fetch` and the SDK console logger. */\nexport const langwatchFetch: LangWatchFetch = createLangWatchFetch();\n","/**\n * The reconnect loop both LangWatch sockets run on.\n *\n * The connected-agents client (`client.ts`) and the local control client\n * (`cli/commands/langy/relay-client.ts`) open different sockets and speak\n * different frames, but they keep them alive the same way: open, register,\n * watch for a heartbeat, and come back with a jittered backoff when the\n * platform goes away. That part lives here so there is one implementation of\n * it rather than two that drift.\n */\n\nimport {\n type AgentTransport,\n defaultSocketFactory,\n HttpLongPollSocket,\n NoWebSocketError,\n type SocketFactory,\n type SocketLike,\n} from \"./transport\";\n\nexport const RECONNECT_BASE_MS = 1_000;\nexport const RECONNECT_MAX_MS = 30_000;\n\n/** The delay before reconnect attempt `attempt` (0-based), with jitter, in the 1 s to 30 s window. */\nexport function reconnectDelayMs({\n attempt,\n baseMs = RECONNECT_BASE_MS,\n maxMs = RECONNECT_MAX_MS,\n random = Math.random,\n}: {\n attempt: number;\n baseMs?: number;\n maxMs?: number;\n random?: () => number;\n}): number {\n const exponential = Math.min(maxMs, baseMs * 2 ** Math.min(attempt, 16));\n const jittered = exponential * (0.75 + random() * 0.5);\n return Math.round(Math.min(maxMs, Math.max(baseMs, jittered)));\n}\n\n/**\n * How long the client waits for a sign of life before it drops the socket:\n * three heartbeats, and never less than fifteen seconds.\n */\nexport function watchdogDelayMs(heartbeatIntervalMs: number): number {\n return Math.max(15_000, heartbeatIntervalMs * 3);\n}\n\nexport const describeError = (error: unknown): string =>\n error instanceof Error ? error.message : String(error);\n\n/** How a socket is opened for a transport, so the caller never repeats the branch. */\nexport function openTransportSocket({\n transport,\n websocketUrl,\n httpUrl,\n headers,\n socketFactory = defaultSocketFactory,\n}: {\n transport: AgentTransport;\n websocketUrl: string;\n httpUrl: string;\n headers: Record<string, string>;\n socketFactory?: SocketFactory;\n}): SocketLike {\n return transport === \"http\"\n ? new HttpLongPollSocket({ url: httpUrl, headers })\n : socketFactory({ url: websocketUrl, headers });\n}\n\nexport { NoWebSocketError };\n","/**\n * `connectAgent`: the function that runs an agent becomes a simulation target.\n *\n * The wrapper resolves the environment and the parameter schema at definition,\n * registers the agent with the process-wide client, and returns a function\n * that is directly callable (for unit tests and local runs) and exposes\n * `disconnect()`.\n *\n * @see specs/typescript-sdk/agent-wrapper.feature\n */\n\nimport { ConsoleLogger, type Logger } from \"../logger\";\nimport { getSharedClient, warnOnce, type AgentRuntime } from \"./client\";\nimport {\n resolveEnabled,\n resolveEnvironment,\n resolveInstanceLabel,\n} from \"./identity\";\nimport type { AgentMessage, AgentParameterValue, JsonSchemaObject } from \"./protocol\";\nimport type { AgentTransport } from \"./transport\";\nimport {\n AgentParameterError,\n createParameterReader,\n parameterSpecsFromSchema,\n toParameterSchema,\n type InferStandardOutput,\n type ParameterDefinition,\n type ParameterDefinitions,\n type ParameterInput,\n type StandardJsonSchema,\n} from \"./schema\";\n\n/** The default call timeout, and the cap the platform enforces. */\nexport const DEFAULT_TIMEOUT_MS = 120_000;\nexport const MAX_TIMEOUT_MS = 300_000;\nexport const DEFAULT_CONCURRENCY = 10;\n\n/** What a handler may return: a string, one message, a list of messages, or an output with a session. */\nexport type AgentOutput = string | AgentMessage | AgentMessage[];\n\n/** The output of one turn plus the session the agent keeps for the next turn of the same thread. */\nexport interface AgentResult {\n output: AgentOutput;\n session?: unknown;\n}\n\nexport type AgentReply = AgentOutput | AgentResult;\n\n/** The one object a handler receives on every turn. */\nexport interface AgentCall<P = Record<string, AgentParameterValue>> {\n /** The full conversation, OpenAI style. */\n messages: AgentMessage[];\n /** The messages added since the last turn of this thread. */\n newMessages: AgentMessage[];\n /** The platform's conversation id. */\n threadId: string;\n /** The value the handler returned as `session` on the previous turn of this thread, null on the first. */\n session: unknown;\n /** The run parameters, validated and with defaults filled. */\n params: P;\n /** The trace id of the turn, so the agent's own spans join it. Empty when the call carries none. */\n traceId: string;\n}\n\nexport type AgentHandler<P> = (call: AgentCall<P>) => AgentReply | Promise<AgentReply>;\n\n/** What a direct call of the wrapped function takes: messages, and anything else is optional. */\nexport interface DirectAgentCall<P> {\n messages: AgentMessage[];\n newMessages?: AgentMessage[];\n threadId?: string;\n session?: unknown;\n params?: Partial<P>;\n traceId?: string;\n}\n\nexport interface ConnectAgentOptions<P extends ParameterInput = ParameterDefinitions> {\n /** The agent name. One row per name and environment on the platform. */\n name: string;\n /** Resolved from LANGWATCH_AGENT_ENVIRONMENT, APP_ENV, ENVIRONMENT, NODE_ENV, else development. */\n environment?: string;\n /** A definition map, a Standard JSON Schema object, or a JSON Schema object. */\n parameters?: P;\n /**\n * Whether this process connects. Takes any boolean, so one expression can\n * gate the deployments that connect. Without it the default is true, except\n * when CI is truthy; a value given here replaces that rule rather than adding\n * to it, so keep the CI half: `process.env.APP_ENV !== \"production\" && !process.env.CI`.\n * LANGWATCH_AGENT_CONNECT=0 always disables.\n */\n enabled?: boolean;\n /** Names this instance in the platform. Also LANGWATCH_AGENT_INSTANCE_LABEL. */\n instanceLabel?: string;\n /** Per call, default 120000, at most 300000. */\n timeoutMs?: number;\n /**\n * Calls in flight per instance, default 10. A test suite sends several\n * scenarios at once; the ceiling is there because the model providers rate\n * limit the calls behind them.\n */\n concurrency?: number;\n /** Keep every turn of a thread on the instance that answered the first one. */\n sticky?: boolean;\n apiKey?: string;\n endpoint?: string;\n projectId?: string;\n /** `websocket` (default, falls back to HTTP when the upgrade is refused) or `http`. Also LANGWATCH_AGENT_TRANSPORT. */\n transport?: AgentTransport;\n logger?: Logger;\n}\n\n/** The wrapped function: callable, and connected until `disconnect()`. */\nexport interface ConnectedAgent<P> {\n (call: DirectAgentCall<P>): Promise<AgentResult>;\n readonly name: string;\n readonly environment: string;\n /** The parameter schema as registered. */\n readonly parameters: JsonSchemaObject;\n /** Send deregister and close the socket when this was the last agent of the process. */\n disconnect: () => Promise<void>;\n}\n\ntype Widen<V> = V extends string ? string : V extends number ? number : V extends boolean ? boolean : V;\n\ntype ParameterValueOf<D extends ParameterDefinition> = D extends {\n options: readonly (infer O extends string)[];\n}\n ? O\n : D extends { type: \"number\" }\n ? number\n : D extends { type: \"boolean\" }\n ? boolean\n : D extends { type: \"string\" }\n ? string\n : D extends { default: infer V }\n ? Widen<V>\n : string;\n\n/** The `params` type a definition map gives the handler. */\nexport type InferParameters<P extends ParameterDefinitions> = {\n [K in keyof P]: ParameterValueOf<P[K]>;\n};\n\nconst isMessage = (value: unknown): value is AgentMessage =>\n typeof value === \"object\" && value !== null && !Array.isArray(value) && typeof (value as AgentMessage).role === \"string\";\n\n/** One of the four reply shapes as the `{ output, session }` the result frame carries. */\nexport function normalizeReply(reply: unknown): AgentResult {\n if (typeof reply === \"string\") return { output: reply };\n if (Array.isArray(reply) && reply.every(isMessage)) return { output: reply };\n if (isMessage(reply)) return { output: reply };\n if (typeof reply === \"object\" && reply !== null && \"output\" in reply) {\n const { output, session } = reply as { output: unknown; session?: unknown };\n const normalized = normalizeReply(output);\n return session === undefined ? normalized : { output: normalized.output, session };\n }\n throw new Error(\n \"the agent handler must return a string, a message, a list of messages, or { output, session }\",\n );\n}\n\nconst clampTimeout = ({ timeoutMs, logger, name }: { timeoutMs: number | undefined; logger: Logger; name: string }): number => {\n if (timeoutMs === undefined) return DEFAULT_TIMEOUT_MS;\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return DEFAULT_TIMEOUT_MS;\n if (timeoutMs > MAX_TIMEOUT_MS) {\n logger.warn(`agent \"${name}\": timeoutMs ${timeoutMs} is above the ${MAX_TIMEOUT_MS} cap, using the cap`);\n return MAX_TIMEOUT_MS;\n }\n return Math.floor(timeoutMs);\n};\n\nconst readApiKey = (explicit: string | undefined): string | undefined => {\n const candidate = explicit ?? process.env.LANGWATCH_API_KEY;\n return typeof candidate === \"string\" && candidate.trim() !== \"\" ? candidate.trim() : undefined;\n};\n\nconst readProjectId = (explicit: string | undefined): string | undefined => {\n const candidate = explicit ?? process.env.LANGWATCH_PROJECT_ID;\n return typeof candidate === \"string\" && candidate.trim() !== \"\" ? candidate.trim() : undefined;\n};\n\n/**\n * A schema library object (zod 4, valibot, arktype: anything with Standard\n * Schema and Standard JSON Schema) types `params` as its parsed output and\n * validates every call's values before the handler runs.\n */\nexport function connectAgent<const S extends StandardJsonSchema>(\n options: ConnectAgentOptions<S> & { parameters: S },\n handler: AgentHandler<InferStandardOutput<S>>,\n): ConnectedAgent<InferStandardOutput<S>>;\nexport function connectAgent<const P extends ParameterDefinitions = Record<string, never>>(\n options: ConnectAgentOptions<P>,\n handler: AgentHandler<InferParameters<P>>,\n): ConnectedAgent<InferParameters<P>>;\nexport function connectAgent(\n options: ConnectAgentOptions<JsonSchemaObject>,\n handler: AgentHandler<Record<string, AgentParameterValue>>,\n): ConnectedAgent<Record<string, AgentParameterValue>>;\nexport function connectAgent(\n options: ConnectAgentOptions<ParameterInput>,\n handler: AgentHandler<Record<string, AgentParameterValue>>,\n): ConnectedAgent<Record<string, AgentParameterValue>> {\n const logger = options.logger ?? new ConsoleLogger({ level: \"info\", prefix: \"LangWatch\" });\n const name = options.name?.trim();\n if (!name) throw new Error(\"connectAgent needs a name\");\n\n const environment = resolveEnvironment({ explicit: options.environment });\n const parameters = toParameterSchema(options.parameters);\n const specs = parameterSpecsFromSchema(parameters);\n const timeoutMs = clampTimeout({ timeoutMs: options.timeoutMs, logger, name });\n const concurrency = Math.max(1, Math.floor(options.concurrency ?? DEFAULT_CONCURRENCY));\n\n const runHandler = async (call: AgentCall<Record<string, AgentParameterValue>>): Promise<AgentResult> =>\n normalizeReply(await handler(call));\n\n const readParams = createParameterReader({ input: options.parameters, specs });\n\n const invoke = async (call: DirectAgentCall<Record<string, AgentParameterValue>>): Promise<AgentResult> => {\n const params = await readParams(call.params as Record<string, AgentParameterValue> | undefined);\n return runHandler({\n messages: call.messages,\n newMessages: call.newMessages ?? call.messages,\n threadId: call.threadId ?? `local_${Date.now().toString(36)}`,\n session: call.session ?? null,\n params,\n traceId: call.traceId ?? \"\",\n });\n };\n\n const runtime: AgentRuntime = {\n name,\n environment,\n register: {\n name,\n environment,\n parameters,\n concurrency,\n timeoutMs,\n ...(options.sticky ? { sticky: true } : {}),\n },\n readParams,\n concurrency,\n timeoutMs,\n run: runHandler,\n };\n\n let detach: (() => Promise<void>) | undefined;\n\n if (!resolveEnabled({ explicit: options.enabled })) {\n logger.debug(`agent \"${name}\" not connected to LangWatch: the connection is disabled`);\n } else {\n const apiKey = readApiKey(options.apiKey);\n if (!apiKey) {\n warnOnce({\n logger,\n key: \"no-api-key\",\n message: `agent \"${name}\" not connected to LangWatch: no API key. Set LANGWATCH_API_KEY to run simulations against it.`,\n });\n } else {\n const client = getSharedClient({\n apiKey,\n endpoint: options.endpoint,\n projectId: readProjectId(options.projectId),\n instanceLabel: resolveInstanceLabel({ explicit: options.instanceLabel }),\n transport: options.transport,\n logger,\n });\n client.addAgent(runtime);\n detach = () => client.removeAgent(runtime);\n }\n }\n\n const connected = Object.assign(invoke, {\n environment,\n parameters,\n disconnect: async (): Promise<void> => {\n if (!detach) return;\n const release = detach;\n detach = undefined;\n await release();\n },\n });\n // A function's own `name` is read-only but configurable, so it is defined rather than assigned.\n Object.defineProperty(connected, \"name\", { value: name, configurable: true });\n\n return connected as ConnectedAgent<Record<string, AgentParameterValue>>;\n}\n\nexport { AgentParameterError };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACkBA,IAAM,gBAA0C;AAAA,EAC9C,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AACT;AAyBO,IAAM,gBAAN,MAAsC;AAAA,EAI3C,YAAY,UAAgC,EAAE,OAAO,OAAO,GAAG;AAa/D,iBAAuD,CAAC,YAAoB,SAA0B;AACpG,UAAI,KAAK,UAAU,OAAO,EAA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O;AACL,UAAM,SAAS,WAAW,QAAQ,MAAM;AACxC,QAAI,CAAC,QAAQ;AACX,MAAAC,UAAS;AAAA,QACP;AAAA,QACA,KAAK;AAAA,QACL,SAAS,UAAU,IAAI;AAAA,MACzB,CAAC;AAAA,IACH,OAAO;AACL,YAAM,SAAS,gBAAgB;AAAA,QAC7B;AAAA,QACA,UAAU,QAAQ;AAAA,QAClB,WAAW,cAAc,QAAQ,SAAS;AAAA,QAC1C,eAAe,qBAAqB,EAAE,UAAU,QAAQ,cAAc,CAAC;AAAA,QACvE,WAAW,QAAQ;AAAA,QACnB;AAAA,MACF,CAAC;AACD,aAAO,SAAS,OAAO;AACvB,eAAS,MAAM,OAAO,YAAY,OAAO;AAAA,IAC3C;AAAA,EACF;AAEA,QAAM,YAAY,OAAO,OAAO,QAAQ;AAAA,IACtC;AAAA,IACA;AAAA,IACA,YAAY,YAA2B;AACrC,UAAI,CAAC,OAAQ;AACb,YAAM,UAAU;AAChB,eAAS;AACT,YAAM,QAAQ;AAAA,IAChB;AAAA,EACF,CAAC;AAED,SAAO,eAAe,WAAW,QAAQ,EAAE,OAAO,MAAM,cAAc,KAAK,CAAC;AAE5E,SAAO;AACT;","names":["isSet","isRecord","isSet","call","warnOnce","readParams","warnOnce"]}
1
+ {"version":3,"sources":["../../src/agent/index.ts","../../src/logger/index.ts","../../src/agent/client.ts","../../src/agent/identity.ts","../../package.json","../../src/internal/constants.ts","../../src/internal/endpoint.ts","../../src/agent/protocol.ts","../../src/agent/schema.ts","../../src/agent/transport.ts","../../src/internal/http/langwatchFetch.ts","../../src/agent/reconnect.ts","../../src/agent/define.ts"],"sourcesContent":["/**\n * `langwatch/agent`: connect the function that runs an agent to LangWatch\n * so simulations run against it with no public URL.\n *\n * Node only, and outbound only. The default transport is a WebSocket that\n * carries the API key in its request headers. It falls back to HTTP long\n * polling when a proxy refuses the upgrade, and\n * `LANGWATCH_AGENT_TRANSPORT=http` selects HTTP long polling from the start.\n *\n * @see dev/docs/adr/128-connected-agents.md\n */\n\nexport { connectAgent, normalizeReply, DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS } from \"./define\";\nexport type {\n AgentCall,\n AgentHandler,\n AgentOutput,\n AgentReply,\n AgentResult,\n ConnectAgentOptions,\n ConnectedAgent,\n DirectAgentCall,\n InferParameters,\n} from \"./define\";\nexport { AgentParameterError, toParameterSchema, parameterSpecsFromSchema } from \"./schema\";\nexport type {\n ParameterDefinition,\n ParameterDefinitions,\n ParameterInput,\n ParameterSpec,\n ParameterType,\n StandardJsonSchema,\n} from \"./schema\";\nexport { PROTOCOL_VERSION } from \"./protocol\";\nexport type { AgentMessage, AgentParameterValue, JsonSchemaObject } from \"./protocol\";\nexport { resolveEnvironment, sanitizeEnvironment, resolveConnectUrl, resolveHttpConnectUrl } from \"./identity\";\nexport { resolveTransport, AGENT_TRANSPORTS } from \"./transport\";\nexport type { AgentTransport } from \"./transport\";\n","// Logger utility for SDKs\n//\n// Usage:\n// - If you pass your own Logger implementation, the SDK will use it as-is (no log level filtering or prefixing applied).\n// - If you use ConsoleLogger, you can specify log level and prefix options.\n// - NoOpLogger disables all logging.\n//\n// Example:\n// const logger = new ConsoleLogger({ level: \"warn\", prefix: \"SDK\" });\n// logger.info(\"This will not show\");\n// logger.warn(\"This will show with prefix\");\n//\n// // If you pass your own logger, SDK will not filter logs:\n// const customLogger: Logger = { ... };\n// // SDK uses customLogger as-is\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nconst logLevelOrder: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n} as const;\n\nexport interface Logger {\n debug: (message: string, ...args: unknown[]) => void;\n info: (message: string, ...args: unknown[]) => void;\n warn: (message: string, ...args: unknown[]) => void;\n error: (message: string, ...args: unknown[]) => void;\n}\n\nexport class NoOpLogger implements Logger {\n debug: () => void = () => { /* noop */ }\n info: () => void = () => { /* noop */ }\n warn: () => void = () => { /* noop */ }\n error: () => void = () => { /* noop */ }\n}\n\ninterface ConsoleLoggerOptions {\n level: LogLevel;\n prefix?: string;\n}\n\n/**\n * ConsoleLogger applies log level filtering and optional prefixing.\n * If you pass your own Logger, the SDK will not apply log level filtering or prefixing.\n */\nexport class ConsoleLogger implements Logger {\n private level: LogLevel;\n private prefix?: string;\n\n constructor(options: ConsoleLoggerOptions = { level: \"warn\" }) {\n this.level = options.level;\n this.prefix = options.prefix;\n }\n\n private shouldLog(level: LogLevel): boolean {\n return logLevelOrder[level] >= logLevelOrder[this.level];\n }\n\n private format(message: string): string {\n return this.prefix ? `[${this.prefix}] ${message}` : message;\n }\n\n debug: (message: string, ...args: unknown[]) => void = (message: string, ...args: unknown[]): void => {\n if (this.shouldLog(\"debug\")) console.debug(this.format(message), ...args);\n };\n info: (message: string, ...args: unknown[]) => void = (message: string, ...args: unknown[]): void => {\n if (this.shouldLog(\"info\")) console.info(this.format(message), ...args);\n };\n warn: (message: string, ...args: unknown[]) => void = (message: string, ...args: unknown[]): void => {\n if (this.shouldLog(\"warn\")) console.warn(this.format(message), ...args);\n }\n error: (message: string, ...args: unknown[]) => void = (message: string, ...args: unknown[]): void => {\n if (this.shouldLog(\"error\")) console.error(this.format(message), ...args);\n }\n}\n","/**\n * One shared connection per process to `/api/v1/agents/connect`.\n *\n * The client holds every agent the process defined, registers them all on\n * one socket, answers `call` frames by running the agent's function, and\n * reconnects with backoff when the platform goes away. Nothing in here throws\n * into customer code: every frame is handled under a catch that logs, and a\n * failure on the LangWatch side produces one warning that names the fix and\n * leaves the application running as if the wrapper were absent.\n *\n * @see dev/docs/adr/128-connected-agents.md\n */\n\nimport { context, propagation, trace } from \"@opentelemetry/api\";\nimport type { Logger } from \"../logger\";\nimport type { AgentCall, AgentResult } from \"./define\";\nimport {\n buildConnectHeaders,\n buildInstance,\n resolveConnectUrl,\n resolveHttpConnectUrl,\n SDK_IDENTITY,\n} from \"./identity\";\nimport {\n parseServerFrame,\n PROTOCOL_VERSION,\n serializeFrame,\n traceIdFromTraceparent,\n type AgentParameterValue,\n type CallFrame,\n type ClientFrame,\n type RefusedFrame,\n type RegisterAgent,\n type RegisterInstance,\n type RegisteredAgent,\n type RegisteredFrame,\n} from \"./protocol\";\nimport { AgentParameterError, type ParameterReader } from \"./schema\";\nimport {\n describeError,\n NoWebSocketError,\n openTransportSocket,\n RECONNECT_BASE_MS,\n RECONNECT_MAX_MS,\n reconnectDelayMs,\n watchdogDelayMs,\n} from \"./reconnect\";\nimport {\n type AgentTransport,\n defaultSocketFactory,\n resolveTransport,\n type SocketFactory,\n type SocketLike,\n} from \"./transport\";\n\n/** One defined agent as the client runs it. */\nexport interface AgentRuntime {\n name: string;\n environment: string;\n register: RegisterAgent;\n /** Defaults, coercion and the schema's own validation, before every call. */\n readParams: ParameterReader;\n concurrency: number;\n timeoutMs: number;\n run: (call: AgentCall<Record<string, AgentParameterValue>>) => Promise<AgentResult>;\n}\n\nexport interface AgentClientConfig {\n apiKey: string;\n endpoint?: string;\n projectId?: string;\n instanceLabel?: string;\n /** `websocket` (default) or `http`; also `LANGWATCH_AGENT_TRANSPORT`. */\n transport?: AgentTransport;\n logger: Logger;\n socketFactory?: SocketFactory;\n /** Reconnect delays, for tests. Defaults to 1 s doubling up to 30 s. */\n backoff?: { baseMs: number; maxMs: number };\n /** How often the same unreachable-endpoint warning may repeat, for tests. */\n failureNoticeIntervalMs?: number;\n}\n\n/** The unreachable-endpoint warning repeats at most this often. */\nexport const FAILURE_NOTICE_INTERVAL_MS = 5 * 60_000;\n\nconst NOT_CONNECTED = \"not connected to LangWatch\";\n\n/** The one line a refusal produces: what went wrong and what fixes it. */\nexport function refusalAdvice(frame: RefusedFrame): string {\n switch (frame.code) {\n case \"project_required\": {\n const projects = Array.isArray(frame.meta?.projects) ? frame.meta.projects : [];\n const listed = projects\n .map((project) => {\n const entry = project as { id?: unknown; name?: unknown };\n const id = typeof entry.id === \"string\" ? entry.id : \"\";\n const name = typeof entry.name === \"string\" ? entry.name : \"\";\n return name && id ? `${name} (${id})` : id || name;\n })\n .filter((line) => line !== \"\");\n return `the API key reaches more than one project. Set LANGWATCH_PROJECT_ID to one of: ${listed.length > 0 ? listed.join(\", \") : \"the projects the key reaches\"}.`;\n }\n case \"api_key_invalid\":\n return \"the API key is not valid. Set LANGWATCH_API_KEY to a key from the project settings.\";\n case \"key_type_not_allowed\":\n return \"this key type cannot connect agents. Set LANGWATCH_API_KEY to a personal or project API key.\";\n case \"permission_denied\":\n return \"the API key cannot manage scenarios. Use a key with the scenarios:manage permission.\";\n case \"protocol_invalid\":\n return `${frame.message} Update the langwatch package to a version that speaks protocol ${PROTOCOL_VERSION} or later.`;\n case \"replica_count_unsupported\":\n return `${frame.message} Connected agents on a LangWatch deployment without Redis need one app replica.`;\n case \"parameters_invalid\":\n case \"environment_invalid\":\n return frame.message;\n default:\n return `${frame.message} (${frame.code})`;\n }\n}\n\ninterface InFlightCall {\n runtime: AgentRuntime;\n /** True once the call was cancelled or timed out: a late result is dropped. */\n cancelled: boolean;\n /** The timer that ends the call on its deadline, cleared when the call ends. */\n timer: NodeJS.Timeout | null;\n}\n\nconst SHUTDOWN_SIGNALS = [\"SIGINT\", \"SIGTERM\"] as const;\ntype ShutdownSignal = (typeof SHUTDOWN_SIGNALS)[number];\n\nconst CLOSE_GRACE_MS = 500;\n\nexport class AgentClient {\n private readonly agents: AgentRuntime[] = [];\n private readonly byId = new Map<string, AgentRuntime>();\n private readonly inFlight = new Map<string, InFlightCall>();\n private readonly instance: RegisterInstance;\n private readonly url: string;\n private readonly httpUrl: string;\n private readonly headers: Record<string, string>;\n /** The transport in use: the configured one, or HTTP after a refused upgrade. */\n private activeTransport: AgentTransport;\n private upgradeStatus: number | null = null;\n private transportAnnounced = false;\n private readonly logger: Logger;\n private readonly openSocket: SocketFactory;\n private readonly backoff: { baseMs: number; maxMs: number };\n private readonly failureNoticeIntervalMs: number;\n\n private socket: SocketLike | null = null;\n private registered = false;\n private stopped = false;\n /** True while a socket is closed on purpose to register the full agent list again. */\n private restarting = false;\n private attempt = 0;\n private connectTimer: NodeJS.Timeout | null = null;\n private watchdog: NodeJS.Timeout | null = null;\n private heartbeatIntervalMs = 10_000;\n private closeWaiters: Array<() => void> = [];\n private lastError: string | null = null;\n private failureNoticeAt: number | null = null;\n private gaveUp = false;\n\n constructor(config: AgentClientConfig) {\n this.instance = buildInstance({ label: config.instanceLabel });\n this.url = resolveConnectUrl(config.endpoint);\n this.httpUrl = resolveHttpConnectUrl(config.endpoint);\n this.activeTransport = resolveTransport({ explicit: config.transport });\n this.headers = buildConnectHeaders({ apiKey: config.apiKey, projectId: config.projectId });\n this.logger = config.logger;\n this.openSocket = config.socketFactory ?? defaultSocketFactory;\n this.backoff = config.backoff ?? { baseMs: RECONNECT_BASE_MS, maxMs: RECONNECT_MAX_MS };\n this.failureNoticeIntervalMs = config.failureNoticeIntervalMs ?? FAILURE_NOTICE_INTERVAL_MS;\n }\n\n get instanceId(): string {\n return this.instance.id;\n }\n\n /** The transport the client speaks now. */\n get transport(): AgentTransport {\n return this.activeTransport;\n }\n\n get isRegistered(): boolean {\n return this.registered;\n }\n\n /** True once the client gave up: refused, or no socket implementation. No timer is left behind. */\n get isStopped(): boolean {\n return this.stopped;\n }\n\n /** True while a reconnect is scheduled with a timer that keeps the process up. */\n get hasPendingConnect(): boolean {\n return this.connectTimer?.hasRef() ?? false;\n }\n\n /** True while the client is between attempts or inside one, with the process kept up. */\n get isRetrying(): boolean {\n if (this.stopped) return false;\n return this.connectTimer ? this.connectTimer.hasRef() : this.socket !== null;\n }\n\n /** Adds an agent and connects on the next tick, or reconnects when a socket is already open. */\n addAgent(runtime: AgentRuntime): void {\n this.agents.push(runtime);\n if (this.gaveUp) {\n this.logger.debug(`agent \"${runtime.name}\" ${NOT_CONNECTED}: the connection gave up earlier in this process`);\n return;\n }\n this.stopped = false;\n if (this.socket) {\n // The platform ignores a second register on an open socket, whether the\n // first one is still on its way or already answered. A fresh socket\n // carries the complete list.\n this.restartSocket();\n return;\n }\n this.scheduleConnect(0);\n }\n\n /** Closes the socket and connects again at once, keeping the reconnect loop. */\n private restartSocket(): void {\n const socket = this.socket;\n if (!socket) return;\n this.restarting = true;\n try {\n socket.close(1000, \"agents changed\");\n } catch {\n this.restarting = false;\n this.socket = null;\n this.scheduleConnect(0);\n }\n }\n\n /** Removes an agent; the last one leaving deregisters and closes the socket. */\n async removeAgent(runtime: AgentRuntime): Promise<void> {\n const index = this.agents.indexOf(runtime);\n if (index !== -1) this.agents.splice(index, 1);\n for (const [id, agent] of this.byId) if (agent === runtime) this.byId.delete(id);\n if (this.agents.length === 0) {\n await this.disconnect();\n return;\n }\n // The open socket registered the agent that just left, and the platform\n // ignores a second register on it. A fresh socket carries the list as it\n // stands now.\n this.restartSocket();\n }\n\n /** Sends deregister, closes the socket and stops reconnecting. */\n async disconnect(): Promise<void> {\n this.stopped = true;\n this.clearTimers();\n const socket = this.socket;\n if (!socket) return;\n if (this.registered) this.send({ type: \"deregister\", protocol: PROTOCOL_VERSION });\n const closed = new Promise<void>((resolve) => this.closeWaiters.push(resolve));\n try {\n socket.close(1000, \"deregister\");\n } catch {\n // The socket is already gone.\n }\n const grace = new Promise<void>((resolve) => {\n const timer = setTimeout(() => {\n try {\n socket.terminate();\n } catch {\n // Already gone.\n }\n resolve();\n }, CLOSE_GRACE_MS);\n timer.unref();\n });\n await Promise.race([closed, grace]);\n }\n\n /** Deregister with no wait, for a process that is already exiting. */\n shutdownNow(): void {\n this.stopped = true;\n this.clearTimers();\n if (!this.socket) return;\n try {\n if (this.registered) this.send({ type: \"deregister\", protocol: PROTOCOL_VERSION });\n this.socket.close(1000, \"deregister\");\n } catch {\n // The socket is already gone.\n }\n }\n\n private agentNames(): string {\n return this.agents.map((agent) => `\"${agent.name}\"`).join(\", \") || \"the agent\";\n }\n\n /**\n * The reconnect timer keeps its ref on purpose: a script whose only job is\n * the agent must stay up while it retries. Giving up clears every timer.\n */\n private scheduleConnect(delayMs: number): void {\n if (this.stopped || this.connectTimer || this.socket) return;\n this.connectTimer = setTimeout(() => {\n this.connectTimer = null;\n this.connect();\n }, delayMs);\n }\n\n private clearTimers(): void {\n if (this.connectTimer) {\n clearTimeout(this.connectTimer);\n this.connectTimer = null;\n }\n if (this.watchdog) {\n clearTimeout(this.watchdog);\n this.watchdog = null;\n }\n }\n\n private giveUp(reason: string): void {\n this.stopped = true;\n this.gaveUp = true;\n this.clearTimers();\n this.logger.warn(`agent ${this.agentNames()} ${NOT_CONNECTED}: ${reason}`);\n }\n\n private connect(): void {\n if (this.stopped || this.socket) return;\n let socket: SocketLike;\n try {\n socket = openTransportSocket({\n transport: this.activeTransport,\n websocketUrl: this.url,\n httpUrl: this.httpUrl,\n headers: this.headers,\n socketFactory: this.openSocket,\n });\n } catch (error) {\n if (error instanceof NoWebSocketError) {\n this.giveUp(\n \"the ws package is not installed. Run npm install ws; the platform reads the API key from a request header, and only ws can send it.\",\n );\n return;\n }\n this.lastError = describeError(error);\n this.onClosed();\n return;\n }\n this.socket = socket;\n socket.onOpen(() => this.guard(() => this.send(this.registerFrame())));\n socket.onMessage((data) => this.guard(() => this.onMessage(data)));\n socket.onError((error) => {\n this.lastError = describeError(error);\n });\n socket.onPing(() => this.armWatchdog());\n socket.onUpgradeRefused?.((status) => {\n this.upgradeStatus = status;\n });\n socket.onClose((code) => this.guard(() => this.onClosed(code)));\n }\n\n private onClosed(code?: number): void {\n const wasRegistered = this.registered;\n const restarting = this.restarting;\n this.restarting = false;\n this.socket = null;\n this.registered = false;\n if (this.watchdog) {\n clearTimeout(this.watchdog);\n this.watchdog = null;\n }\n for (const waiter of this.closeWaiters.splice(0)) waiter();\n if (this.stopped) return;\n if (this.upgradeStatus !== null && this.activeTransport === \"websocket\") {\n // A proxy answered the upgrade with a status: the socket can never\n // open here, and the same frames travel over plain HTTP.\n const status = this.upgradeStatus;\n this.upgradeStatus = null;\n this.activeTransport = \"http\";\n this.logger.warn(\n `the WebSocket upgrade to ${this.url} was answered with HTTP ${status}; using the HTTP transport at ${this.httpUrl} instead`,\n );\n this.scheduleConnect(0);\n return;\n }\n if (restarting) {\n this.scheduleConnect(0);\n return;\n }\n const delay = reconnectDelayMs({ attempt: this.attempt, ...this.backoff });\n this.attempt += 1;\n this.noteDisconnected({ wasRegistered, code });\n this.scheduleConnect(delay);\n }\n\n /**\n * One warning when the platform cannot be reached, one when a live\n * connection is lost, and silence while the retries run: the same notice\n * repeats only after the notice interval, and a reconnect resets it.\n */\n private noteDisconnected({ wasRegistered, code }: { wasRegistered: boolean; code?: number }): void {\n const now = Date.now();\n if (wasRegistered) {\n this.logger.warn(\n `lost the connection to LangWatch${code === undefined ? \"\" : ` (${code})`}, reconnecting with backoff`,\n );\n this.failureNoticeAt = now;\n return;\n }\n const stale =\n this.failureNoticeAt === null || now - this.failureNoticeAt >= this.failureNoticeIntervalMs;\n if (!stale) return;\n this.failureNoticeAt = now;\n const cause = this.lastError ? ` (${this.lastError})` : \"\";\n this.logger.warn(\n `agent ${this.agentNames()} ${NOT_CONNECTED}: could not reach ${this.url}${cause}. Check LANGWATCH_ENDPOINT and the network; retrying with backoff.`,\n );\n }\n\n private armWatchdog(): void {\n if (this.watchdog) clearTimeout(this.watchdog);\n const socket = this.socket;\n if (!socket) return;\n this.watchdog = setTimeout(() => {\n this.watchdog = null;\n this.logger.warn(\"no heartbeat from LangWatch, reconnecting\");\n try {\n socket.terminate();\n } catch {\n // The close event follows either way.\n }\n }, watchdogDelayMs(this.heartbeatIntervalMs));\n }\n\n private registerFrame(): ClientFrame {\n return {\n type: \"register\",\n protocol: PROTOCOL_VERSION,\n sdk: SDK_IDENTITY,\n instance: { ...this.instance, inFlightCallIds: [...this.inFlight.keys()] },\n agents: this.agents.map((agent) => agent.register),\n };\n }\n\n private send(frame: ClientFrame): void {\n const socket = this.socket;\n if (!socket) return;\n try {\n socket.send(serializeFrame(frame));\n } catch (error) {\n this.logger.debug(`could not send ${frame.type}: ${describeError(error)}`);\n }\n }\n\n private onMessage(data: string): void {\n const frame = parseServerFrame(data);\n if (!frame) {\n this.logger.debug(\"dropped a frame the SDK does not know\");\n return;\n }\n this.armWatchdog();\n switch (frame.type) {\n case \"registered\":\n this.onRegistered(frame);\n return;\n case \"refused\":\n this.onRefused(frame);\n return;\n case \"call\":\n void this.onCall(frame);\n return;\n case \"cancel\": {\n const call = this.inFlight.get(frame.callId);\n if (!call) return;\n call.cancelled = true;\n // The handler may run for as long as it wants; the slot it held is\n // free at once, so the next call is not refused as busy.\n this.releaseCall({ callId: frame.callId, entry: call });\n return;\n }\n }\n }\n\n private onRefused(frame: RefusedFrame): void {\n this.giveUp(refusalAdvice(frame));\n try {\n this.socket?.close(1000, frame.code);\n } catch {\n // The platform closes after refused either way.\n }\n }\n\n private onRegistered(frame: RegisteredFrame): void {\n this.registered = true;\n this.attempt = 0;\n if (this.failureNoticeAt !== null) {\n this.logger.info(\"connected to LangWatch\");\n this.failureNoticeAt = null;\n }\n if (this.activeTransport === \"http\" && !this.transportAnnounced) {\n this.transportAnnounced = true;\n this.logger.info(`connected to LangWatch over HTTP long polling at ${this.httpUrl}`);\n }\n this.heartbeatIntervalMs = frame.heartbeatIntervalMs;\n if (frame.instanceId && frame.instanceId !== this.instance.id) this.instance.id = frame.instanceId;\n this.byId.clear();\n for (const entry of frame.agents) {\n const runtime = this.agents.find(\n (agent) => agent.name === entry.name && agent.environment === entry.environment,\n );\n if (!runtime) continue;\n this.byId.set(entry.id, runtime);\n this.logger.info(\n `agent \"${entry.name}\" (${entry.environment}) is online${entry.url ? `: ${entry.url}` : \"\"}`,\n );\n const scopeNote = scopeBanner(entry);\n if (scopeNote) this.logger.info(scopeNote);\n for (const note of entry.parameterNotes) this.logger.warn(`agent \"${entry.name}\": ${note}`);\n }\n this.armWatchdog();\n }\n\n private async onCall(frame: CallFrame): Promise<void> {\n const runtime = this.byId.get(frame.agentId);\n if (!runtime) {\n this.sendError({\n callId: frame.callId,\n code: \"agent_call_failed\",\n message: `no agent registered as ${frame.agentId}`,\n });\n return;\n }\n const busy = [...this.inFlight.values()].filter((call) => call.runtime === runtime).length;\n if (busy >= runtime.concurrency) {\n this.sendError({\n callId: frame.callId,\n code: \"agent_busy\",\n message: `agent \"${runtime.name}\" has ${busy} call${busy === 1 ? \"\" : \"s\"} in flight, its limit`,\n });\n return;\n }\n if (frame.deadlineAt !== null && frame.deadlineAt <= Date.now()) {\n this.sendError({\n callId: frame.callId,\n code: \"agent_call_timeout\",\n message: \"the call deadline passed before it started\",\n });\n return;\n }\n\n // The slot is taken before the first await. Reading the parameters is\n // asynchronous, and a second call arriving inside that window would pass\n // the concurrency check above if the entry were written after it.\n const entry: InFlightCall = { runtime, cancelled: false, timer: null };\n this.inFlight.set(frame.callId, entry);\n\n let params: Record<string, AgentParameterValue>;\n try {\n params = await runtime.readParams(frame.params);\n } catch (error) {\n this.releaseCall({ callId: frame.callId, entry });\n this.sendError({\n callId: frame.callId,\n code: \"agent_parameter_invalid\",\n message: describeError(error),\n });\n return;\n }\n if (entry.cancelled) {\n this.releaseCall({ callId: frame.callId, entry });\n return;\n }\n\n // The ack means the function started: before it the platform may hand the\n // call to another instance, so it stays after the parameters are read.\n this.send({ type: \"ack\", protocol: PROTOCOL_VERSION, callId: frame.callId });\n this.armCallDeadline({ frame, entry, runtime });\n\n const parent = frame.traceparent\n ? propagation.extract(context.active(), { traceparent: frame.traceparent })\n : context.active();\n const traceId =\n trace.getSpanContext(parent)?.traceId ?? traceIdFromTraceparent(frame.traceparent) ?? \"\";\n\n const call: AgentCall<Record<string, AgentParameterValue>> = {\n messages: frame.messages,\n newMessages: frame.newMessages,\n threadId: frame.threadId,\n session: frame.session,\n params,\n traceId,\n };\n\n try {\n const result = await context.with(parent, () => runtime.run(call));\n if (entry.cancelled) return;\n // The handler answered, so its deadline is over. Disarming it before\n // the export matters: an export slower than what is left of the limit\n // would otherwise let the timer answer the call, and this branch would\n // then answer it a second time.\n this.releaseCall({ callId: frame.callId, entry });\n await this.flushSpans();\n this.send({\n type: \"result\",\n protocol: PROTOCOL_VERSION,\n callId: frame.callId,\n output: result.output,\n ...(result.session === undefined ? {} : { session: result.session }),\n });\n } catch (error) {\n if (entry.cancelled) return;\n const code = error instanceof AgentParameterError ? error.code : \"agent_call_failed\";\n const message = describeError(error);\n this.logger.warn(`agent \"${runtime.name}\" call ${frame.callId} failed: ${message}`);\n this.releaseCall({ callId: frame.callId, entry });\n await this.flushSpans();\n this.sendError({ callId: frame.callId, code, message });\n } finally {\n this.releaseCall({ callId: frame.callId, entry });\n }\n }\n\n /**\n * Exports the spans of the call now instead of at the exporter's next\n * schedule. The judge reads the agent's spans right after the last turn,\n * and a batch exporter would otherwise hold them for seconds, which is what\n * made the judge report the spans missing.\n *\n * The call awaits this before it sends its result or its error: the frame is\n * what tells the platform the turn is over, so a frame that goes out first\n * lets the judge read the call while its spans are still in the exporter.\n */\n private async flushSpans(): Promise<void> {\n const provider = trace.getTracerProvider() as { getDelegate?: () => unknown };\n const delegate =\n typeof provider.getDelegate === \"function\" ? provider.getDelegate() : provider;\n const flush = (delegate as { forceFlush?: () => Promise<void> } | null)?.forceFlush;\n if (typeof flush !== \"function\") return;\n try {\n await flush.call(delegate);\n } catch (error) {\n this.logger.debug(`span flush after a call failed: ${describeError(error)}`);\n }\n }\n\n /** Frees the slot the call holds and drops its deadline timer. */\n private releaseCall({ callId, entry }: { callId: string; entry: InFlightCall }): void {\n if (entry.timer) {\n clearTimeout(entry.timer);\n entry.timer = null;\n }\n if (this.inFlight.get(callId) === entry) this.inFlight.delete(callId);\n }\n\n /**\n * The call ends on its deadline: one timeout result, and the slot is free\n * from that moment. A handler that never returns then costs one call, not\n * every call after it.\n */\n private armCallDeadline({\n frame,\n entry,\n runtime,\n }: {\n frame: CallFrame;\n entry: InFlightCall;\n runtime: AgentRuntime;\n }): void {\n const fromDeadline = frame.deadlineAt === null ? Infinity : frame.deadlineAt - Date.now();\n const limit = Math.min(fromDeadline, runtime.timeoutMs);\n if (!Number.isFinite(limit)) return;\n const timer = setTimeout(() => {\n entry.timer = null;\n if (entry.cancelled) return;\n // The handler keeps running: a function cannot be stopped from here.\n // Its late result is dropped, because the platform has an answer.\n entry.cancelled = true;\n this.releaseCall({ callId: frame.callId, entry });\n this.logger.warn(\n `agent \"${runtime.name}\" call ${frame.callId} passed its ${limit} ms limit`,\n );\n this.sendError({\n callId: frame.callId,\n code: \"agent_call_timeout\",\n message: `the call passed the ${limit} ms limit of agent \"${runtime.name}\"`,\n });\n }, Math.max(0, limit));\n timer.unref();\n entry.timer = timer;\n }\n\n private sendError({ callId, code, message }: { callId: string; code: string; message: string }): void {\n this.send({ type: \"result\", protocol: PROTOCOL_VERSION, callId, error: { code, message } });\n }\n\n private guard(action: () => void): void {\n try {\n action();\n } catch (error) {\n this.logger.error(`agent client error: ${describeError(error)}`);\n }\n }\n}\n\nlet shared: AgentClient | null = null;\nlet sharedKey: string | null = null;\nlet hooksInstalled = false;\nconst noticesGiven = new Set<string>();\nlet testOverrides: Partial<AgentClientConfig> = {};\n\nconst signalHandlers = new Map<ShutdownSignal, () => void>();\n\nconst onShutdownSignal = (signal: ShutdownSignal): void => {\n const client = shared;\n const finish = () => {\n const handler = signalHandlers.get(signal);\n if (handler) process.removeListener(signal, handler);\n if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);\n };\n if (!client) {\n finish();\n return;\n }\n void client.disconnect().finally(finish);\n};\n\nconst onBeforeExit = (): void => {\n shared?.shutdownNow();\n};\n\nconst installShutdownHooks = (): void => {\n if (hooksInstalled) return;\n hooksInstalled = true;\n for (const signal of SHUTDOWN_SIGNALS) {\n const handler = () => onShutdownSignal(signal);\n signalHandlers.set(signal, handler);\n process.on(signal, handler);\n }\n process.on(\"beforeExit\", onBeforeExit);\n};\n\nconst removeShutdownHooks = (): void => {\n if (!hooksInstalled) return;\n hooksInstalled = false;\n for (const [signal, handler] of signalHandlers) process.removeListener(signal, handler);\n signalHandlers.clear();\n process.removeListener(\"beforeExit\", onBeforeExit);\n};\n\n/** One warning per process for a condition every agent definition would repeat. */\nexport function warnOnce({ logger, key, message }: { logger: Logger; key: string; message: string }): void {\n if (noticesGiven.has(key)) {\n logger.debug(message);\n return;\n }\n noticesGiven.add(key);\n logger.warn(message);\n}\n\n/**\n * The one client of this process. The first agent's credentials and endpoint\n * are the ones used; a later agent that names different ones is told so and\n * shares the socket anyway.\n */\nexport function getSharedClient(config: AgentClientConfig): AgentClient {\n const key = `${config.endpoint ?? \"\"}|${config.projectId ?? \"\"}|${config.apiKey}`;\n if (shared) {\n if (sharedKey !== key) {\n warnOnce({\n logger: config.logger,\n key: \"credentials-differ\",\n message:\n \"connectAgent: this process already has an agent connection with other credentials or endpoint; the first ones are used\",\n });\n }\n return shared;\n }\n shared = new AgentClient({ ...config, ...testOverrides });\n sharedKey = key;\n installShutdownHooks();\n return shared;\n}\n\n/** Settings the next shared client is built with, on top of what the agent gave. For tests. */\nexport function overrideSharedClientForTests(overrides: Partial<AgentClientConfig>): void {\n testOverrides = overrides;\n}\n\n/** Drops the shared client so the next definition starts a new one. For tests. */\nexport async function resetSharedClient(): Promise<void> {\n const client = shared;\n shared = null;\n sharedKey = null;\n noticesGiven.clear();\n testOverrides = {};\n removeShutdownHooks();\n if (client) await client.disconnect();\n}\n\n/** The client the process shares right now, so a test can read its state. */\nexport function sharedClientForTests(): AgentClient | null {\n return shared;\n}\n\n/** The shutdown handlers as installed, so a test can drive a signal without raising it. */\nexport const shutdownForTests = { onShutdownSignal, onBeforeExit };\n\n/**\n * What the process prints under \"is online\" when the agent is not shared. A\n * personal agent is invisible to every other key, which is the surprise this\n * line prevents; a host-scoped one is reachable by the whole project.\n */\nconst scopeBanner = (entry: RegisteredAgent): string | null => {\n switch (entry.scope.kind) {\n case \"shared\":\n return null;\n case \"owner\":\n return (\n `agent \"${entry.name}\" is personal to the owner of this API key; only their runs can target it. ` +\n `Set LANGWATCH_AGENT_ENVIRONMENT to a shared name such as dev-shared to share it with the project`\n );\n case \"host\":\n return `agent \"${entry.name}\" is scoped to this machine (${entry.scope.hostLabel}); anyone in the project can target it`;\n }\n};\n","/**\n * Who and where a connected agent is: its environment, its instance identity\n * and the endpoint it connects to. Every read of the machine is defensive, so\n * a locked-down sandbox with no hostname or no passwd entry still connects.\n */\n\nimport * as os from \"node:os\";\nimport { randomUUID } from \"node:crypto\";\nimport { LANGWATCH_SDK_VERSION } from \"../internal/constants\";\nimport { resolveEndpoint } from \"../internal/endpoint\";\nimport type { RegisterInstance, RegisterSdk } from \"./protocol\";\n\nexport const DEFAULT_ENVIRONMENT = \"development\";\nconst ENVIRONMENT_MAX_LENGTH = 32;\n\n/** The environment variables read in order after the explicit option. */\nconst ENVIRONMENT_VARIABLES = [\n \"LANGWATCH_AGENT_ENVIRONMENT\",\n \"APP_ENV\",\n \"ENVIRONMENT\",\n \"NODE_ENV\",\n] as const;\n\nconst isSet = (value: string | undefined): value is string =>\n typeof value === \"string\" && value.trim() !== \"\";\n\n/**\n * An environment name as the platform stores it: lowercase, `[a-z0-9_-]`\n * only, at most 32 characters. Anything else collapses to a dash, and an\n * empty result is the default environment.\n */\nexport function sanitizeEnvironment(name: string): string {\n const cleaned = name\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, ENVIRONMENT_MAX_LENGTH)\n .replace(/-+$/g, \"\");\n return cleaned === \"\" ? DEFAULT_ENVIRONMENT : cleaned;\n}\n\n/**\n * The environment an agent registers under: the explicit option, then\n * `LANGWATCH_AGENT_ENVIRONMENT`, `APP_ENV`, `ENVIRONMENT`, `NODE_ENV`, else\n * `development`.\n */\nexport function resolveEnvironment({\n explicit,\n env = process.env,\n}: {\n explicit?: string;\n env?: NodeJS.ProcessEnv;\n}): string {\n if (isSet(explicit)) return sanitizeEnvironment(explicit);\n for (const name of ENVIRONMENT_VARIABLES) {\n const value = env[name];\n if (isSet(value)) return sanitizeEnvironment(value);\n }\n return DEFAULT_ENVIRONMENT;\n}\n\nconst isTruthy = (value: string | undefined): boolean => {\n if (!isSet(value)) return false;\n const lowered = value.trim().toLowerCase();\n return lowered !== \"0\" && lowered !== \"false\" && lowered !== \"no\" && lowered !== \"off\";\n};\n\n/**\n * Whether the agent connects at all. `LANGWATCH_AGENT_CONNECT=0` (or false)\n * always disables it; the explicit option wins next; otherwise the connection\n * is on, except when `CI` is truthy.\n */\nexport function resolveEnabled({\n explicit,\n env = process.env,\n}: {\n explicit?: boolean;\n env?: NodeJS.ProcessEnv;\n}): boolean {\n const flag = env.LANGWATCH_AGENT_CONNECT;\n if (isSet(flag) && !isTruthy(flag)) return false;\n if (explicit !== undefined) return explicit;\n return !isTruthy(env.CI);\n}\n\n/** The instance label: the option, then `LANGWATCH_AGENT_INSTANCE_LABEL`. */\nexport function resolveInstanceLabel({\n explicit,\n env = process.env,\n}: {\n explicit?: string;\n env?: NodeJS.ProcessEnv;\n}): string | undefined {\n if (isSet(explicit)) return explicit.trim();\n const fromEnv = env.LANGWATCH_AGENT_INSTANCE_LABEL;\n return isSet(fromEnv) ? fromEnv.trim() : undefined;\n}\n\n/** The two reads of the machine, replaceable so a test can make them fail. */\nexport interface MachineReader {\n hostname: () => string;\n userInfo: () => { username: string };\n}\n\nconst HOST_LABEL_MAX_LENGTH = 24;\n\n/**\n * A short label for this machine: lowercase, `[a-z0-9-]`, 24 characters.\n *\n * The platform scopes a development agent connected with a project key to\n * this label, and the Python SDK sends the same shape, so one machine reads\n * the same whichever SDK connected it.\n */\nexport function hostLabel(hostname: string): string {\n return hostname\n .toLowerCase()\n .replace(/\\.(local|lan|home|localdomain)$/i, \"\")\n .replace(/[^a-z0-9-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, HOST_LABEL_MAX_LENGTH);\n}\n\nconst readHostname = (machine: MachineReader): string => {\n try {\n return hostLabel(machine.hostname());\n } catch {\n return \"\";\n }\n};\n\nconst readUsername = (machine: MachineReader): string => {\n try {\n return machine.userInfo().username;\n } catch {\n return \"\";\n }\n};\n\n/** The identity one process announces in `register`, built once. */\nexport function buildInstance({\n label,\n machine = os,\n}: {\n label?: string;\n machine?: MachineReader;\n}): RegisterInstance {\n return {\n id: `inst_${randomUUID().replace(/-/g, \"\")}`,\n hostname: readHostname(machine),\n username: readUsername(machine),\n pid: process.pid,\n startedAt: new Date().toISOString(),\n ...(label ? { label } : {}),\n inFlightCallIds: [],\n };\n}\n\n/** The SDK block of `register`. */\nexport const SDK_IDENTITY: RegisterSdk = {\n name: \"langwatch-typescript\",\n version: LANGWATCH_SDK_VERSION,\n language: \"typescript\",\n};\n\nexport const USER_AGENT = `langwatch-typescript/${LANGWATCH_SDK_VERSION}`;\n\nexport const CONNECT_PATH = \"/api/v1/agents/connect\";\n\n/**\n * The socket URL for an endpoint: `https://app.langwatch.ai` becomes\n * `wss://app.langwatch.ai/api/v1/agents/connect`, `http://localhost:5560`\n * becomes `ws://localhost:5560/api/v1/agents/connect`.\n */\nexport function resolveConnectUrl(endpoint?: string | null): string {\n const base = resolveEndpoint(endpoint);\n const socketBase = base.replace(/^http(s?):\\/\\//i, (_match, secure: string) =>\n secure ? \"wss://\" : \"ws://\",\n );\n return `${socketBase}${CONNECT_PATH}`;\n}\n\n/**\n * The base of the HTTP long-poll routes for an endpoint:\n * `https://app.langwatch.ai` becomes `https://app.langwatch.ai/api/v1/agents/connect`.\n */\nexport function resolveHttpConnectUrl(endpoint?: string | null): string {\n return `${resolveEndpoint(endpoint)}${CONNECT_PATH}`;\n}\n\n/** The headers the socket opens with. */\nexport function buildConnectHeaders({\n apiKey,\n projectId,\n}: {\n apiKey: string;\n projectId?: string;\n}): Record<string, string> {\n const headers: Record<string, string> = {\n Authorization: `Bearer ${apiKey}`,\n \"User-Agent\": USER_AGENT,\n };\n if (isSet(projectId)) headers[\"X-Project-Id\"] = projectId;\n return headers;\n}\n","{\n \"name\": \"langwatch\",\n \"version\": \"1.18.0\",\n \"description\": \"LangWatch TypeScript/JavaScript SDK. Interact with the full LangWatch API and use the LangWatch OpenTelemetry SDK to instrument your application. For more information, see https://docs.langwatch.ai/integration/typescript/guide\",\n \"main\": \"dist/index.js\",\n \"module\": \"dist/index.mjs\",\n \"types\": \"dist/index.d.ts\",\n \"author\": \"LangWatch\",\n \"license\": \"MIT\",\n \"engines\": {\n \"node\": \">=20\",\n \"pnpm\": \">=8\"\n },\n \"files\": [\n \"dist\",\n \"!dist/bin\",\n \"!dist/cli/*.map\",\n \"README.md\",\n \"LICENSE\"\n ],\n \"bin\": {\n \"lw\": \"./dist/cli/index.js\",\n \"langwatch\": \"./dist/cli/index.js\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.js\"\n },\n \"./observability\": {\n \"types\": \"./dist/observability-sdk/index.d.ts\",\n \"require\": \"./dist/observability-sdk/index.js\",\n \"import\": \"./dist/observability-sdk/index.mjs\"\n },\n \"./observability/node\": {\n \"types\": \"./dist/observability-sdk/setup/node/index.d.ts\",\n \"require\": \"./dist/observability-sdk/setup/node/index.js\",\n \"import\": \"./dist/observability-sdk/setup/node/index.mjs\"\n },\n \"./observability/instrumentation/langchain\": {\n \"types\": \"./dist/observability-sdk/instrumentation/langchain/index.d.ts\",\n \"require\": \"./dist/observability-sdk/instrumentation/langchain/index.js\",\n \"import\": \"./dist/observability-sdk/instrumentation/langchain/index.mjs\"\n },\n \"./agent\": {\n \"types\": \"./dist/agent/index.d.ts\",\n \"require\": \"./dist/agent/index.js\",\n \"import\": \"./dist/agent/index.mjs\"\n }\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/langwatch/langwatch.git\",\n \"directory\": \"typescript-sdk\"\n },\n \"scripts\": {\n \"generate\": \"pnpm run generate:server-types && pnpm run generate:openapi-types\",\n \"cli\": \"node dist/cli/index.js\",\n \"prelint\": \"pnpm run generate\",\n \"lint\": \"eslint .\",\n \"pretest\": \"pnpm run generate\",\n \"test\": \"vitest\",\n \"test:unit\": \"vitest run --exclude '**/*.integration.test.ts'\",\n \"test:e2e\": \"dotenv -- vitest run -c ./vitest.e2e.config.mts\",\n \"test:governance-e2e\": \"vitest run -c ./vitest.governance-e2e.config.mts\",\n \"test:seed\": \"dotenv -e .env.test -- bash -c 'cd ../../platform/app && pnpm prisma:seed'\",\n \"prebuild\": \"pnpm run generate\",\n \"build\": \"tsc --noEmit && rm -rf dist && tsup\",\n \"postbuild\": \"node -e \\\"const{statSync}=require('node:fs'),{execFileSync}=require('node:child_process');const f='dist/cli/index.js',want=require('./package.json').version;const s=statSync(f);if(process.platform!=='win32'&&!(s.mode&0o111))throw new Error(f+' is not executable');const got=execFileSync(process.execPath,[f,'--version'],{encoding:'utf8',env:{...process.env,LANGWATCH_NO_DAEMON:'1'}}).trim();if(got!==want)throw new Error('version mismatch: '+f+' reports '+got+', package.json says '+want);console.log('postbuild: '+f+' ok ('+got+')')\\\"\",\n \"build:binary\": \"bun run scripts/build-cli-binary.ts\",\n \"tarball\": \"pnpm build && pnpm pack\",\n \"typecheck\": \"tsc --noEmit\",\n \"prepublish\": \"pnpm run build\",\n \"generate:openapi-types\": \"pnpm exec openapi-typescript ../../platform/app/src/app/api/openapiLangWatch.json -o ./src/internal/generated/openapi/api-client.ts && node scripts/patch-generated-openapi.mjs\",\n \"generate:server-types\": \"./copy-types.sh\"\n },\n \"devDependencies\": {\n \"@eslint/js\": \"^9.32.0\",\n \"@langchain/core\": \">=0.3.68 <0.4.0\",\n \"@langchain/langgraph\": \">=0.4.0 <1.0.0\",\n \"@langchain/openai\": \">=0.6.0 <1.0.0\",\n \"@langwatch/langy\": \"workspace:*\",\n \"@opentelemetry/sdk-node\": \"0.221.0\",\n \"@opentelemetry/sdk-trace-node\": \"^2.0.1\",\n \"@opentelemetry/sdk-trace-web\": \">=2.0.1\",\n \"@types/debug\": \"^4.1.12\",\n \"@types/js-yaml\": \"^4.0.9\",\n \"@types/node\": \"^26.2.0\",\n \"@types/prompts\": \"^2.4.9\",\n \"@types/ws\": \"^8.18.1\",\n \"@vercel/otel\": \"^1.13.0\",\n \"@vitest/coverage-v8\": \"^4.1.0\",\n \"dotenv-cli\": \"^11.0.0\",\n \"esbuild\": \"^0.28.1\",\n \"eslint\": \"^9.32.0\",\n \"fets\": \"^0.8.5\",\n \"fishery\": \"^2.3.1\",\n \"langchain\": \">=0.3.0 <2.0.0\",\n \"msw\": \"^2.10.4\",\n \"nock\": \"^14.0.8\",\n \"openapi-msw\": \"^1.2.0\",\n \"openapi-typescript\": \"7.13.0\",\n \"tsup\": \"^8.5.0\",\n \"typescript\": \"^6.0.3\",\n \"typescript-eslint\": \"^8.38.0\",\n \"vitest\": \"^4.1.0\",\n \"vitest-mock-extended\": \"^5.1.1\",\n \"yaml\": \"^2.8.1\"\n },\n \"dependencies\": {\n \"@opentelemetry/api\": \"^1.9.0\",\n \"@opentelemetry/api-logs\": \"0.221.0\",\n \"@opentelemetry/core\": \"^2.0.1\",\n \"@opentelemetry/exporter-logs-otlp-http\": \"0.221.0\",\n \"@opentelemetry/exporter-trace-otlp-http\": \"0.221.0\",\n \"@opentelemetry/instrumentation\": \"0.221.0\",\n \"@opentelemetry/resources\": \"^2.0.1\",\n \"@opentelemetry/sdk-logs\": \"0.221.0\",\n \"@opentelemetry/sdk-metrics\": \"^2.0.1\",\n \"@opentelemetry/sdk-node\": \"^0.221.0\",\n \"@opentelemetry/sdk-trace-base\": \"^2.0.1\",\n \"@opentelemetry/semantic-conventions\": \"^1.36.0\",\n \"chalk\": \"^6.0.0\",\n \"cloudflared\": \"0.7.1\",\n \"commander\": \"^15.0.0\",\n \"dotenv\": \"^17.3.1\",\n \"js-yaml\": \"^5.2.0\",\n \"jsonc-parser\": \"^3.3.1\",\n \"liquidjs\": \"^10.27.0\",\n \"open\": \"^11.0.0\",\n \"openapi-fetch\": \"^0.17.0\",\n \"ora\": \"^9.3.0\",\n \"prompts\": \"^2.4.2\",\n \"ws\": \"^8.21.0\",\n \"xksuid\": \"^0.0.4\",\n \"zod\": \"^4.0.14\"\n },\n \"peerDependencies\": {\n \"@ai-sdk/openai\": \">=2.0.0 <5.0.0\",\n \"@langchain/core\": \">=0.3.0 <2.0.0\",\n \"@langchain/langgraph\": \">=0.4.0 <2.0.0\",\n \"@langchain/openai\": \">=0.6.0 <2.0.0\",\n \"@opentelemetry/context-async-hooks\": \"^2.1.0\",\n \"@opentelemetry/context-zone\": \">=1.19.0 <3.0.0\",\n \"@opentelemetry/sdk-trace-web\": \">=1.19.0 <3.0.0\",\n \"langchain\": \">=0.3.0 <2.0.0\"\n },\n \"peerDependenciesMeta\": {\n \"@ai-sdk/openai\": {\n \"optional\": true\n },\n \"@langchain/core\": {\n \"optional\": true\n },\n \"@langchain/langgraph\": {\n \"optional\": true\n },\n \"@langchain/openai\": {\n \"optional\": true\n },\n \"@opentelemetry/context-async-hooks\": {\n \"optional\": true\n },\n \"@opentelemetry/context-zone\": {\n \"optional\": true\n },\n \"@opentelemetry/sdk-trace-web\": {\n \"optional\": true\n },\n \"langchain\": {\n \"optional\": true\n }\n }\n}\n","import { version } from \"../../package.json\";\nimport { getRuntime } from \"./runtime\";\n\nexport const LANGWATCH_SDK_RUNTIME = getRuntime;\n\nexport const LANGWATCH_SDK_NAME_OBSERVABILITY = \"langwatch-observability-sdk\";\nexport const LANGWATCH_SDK_NAME_CLIENT = \"langwatch-client-sdk\";\nexport const LANGWATCH_SDK_LANGUAGE = \"typescript\";\nexport const LANGWATCH_SDK_VERSION = version;\n\nexport const DEFAULT_ENDPOINT = \"https://app.langwatch.ai\";\nexport const DEFAULT_SERVICE_NAME = \"unknown-service.langwatch\";\n\nexport const TRACES_PATH = \"/api/otel/v1/traces\";\nexport const LOGS_PATH = \"/api/otel/v1/logs\";\nexport const METRICS_PATH = \"/api/otel/v1/metrics\";\n","/**\n * Single place where a configured LangWatch endpoint becomes a usable base URL.\n *\n * Most services build request URLs by concatenation — `${endpoint}/api/...` —\n * and every path already carries its own leading slash. A trailing slash on the\n * endpoint therefore yields `https://app.langwatch.ai//api/experiment/init`,\n * which the router does not match, and the caller gets an opaque\n * `{\"error\":\"Not Found\"}` with nothing pointing at the real cause. Normalizing\n * at the point of resolution keeps every call site free of that concern.\n */\n\nimport { DEFAULT_ENDPOINT } from \"./constants\";\n\nconst isSet = (value: string | null | undefined): value is string =>\n typeof value === \"string\" && value.trim() !== \"\";\n\n/**\n * Trim surrounding whitespace and drop any trailing slashes.\n *\n * Scanned rather than matched with `/\\/+$/`: a repeated character class bound\n * to an anchor backtracks from every start index, which is quadratic on a\n * string of many slashes. The endpoint is configuration rather than attacker\n * input, but a linear scan costs nothing and leaves no such edge to reason\n * about.\n */\nexport const normalizeEndpoint = (endpoint: string): string => {\n const trimmed = endpoint.trim();\n let end = trimmed.length;\n while (end > 0 && trimmed[end - 1] === \"/\") end--;\n return trimmed.slice(0, end);\n};\n\n/**\n * Resolve the endpoint from an explicit value, then `LANGWATCH_ENDPOINT`, then\n * the cloud default. Blank values are treated as unset so that an empty\n * `LANGWATCH_ENDPOINT=` in a `.env` falls through to the default rather than\n * producing relative request URLs.\n */\nexport const resolveEndpoint = (endpoint?: string | null): string => {\n for (const candidate of [endpoint, process.env.LANGWATCH_ENDPOINT]) {\n if (!isSet(candidate)) continue;\n const normalized = normalizeEndpoint(candidate);\n if (normalized !== \"\") return normalized;\n }\n return normalizeEndpoint(DEFAULT_ENDPOINT);\n};\n\n/**\n * The OTLP logs endpoint an environment asks for, per the OTel exporter spec:\n * the signal-specific variable wins and is used verbatim; the generic variable\n * is a base that `/v1/logs` hangs off. Null when neither is set, which means no\n * OTLP transport rather than a default one.\n *\n * It lives here rather than beside either of its callers because both need it\n * and their module graphs must stay apart. The CLI's live event channel loads\n * the OpenTelemetry logs pipeline and the card contract; the session context\n * hook is bundled into a zero-dependency single file that ships inside the\n * agent plugin. Reaching into the event channel for this one pure env read\n * would put the whole telemetry graph in that bundle.\n */\nexport const resolveLogsEndpoint = (\n env: NodeJS.ProcessEnv = process.env,\n): string | null => {\n const signal = env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT?.trim();\n if (signal) return signal;\n\n const generic = env.OTEL_EXPORTER_OTLP_ENDPOINT?.trim();\n if (generic) return `${normalizeEndpoint(generic)}/v1/logs`;\n\n return null;\n};\n","/**\n * The frames the SDK and the platform exchange over the agent socket.\n *\n * Every frame is one JSON text message with a `type` and the protocol\n * version. The shapes here match the contract table in ADR-128 and the\n * platform's own frame module; the validators are small and hand-written\n * because this file is part of the public `langwatch/agent` surface, where no\n * schema library may cross as a value.\n *\n * @see dev/docs/adr/128-connected-agents.md\n */\n\nexport const PROTOCOL_VERSION = 1;\n\n/** One conversation message, OpenAI style. Extra keys are carried as is. */\nexport interface AgentMessage {\n role: string;\n content?: unknown;\n [key: string]: unknown;\n}\n\n/** The value of one run parameter as the platform sends it. */\nexport type AgentParameterValue = string | number | boolean;\n\n/** A JSON Schema object as the SDK sends it in `register`. */\nexport type JsonSchemaObject = Record<string, unknown>;\n\nexport interface RegisterSdk {\n name: string;\n version: string;\n language: string;\n}\n\nexport interface RegisterInstance {\n id: string;\n hostname: string;\n username: string;\n pid: number;\n startedAt: string;\n label?: string;\n inFlightCallIds: string[];\n}\n\nexport interface RegisterAgent {\n name: string;\n environment: string;\n parameters: JsonSchemaObject;\n concurrency?: number;\n timeoutMs?: number;\n sticky?: boolean;\n}\n\nexport interface RegisterFrame {\n type: \"register\";\n protocol: typeof PROTOCOL_VERSION;\n sdk: RegisterSdk;\n instance: RegisterInstance;\n agents: RegisterAgent[];\n}\n\nexport interface AckFrame {\n type: \"ack\";\n protocol: typeof PROTOCOL_VERSION;\n callId: string;\n}\n\nexport interface CallError {\n code: string;\n message: string;\n}\n\nexport type ResultFrame =\n | {\n type: \"result\";\n protocol: typeof PROTOCOL_VERSION;\n callId: string;\n output: unknown;\n session?: unknown;\n }\n | {\n type: \"result\";\n protocol: typeof PROTOCOL_VERSION;\n callId: string;\n error: CallError;\n };\n\nexport interface DeregisterFrame {\n type: \"deregister\";\n protocol: typeof PROTOCOL_VERSION;\n}\n\n/** Everything the SDK sends. */\nexport type ClientFrame = RegisterFrame | AckFrame | ResultFrame | DeregisterFrame;\n\n/** Who can target the agent: everyone, the owner of the registering key, or the project through this machine. */\nexport type RegisteredAgentScope =\n | { kind: \"shared\" }\n | { kind: \"owner\" }\n | { kind: \"host\"; hostLabel: string };\n\nexport interface RegisteredAgent {\n name: string;\n environment: string;\n id: string;\n url: string;\n parameterNotes: string[];\n scope: RegisteredAgentScope;\n}\n\nexport interface RegisteredFrame {\n type: \"registered\";\n protocol: number;\n agents: RegisteredAgent[];\n heartbeatIntervalMs: number;\n instanceId: string;\n}\n\nexport interface RefusedFrame {\n type: \"refused\";\n protocol: number;\n code: string;\n message: string;\n /** Extra data for one code, for example the projects a key reaches under `project_required`. */\n meta?: Record<string, unknown>;\n}\n\nexport interface CallRun {\n scenarioRunId?: string;\n scenarioName?: string;\n batchRunId?: string;\n}\n\nexport interface CallFrame {\n type: \"call\";\n protocol: number;\n callId: string;\n agentId: string;\n threadId: string;\n messages: AgentMessage[];\n newMessages: AgentMessage[];\n params: Record<string, AgentParameterValue>;\n session: unknown;\n traceparent: string | null;\n /** Epoch milliseconds, null when the platform sent none. */\n deadlineAt: number | null;\n run: CallRun;\n}\n\nexport interface CancelFrame {\n type: \"cancel\";\n protocol: number;\n callId: string;\n}\n\n/** Everything the platform sends. */\nexport type ServerFrame = RegisteredFrame | RefusedFrame | CallFrame | CancelFrame;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isString = (value: unknown): value is string => typeof value === \"string\";\n\nconst isMessageList = (value: unknown): value is AgentMessage[] =>\n Array.isArray(value) && value.every((item) => isRecord(item) && isString(item.role));\n\nconst isStringList = (value: unknown): value is string[] =>\n Array.isArray(value) && value.every(isString);\n\n/** A platform that predates the scope field registers everything as shared. */\nconst readScope = (value: unknown): RegisteredAgentScope => {\n if (!isRecord(value)) return { kind: \"shared\" };\n if (value.kind === \"owner\") return { kind: \"owner\" };\n if (value.kind === \"host\" && isString(value.hostLabel)) return { kind: \"host\", hostLabel: value.hostLabel };\n return { kind: \"shared\" };\n};\n\nconst readRegistered = (frame: Record<string, unknown>): RegisteredFrame | null => {\n if (!Array.isArray(frame.agents) || !isString(frame.instanceId)) return null;\n const agents: RegisteredAgent[] = [];\n for (const entry of frame.agents) {\n if (!isRecord(entry) || !isString(entry.name)) return null;\n const id = isString(entry.id) ? entry.id : isString(entry.agentId) ? entry.agentId : null;\n if (id === null) return null;\n agents.push({\n name: entry.name,\n environment: isString(entry.environment) ? entry.environment : \"\",\n id,\n url: isString(entry.url) ? entry.url : \"\",\n parameterNotes: isStringList(entry.parameterNotes) ? entry.parameterNotes : [],\n scope: readScope(entry.scope),\n });\n }\n return {\n type: \"registered\",\n protocol: typeof frame.protocol === \"number\" ? frame.protocol : PROTOCOL_VERSION,\n agents,\n heartbeatIntervalMs:\n typeof frame.heartbeatIntervalMs === \"number\" ? frame.heartbeatIntervalMs : 10_000,\n instanceId: frame.instanceId,\n };\n};\n\nconst readRefused = (frame: Record<string, unknown>): RefusedFrame => ({\n type: \"refused\",\n protocol: typeof frame.protocol === \"number\" ? frame.protocol : PROTOCOL_VERSION,\n code: isString(frame.code) ? frame.code : \"agent_register_refused\",\n message: isString(frame.message) ? frame.message : \"The platform refused the registration.\",\n ...(isRecord(frame.meta) ? { meta: frame.meta } : {}),\n});\n\nconst readParams = (value: unknown): Record<string, AgentParameterValue> => {\n if (!isRecord(value)) return {};\n const params: Record<string, AgentParameterValue> = {};\n for (const [name, item] of Object.entries(value)) {\n if (typeof item === \"string\" || typeof item === \"number\" || typeof item === \"boolean\") {\n params[name] = item;\n }\n }\n return params;\n};\n\n/** A deadline as epoch milliseconds, from a number or an ISO string. */\nconst readDeadline = (value: unknown): number | null => {\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (isString(value)) {\n const parsed = Date.parse(value);\n return Number.isNaN(parsed) ? null : parsed;\n }\n return null;\n};\n\nconst readCall = (frame: Record<string, unknown>): CallFrame | null => {\n if (!isString(frame.callId) || !isString(frame.agentId)) return null;\n const messages = isMessageList(frame.messages) ? frame.messages : [];\n const run = isRecord(frame.run) ? frame.run : {};\n return {\n type: \"call\",\n protocol: typeof frame.protocol === \"number\" ? frame.protocol : PROTOCOL_VERSION,\n callId: frame.callId,\n agentId: frame.agentId,\n threadId: isString(frame.threadId) ? frame.threadId : \"\",\n messages,\n newMessages: isMessageList(frame.newMessages) ? frame.newMessages : messages,\n params: readParams(frame.params),\n session: frame.session === undefined ? null : frame.session,\n traceparent: isString(frame.traceparent) ? frame.traceparent : null,\n deadlineAt: readDeadline(frame.deadlineAt),\n run: {\n ...(isString(run.scenarioRunId) ? { scenarioRunId: run.scenarioRunId } : {}),\n ...(isString(run.scenarioName) ? { scenarioName: run.scenarioName } : {}),\n ...(isString(run.batchRunId) ? { batchRunId: run.batchRunId } : {}),\n },\n };\n};\n\n/**\n * Reads one text message from the platform into a typed frame, or null when\n * the message is not a frame this protocol version knows. Unknown types and\n * malformed frames are dropped rather than thrown, so a newer platform never\n * crashes an older SDK.\n */\nexport function parseServerFrame(raw: string): ServerFrame | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return null;\n }\n if (!isRecord(parsed) || !isString(parsed.type)) return null;\n switch (parsed.type) {\n case \"registered\":\n return readRegistered(parsed);\n case \"refused\":\n return readRefused(parsed);\n case \"call\":\n return readCall(parsed);\n case \"cancel\":\n return isString(parsed.callId)\n ? {\n type: \"cancel\",\n protocol: typeof parsed.protocol === \"number\" ? parsed.protocol : PROTOCOL_VERSION,\n callId: parsed.callId,\n }\n : null;\n default:\n return null;\n }\n}\n\n/** One frame as the text the socket carries. */\nexport function serializeFrame(frame: ClientFrame): string {\n return JSON.stringify(frame);\n}\n\n/** The trace id of a W3C traceparent header, or null when it does not parse. */\nexport function traceIdFromTraceparent(traceparent: string | null | undefined): string | null {\n if (!traceparent) return null;\n const parts = traceparent.trim().split(\"-\");\n const traceId = parts[1];\n if (parts.length < 4 || !traceId || !/^[0-9a-f]{32}$/i.test(traceId)) return null;\n return traceId.toLowerCase();\n}\n","/**\n * The run parameters an agent declares, and the values a call supplies.\n *\n * Three forms are accepted: a definition map, any Standard JSON Schema object\n * (read through `\"~standard\".jsonSchema`, so zod 4, valibot and arktype work\n * without this package importing them), or a plain JSON Schema. A schema\n * library instance that offers no JSON Schema converter is refused with the\n * three forms named, because the SDK never takes a zod instance as a value.\n */\n\nimport type { AgentParameterValue, JsonSchemaObject } from \"./protocol\";\n\n/** The scalar types a run parameter may hold. */\nexport type ParameterType = \"string\" | \"number\" | \"boolean\";\n\n/** One entry of the definition map. */\nexport interface ParameterDefinition {\n /** The value type. Read from `options`, then `default`, else string. */\n type?: ParameterType;\n /** A closed list of accepted values. */\n options?: readonly string[];\n /** The value a run takes when it does not supply one. Without it the parameter is required. */\n default?: AgentParameterValue;\n description?: string;\n}\n\n/** Parameters declared by name. */\nexport type ParameterDefinitions = Record<string, ParameterDefinition>;\n\n/**\n * The Standard JSON Schema converter an object exposes under `\"~standard\"`.\n * Method syntax on purpose: a library narrows `target` to its own union, and\n * a method parameter is checked bivariantly, so zod 4, valibot and arktype\n * all fit without the SDK naming any of them.\n */\nexport interface StandardJsonSchemaConverter {\n input?(options: { readonly target: string }): Record<string, unknown>;\n output?(options: { readonly target: string }): Record<string, unknown>;\n}\n\n/** One problem a Standard Schema `validate` reports. */\nexport interface StandardSchemaIssue {\n readonly message: string;\n readonly path?: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }> | undefined;\n}\n\nexport type StandardSchemaResult<O> =\n | { readonly value: O; readonly issues?: undefined }\n | { readonly issues: ReadonlyArray<StandardSchemaIssue> };\n\n/**\n * Any object that implements the Standard JSON Schema interface. When it also\n * implements Standard Schema (`validate`), the values of every call go\n * through it before the handler runs, so a zod 4 schema validates, fills its\n * defaults and types `params` in one place.\n */\nexport interface StandardJsonSchema<O = unknown> {\n readonly \"~standard\": {\n readonly jsonSchema: StandardJsonSchemaConverter;\n validate?(value: unknown): StandardSchemaResult<O> | Promise<StandardSchemaResult<O>>;\n /** Type-only, from Standard Schema: the parsed output type. */\n readonly types?: { readonly input: unknown; readonly output: O } | undefined;\n };\n}\n\n/** The `params` type a Standard Schema object gives the handler: its parsed output. */\nexport type InferStandardOutput<S> = S extends { readonly \"~standard\": { readonly types?: infer T } }\n ? [NonNullable<T>] extends [never]\n ? Record<string, AgentParameterValue>\n : NonNullable<T> extends { readonly output: infer O }\n ? O extends Record<string, unknown>\n ? O\n : Record<string, AgentParameterValue>\n : Record<string, AgentParameterValue>\n : Record<string, AgentParameterValue>;\n\n/** Every form `parameters` accepts. */\nexport type ParameterInput = ParameterDefinitions | StandardJsonSchema | JsonSchemaObject;\n\n/** One parameter as the platform lists it, derived from the schema. */\nexport interface ParameterSpec {\n name: string;\n type: ParameterType;\n options?: string[];\n default?: AgentParameterValue;\n description?: string;\n required?: boolean;\n}\n\n/** The refusal of a parameter definition or of a value a call supplied. */\nexport class AgentParameterError extends Error {\n readonly code = \"agent_parameter_invalid\";\n constructor(message: string) {\n super(message);\n this.name = \"AgentParameterError\";\n }\n}\n\nconst ACCEPTED_FORMS =\n \"parameters must be a definition map ({ model: { options: [...], default: '...' } }), a Standard JSON Schema object (one with \\\"~standard\\\".jsonSchema), or a JSON Schema object ({ type: 'object', properties })\";\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isStandardJsonSchema = (value: unknown): value is StandardJsonSchema => {\n if (!isRecord(value)) return false;\n const standard = value[\"~standard\"];\n return isRecord(standard) && isRecord(standard.jsonSchema);\n};\n\nconst isJsonSchemaObject = (value: unknown): value is JsonSchemaObject =>\n isRecord(value) && value.type === \"object\" && isRecord(value.properties);\n\nconst isDefinitionMap = (value: unknown): value is ParameterDefinitions =>\n isRecord(value) && Object.values(value).every(isRecord);\n\nconst definitionType = (definition: ParameterDefinition): ParameterType => {\n if (definition.type) return definition.type;\n if (definition.options) return \"string\";\n const value = definition.default;\n if (typeof value === \"number\") return \"number\";\n if (typeof value === \"boolean\") return \"boolean\";\n return \"string\";\n};\n\nconst definitionMapToSchema = (definitions: ParameterDefinitions): JsonSchemaObject => {\n const properties: Record<string, Record<string, unknown>> = {};\n const required: string[] = [];\n for (const [name, definition] of Object.entries(definitions)) {\n const property: Record<string, unknown> = { type: definitionType(definition) };\n if (definition.options) property.enum = [...definition.options];\n if (definition.default !== undefined) property.default = definition.default;\n else required.push(name);\n if (definition.description !== undefined) property.description = definition.description;\n properties[name] = property;\n }\n const schema: JsonSchemaObject = { type: \"object\", properties };\n if (required.length > 0) schema.required = required;\n return schema;\n};\n\nconst readStandardJsonSchema = (input: StandardJsonSchema): JsonSchemaObject => {\n const converter = input[\"~standard\"].jsonSchema;\n const options = { target: \"draft-2020-12\" };\n const schema = converter.input?.(options) ?? converter.output?.(options);\n if (schema === undefined) {\n throw new AgentParameterError(`the \"~standard\".jsonSchema converter has no input function; ${ACCEPTED_FORMS}`);\n }\n if (!isRecord(schema)) {\n throw new AgentParameterError(`the \"~standard\".jsonSchema converter returned no object; ${ACCEPTED_FORMS}`);\n }\n return schema;\n};\n\n/**\n * The parameter schema the `register` frame carries, from any accepted form.\n * No parameters is an object schema with no properties.\n */\nexport function toParameterSchema(input: ParameterInput | undefined): JsonSchemaObject {\n if (input === undefined) return { type: \"object\", properties: {} };\n if (isStandardJsonSchema(input)) return readStandardJsonSchema(input);\n if (isJsonSchemaObject(input)) return input;\n if (isDefinitionMap(input)) return definitionMapToSchema(input);\n throw new AgentParameterError(ACCEPTED_FORMS);\n}\n\nconst specType = (property: Record<string, unknown>): ParameterType => {\n const type = Array.isArray(property.type)\n ? property.type.find((item) => item !== \"null\")\n : property.type;\n if (type === \"number\" || type === \"integer\") return \"number\";\n if (type === \"boolean\") return \"boolean\";\n return \"string\";\n};\n\nconst scalar = (value: unknown): AgentParameterValue | undefined =>\n typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\"\n ? value\n : undefined;\n\n/**\n * The parameters a schema declares, one spec per property, the way the\n * platform lists them. Unsupported property types read as text.\n */\nexport function parameterSpecsFromSchema(schema: JsonSchemaObject): ParameterSpec[] {\n const properties = isRecord(schema.properties) ? schema.properties : {};\n const required = new Set(Array.isArray(schema.required) ? schema.required : []);\n const specs: ParameterSpec[] = [];\n for (const [name, raw] of Object.entries(properties)) {\n const property = isRecord(raw) ? raw : {};\n const spec: ParameterSpec = { name, type: specType(property) };\n const options = Array.isArray(property.enum)\n ? property.enum.filter((item): item is string => typeof item === \"string\")\n : undefined;\n if (options && options.length > 0) spec.options = options;\n const fallback = scalar(property.default);\n if (fallback !== undefined) spec.default = fallback;\n if (typeof property.description === \"string\") spec.description = property.description;\n spec.required = fallback === undefined && required.has(name);\n specs.push(spec);\n }\n return specs;\n}\n\nconst coerce = ({\n spec,\n value,\n}: {\n spec: ParameterSpec;\n value: AgentParameterValue;\n}): AgentParameterValue => {\n if (spec.type === \"number\") {\n const asNumber = typeof value === \"number\" ? value : Number(value);\n if (typeof value === \"boolean\" || !Number.isFinite(asNumber) || String(value).trim() === \"\") {\n throw new AgentParameterError(`parameter \"${spec.name}\" must be a number, got ${JSON.stringify(value)}`);\n }\n return asNumber;\n }\n if (spec.type === \"boolean\") {\n if (typeof value === \"boolean\") return value;\n if (value === \"true\") return true;\n if (value === \"false\") return false;\n throw new AgentParameterError(`parameter \"${spec.name}\" must be true or false, got ${JSON.stringify(value)}`);\n }\n const asString = typeof value === \"string\" ? value : String(value);\n if (spec.options && !spec.options.includes(asString)) {\n throw new AgentParameterError(\n `parameter \"${spec.name}\" must be one of ${spec.options.join(\", \")}, got ${JSON.stringify(value)}`,\n );\n }\n return asString;\n};\n\n/**\n * The values the handler receives: every declared parameter, from the call or\n * from its default. A required parameter with no value, or a value of the\n * wrong type or outside the options, is refused with `agent_parameter_invalid`\n * before the handler runs. Names the schema does not declare pass through.\n */\nexport function resolveParameterValues({\n specs,\n supplied,\n}: {\n specs: ParameterSpec[];\n supplied: Record<string, AgentParameterValue> | undefined;\n}): Record<string, AgentParameterValue> {\n const values: Record<string, AgentParameterValue> = { ...(supplied ?? {}) };\n for (const spec of specs) {\n const value = values[spec.name];\n if (value === undefined) {\n if (spec.default !== undefined) {\n values[spec.name] = spec.default;\n continue;\n }\n if (!spec.required) continue;\n throw new AgentParameterError(`parameter \"${spec.name}\" is required and the run did not supply it`);\n }\n values[spec.name] = coerce({ spec, value });\n }\n return values;\n}\n\nconst issuePath = (issue: StandardSchemaIssue): string =>\n (issue.path ?? [])\n .map((segment) =>\n typeof segment === \"object\" && segment !== null ? String(segment.key) : String(segment),\n )\n .join(\".\");\n\n/**\n * The values after the schema's own `validate`: a zod 4 schema refines,\n * fills its defaults and strips what it does not declare. A refusal names\n * every issue with its path. Names the schema does not declare pass through\n * untouched, so a scenario-declared parameter still reaches the handler.\n */\nexport async function validateParameterValues({\n schema,\n values,\n}: {\n schema: StandardJsonSchema;\n values: Record<string, AgentParameterValue>;\n}): Promise<Record<string, AgentParameterValue>> {\n const standard = schema[\"~standard\"];\n const result = await standard.validate?.(values);\n if (result === undefined) return values;\n if (result.issues) {\n const detail = result.issues\n .map((issue) => {\n const path = issuePath(issue);\n return path ? `${path}: ${issue.message}` : issue.message;\n })\n .join(\"; \");\n throw new AgentParameterError(`parameters refused by the schema: ${detail}`);\n }\n const parsed = isRecord(result.value) ? (result.value as Record<string, AgentParameterValue>) : {};\n return { ...values, ...parsed };\n}\n\n/** What every call's parameters go through before the handler runs. */\nexport type ParameterReader = (\n supplied: Record<string, AgentParameterValue> | undefined,\n) => Promise<Record<string, AgentParameterValue>>;\n\n/**\n * The reader of one agent: defaults and coercion from the specs, then the\n * schema's own validation when the input carries one.\n */\nexport function createParameterReader({\n input,\n specs,\n}: {\n input: ParameterInput | undefined;\n specs: ParameterSpec[];\n}): ParameterReader {\n const schema = isStandardJsonSchema(input) ? input : undefined;\n return async (supplied) => {\n const values = resolveParameterValues({ specs, supplied });\n return schema ? validateParameterValues({ schema, values }) : values;\n };\n}\n","/**\n * The connection the client speaks over, behind one small interface so the\n * client never depends on how the frames travel.\n *\n * Two transports carry the same frames. The WebSocket is the default and it\n * needs the `ws` package: the platform authenticates from the request\n * headers of the upgrade, and no global `WebSocket` constructor can send\n * them. HTTP long polling is for a network that blocks WebSockets: one POST\n * registers, a GET waits for the next frames, a POST carries the answers. It\n * speaks through the global `fetch` (Node 20+).\n */\n\nimport { createRequire } from \"node:module\";\nimport type { WebSocket as WsWebSocket } from \"ws\";\nimport { langwatchFetch } from \"../internal/http/langwatchFetch\";\n\nexport const AGENT_TRANSPORTS = [\"websocket\", \"http\"] as const;\nexport type AgentTransport = (typeof AGENT_TRANSPORTS)[number];\n\n/** The header the poll and frames requests carry the instance token in. */\nexport const INSTANCE_TOKEN_HEADER = \"X-Agent-Instance-Token\";\n\nconst isSet = (value: string | undefined): value is string =>\n typeof value === \"string\" && value.trim() !== \"\";\n\n/**\n * The transport to start with: the explicit option, then\n * `LANGWATCH_AGENT_TRANSPORT`, else the WebSocket. Anything that is not\n * `http` is the WebSocket, which falls back to HTTP on its own when the\n * upgrade is refused.\n */\nexport function resolveTransport({\n explicit,\n env = process.env,\n}: {\n explicit?: string;\n env?: NodeJS.ProcessEnv;\n}): AgentTransport {\n const candidate = isSet(explicit) ? explicit : env.LANGWATCH_AGENT_TRANSPORT;\n return isSet(candidate) && candidate.trim().toLowerCase() === \"http\" ? \"http\" : \"websocket\";\n}\n\nexport interface SocketLike {\n send: (data: string) => void;\n close: (code?: number, reason?: string) => void;\n /** Drop the connection without a close handshake. */\n terminate: () => void;\n onOpen: (listener: () => void) => void;\n onMessage: (listener: (data: string) => void) => void;\n onClose: (listener: (code: number) => void) => void;\n onError: (listener: (error: unknown) => void) => void;\n /** The platform pings for liveness; the pong is automatic, this only reports it. */\n onPing: (listener: () => void) => void;\n /**\n * The upgrade was answered with an HTTP status instead of a switch of\n * protocols: a proxy in the way. Only `ws` can tell; the close follows.\n */\n onUpgradeRefused?: (listener: (status: number) => void) => void;\n}\n\nexport type SocketFactory = (args: { url: string; headers: Record<string, string> }) => SocketLike;\n\n/** Thrown when the `ws` package is not installed. */\nexport class NoWebSocketError extends Error {\n constructor() {\n super(\"the ws package is not installed, so no socket can carry the API key header\");\n this.name = \"NoWebSocketError\";\n }\n}\n\nconst textOf = (data: unknown): string => {\n if (typeof data === \"string\") return data;\n if (Buffer.isBuffer(data)) return data.toString(\"utf8\");\n if (Array.isArray(data)) return Buffer.concat(data as Buffer[]).toString(\"utf8\");\n if (data instanceof ArrayBuffer) return Buffer.from(data).toString(\"utf8\");\n return String(data);\n};\n\nconst wrapWs = (socket: WsWebSocket): SocketLike => {\n const closeListeners: Array<(code: number) => void> = [];\n let closed = false;\n const emitClose = (code: number) => {\n if (closed) return;\n closed = true;\n for (const listener of closeListeners) listener(code);\n };\n socket.on(\"close\", (code) => emitClose(code));\n return {\n send: (data) => socket.send(data),\n close: (code, reason) => socket.close(code, reason),\n terminate: () => socket.terminate(),\n onOpen: (listener) => socket.on(\"open\", listener),\n onMessage: (listener) => socket.on(\"message\", (data) => listener(textOf(data))),\n onClose: (listener) => closeListeners.push(listener),\n onError: (listener) => socket.on(\"error\", listener),\n onPing: (listener) => socket.on(\"ping\", listener),\n onUpgradeRefused: (listener) =>\n socket.on(\"unexpected-response\", (request, response) => {\n listener(response.statusCode ?? 0);\n // With a listener attached, `ws` leaves the request open and emits\n // no close of its own; both are finished here.\n response.resume();\n request.destroy();\n emitClose(1006);\n }),\n };\n};\n\ntype WsConstructor = new (\n url: string,\n options: { headers: Record<string, string> },\n) => WsWebSocket;\n\n/**\n * The `ws` constructor, or null when the package cannot be loaded. It is\n * required rather than imported: a runtime or a bundle without `ws` must\n * reach the factory below and get one clear message, never fail while this\n * module loads.\n */\nconst wsConstructor = (): WsConstructor | null => {\n try {\n const loaded = createRequire(__filename)(\"ws\") as { WebSocket?: unknown };\n return typeof loaded.WebSocket === \"function\" ? (loaded.WebSocket as WsConstructor) : null;\n } catch {\n return null;\n }\n};\n\n/**\n * Opens a socket with `ws`. A global `WebSocket` is no substitute: it takes\n * no request headers, the API key never travels in the URL, and the platform\n * would refuse every socket it opened.\n */\nexport const defaultSocketFactory: SocketFactory = ({ url, headers }) => {\n const Ws = wsConstructor();\n if (!Ws) throw new NoWebSocketError();\n return wrapWs(new Ws(url, { headers }));\n};\n\n// ---------------------------------------------------------------------------\n// HTTP long polling\n// ---------------------------------------------------------------------------\n\n/** The close code the client reads as \"register again at once\". */\nexport const SESSION_LOST_CLOSE_CODE = 1012;\n\n/** How a failed post of a frame is retried before the session is dropped. */\nconst POST_RETRY_DELAYS_MS = [250, 500, 1000];\n\n/**\n * The shortest gap between a poll that answered no frames and the next one.\n * The platform holds a poll for its own wait, so this costs nothing there; it\n * bounds a proxy that answers at once, which would otherwise spin.\n */\nconst EMPTY_POLL_FLOOR_MS = 250;\n\n/**\n * How long a close waits for the queued frames to go out before it drops them.\n * A frames request has no deadline of its own, so a proxy that accepts the\n * request and never answers would otherwise keep the socket from ever\n * reporting its close, and the client that is waiting to open a replacement\n * would wait with it.\n */\nconst CLOSE_DEADLINE_MS = 500;\n\nconst describe = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\nconst wait = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms).unref());\n\nexport interface HttpLongPollOptions {\n /** `https://app.langwatch.ai/api/v1/agents/connect`, the base the three routes hang off. */\n url: string;\n headers: Record<string, string>;\n fetch?: typeof fetch;\n}\n\n/**\n * The same frames over three requests. `send` of a register frame posts it\n * and starts the poll loop on the registered answer; `send` of any other\n * frame posts it in order; every frame a poll answers with is a message.\n * A poll that is refused, that fails or that names an unknown session ends\n * the connection the way a dropped socket would, and the client reconnects\n * with its own backoff, registering again.\n */\nexport class HttpLongPollSocket implements SocketLike {\n private readonly url: string;\n private readonly headers: Record<string, string>;\n private readonly fetchImpl: typeof fetch;\n private readonly messageListeners: Array<(data: string) => void> = [];\n private readonly closeListeners: Array<(code: number) => void> = [];\n private readonly errorListeners: Array<(error: unknown) => void> = [];\n private readonly pingListeners: Array<() => void> = [];\n private readonly inFlight = new Set<string>();\n private readonly polls = new AbortController();\n private readonly frames = new AbortController();\n private outbox: Promise<void> = Promise.resolve();\n private token: string | null = null;\n private closed = false;\n private closeEmitted = false;\n /** Settled once the register was answered, so a frame sent before it waits. */\n private readonly registered: Promise<void>;\n private settleRegistered: () => void = () => undefined;\n\n constructor(options: HttpLongPollOptions) {\n this.url = options.url;\n this.headers = options.headers;\n const fetchImpl = options.fetch ?? (typeof globalThis.fetch === \"function\" ? langwatchFetch : undefined);\n if (typeof fetchImpl !== \"function\") {\n throw new Error(\"the HTTP transport needs a global fetch; run on Node 20 or later\");\n }\n this.fetchImpl = fetchImpl;\n this.registered = new Promise<void>((resolve) => {\n this.settleRegistered = resolve;\n });\n }\n\n send(data: string): void {\n let frame: { type?: unknown; callId?: unknown };\n try {\n frame = JSON.parse(data) as { type?: unknown; callId?: unknown };\n } catch {\n return;\n }\n if (frame.type === \"register\") {\n void this.register(data);\n return;\n }\n if (frame.type === \"ack\" && typeof frame.callId === \"string\") this.inFlight.add(frame.callId);\n if (frame.type === \"result\" && typeof frame.callId === \"string\") this.inFlight.delete(frame.callId);\n this.outbox = this.outbox\n .then(() => this.registered)\n .then(() => this.post(data))\n .catch(() => undefined);\n }\n\n /**\n * Stops polling, lets the frames already queued go out, then reports the\n * close. The wait is bounded: on the deadline the frame requests are aborted\n * and the close is reported anyway, so a request that never answers cannot\n * hold the connection open.\n */\n close(code = 1000): void {\n this.closed = true;\n this.polls.abort();\n const deadline = setTimeout(() => {\n this.frames.abort();\n this.emitClose(code);\n }, CLOSE_DEADLINE_MS);\n deadline.unref();\n void this.outbox.finally(() => {\n clearTimeout(deadline);\n this.emitClose(code);\n });\n }\n\n terminate(): void {\n this.closed = true;\n this.polls.abort();\n this.frames.abort();\n this.emitClose(1006);\n }\n\n onOpen(listener: () => void): void {\n // There is nothing to open: the register frame is the first request.\n setTimeout(() => {\n if (!this.closed) listener();\n }, 0);\n }\n\n onMessage(listener: (data: string) => void): void {\n this.messageListeners.push(listener);\n }\n\n onClose(listener: (code: number) => void): void {\n this.closeListeners.push(listener);\n }\n\n onError(listener: (error: unknown) => void): void {\n this.errorListeners.push(listener);\n }\n\n onPing(listener: () => void): void {\n this.pingListeners.push(listener);\n }\n\n private requestHeaders(): Record<string, string> {\n return {\n ...this.headers,\n \"Content-Type\": \"application/json\",\n ...(this.token ? { [INSTANCE_TOKEN_HEADER]: this.token } : {}),\n };\n }\n\n private async register(data: string): Promise<void> {\n let response: Response;\n try {\n response = await this.fetchImpl(`${this.url}/register`, {\n method: \"POST\",\n headers: this.requestHeaders(),\n body: data,\n signal: this.polls.signal,\n });\n } catch (error) {\n if (!this.closed) this.fail(`could not reach ${this.url}/register (${describe(error)})`, 1006);\n return;\n }\n const body = await this.jsonOf(response);\n const frame = body && typeof body.frame === \"object\" && body.frame !== null ? body.frame : null;\n if (!frame) {\n this.fail(`the register request was answered with HTTP ${response.status}`, 1006);\n return;\n }\n if (typeof body?.instanceToken === \"string\") this.token = body.instanceToken;\n this.settleRegistered();\n this.emitMessage(JSON.stringify(frame));\n if ((frame as { type?: unknown }).type !== \"registered\") return;\n if (!this.token) {\n // Registered with no token: no poll can be addressed, so the connection\n // is finished here. The close is what makes the client register again.\n this.fail(\"the register answer carried no instance token\", 1006);\n return;\n }\n void this.pollLoop();\n }\n\n private async pollLoop(): Promise<void> {\n while (!this.closed && this.token) {\n const query = this.inFlight.size > 0 ? `?inFlight=${encodeURIComponent([...this.inFlight].join(\",\"))}` : \"\";\n const startedAt = Date.now();\n let response: Response;\n try {\n response = await this.fetchImpl(`${this.url}/poll${query}`, {\n method: \"GET\",\n headers: this.requestHeaders(),\n signal: this.polls.signal,\n });\n } catch (error) {\n if (!this.closed) this.fail(`the poll failed (${describe(error)})`, 1006);\n return;\n }\n if (this.closed) return;\n if (response.status === 410) {\n this.fail(\"the platform no longer knows this instance, registering again\", SESSION_LOST_CLOSE_CODE);\n return;\n }\n const body = await this.jsonOf(response);\n if (!response.ok) {\n const answered = body && typeof body.frame === \"object\" && body.frame !== null ? body.frame : null;\n if (answered) this.emitMessage(JSON.stringify(answered));\n if ((answered as { type?: unknown } | null)?.type === \"refused\") {\n // The platform refused the credential: the client prints and gives\n // up, and closes the connection itself.\n return;\n }\n this.fail(`the poll was answered with HTTP ${response.status}`, 1006);\n return;\n }\n const frames = Array.isArray(body?.frames) ? (body.frames as unknown[]) : [];\n for (const frame of frames) {\n const entry = frame as { type?: unknown; callId?: unknown };\n if (entry.type === \"cancel\" && typeof entry.callId === \"string\") this.inFlight.delete(entry.callId);\n this.emitMessage(JSON.stringify(frame));\n }\n for (const listener of this.pingListeners) listener();\n if (frames.length === 0) {\n const elapsedMs = Date.now() - startedAt;\n if (elapsedMs < EMPTY_POLL_FLOOR_MS) await wait(EMPTY_POLL_FLOOR_MS - elapsedMs);\n }\n }\n }\n\n private async post(data: string): Promise<void> {\n if (!this.token) return;\n for (let attempt = 0; ; attempt += 1) {\n if (this.frames.signal.aborted) return;\n let response: Response | null = null;\n try {\n response = await this.fetchImpl(`${this.url}/frames`, {\n method: \"POST\",\n headers: this.requestHeaders(),\n body: `{\"frames\":[${data}]}`,\n signal: this.frames.signal,\n });\n } catch {\n if (this.frames.signal.aborted) return;\n response = null;\n }\n if (response?.ok) return;\n if (response?.status === 410) {\n this.fail(\"the platform no longer knows this instance, registering again\", SESSION_LOST_CLOSE_CODE);\n return;\n }\n if (response && response.status < 500) return;\n const delay = POST_RETRY_DELAYS_MS[attempt];\n if (delay === undefined) {\n this.fail(`a frame could not be posted after ${attempt} retries`, 1006);\n return;\n }\n await wait(delay);\n }\n }\n\n private async jsonOf(response: Response): Promise<Record<string, unknown> | null> {\n try {\n const parsed = (await response.json()) as unknown;\n return typeof parsed === \"object\" && parsed !== null ? (parsed as Record<string, unknown>) : null;\n } catch {\n return null;\n }\n }\n\n private fail(message: string, code: number): void {\n for (const listener of this.errorListeners) listener(new Error(message));\n this.closed = true;\n this.polls.abort();\n this.frames.abort();\n this.emitClose(code);\n }\n\n private emitMessage(data: string): void {\n for (const listener of this.messageListeners) listener(data);\n }\n\n private emitClose(code: number): void {\n if (this.closeEmitted) return;\n this.closeEmitted = true;\n // A frame still waiting for the register answer is released; with no\n // token it is dropped, the way a frame on a closed socket is.\n this.settleRegistered();\n for (const listener of this.closeListeners) listener(code);\n }\n}\n","/**\n * The one HTTP client every request to the LangWatch API goes through.\n *\n * A LangWatch endpoint configured as `http://app.langwatch.ai` answers with a\n * redirect to https. The global `fetch` follows it on its own and, for a 301\n * or 302, turns the POST into a GET and drops the body, so the event is lost\n * without an error. This client sends with `redirect: \"manual\"` and applies a\n * rule per method to the 3xx it gets back.\n *\n * GET and HEAD follow a 301, 302, 303, 307 or 308 with the same method, up to\n * five hops. A hop that keeps the origin, or only upgrades http to https on\n * the same host and port, keeps every header; any other hop drops the\n * credential headers first. A hop from https to http and a hop without a\n * Location are refused.\n *\n * Every other method follows exactly one redirect, and only when the target is\n * the same URL with the scheme changed from http to https (same host, port,\n * path and query). The replay uses the same method, headers and body bytes.\n *\n * Every refused redirect throws `LangWatchRedirectError`.\n *\n * This module depends on the SDK logger only, so the CLI boot graph and the\n * `agent` entry can import it without pulling anything else in.\n */\nimport { ConsoleLogger, type Logger } from \"../../logger\";\n\nconst REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);\n\n/** Methods that follow a redirect to any http or https URL. */\nconst FOLLOWING_METHODS = new Set([\"GET\", \"HEAD\"]);\n\n/** The most redirects a GET or HEAD follows before the next one is refused. */\nexport const MAX_FOLLOW_HOPS = 5;\n\n/**\n * Headers dropped when a GET or HEAD hop leaves the origin: the three the Fetch\n * standard strips on a cross-origin redirect, plus the names LangWatch keys on.\n */\nconst CREDENTIAL_HEADERS = [\n \"authorization\",\n \"cookie\",\n \"proxy-authorization\",\n \"x-api-key\",\n \"x-auth-token\",\n \"x-project-id\",\n];\n\nexport class LangWatchRedirectError extends Error {\n readonly url: string;\n readonly location: string | null;\n readonly status: number;\n\n constructor({\n url,\n location,\n status,\n }: {\n url: string;\n location: string | null;\n status: number;\n }) {\n super(\n `LangWatch refused to follow a redirect from ${url} to ${location ?? \"an unknown location\"} (HTTP ${status}). Set the endpoint to the final URL.`,\n );\n this.name = \"LangWatchRedirectError\";\n this.url = url;\n this.location = location;\n this.status = status;\n }\n}\n\nexport type LangWatchFetch = typeof globalThis.fetch;\n\nexport interface CreateLangWatchFetchOptions {\n /** The transport to send with. Defaults to the global `fetch` at call time. */\n fetch?: LangWatchFetch;\n /** Receives the one warning per process about an http endpoint. */\n logger?: Logger;\n}\n\n/** Origins that already produced the http-to-https warning in this process. */\nconst warnedOrigins = new Set<string>();\n\n/** Forgets which origins were warned about. For tests only. */\nexport const resetSchemeUpgradeWarnings = (): void => {\n warnedOrigins.clear();\n};\n\nconst isRedirect = (response: Response): boolean =>\n response.type === \"opaqueredirect\" || REDIRECT_STATUSES.has(response.status);\n\nconst isStream = (body: unknown): boolean =>\n typeof ReadableStream !== \"undefined\" && body instanceof ReadableStream;\n\nconst abortError = (signal: AbortSignal): Error => {\n const reason: unknown = signal.reason;\n if (reason instanceof Error) return reason;\n if (typeof DOMException !== \"undefined\") {\n return new DOMException(\"This operation was aborted\", \"AbortError\");\n }\n return Object.assign(new Error(\"This operation was aborted\"), { name: \"AbortError\" });\n};\n\n/**\n * Releases the unread copy of a request body.\n *\n * `Request.clone` tees the body stream, and a branch nobody reads holds every\n * chunk the other branch consumes in memory. Cancelling the copy the replay\n * never needs keeps a streamed upload from being buffered whole.\n *\n * The cancellation is never awaited: a tee only settles the promise its\n * `cancel` returns once both branches are cancelled, so waiting on the copy\n * while the sent branch is still live would never return.\n */\nconst discard = (spare: Request | null): void => {\n void spare?.body?.cancel().catch(() => undefined);\n};\n\n/**\n * The body bytes to replay, read under the caller's signal.\n *\n * A `Request` built from a stream hands its copy over as a stream too, and\n * reading one that never ends would leave the call pending for good, past an\n * abort the caller already made. The read races the signal and cancels the\n * copy it loses to, so an aborted call settles.\n */\nconst replayBody = async ({\n spare,\n signal,\n}: {\n spare: Request;\n signal: AbortSignal | null | undefined;\n}): Promise<ArrayBuffer> => {\n if (!signal) return spare.arrayBuffer();\n if (signal.aborted) throw abortError(signal);\n\n const aborted = new Promise<never>((_, reject) => {\n signal.addEventListener(\"abort\", () => reject(abortError(signal)), { once: true });\n });\n // An abort that arrives after the read already won still rejects this one,\n // and nothing would be waiting on it by then.\n void aborted.catch(() => undefined);\n try {\n return await Promise.race([spare.arrayBuffer(), aborted]);\n } catch (error) {\n discard(spare);\n throw error;\n }\n};\n\nconst requestUrl = (input: RequestInfo | URL): string => {\n if (typeof input === \"string\") return input;\n if (input instanceof URL) return input.href;\n return input.url;\n};\n\nconst parseHop = ({\n url,\n location,\n}: {\n url: string;\n location: string;\n}): { from: URL; to: URL } | null => {\n try {\n const from = new URL(url);\n return { from, to: new URL(location, from) };\n } catch {\n return null;\n }\n};\n\n/** Same host and port, with the scheme changed from http to https. */\nconst isSchemeUpgrade = ({ from, to }: { from: URL; to: URL }): boolean =>\n from.protocol === \"http:\" &&\n to.protocol === \"https:\" &&\n from.hostname === to.hostname &&\n from.port === to.port;\n\n/**\n * The https URL to replay against when `location` only upgrades the scheme of\n * `url`, and null for any other target. The URL parser drops a default port,\n * so `http://host:80` and `https://host:443` both read as no port.\n */\nexport const schemeUpgradeTarget = ({\n url,\n location,\n}: {\n url: string;\n location: string;\n}): string | null => {\n const hop = parseHop({ url, location });\n if (hop === null || !isSchemeUpgrade(hop)) return null;\n const { from, to } = hop;\n if (from.pathname !== to.pathname) return null;\n if (from.search !== to.search) return null;\n to.hash = \"\";\n return to.href;\n};\n\n/**\n * The URL a GET or HEAD follows to, and null when the hop is refused: a\n * target that is not http or https, or a downgrade from https to http.\n */\nexport const followTarget = ({\n url,\n location,\n}: {\n url: string;\n location: string;\n}): string | null => {\n const hop = parseHop({ url, location });\n if (hop === null) return null;\n const { from, to } = hop;\n if (to.protocol !== \"http:\" && to.protocol !== \"https:\") return null;\n if (from.protocol === \"https:\" && to.protocol === \"http:\") return null;\n to.hash = \"\";\n return to.href;\n};\n\n/** A hop keeps its credential headers on the same origin and on an https upgrade of the same host. */\nconst keepsCredentials = ({ from, to }: { from: URL; to: URL }): boolean =>\n from.origin === to.origin || isSchemeUpgrade({ from, to });\n\nconst withoutCredentials = (headers: Headers): Headers => {\n const stripped = new Headers(headers);\n for (const name of CREDENTIAL_HEADERS) stripped.delete(name);\n return stripped;\n};\n\nconst warnOnce = ({ url, logger }: { url: string; logger: Logger }): void => {\n const { origin, host } = new URL(url);\n if (warnedOrigins.has(origin)) return;\n warnedOrigins.add(origin);\n logger.warn(\n `LangWatch endpoint ${origin} redirected to https. Set the endpoint to https://${host} to skip the extra round trip.`,\n );\n};\n\nconst refusalOf = ({\n url,\n response,\n}: {\n url: string;\n response: Response;\n}): LangWatchRedirectError =>\n new LangWatchRedirectError({\n url,\n location: response.headers.get(\"location\"),\n status: response.status,\n });\n\n/**\n * What `fetch(input, init)` would send, as one request both sends read from.\n * `init` wins over a `Request` input field by field, so reading the raw input\n * for the replay would resend a method, headers or body the caller overrode.\n * A plain URL input stays null: the non-Request path keeps `init` as it is, so\n * a stream body reaches the transport untouched.\n */\nconst effectiveRequest = ({\n input,\n init,\n}: {\n input: RequestInfo | URL;\n init: RequestInit | undefined;\n}): Request | null =>\n typeof Request !== \"undefined\" && input instanceof Request\n ? new Request(input, { ...init, redirect: \"manual\" })\n : null;\n\ninterface Hop {\n send: LangWatchFetch;\n log: Logger;\n effective: Request | null;\n init: RequestInit | undefined;\n url: string;\n first: Response;\n}\n\n/** The GET and HEAD rule: follow with the same method, up to MAX_FOLLOW_HOPS. */\nconst follow = async ({\n send,\n log,\n effective,\n init,\n url,\n method,\n first,\n}: Hop & { method: string }): Promise<Response> => {\n let headers = new Headers(effective?.headers ?? init?.headers);\n const signal = effective?.signal ?? init?.signal;\n let current = url;\n let response = first;\n\n for (let hop = 0; hop < MAX_FOLLOW_HOPS; hop++) {\n const location = response.headers.get(\"location\");\n const target = location === null ? null : followTarget({ url: current, location });\n if (target === null) throw refusalOf({ url: current, response });\n\n const from = new URL(current);\n const to = new URL(target);\n if (!keepsCredentials({ from, to })) headers = withoutCredentials(headers);\n if (isSchemeUpgrade({ from, to })) warnOnce({ url: current, logger: log });\n\n current = target;\n response = effective\n ? await send(new Request(target, { method, headers, signal, redirect: \"manual\" }))\n : await send(target, { ...init, method, headers, body: undefined, redirect: \"manual\" });\n if (!isRedirect(response)) return response;\n }\n\n throw refusalOf({ url: current, response });\n};\n\n/** The rule for every other method: one hop, and only an https upgrade of the same URL. */\nconst upgrade = async ({\n send,\n log,\n effective,\n init,\n url,\n first,\n spare,\n}: Hop & { spare: Request | null }): Promise<Response> => {\n const location = first.headers.get(\"location\");\n const refused = refusalOf({ url, response: first });\n const target = location === null ? null : schemeUpgradeTarget({ url, location });\n if (location === null || first.status === 303 || target === null || isStream(init?.body)) {\n discard(spare);\n throw refused;\n }\n\n warnOnce({ url, logger: log });\n\n const second = effective\n ? await send(\n new Request(target, {\n method: effective.method,\n headers: effective.headers,\n body: spare ? await replayBody({ spare, signal: effective.signal }) : null,\n signal: effective.signal,\n redirect: \"manual\",\n }),\n )\n : await send(target, { ...init, redirect: \"manual\" });\n if (!isRedirect(second)) return second;\n\n throw refusalOf({ url: target, response: second });\n};\n\n/**\n * Builds a `fetch` that applies the redirect rule. Pass `fetch` to send through\n * another transport (a test double, a proxying client) and `logger` to route\n * the http endpoint warning.\n */\nexport const createLangWatchFetch = ({\n fetch: fetchImpl,\n logger,\n}: CreateLangWatchFetchOptions = {}): LangWatchFetch => {\n const send: LangWatchFetch =\n fetchImpl ?? ((input, init) => globalThis.fetch(input, init));\n const log = logger ?? new ConsoleLogger({ level: \"warn\", prefix: \"LangWatch\" });\n\n return async (input, init) => {\n const url = requestUrl(input);\n const effective = effectiveRequest({ input, init });\n const method = (effective?.method ?? init?.method ?? \"GET\").toUpperCase();\n // A Request carries its body as a stream that one send consumes, so a copy\n // is taken before the first send and read only if the replay happens.\n const spare = effective !== null && effective.body !== null ? effective.clone() : null;\n\n const first = effective\n ? await send(effective)\n : await send(input, { ...init, redirect: \"manual\" });\n if (!isRedirect(first)) {\n discard(spare);\n return first;\n }\n\n const hop = { send, log, effective, init, url, first };\n if (!FOLLOWING_METHODS.has(method)) return upgrade({ ...hop, spare });\n\n discard(spare);\n return follow({ ...hop, method });\n };\n};\n\n/** The shared client, bound to the global `fetch` and the SDK console logger. */\nexport const langwatchFetch: LangWatchFetch = createLangWatchFetch();\n","/**\n * The reconnect loop both LangWatch sockets run on.\n *\n * The connected-agents client (`client.ts`) and the local control client\n * (`cli/commands/langy/relay-client.ts`) open different sockets and speak\n * different frames, but they keep them alive the same way: open, register,\n * watch for a heartbeat, and come back with a jittered backoff when the\n * platform goes away. That part lives here so there is one implementation of\n * it rather than two that drift.\n */\n\nimport {\n type AgentTransport,\n defaultSocketFactory,\n HttpLongPollSocket,\n NoWebSocketError,\n type SocketFactory,\n type SocketLike,\n} from \"./transport\";\n\nexport const RECONNECT_BASE_MS = 1_000;\nexport const RECONNECT_MAX_MS = 30_000;\n\n/** The delay before reconnect attempt `attempt` (0-based), with jitter, in the 1 s to 30 s window. */\nexport function reconnectDelayMs({\n attempt,\n baseMs = RECONNECT_BASE_MS,\n maxMs = RECONNECT_MAX_MS,\n random = Math.random,\n}: {\n attempt: number;\n baseMs?: number;\n maxMs?: number;\n random?: () => number;\n}): number {\n const exponential = Math.min(maxMs, baseMs * 2 ** Math.min(attempt, 16));\n const jittered = exponential * (0.75 + random() * 0.5);\n return Math.round(Math.min(maxMs, Math.max(baseMs, jittered)));\n}\n\n/**\n * How long the client waits for a sign of life before it drops the socket:\n * three heartbeats, and never less than fifteen seconds.\n */\nexport function watchdogDelayMs(heartbeatIntervalMs: number): number {\n return Math.max(15_000, heartbeatIntervalMs * 3);\n}\n\nexport const describeError = (error: unknown): string =>\n error instanceof Error ? error.message : String(error);\n\n/** How a socket is opened for a transport, so the caller never repeats the branch. */\nexport function openTransportSocket({\n transport,\n websocketUrl,\n httpUrl,\n headers,\n socketFactory = defaultSocketFactory,\n}: {\n transport: AgentTransport;\n websocketUrl: string;\n httpUrl: string;\n headers: Record<string, string>;\n socketFactory?: SocketFactory;\n}): SocketLike {\n return transport === \"http\"\n ? new HttpLongPollSocket({ url: httpUrl, headers })\n : socketFactory({ url: websocketUrl, headers });\n}\n\nexport { NoWebSocketError };\n","/**\n * `connectAgent`: the function that runs an agent becomes a simulation target.\n *\n * The wrapper resolves the environment and the parameter schema at definition,\n * registers the agent with the process-wide client, and returns a function\n * that is directly callable (for unit tests and local runs) and exposes\n * `disconnect()`.\n *\n * @see specs/typescript-sdk/agent-wrapper.feature\n */\n\nimport { ConsoleLogger, type Logger } from \"../logger\";\nimport { getSharedClient, warnOnce, type AgentRuntime } from \"./client\";\nimport {\n resolveEnabled,\n resolveEnvironment,\n resolveInstanceLabel,\n} from \"./identity\";\nimport type { AgentMessage, AgentParameterValue, JsonSchemaObject } from \"./protocol\";\nimport type { AgentTransport } from \"./transport\";\nimport {\n AgentParameterError,\n createParameterReader,\n parameterSpecsFromSchema,\n toParameterSchema,\n type InferStandardOutput,\n type ParameterDefinition,\n type ParameterDefinitions,\n type ParameterInput,\n type StandardJsonSchema,\n} from \"./schema\";\n\n/** The default call timeout, and the cap the platform enforces. */\nexport const DEFAULT_TIMEOUT_MS = 120_000;\nexport const MAX_TIMEOUT_MS = 300_000;\nexport const DEFAULT_CONCURRENCY = 10;\n\n/** What a handler may return: a string, one message, a list of messages, or an output with a session. */\nexport type AgentOutput = string | AgentMessage | AgentMessage[];\n\n/** The output of one turn plus the session the agent keeps for the next turn of the same thread. */\nexport interface AgentResult {\n output: AgentOutput;\n session?: unknown;\n}\n\nexport type AgentReply = AgentOutput | AgentResult;\n\n/** The one object a handler receives on every turn. */\nexport interface AgentCall<P = Record<string, AgentParameterValue>> {\n /** The full conversation, OpenAI style. */\n messages: AgentMessage[];\n /** The messages added since the last turn of this thread. */\n newMessages: AgentMessage[];\n /** The platform's conversation id. */\n threadId: string;\n /** The value the handler returned as `session` on the previous turn of this thread, null on the first. */\n session: unknown;\n /** The run parameters, validated and with defaults filled. */\n params: P;\n /** The trace id of the turn, so the agent's own spans join it. Empty when the call carries none. */\n traceId: string;\n}\n\nexport type AgentHandler<P> = (call: AgentCall<P>) => AgentReply | Promise<AgentReply>;\n\n/** What a direct call of the wrapped function takes: messages, and anything else is optional. */\nexport interface DirectAgentCall<P> {\n messages: AgentMessage[];\n newMessages?: AgentMessage[];\n threadId?: string;\n session?: unknown;\n params?: Partial<P>;\n traceId?: string;\n}\n\nexport interface ConnectAgentOptions<P extends ParameterInput = ParameterDefinitions> {\n /** The agent name. One row per name and environment on the platform. */\n name: string;\n /** Resolved from LANGWATCH_AGENT_ENVIRONMENT, APP_ENV, ENVIRONMENT, NODE_ENV, else development. */\n environment?: string;\n /** A definition map, a Standard JSON Schema object, or a JSON Schema object. */\n parameters?: P;\n /**\n * Whether this process connects. Takes any boolean, so one expression can\n * gate the deployments that connect. Without it the default is true, except\n * when CI is truthy; a value given here replaces that rule rather than adding\n * to it, so keep the CI half: `process.env.APP_ENV !== \"production\" && !process.env.CI`.\n * LANGWATCH_AGENT_CONNECT=0 always disables.\n */\n enabled?: boolean;\n /** Names this instance in the platform. Also LANGWATCH_AGENT_INSTANCE_LABEL. */\n instanceLabel?: string;\n /** Per call, default 120000, at most 300000. */\n timeoutMs?: number;\n /**\n * Calls in flight per instance, default 10. A test suite sends several\n * scenarios at once; the ceiling is there because the model providers rate\n * limit the calls behind them.\n */\n concurrency?: number;\n /** Keep every turn of a thread on the instance that answered the first one. */\n sticky?: boolean;\n apiKey?: string;\n endpoint?: string;\n projectId?: string;\n /** `websocket` (default, falls back to HTTP when the upgrade is refused) or `http`. Also LANGWATCH_AGENT_TRANSPORT. */\n transport?: AgentTransport;\n logger?: Logger;\n}\n\n/** The wrapped function: callable, and connected until `disconnect()`. */\nexport interface ConnectedAgent<P> {\n (call: DirectAgentCall<P>): Promise<AgentResult>;\n readonly name: string;\n readonly environment: string;\n /** The parameter schema as registered. */\n readonly parameters: JsonSchemaObject;\n /** Send deregister and close the socket when this was the last agent of the process. */\n disconnect: () => Promise<void>;\n}\n\ntype Widen<V> = V extends string ? string : V extends number ? number : V extends boolean ? boolean : V;\n\ntype ParameterValueOf<D extends ParameterDefinition> = D extends {\n options: readonly (infer O extends string)[];\n}\n ? O\n : D extends { type: \"number\" }\n ? number\n : D extends { type: \"boolean\" }\n ? boolean\n : D extends { type: \"string\" }\n ? string\n : D extends { default: infer V }\n ? Widen<V>\n : string;\n\n/** The `params` type a definition map gives the handler. */\nexport type InferParameters<P extends ParameterDefinitions> = {\n [K in keyof P]: ParameterValueOf<P[K]>;\n};\n\nconst isMessage = (value: unknown): value is AgentMessage =>\n typeof value === \"object\" && value !== null && !Array.isArray(value) && typeof (value as AgentMessage).role === \"string\";\n\n/** One of the four reply shapes as the `{ output, session }` the result frame carries. */\nexport function normalizeReply(reply: unknown): AgentResult {\n if (typeof reply === \"string\") return { output: reply };\n if (Array.isArray(reply) && reply.every(isMessage)) return { output: reply };\n if (isMessage(reply)) return { output: reply };\n if (typeof reply === \"object\" && reply !== null && \"output\" in reply) {\n const { output, session } = reply as { output: unknown; session?: unknown };\n const normalized = normalizeReply(output);\n return session === undefined ? normalized : { output: normalized.output, session };\n }\n throw new Error(\n \"the agent handler must return a string, a message, a list of messages, or { output, session }\",\n );\n}\n\nconst clampTimeout = ({ timeoutMs, logger, name }: { timeoutMs: number | undefined; logger: Logger; name: string }): number => {\n if (timeoutMs === undefined) return DEFAULT_TIMEOUT_MS;\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return DEFAULT_TIMEOUT_MS;\n if (timeoutMs > MAX_TIMEOUT_MS) {\n logger.warn(`agent \"${name}\": timeoutMs ${timeoutMs} is above the ${MAX_TIMEOUT_MS} cap, using the cap`);\n return MAX_TIMEOUT_MS;\n }\n return Math.floor(timeoutMs);\n};\n\nconst readApiKey = (explicit: string | undefined): string | undefined => {\n const candidate = explicit ?? process.env.LANGWATCH_API_KEY;\n return typeof candidate === \"string\" && candidate.trim() !== \"\" ? candidate.trim() : undefined;\n};\n\nconst readProjectId = (explicit: string | undefined): string | undefined => {\n const candidate = explicit ?? process.env.LANGWATCH_PROJECT_ID;\n return typeof candidate === \"string\" && candidate.trim() !== \"\" ? candidate.trim() : undefined;\n};\n\n/**\n * A schema library object (zod 4, valibot, arktype: anything with Standard\n * Schema and Standard JSON Schema) types `params` as its parsed output and\n * validates every call's values before the handler runs.\n */\nexport function connectAgent<const S extends StandardJsonSchema>(\n options: ConnectAgentOptions<S> & { parameters: S },\n handler: AgentHandler<InferStandardOutput<S>>,\n): ConnectedAgent<InferStandardOutput<S>>;\nexport function connectAgent<const P extends ParameterDefinitions = Record<string, never>>(\n options: ConnectAgentOptions<P>,\n handler: AgentHandler<InferParameters<P>>,\n): ConnectedAgent<InferParameters<P>>;\nexport function connectAgent(\n options: ConnectAgentOptions<JsonSchemaObject>,\n handler: AgentHandler<Record<string, AgentParameterValue>>,\n): ConnectedAgent<Record<string, AgentParameterValue>>;\nexport function connectAgent(\n options: ConnectAgentOptions<ParameterInput>,\n handler: AgentHandler<Record<string, AgentParameterValue>>,\n): ConnectedAgent<Record<string, AgentParameterValue>> {\n const logger = options.logger ?? new ConsoleLogger({ level: \"info\", prefix: \"LangWatch\" });\n const name = options.name?.trim();\n if (!name) throw new Error(\"connectAgent needs a name\");\n\n const environment = resolveEnvironment({ explicit: options.environment });\n const parameters = toParameterSchema(options.parameters);\n const specs = parameterSpecsFromSchema(parameters);\n const timeoutMs = clampTimeout({ timeoutMs: options.timeoutMs, logger, name });\n const concurrency = Math.max(1, Math.floor(options.concurrency ?? DEFAULT_CONCURRENCY));\n\n const runHandler = async (call: AgentCall<Record<string, AgentParameterValue>>): Promise<AgentResult> =>\n normalizeReply(await handler(call));\n\n const readParams = createParameterReader({ input: options.parameters, specs });\n\n const invoke = async (call: DirectAgentCall<Record<string, AgentParameterValue>>): Promise<AgentResult> => {\n const params = await readParams(call.params as Record<string, AgentParameterValue> | undefined);\n return runHandler({\n messages: call.messages,\n newMessages: call.newMessages ?? call.messages,\n threadId: call.threadId ?? `local_${Date.now().toString(36)}`,\n session: call.session ?? null,\n params,\n traceId: call.traceId ?? \"\",\n });\n };\n\n const runtime: AgentRuntime = {\n name,\n environment,\n register: {\n name,\n environment,\n parameters,\n concurrency,\n timeoutMs,\n ...(options.sticky ? { sticky: true } : {}),\n },\n readParams,\n concurrency,\n timeoutMs,\n run: runHandler,\n };\n\n let detach: (() => Promise<void>) | undefined;\n\n if (!resolveEnabled({ explicit: options.enabled })) {\n logger.debug(`agent \"${name}\" not connected to LangWatch: the connection is disabled`);\n } else {\n const apiKey = readApiKey(options.apiKey);\n if (!apiKey) {\n warnOnce({\n logger,\n key: \"no-api-key\",\n message: `agent \"${name}\" not connected to LangWatch: no API key. Set LANGWATCH_API_KEY to run simulations against it.`,\n });\n } else {\n const client = getSharedClient({\n apiKey,\n endpoint: options.endpoint,\n projectId: readProjectId(options.projectId),\n instanceLabel: resolveInstanceLabel({ explicit: options.instanceLabel }),\n transport: options.transport,\n logger,\n });\n client.addAgent(runtime);\n detach = () => client.removeAgent(runtime);\n }\n }\n\n const connected = Object.assign(invoke, {\n environment,\n parameters,\n disconnect: async (): Promise<void> => {\n if (!detach) return;\n const release = detach;\n detach = undefined;\n await release();\n },\n });\n // A function's own `name` is read-only but configurable, so it is defined rather than assigned.\n Object.defineProperty(connected, \"name\", { value: name, configurable: true });\n\n return connected as ConnectedAgent<Record<string, AgentParameterValue>>;\n}\n\nexport { AgentParameterError };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACkBA,IAAM,gBAA0C;AAAA,EAC9C,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;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