Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 37 additions & 3 deletions src/agent/fetch-chain/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,16 @@ export function isDeadClosureError(err: unknown): boolean {
return err instanceof TypeError && /is not a function$/.test(err.message);
}

function urlOf(input: string | URL | Request): string | undefined {
try {
if (typeof input === "string") return input;
if (input instanceof URL) return input.href;
return input.url;
} catch {
return undefined;
}
}

function noteFetch(f: unknown): void {
if (typeof f !== "function") return;
const fn = f as typeof globalThis.fetch;
Expand All @@ -107,7 +117,10 @@ function nextLiveAnchor(dead: typeof globalThis.fetch): typeof globalThis.fetch
return observedFetches.find((f) => !knownDeadFetches.has(f));
}

export function installFetchChain(makeDispatch: (send: typeof globalThis.fetch) => typeof globalThis.fetch): void {
export function installFetchChain(
makeDispatch: (send: typeof globalThis.fetch) => typeof globalThis.fetch,
opts: { inlineOrigin?: string } = {},
): void {
const orig = globalThis.fetch;
noteFetch(orig);
const makeChain = (downstream: typeof globalThis.fetch) => {
Expand Down Expand Up @@ -163,7 +176,18 @@ export function installFetchChain(makeDispatch: (send: typeof globalThis.fetch)
}
const depth = dispatchDepth.getStore();
if (depth === 1) {
if (Reflect.get(ds, "__piWebAccessProxyFetch") === true) return send(input, init);
if (Reflect.get(ds, "__piWebAccessProxyFetch") === true || Reflect.get(ds, "__piWebAccessSharedProxyFetch") === true) return send(input, init);
// #6829: INLINE_ORIGIN URLs are served IN-PROCESS by the inline
// transport link below, not by the host's native fetch. The
// #1662 cutoff below would hand them to the oldest live anchor
// (the host fetch) → a real DNS lookup for the pseudo-origin →
// guaranteed ENOTFOUND, every model call, until restart. Continue
// the descent instead: the inline engine is reached via the #4527
// chainHop legitimate descent and serves the URL in-process.
if (opts.inlineOrigin !== undefined) {
const url = urlOf(input);
if (url !== undefined && url.startsWith(opts.inlineOrigin)) return send(input, init);
}
const anchor = observedFetches.find((f) => !knownDeadFetches.has(f));
if (anchor !== undefined && anchor !== ds) {
if (!warnedReentry) {
Expand All @@ -184,6 +208,14 @@ export function installFetchChain(makeDispatch: (send: typeof globalThis.fetch)
Object.defineProperty(chain, "__piWebAccessProxyFetch", {
get: () => Reflect.get(ds, "__piWebAccessProxyFetch"),
});
// #6829: pi-web-access >= 0.46 renamed its marker to __piWebAccessSharedProxyFetch
// and its install guard keys on THAT name. Propagate it the same way so a
// re-armed top still reads as "a pi-web-access wrapper is already in this
// chain" — without it, every proxied web tool call re-wraps the top and the
// chain grows one (wrapper, bili-link) pair per call (the #1662 churn shape).
Object.defineProperty(chain, "__piWebAccessSharedProxyFetch", {
get: () => Reflect.get(ds, "__piWebAccessSharedProxyFetch"),
});
return chain;
};

Expand Down Expand Up @@ -223,7 +255,9 @@ export function installFetchChain(makeDispatch: (send: typeof globalThis.fetch)
// leaves; "evict" was the pre-self-heal framing and is dropped
// from the wording. Unknown wrappers and any LATER (repeat /
// abnormal) marked install keep the full diagnostic below.
const webAccess = Reflect.get(v, "__piWebAccessProxyFetch") === true;
// #6829: recognize BOTH marker names — pi-web-access < 0.46 uses
// __piWebAccessProxyFetch, >= 0.46 uses __piWebAccessSharedProxyFetch.
const webAccess = Reflect.get(v, "__piWebAccessProxyFetch") === true || Reflect.get(v, "__piWebAccessSharedProxyFetch") === true;
// Visibility (#1158): a third-party install used to be silent —
// log it so "un-routed by a third party" is diagnosable. Past
// REARM_LIMIT the WARNING stops (log spam), but the adoption
Expand Down
3 changes: 2 additions & 1 deletion src/agent/native-intercept.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import { installFetchChain, isDeadClosureError, resetFetchChainForTest } from "./fetch-chain/index.js";
import { logHostEvent } from "./host-log.js";
import { INLINE_ORIGIN } from "../inline-engine.js";

import { envMillis } from "./native-bootstrap.js";
import { matchModelEndpoint, type ModelEndpointPattern } from "../model-endpoints.js";
Expand Down Expand Up @@ -2221,7 +2222,7 @@ export function installNativeFetchIntercept(initialState: NativeInterceptState):
}
throw err;
}
});
}, { inlineOrigin: INLINE_ORIGIN });
g[INTERCEPT_FLAG] = true;
return true;
}
Expand Down
2 changes: 1 addition & 1 deletion src/agent/pi-inline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export function installInlineTransport(): boolean {
throw err;
}
};
});
}, { inlineOrigin: INLINE_ORIGIN });
return true;
}

Expand Down
92 changes: 92 additions & 0 deletions tests/native-intercept-selfheal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { after, test } from "node:test";
import { installFetchChain } from "../src/agent/fetch-chain/index.js";
import { installNativeFetchIntercept, type NativeInterceptState } from "../src/agent/native-intercept.js";
import { INLINE_ORIGIN } from "../src/inline-engine.js";

