UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

63 lines (62 loc) • 2.88 kB
import { Dispatcher, getGlobalDispatcher } from "undici"; import UnwrapHandler from "undici/lib/handler/unwrap-handler.js"; import WrapHandler from "undici/lib/handler/wrap-handler.js"; function handlerApi(handler) { return typeof handler.onRequestStart === "function" ? 2 : 1; } function inSlotApi(api, handler) { return api === 1 ? UnwrapHandler.unwrap(handler) : WrapHandler.wrap(handler); } function slot(version) { const held = Reflect.get(globalThis, Symbol.for(`undici.globalDispatcher.${String(version)}`)); return isDispatcher(held) ? held : undefined; } function isDispatcher(value) { return typeof value === "object" && value !== null && typeof Reflect.get(value, "dispatch") === "function"; } function hostDispatcher(callerApi) { const own = callerApi === 2 ? slot(2) : undefined; return own !== undefined ? { dispatcher: own, api: 2 } : { dispatcher: slot(1) ?? getGlobalDispatcher(), api: 1 }; } function hostDispatchers() { const out = []; for (const d of [slot(2), slot(1), getGlobalDispatcher()]) if (d !== undefined && !out.includes(d)) out.push(d); return out; } function hostMember(key) { const hosts = hostDispatchers(); for (const host of hosts) { const value = Reflect.get(host, key, host); if (value) return typeof value === "function" ? value.bind(host) : value; } const newest = hosts[0]; return newest === undefined ? undefined : Reflect.get(newest, key, newest); } const CALLER_API = Symbol("engine.callerDispatcherApi"); class EngineDispatcher extends Dispatcher { dispatch(options, handler) { const { [CALLER_API]: callerApi, ...rest } = options; const host = hostDispatcher(callerApi ?? handlerApi(handler)); return host.dispatcher.dispatch({ ...rest, headersTimeout: 0, bodyTimeout: 0 }, inSlotApi(host.api, handler)); } compose(...interceptors) { const composed = super.compose(...interceptors); const chain = composed.dispatch; const enter = (options, handler) => { const stamped = { ...options, [CALLER_API]: options[CALLER_API] ?? handlerApi(handler) }; return chain(stamped, handler); }; return new Proxy(composed, { get: (target, key, receiver) => (key === "dispatch" ? enter : Reflect.get(target, key, receiver)) }); } } const SENDING_MEMBERS = new Set(Reflect.ownKeys(Dispatcher.prototype).filter((key) => key !== "constructor" && key !== "close" && key !== "destroy")); export const ENGINE_DISPATCHER = new Proxy(new EngineDispatcher(), { get: (engine, key, standIn) => (SENDING_MEMBERS.has(key) ? Reflect.get(engine, key, standIn) : hostMember(key)), }); export function resolveFetch(config) { const inner = config.fetchImpl ?? fetch; return (input, init) => inner(input, { ...init, dispatcher: ENGINE_DISPATCHER }); }