Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(anthropic-compat-proxy): 回环端口 ECONNREFUSED 的 502 明确提示本地代理 / SSH 隧道未启动 (#4102)
fico-hubbcbe6400dd47
diff --git a/packages/anthropic-compat-proxy/src/outbound-proxy.ts b/packages/anthropic-compat-proxy/src/outbound-proxy.tsindex 00eba682d2..d256d77823 100644--- a/packages/anthropic-compat-proxy/src/outbound-proxy.ts+++ b/packages/anthropic-compat-proxy/src/outbound-proxy.ts@@ -350,7 +350,8 @@ export class TunnelingHttpsAgent extends HttpsAgent {connectReq.destroy(new Error(`outbound proxy ${this.proxy.url} CONNECT ${authority} timed out`));});connectReq.on('error', (err) => {- settle(new Error(`outbound proxy ${this.proxy.url} unreachable: ${err.message}`));+ // 保留底层 errno(cause):server.ts 的 502 分类要沿错误链找 ECONNREFUSED + 回环地址。+ settle(new Error(`outbound proxy ${this.proxy.url} unreachable: ${err.message}`, { cause: err }));});connectReq.end();// socket 走异步 callback 交付;返回 undefined 告知调用方等 callback。diff --git a/packages/anthropic-compat-proxy/src/server-outbound-proxy.test.ts b/packages/anthropic-compat-proxy/src/server-outbound-proxy.test.tsindex beb7665faa..de3f9293f4 100644--- a/packages/anthropic-compat-proxy/src/server-outbound-proxy.test.ts+++ b/packages/anthropic-compat-proxy/src/server-outbound-proxy.test.ts@@ -87,6 +87,52 @@ describe('anthropic-compat-proxy outbound proxy wiring', () => {expect(connects).toEqual(['upstream.invalid:443']);});+ it('classifies a closed loopback HTTP CONNECT proxy port as upstream_loopback_refused (#4100)', async () => {+ // 先拿一个刚释放的回环端口:代理进程 / SSH 隧道没起来的形态。+ const placeholder = createHttpServer();+ const closedPort = await listenOnAvailableLoopbackPort(placeholder);+ await new Promise<void>((r) => placeholder.close(() => r()));++ proxy = await createAnthropicCompatProxy({+ upstream: 'https://upstream.invalid',+ transformRequest: [],+ resolveOutboundProxy: () => `http://127.0.0.1:${closedPort}`,+ });++ const res = await fetch(`${proxy.url}/v1/messages`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ model: 'x', messages: [] }),+ });+ expect(res.status).toBe(502);+ const body = await res.json() as { error: { code?: string; message: string } };+ expect(body.error.code).toBe('upstream_loopback_refused');+ expect(body.error.message).toContain(`outbound proxy at 127.0.0.1:${closedPort}`);+ expect(body.error.message).toContain('nothing is listening');+ });++ it('classifies a closed loopback SOCKS5 proxy port as upstream_loopback_refused (#4100)', async () => {+ const placeholder = createHttpServer();+ const closedPort = await listenOnAvailableLoopbackPort(placeholder);+ await new Promise<void>((r) => placeholder.close(() => r()));++ proxy = await createAnthropicCompatProxy({+ upstream: 'http://upstream.invalid:8080/v1',+ transformRequest: [],+ resolveOutboundProxy: () => `socks5://127.0.0.1:${closedPort}`,+ });++ const res = await fetch(`${proxy.url}/messages`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ model: 'x', messages: [] }),+ });+ expect(res.status).toBe(502);+ const body = await res.json() as { error: { code?: string; message: string } };+ expect(body.error.code).toBe('upstream_loopback_refused');+ expect(body.error.message).toContain(`outbound proxy at 127.0.0.1:${closedPort}`);+ });+it('tunnels upstreams through SOCKS5 and hands the domain to the proxy unresolved', async () => {const seen: Array<{ url: string; host?: string }> = [];const upstream = createHttpServer((req, res) => {diff --git a/packages/anthropic-compat-proxy/src/server.test.ts b/packages/anthropic-compat-proxy/src/server.test.tsindex 79bc9d1823..5b3dc95940 100644--- a/packages/anthropic-compat-proxy/src/server.test.ts+++ b/packages/anthropic-compat-proxy/src/server.test.ts@@ -148,6 +148,30 @@ describe('anthropic-compat-proxy loopback port guard', () => {expect(result).toEqual({ status: 200, text: JSON.stringify({ ok: true }) });});+ it('reports a refused loopback upstream as "nothing is listening" with a stable code (#4100)', async () => {+ const upstream = await startFakeUpstream((_idx, _body, res) => {+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end('{}');+ });+ const port = Number(new URL(upstream.url).port);+ // 上游先关掉:自定义供应商指向的本地代理 / SSH 隧道没起来,端口无监听。+ await upstream.close();++ proxy = await createAnthropicCompatProxy({+ upstream: upstream.url,+ transformRequest: [],+ });++ const result = await post(proxy.url, { model: 'test-model' });+ expect(result.status).toBe(502);+ const json = JSON.parse(result.text) as { error: { type: string; code?: string; message: string } };+ expect(json.error.type).toBe('proxy_error');+ expect(json.error.code).toBe('upstream_loopback_refused');+ expect(json.error.message).toMatch(new RegExp(`connect ECONNREFUSED 127\\.0\\.0\\.1:${port}`));+ expect(json.error.message).toMatch(/nothing is listening on that local port/);+ expect(json.error.message).toMatch(/local proxy or an SSH tunnel/);+ });+it('pipes successful response bodies through a request-scoped transform', async () => {const upstream = await startFakeUpstream((_idx, _body, res) => {const payload = '{"source":"upstream"}';diff --git a/packages/anthropic-compat-proxy/src/server.ts b/packages/anthropic-compat-proxy/src/server.tsindex 44f6d6edb9..d3cae2e1b1 100644--- a/packages/anthropic-compat-proxy/src/server.ts+++ b/packages/anthropic-compat-proxy/src/server.ts@@ -35,6 +35,7 @@ import {type OutboundProxyTarget,} from './outbound-proxy.js';import { Socks5HttpAgent, Socks5HttpsAgent } from './socks5.js';+import { describeUpstreamRequestFailure } from './upstream-failure.js';import { stripNonAnthropicFields, stripToolUseProviderSpecificFields } from './transform.js';import {collectToolUseIdsForResponseRewrite,@@ -1786,7 +1787,9 @@ function forward(});if (upstreamResponseTerminal === null) upstreamResponseTerminal = 'error';const upstreamError = err instanceof Error ? err : new Error(String(err));- finishClientAfterUpstreamFailure(upstreamError, `upstream unreachable: ${String(err)}`);+ // 回环端口 ECONNREFUSED 单独措辞(本机没监听 ≠ 远端服务故障,#4100);其余逐字不变。+ const failure = describeUpstreamRequestFailure(err, { viaOutboundProxy: Boolean(outboundProxy) });+ finishClientAfterUpstreamFailure(upstreamError, failure.message, failure.code);});upstreamReq.on('timeout', () => {diff --git a/packages/anthropic-compat-proxy/src/socks5.ts b/packages/anthropic-compat-proxy/src/socks5.tsindex ad21f5b4ee..cce4d08e0c 100644--- a/packages/anthropic-compat-proxy/src/socks5.ts+++ b/packages/anthropic-compat-proxy/src/socks5.ts@@ -211,7 +211,9 @@ export async function socks5Connect(destPort: number,): Promise<Socket> {const authority = formatAuthority(destHost, destPort);- const fail = (message: string): Error => new Error(`outbound proxy ${proxy.url} ${message}`);+ // cause 保留底层 errno:server.ts 的 502 分类要沿错误链找 ECONNREFUSED + 回环地址。+ const fail = (message: string, cause?: unknown): Error =>+ new Error(`outbound proxy ${proxy.url} ${message}`, cause === undefined ? undefined : { cause });const destination = encodeDestination(destHost);if (!destination) throw fail(`cannot encode destination ${authority}`);@@ -237,7 +239,7 @@ export async function socks5Connect(// socket 层错误 / 提前 EOF 唤醒等待中的 read,避免握手 Promise 永久悬挂。const onError = (err: Error): void => {- reader.fail(timedOut ? fail(`CONNECT ${authority} timed out`) : fail(`unreachable: ${err.message}`));+ reader.fail(timedOut ? fail(`CONNECT ${authority} timed out`) : fail(`unreachable: ${err.message}`, err));};const onClose = (): void => {reader.fail(timedOut@@ -251,7 +253,7 @@ export async function socks5Connect(await new Promise<void>((resolve, reject) => {if (!socket.connecting) { resolve(); return; }socket.once('connect', resolve);- socket.once('error', (err: Error) => reject(fail(`unreachable: ${err.message}`)));+ socket.once('error', (err: Error) => reject(fail(`unreachable: ${err.message}`, err)));socket.once('close', () => reject(fail('unreachable: connection closed')));});diff --git a/packages/anthropic-compat-proxy/src/upstream-failure.test.ts b/packages/anthropic-compat-proxy/src/upstream-failure.test.tsnew file mode 100644index 0000000000..5015943ef8--- /dev/null+++ b/packages/anthropic-compat-proxy/src/upstream-failure.test.ts@@ -0,0 +1,78 @@+import { describe, expect, it } from 'vitest';++import {+ describeUpstreamRequestFailure,+ findLoopbackRefusedConnection,+ UPSTREAM_LOOPBACK_REFUSED_CODE,+} from './upstream-failure.js';++function errno(code: string, address?: string, port?: number): Error {+ return Object.assign(new Error(`connect ${code} ${address ?? ''}:${port ?? ''}`), {+ code,+ syscall: 'connect',+ ...(address !== undefined ? { address } : {}),+ ...(port !== undefined ? { port } : {}),+ });+}++describe('findLoopbackRefusedConnection (#4100)', () => {+ it('recognises ECONNREFUSED against loopback addresses, including happy-eyeballs AggregateError', () => {+ expect(findLoopbackRefusedConnection(errno('ECONNREFUSED', '127.0.0.1', 18080)))+ .toEqual({ address: '127.0.0.1', port: 18080 });+ expect(findLoopbackRefusedConnection(errno('ECONNREFUSED', '::1', 18080)))+ .toEqual({ address: '::1', port: 18080 });+ expect(findLoopbackRefusedConnection(errno('ECONNREFUSED', '::ffff:127.0.0.1', 18080)))+ .toEqual({ address: '::ffff:127.0.0.1', port: 18080 });+ const aggregate = new AggregateError(+ [errno('ECONNREFUSED', '::1', 18080), errno('ECONNREFUSED', '127.0.0.1', 18080)],+ 'aggregate',+ );+ expect(findLoopbackRefusedConnection(aggregate)).toEqual({ address: '::1', port: 18080 });+ });++ it('follows Error.cause so proxy-agent wrappers (outbound-proxy.ts / socks5.ts) keep their errno', () => {+ const wrapped = new Error('outbound proxy http://127.0.0.1:7890 unreachable: connect ECONNREFUSED 127.0.0.1:7890', {+ cause: errno('ECONNREFUSED', '127.0.0.1', 7890),+ });+ expect(findLoopbackRefusedConnection(wrapped)).toEqual({ address: '127.0.0.1', port: 7890 });+ // 二级包装 + AggregateError 混合也能找到+ const nested = new Error('outer', { cause: new AggregateError([errno('ECONNREFUSED', '::1', 1080)], 'agg') });+ expect(findLoopbackRefusedConnection(nested)).toEqual({ address: '::1', port: 1080 });+ // 没带 cause 的纯文本包装:不猜,保持通用文案+ expect(findLoopbackRefusedConnection(new Error('outbound proxy unreachable: connect ECONNREFUSED 127.0.0.1:7890'))).toBeNull();+ });++ it('leaves every other failure alone: non-loopback refusal, timeouts, DNS, non-errors', () => {+ expect(findLoopbackRefusedConnection(errno('ECONNREFUSED', '10.0.0.8', 443))).toBeNull();+ expect(findLoopbackRefusedConnection(errno('ECONNREFUSED', '127.example.com', 443))).toBeNull();+ expect(findLoopbackRefusedConnection(errno('ETIMEDOUT', '127.0.0.1', 18080))).toBeNull();+ expect(findLoopbackRefusedConnection(errno('ENOTFOUND'))).toBeNull();+ expect(findLoopbackRefusedConnection(new AggregateError([errno('ETIMEDOUT', '127.0.0.1', 1)], 'x'))).toBeNull();+ expect(findLoopbackRefusedConnection('ECONNREFUSED 127.0.0.1:18080')).toBeNull();+ expect(findLoopbackRefusedConnection(null)).toBeNull();+ });+});++describe('describeUpstreamRequestFailure (#4100)', () => {+ it('keeps the historical "upstream unreachable: <err>" text verbatim for everything else', () => {+ const err = errno('ETIMEDOUT', '10.0.0.8', 443);+ expect(describeUpstreamRequestFailure(err, { viaOutboundProxy: false }))+ .toEqual({ message: `upstream unreachable: ${String(err)}` });+ });++ it('turns a refused loopback port into an actionable message with a stable code', () => {+ const described = describeUpstreamRequestFailure(errno('ECONNREFUSED', '127.0.0.1', 18080), { viaOutboundProxy: false });+ expect(described.code).toBe(UPSTREAM_LOOPBACK_REFUSED_CODE);+ expect(described.message).toMatch(/^upstream unreachable: connect ECONNREFUSED 127\.0\.0\.1:18080/);+ expect(described.message).toMatch(/nothing is listening/);+ expect(described.message).toMatch(/configured upstream at 127\.0\.0\.1:18080/);+ expect(described.message).toMatch(/local proxy or an SSH tunnel/);+ expect(described.message).toMatch(/not a remote service or subscription problem/);+ });++ it('blames the outbound proxy instead when the refused loopback port is the proxy hop', () => {+ const described = describeUpstreamRequestFailure(errno('ECONNREFUSED', '127.0.0.1', 7890), { viaOutboundProxy: true });+ expect(described.code).toBe(UPSTREAM_LOOPBACK_REFUSED_CODE);+ expect(described.message).toMatch(/outbound proxy at 127\.0\.0\.1:7890/);+ });+});diff --git a/packages/anthropic-compat-proxy/src/upstream-failure.ts b/packages/anthropic-compat-proxy/src/upstream-failure.tsnew file mode 100644index 0000000000..51bc352850--- /dev/null+++ b/packages/anthropic-compat-proxy/src/upstream-failure.ts@@ -0,0 +1,86 @@+/**+ * 上游连接失败的分类(#4100)。+ *+ * 代理把上游请求错误原样塞进 502 body(`upstream unreachable: <err>`),harness 再把它+ * 展示给用户。对「连本机回环端口被拒」这一种情况,原样文案会把人带偏:自定义供应商指向+ * 本地代理 / SSH 隧道(如 127.0.0.1:18080),隧道没起来时用户看到的是「上游不可达,通常+ * 是服务端临时问题」,进而去查远端服务或订阅。实际上只是本机没有进程监听那个端口。+ *+ * 这里只做**判定与措辞**,不改任何转发行为:ECONNREFUSED + 目标为回环地址 → 明确说+ * 「本机 <addr>:<port> 没有监听;若该端点是本地代理或 SSH 隧道,先把它启动再重试」,并+ * 给一个稳定的 code 供上层 / 用户识别。happy-eyeballs 的 AggregateError 逐个看内层错误。+ * 经出站代理转发时被拒的是代理本身,措辞随之改成「出站代理没有监听」。+ */++export const UPSTREAM_LOOPBACK_REFUSED_CODE = 'upstream_loopback_refused';++export interface RefusedConnection {+ address: string;+ port: number | null;+}++interface ErrnoLike {+ code?: unknown;+ address?: unknown;+ port?: unknown;+ errors?: unknown;+ cause?: unknown;+}++function isLoopbackAddress(address: string): boolean {+ const a = address.trim().toLowerCase();+ if (a === 'localhost' || a === '::1') return true;+ if (a.startsWith('::ffff:')) return isLoopbackAddress(a.slice('::ffff:'.length));+ return /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(a);+}++/**+ * 从错误链里找出「连接被拒 + 回环地址」的那一条:沿 AggregateError.errors(happy-eyeballs)+ * 与 Error.cause(出站代理 agent 的包装错误,见 outbound-proxy.ts / socks5.ts)逐层查看。+ * 只认 ECONNREFUSED:ETIMEDOUT / ENOTFOUND 等不是「本机没监听」,不改措辞。+ */+export function findLoopbackRefusedConnection(err: unknown): RefusedConnection | null {+ const seen = new Set<unknown>();+ const queue: unknown[] = [err];+ while (queue.length > 0) {+ const current = queue.shift();+ if (!current || typeof current !== 'object' || seen.has(current)) continue;+ seen.add(current);+ const e = current as ErrnoLike;+ if (e.code === 'ECONNREFUSED' && typeof e.address === 'string' && isLoopbackAddress(e.address)) {+ const port = typeof e.port === 'number' && Number.isFinite(e.port) ? e.port : null;+ return { address: e.address, port };+ }+ if (Array.isArray(e.errors)) queue.push(...e.errors);+ if (e.cause !== undefined) queue.push(e.cause);+ }+ return null;+}++export interface UpstreamFailureDescription {+ message: string;+ code?: string;+}++/**+ * 生成 502 body 的 message / code。默认保持既有文案(`upstream unreachable: <err>`)逐字+ * 不变;只有「回环地址 ECONNREFUSED」这一种情况换成可操作的措辞。+ */+export function describeUpstreamRequestFailure(+ err: unknown,+ opts: { viaOutboundProxy: boolean },+): UpstreamFailureDescription {+ const refused = findLoopbackRefusedConnection(err);+ if (!refused) return { message: `upstream unreachable: ${String(err)}` };+ const endpoint = refused.port === null ? refused.address : `${refused.address}:${refused.port}`;+ const what = opts.viaOutboundProxy+ ? `the outbound proxy at ${endpoint} on this machine`+ : `the configured upstream at ${endpoint} on this machine`;+ return {+ code: UPSTREAM_LOOPBACK_REFUSED_CODE,+ message:+ `upstream unreachable: connect ECONNREFUSED ${endpoint} — nothing is listening on that ` ++ `local port, so ${what} is not running. This is not a remote service or subscription ` ++ `problem: if that endpoint is a local proxy or an SSH tunnel, start it and retry.`,+ };+}