// #2827: the fetch-chain diagnostics now land in the shared bili.log instead
// of the terminal. Keep this whole suite hermetic: point XDG_STATE_HOME at a
Expand Down Expand Up @@ -419,6 +421,39 @@ function webAccessProxy() {
};
}

// #6829: mirrors pi-web-access >= 0.46 — the install guard AND the marker moved
// to __piWebAccessSharedProxyFetch; the old __piWebAccessProxyFetch is only
// propagated onto the wrapper when the wrapped fetch already carries it.
function piWebAccess046() {
const proxy = new AsyncLocalStorage<boolean>();
let installs = 0;
let calls = 0;
return {
get installs() { return installs; },
get calls() { return calls; },
install() {
const base = globalThis.fetch;
if (Reflect.get(base, "__piWebAccessSharedProxyFetch") === true) return;
const wrapper = (async (input: string | URL | Request, init?: RequestInit) => {
calls++;
const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url);
if (proxy.getStore() && url.hostname !== "127.0.0.1") return new Response("via-web-proxy");
return base(input, init);
}) as typeof fetch;
Object.defineProperty(wrapper, "__piWebAccessSharedProxyFetch", { value: true });
if (Reflect.get(base, "__piWebAccessProxyFetch") === true) {
Object.defineProperty(wrapper, "__piWebAccessProxyFetch", { value: true });
}
installs++;
globalThis.fetch = wrapper;
},
run<T>(fn: () => T): T {
this.install();
return proxy.run(true, fn);
},
};
}

for (const first of ["bili", "web-access"]) {
test(`pi-web-access: ${first} installs first, 1000 proxy scopes keep one wrapper and routing`, async () => {
const nativeSink: string[] = [];
Expand Down Expand Up @@ -502,6 +537,63 @@ test("pi-web-access: the marker follows the live downstream after a dead closure
assert.deepEqual(nativeSink, ["http://127.0.0.1:40001/bili/https://api.example.invalid/v1/messages"]);
});

// #6829: pi-web-access >= 0.46 renamed its marker, so bili's #2435 coexistence
// branch went unreachable and EVERY install fell into the generic #1158 re-chain.
// The re-armed top then hit the #1662 depth-1 cutoff, which handed bili's own
// INLINE_ORIGIN model URLs to the oldest live anchor (the host's native fetch) —
// a real DNS lookup for the pseudo-origin → getaddrinfo ENOTFOUND on every model
// call until the host restarted. Two defects, one repro:
// (1) ROUTING — the #1662 cutoff must not truncate INLINE_ORIGIN URLs to the
// host anchor; they are served IN-PROCESS by the inline transport link
// below, reached via the #4527 chainHop legitimate descent.
// (2) STABILITY — the chain must propagate the NEW shared-flag marker so
// pi-web-access's own install guard sees "a wrapper is already in the
// chain" and does NOT re-wrap on every proxied web tool call (unbounded
// (wrapper, bili-link) growth, the #1662 churn shape).
test("#6829: 0.46+ pi-web-access re-wrap — INLINE_ORIGIN model traffic is served in-process, wrapper stays one", async () => {
const nativeSink: string[] = [];
const inlineServed: string[] = [];
const nativeFetch = fakeFetch(nativeSink);
const prevFetch = globalThis.fetch;
await withScope(nativeFetch, async () => {
// Innermost link: mimic pi-inline.ts — serve INLINE_ORIGIN URLs in-process.
installFetchChain((send) => {
return async (input: string | URL | Request, init?: RequestInit) => {
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
if (url !== undefined && url.startsWith(INLINE_ORIGIN)) {
inlineServed.push(url);
return new Response("{}", { status: 200 });
}
return send(input, init);
};
}, { inlineOrigin: INLINE_ORIGIN });
// Top link: the real intercept with origin = INLINE_ORIGIN — rewrites a
// model URL to INLINE_ORIGIN/bili/<upstream> (the pi inline lane shape).
installNativeFetchIntercept({ origin: INLINE_ORIGIN, ready: Promise.resolve(INLINE_ORIGIN) });
// pi-web-access 0.46.0 shape wraps the top (shared-flag guard + marker).
const web = piWebAccess046();
web.install();
assert.equal(web.installs, 1);
// A model request must be served in-process by the inline transport,
// NOT reach the host anchor (which would be a real DNS lookup).
const res = await globalThis.fetch("https://api.example.invalid/v1/messages", { method: "POST" });
assert.equal(res.status, 200);
// A second proxied web tool call must NOT re-wrap the top (one wrapper).
assert.equal(await web.run(() => globalThis.fetch("https://example.invalid/article")).then(r => r.text()), "via-web-proxy");
assert.equal(web.installs, 1);
});
// This test double-installs (inline transport + intercept, the pi inline
// lane shape), so the fetch property is left as an accessor; withScope's
// cleanup write re-arms the leftover guard. Restore the plain data property
// so the guard is gone and the next test starts from a clean install.
Object.defineProperty(globalThis, "fetch", { value: prevFetch, writable: true, configurable: true });
// The model URL was served in-process by the inline transport link.
assert.deepEqual(inlineServed, [`${INLINE_ORIGIN}/bili/https://api.example.invalid/v1/messages`]);
// The host anchor never saw an INLINE_ORIGIN URL (no real DNS lookup).
assert.ok(!nativeSink.some((u) => u.startsWith(INLINE_ORIGIN)),
`host anchor received an INLINE_ORIGIN URL (would be a real DNS lookup): ${JSON.stringify(nativeSink)}`);
});

// #2685/#2827: diagnostics-only refinement of the #1158 third-party-install
// notice. A recognized pi-web-access FIRST install is a supported coexistence
// handshake (its own guard makes it the only one, #2435) — it must not read as
Expand Down
Loading