@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
141 lines • 6.07 kB
JavaScript
import { EventEmitter } from "node:events";
import * as undici from "undici";
export const DEFAULT_HTTP_IDLE_TIMEOUT_MS = 300_000;
// Node's 250ms default can terminate valid connection attempts on high-latency routes.
const DEFAULT_AUTO_SELECT_FAMILY_ATTEMPT_TIMEOUT_MS = 2_000;
export const HTTP_IDLE_TIMEOUT_CHOICES = [
{ label: "30 sec", timeoutMs: 30_000 },
{ label: "1 min", timeoutMs: 60_000 },
{ label: "2 min", timeoutMs: 120_000 },
{ label: "5 min", timeoutMs: 300_000 },
{ label: "disabled", timeoutMs: 0 },
];
const originalGlobalFetch = globalThis.fetch;
let installedGlobalFetch;
let multiSessionDispatcherTimeoutMs;
/**
* Whether `configureHttpDispatcher` may replace the global `fetch` (and the
* WebSocket/Headers/Request/Response constructors) with the bundled Undici
* implementation.
*
* Bun keeps its native fetch: the distributed CLI inlines npm undici, and its
* fetch running on Bun 1.3.x answers with the response headers but never
* delivers a streamed body, so every SSE model response stalls after the
* headers (#1890). Bun's own fetch honors HTTP_PROXY / HTTPS_PROXY / NO_PROXY,
* which `applyHttpProxySettings` sets, and stream stalls stay bounded by the
* agent-level idle and stream-start guards derived from the same
* `httpIdleTimeoutMs` setting.
*
* Node installs the globals so fetch and the dispatcher share one undici
* implementation (see the call site); a caller that deliberately replaced
* `fetch` after module load keeps its override.
*/
export function shouldInstallUndiciGlobals(input) {
if (input.versions.bun !== undefined)
return false;
return input.installedFetch === undefined
? input.currentFetch === input.originalFetch
: input.currentFetch === input.installedFetch;
}
function isMultiSessionRpcProcess() {
return process.argv.includes("--multi-session");
}
export function parseHttpIdleTimeoutMs(value) {
if (typeof value === "string") {
const trimmed = value.trim();
if (trimmed.toLowerCase() === "disabled") {
return 0;
}
if (trimmed.length === 0) {
return undefined;
}
return parseHttpIdleTimeoutMs(Number(trimmed));
}
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
return undefined;
}
return Math.floor(value);
}
export function formatHttpIdleTimeoutMs(timeoutMs) {
const choice = HTTP_IDLE_TIMEOUT_CHOICES.find((item) => item.timeoutMs === timeoutMs);
if (choice) {
return choice.label;
}
return `${timeoutMs / 1000} sec`;
}
export function applyHttpProxySettings(httpProxy) {
const proxy = httpProxy?.trim();
if (!proxy)
return;
if (isMultiSessionRpcProcess()) {
const existing = process.env.HTTP_PROXY ?? process.env.HTTPS_PROXY;
if (existing !== undefined && existing !== proxy) {
throw new Error("Multi-session RPC shares one process-global HTTP proxy; proxy settings must be fixed at process startup.");
}
}
process.env.HTTP_PROXY ??= proxy;
process.env.HTTPS_PROXY ??= proxy;
}
const ignoreUndiciDispatcherError = (_error) => { };
// Undici can emit an internal Client "error" while terminating a mid-stream
// fetch body. The body stream still rejects through reader.read(); this listener
// only prevents EventEmitter's unhandled "error" special case from crashing pi.
function withUndiciErrorListener(dispatcher) {
if (dispatcher instanceof EventEmitter) {
EventEmitter.prototype.on.call(dispatcher, "error", ignoreUndiciDispatcherError);
}
return dispatcher;
}
function createUndiciClient(origin, options) {
return withUndiciErrorListener(new undici.Client(origin, options));
}
function createUndiciOriginDispatcher(origin, options) {
const dispatcherOptions = options;
if (dispatcherOptions.connections === 1) {
return createUndiciClient(origin, dispatcherOptions);
}
return withUndiciErrorListener(new undici.Pool(origin, {
...dispatcherOptions,
factory: createUndiciClient,
}));
}
export function configureHttpDispatcher(timeoutMs = DEFAULT_HTTP_IDLE_TIMEOUT_MS) {
const normalizedTimeoutMs = parseHttpIdleTimeoutMs(timeoutMs);
if (normalizedTimeoutMs === undefined) {
throw new Error(`Invalid HTTP idle timeout: ${String(timeoutMs)}`);
}
if (isMultiSessionRpcProcess()) {
if (multiSessionDispatcherTimeoutMs !== undefined && multiSessionDispatcherTimeoutMs !== normalizedTimeoutMs) {
throw new Error("Multi-session RPC shares one process-global Undici dispatcher; HTTP idle timeout must be fixed at process startup.");
}
multiSessionDispatcherTimeoutMs = normalizedTimeoutMs;
}
const dispatcher = withUndiciErrorListener(new undici.EnvHttpProxyAgent({
allowH2: false,
// Keep HTTP origins on CONNECT tunnels as they were before Undici 8.7.
proxyTunnel: true,
bodyTimeout: normalizedTimeoutMs,
connect: {
autoSelectFamilyAttemptTimeout: DEFAULT_AUTO_SELECT_FAMILY_ATTEMPT_TIMEOUT_MS,
},
headersTimeout: normalizedTimeoutMs,
clientFactory: createUndiciClient,
factory: createUndiciOriginDispatcher,
}));
undici.setGlobalDispatcher(dispatcher);
// Keep fetch and the dispatcher on the same undici implementation. Node 26.0's
// bundled fetch can otherwise consume compressed responses through npm undici's
// dispatcher without decompressing them, causing response.json() failures.
// If a caller replaced fetch after module load, preserve that deliberate override.
const shouldInstallGlobals = shouldInstallUndiciGlobals({
versions: process.versions,
currentFetch: globalThis.fetch,
originalFetch: originalGlobalFetch,
installedFetch: installedGlobalFetch,
});
if (shouldInstallGlobals) {
undici.install?.();
installedGlobalFetch = globalThis.fetch;
}
}
//# sourceMappingURL=http-dispatcher.js.map