@openai/agents-core
Version:
The OpenAI Agents SDK is a lightweight yet powerful framework for building multi-agent workflows.
104 lines • 3.15 kB
JavaScript
const sandboxEventSinks = new Set();
export function addSandboxEventSink(sink) {
sandboxEventSinks.add(sink);
return () => {
sandboxEventSinks.delete(sink);
};
}
export function clearSandboxEventSinks() {
sandboxEventSinks.clear();
}
export async function emitSandboxEvent(event) {
if (sandboxEventSinks.size === 0) {
return;
}
await Promise.allSettled([...sandboxEventSinks].map(async (sink) => {
await sink(event);
}));
}
/**
* Create a sink that writes one serialized sandbox event per JSONL line.
*/
export function createSandboxJsonlEventSink(writer) {
return async (event) => {
await writer(`${JSON.stringify(event)}\n`);
};
}
/**
* Create a sink that POSTs each sandbox event as JSON to an HTTP endpoint.
*/
export function createSandboxHttpEventSink(options) {
const headers = { ...options.headers };
return async (event) => {
const fetch = options.fetch ?? readGlobalFetch();
if (!fetch) {
throw new Error('No fetch implementation is available for the sandbox HTTP event sink.');
}
const response = await fetch(options.endpoint, {
method: 'POST',
headers: {
'content-type': 'application/json',
...headers,
},
body: JSON.stringify(event),
});
if (!response.ok) {
const detail = await readHttpErrorDetail(response);
throw new Error(`Sandbox event HTTP sink failed with status ${response.status}${detail}`);
}
};
}
/**
* Create a sink that delivers each event to multiple child sinks.
*/
export function createChainedSandboxEventSink(...sinks) {
return async (event) => {
await Promise.allSettled(sinks.map(async (sink) => {
await sink(event);
}));
};
}
export function serializeSandboxEventError(error) {
if (error instanceof Error) {
const code = readErrorCode(error);
const retryable = readErrorRetryability(error);
return {
name: error.name,
message: error.message,
...(code ? { code } : {}),
...(retryable !== undefined ? { retryable } : {}),
};
}
return {
message: String(error),
};
}
function readErrorCode(error) {
const code = error.code;
return typeof code === 'string' ? code : undefined;
}
function readErrorRetryability(error) {
const retryable = error.retryable;
return typeof retryable === 'boolean' || retryable === null
? retryable
: undefined;
}
function readGlobalFetch() {
return globalThis.fetch;
}
async function readHttpErrorDetail(response) {
if (typeof response.text !== 'function') {
return response.statusText ? `: ${response.statusText}` : '';
}
try {
const text = await response.text();
if (text) {
return `: ${text}`;
}
}
catch {
// Ignore response body read failures and use the status text below.
}
return response.statusText ? `: ${response.statusText}` : '';
}
//# sourceMappingURL=events.mjs.map