@openai/agents-openai
Version:
The OpenAI Agents SDK is a lightweight yet powerful framework for building multi-agent workflows.
402 lines • 14.5 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResponsesWebSocketConnection = exports.ResponsesWebSocketInternalError = exports.RESPONSES_WEBSOCKET_ERROR_MESSAGES = void 0;
exports.throwIfAborted = throwIfAborted;
exports.withAbortSignal = withAbortSignal;
exports.withTimeout = withTimeout;
exports.webSocketFrameToText = webSocketFrameToText;
exports.shouldWrapNoEventWebSocketError = shouldWrapNoEventWebSocketError;
exports.isWebSocketNotOpenError = isWebSocketNotOpenError;
const agents_core_1 = require("@openai/agents-core");
const openai_1 = __importDefault(require("openai"));
exports.RESPONSES_WEBSOCKET_ERROR_MESSAGES = {
connection_closed_before_opening: 'Responses websocket connection closed before opening.',
connection_closed_before_terminal_response_event: 'Responses websocket connection closed before a terminal response event.',
pong_timeout: 'Responses websocket pong timeout.',
socket_not_open: 'Responses websocket is not open.',
};
class ResponsesWebSocketInternalError extends Error {
code;
constructor(code, message = exports.RESPONSES_WEBSOCKET_ERROR_MESSAGES[code]) {
super(message);
this.name = 'ResponsesWebSocketInternalError';
this.code = code;
}
}
exports.ResponsesWebSocketInternalError = ResponsesWebSocketInternalError;
function throwIfAborted(signal) {
if (signal?.aborted) {
throw new openai_1.default.APIUserAbortError();
}
}
async function withAbortSignal(promise, signal) {
throwIfAborted(signal);
if (!signal) {
return promise;
}
return await new Promise((resolve, reject) => {
const onAbort = () => {
reject(new openai_1.default.APIUserAbortError());
};
signal.addEventListener('abort', onAbort, { once: true });
promise.then((value) => {
signal.removeEventListener('abort', onAbort);
resolve(value);
}, (error) => {
signal.removeEventListener('abort', onAbort);
reject(error);
});
});
}
async function withTimeout(promise, timeoutMs, errorMessage) {
if (typeof timeoutMs !== 'number' ||
!Number.isFinite(timeoutMs) ||
timeoutMs <= 0) {
return await promise;
}
return await new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
reject(new Error(errorMessage));
}, timeoutMs);
promise.then((value) => {
clearTimeout(timeoutId);
resolve(value);
}, (error) => {
clearTimeout(timeoutId);
reject(error);
});
});
}
async function webSocketFrameToText(frame) {
if (typeof frame === 'string') {
return frame;
}
if (typeof Blob !== 'undefined' && frame instanceof Blob) {
return await frame.text();
}
if (frame instanceof ArrayBuffer) {
return new TextDecoder().decode(new Uint8Array(frame));
}
if (ArrayBuffer.isView(frame)) {
return new TextDecoder().decode(new Uint8Array(frame.buffer, frame.byteOffset, frame.byteLength));
}
throw new Error('Unsupported websocket frame type for Responses API.');
}
function shouldWrapNoEventWebSocketError(error) {
if (error instanceof ResponsesWebSocketInternalError) {
return (error.code === 'connection_closed_before_opening' ||
error.code === 'connection_closed_before_terminal_response_event');
}
if (!(error instanceof Error)) {
return false;
}
return (error.message ===
exports.RESPONSES_WEBSOCKET_ERROR_MESSAGES.connection_closed_before_opening ||
error.message ===
exports.RESPONSES_WEBSOCKET_ERROR_MESSAGES.connection_closed_before_terminal_response_event);
}
function isWebSocketNotOpenError(error) {
if (error instanceof ResponsesWebSocketInternalError) {
return error.code === 'socket_not_open';
}
if (!(error instanceof Error)) {
return false;
}
if (error.message === exports.RESPONSES_WEBSOCKET_ERROR_MESSAGES.socket_not_open) {
return true;
}
// Native WebSocket implementations can throw InvalidStateError/DOMException
// if the socket closes after the readyState check but before send().
if (error.name === 'InvalidStateError') {
return true;
}
// `ws` throws a plain Error with this message shape for send races.
if (error.message.startsWith('WebSocket is not open: readyState ')) {
return true;
}
return false;
}
function normalizeKeepAliveDurationMs(value, fieldName) {
if (value == null) {
return undefined;
}
if (Number.isFinite(value) && value > 0) {
return value;
}
throw new agents_core_1.UserError(`Responses websocket ${fieldName} must be a positive number of milliseconds or null.`);
}
class ResponsesWebSocketConnection {
#socket;
#messages = [];
#waiters = [];
#closed = false;
#error;
#closedPromise;
#resolveClosed;
#pingIntervalMs;
#pingTimeoutMs;
#pingIntervalTimer;
#pingTimeoutTimer;
#removePongListener;
constructor(socket, keepAliveOptions = {}) {
this.#socket = socket;
this.#pingIntervalMs = normalizeKeepAliveDurationMs(keepAliveOptions.pingIntervalMs, 'pingIntervalMs');
this.#pingTimeoutMs = normalizeKeepAliveDurationMs(keepAliveOptions.pingTimeoutMs, 'pingTimeoutMs');
this.#closedPromise = new Promise((resolve) => {
this.#resolveClosed = resolve;
});
this.#socket.addEventListener('message', this.#onMessage);
this.#socket.addEventListener('error', this.#onError);
this.#socket.addEventListener('close', this.#onClose);
this.#removePongListener = this.#addPongListener();
}
static async connect(url, headers, signal, timeoutMs, timeoutErrorMessage, keepAliveOptions = {}) {
const WebSocketCtor = globalThis.WebSocket;
if (!WebSocketCtor) {
throw new agents_core_1.UserError('Responses websocket transport requires a global WebSocket implementation.');
}
let socket;
try {
socket = new WebSocketCtor(url, { headers });
}
catch (error) {
const wrappedError = new agents_core_1.UserError('Responses websocket transport requires a WebSocket implementation that supports custom headers.');
wrappedError.cause = error;
throw wrappedError;
}
let connection;
try {
connection = new ResponsesWebSocketConnection(socket, keepAliveOptions);
}
catch (error) {
try {
socket.close();
}
catch {
// Ignore close errors for sockets that failed option validation.
}
throw error;
}
try {
await connection.waitForOpen(signal, timeoutMs, timeoutErrorMessage);
connection.#startKeepAlive();
}
catch (error) {
await connection.close();
throw error;
}
return connection;
}
async waitForOpen(signal, timeoutMs, timeoutErrorMessage) {
if (this.#socket.readyState === this.#socket.OPEN) {
return;
}
if (this.#error) {
throw this.#error;
}
if (this.#closed ||
this.#socket.readyState === this.#socket.CLOSED ||
this.#socket.readyState === this.#socket.CLOSING) {
throw new ResponsesWebSocketInternalError('connection_closed_before_opening');
}
const openPromise = new Promise((resolve, reject) => {
const onOpen = () => {
cleanup();
resolve();
};
const onError = () => {
cleanup();
reject(this.#error ??
new Error('Responses websocket connection failed to open.'));
};
const onClose = () => {
cleanup();
reject(this.#error ??
new ResponsesWebSocketInternalError('connection_closed_before_opening'));
};
const cleanup = () => {
this.#socket.removeEventListener('open', onOpen);
this.#socket.removeEventListener('error', onError);
this.#socket.removeEventListener('close', onClose);
};
this.#socket.addEventListener('open', onOpen);
this.#socket.addEventListener('error', onError);
this.#socket.addEventListener('close', onClose);
});
await withAbortSignal(withTimeout(openPromise, timeoutMs, timeoutErrorMessage ??
`Responses websocket connection timed out before opening after ${timeoutMs}ms.`), signal);
}
async send(data) {
if (this.#socket.readyState !== this.#socket.OPEN) {
throw new ResponsesWebSocketInternalError('socket_not_open');
}
this.#socket.send(data);
}
isReusable() {
return (!this.#closed &&
!this.#error &&
this.#socket.readyState === this.#socket.OPEN);
}
async nextFrame(signal) {
throwIfAborted(signal);
return await withAbortSignal(this.#nextFrameInternal(), signal);
}
async close() {
this.#stopKeepAlive();
if (!this.#closed) {
try {
this.#socket.close();
}
catch {
// Ignore close errors and wait for the socket to settle.
}
}
await this.#closedPromise;
}
async #nextFrameInternal() {
if (this.#messages.length > 0) {
return this.#messages.shift() ?? null;
}
if (this.#error) {
throw this.#error;
}
if (this.#closed) {
return null;
}
return await new Promise((resolve, reject) => {
this.#waiters.push({ resolve, reject });
});
}
#addPongListener() {
const socket = this.#socket;
if (typeof socket.on === 'function') {
socket.on('pong', this.#onPong);
return () => {
if (typeof socket.off === 'function') {
socket.off('pong', this.#onPong);
}
else if (typeof socket.removeListener === 'function') {
socket.removeListener('pong', this.#onPong);
}
};
}
if (typeof socket.addEventListener === 'function') {
socket.addEventListener('pong', this.#onPong);
return () => {
socket.removeEventListener('pong', this.#onPong);
};
}
return undefined;
}
#startKeepAlive() {
if (typeof this.#pingIntervalMs !== 'number') {
return;
}
this.#pingIntervalTimer = setInterval(() => {
this.#sendKeepAlivePing();
}, this.#pingIntervalMs);
}
#stopKeepAlive() {
if (this.#pingIntervalTimer) {
clearInterval(this.#pingIntervalTimer);
this.#pingIntervalTimer = undefined;
}
this.#clearKeepAliveTimeout();
this.#removePongListener?.();
this.#removePongListener = undefined;
}
#clearKeepAliveTimeout() {
if (this.#pingTimeoutTimer) {
clearTimeout(this.#pingTimeoutTimer);
this.#pingTimeoutTimer = undefined;
}
}
#sendKeepAlivePing() {
if (this.#closed || this.#socket.readyState !== this.#socket.OPEN) {
return;
}
const socket = this.#socket;
if (typeof socket.ping !== 'function') {
return;
}
if (typeof this.#pingTimeoutMs === 'number') {
if (this.#pingTimeoutTimer) {
return;
}
this.#pingTimeoutTimer = setTimeout(() => {
this.#pingTimeoutTimer = undefined;
this.#error = new ResponsesWebSocketInternalError('pong_timeout');
try {
if (typeof socket.terminate === 'function') {
socket.terminate();
}
else {
socket.close();
}
}
catch {
// Ignore close errors; waiters will be rejected by the stored error.
}
}, this.#pingTimeoutMs);
}
try {
socket.ping();
}
catch (error) {
this.#clearKeepAliveTimeout();
this.#error = error instanceof Error ? error : new Error(String(error));
try {
socket.close();
}
catch {
// Ignore close errors; waiters will be rejected by the stored error.
}
return;
}
}
#onMessage = (event) => {
const data = event.data;
const waiter = this.#waiters.shift();
if (waiter) {
waiter.resolve(data);
return;
}
this.#messages.push(data);
};
#onPong = () => {
this.#clearKeepAliveTimeout();
};
#onError = (event) => {
const maybeError = event?.error;
const maybeMessage = event?.message;
this.#error =
maybeError instanceof Error
? maybeError
: new Error(typeof maybeMessage === 'string' && maybeMessage.length > 0
? maybeMessage
: 'Responses websocket connection error.');
const waiters = this.#waiters.splice(0);
for (const waiter of waiters) {
waiter.reject(this.#error);
}
};
#onClose = () => {
this.#stopKeepAlive();
this.#closed = true;
this.#resolveClosed();
const waiters = this.#waiters.splice(0);
for (const waiter of waiters) {
if (this.#error) {
waiter.reject(this.#error);
}
else {
waiter.resolve(null);
}
}
};
}
exports.ResponsesWebSocketConnection = ResponsesWebSocketConnection;
//# sourceMappingURL=responsesWebSocketConnection.js.map