Skip to content
Closed
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
59 changes: 32 additions & 27 deletions src/agent/dsh-native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -873,15 +873,7 @@ async function spawnFallback(attachOrigin: string, note: string, gen: number): P
markNativeHost(process.env, "dsh");
const start = singleFlight(_spawnForTest ?? bootstrap);
state.respawn = start;
state.onGiveUp = () => {
persistClientEvent("proxy respawn gave up — model traffic goes direct (uncompressed)");
// #3380: only the origin dies here — the host-context tool
// registrations survive, so toolsReady stays put.
register.base = undefined;
// #3562: invalidate in-flight attach chains started before this
// giveUp — their late commits must not resurrect the base.
register.giveUpSeq++;
};
state.onGiveUp = fireGiveUp;
const landed = start().then((origin) => {
// #3616: superseded while spawning — report the landing, write nothing.
if (gen !== originGen) return origin;
Expand Down Expand Up @@ -965,6 +957,25 @@ function landingOwnsRegister(staleOrigin: string | undefined): boolean {
return register.base === undefined || register.base === staleOrigin;
}

/** #4125: the give-up line must name WHY nothing was routable — the bare
* sentence left users unable to self-diagnose (which branch failed: dead
* proxy, saturated proxy, failed spawn, or a send failure with no
* replacement). The interceptor sets state.lastUnavailableReason right
* before firing us; when it is absent we keep the original wording rather
* than invent a reason. */
function fireGiveUp(): void {
const reason = state.lastUnavailableReason;
persistClientEvent(reason === undefined
? "proxy respawn gave up — model traffic goes direct (uncompressed)"
: `proxy respawn gave up — model traffic goes direct (uncompressed): ${reason}`);
// #3380: only the origin dies here — the host-context tool
// registrations survive, so toolsReady stays put.
register.base = undefined;
// #3562: invalidate in-flight attach chains started before this
// giveUp — their late commits must not resurrect the base.
register.giveUpSeq++;
}

async function registerTools(ctx: PluginContext): Promise<void> {
if (register.pending !== undefined) return register.pending;
const base = register.base;
Expand Down Expand Up @@ -1740,15 +1751,7 @@ export function apply(ctx: PluginContext): void {
// and falls back exactly like at startup.
const start = singleFlight(() => verifyAttachAndRecover(attachOrigin));
state.respawn = start;
state.onGiveUp = () => {
persistClientEvent("proxy respawn gave up — model traffic goes direct (uncompressed)");
// #3380: only the origin dies here — the host-context tool
// registrations survive, so toolsReady stays put.
register.base = undefined;
// #3562: invalidate in-flight attach chains started before this
// giveUp — their late commits must not resurrect the base.
register.giveUpSeq++;
};
state.onGiveUp = fireGiveUp;
// #1365: late routed evidence — if model traffic later arrives baked
// against a DIFFERENT origin than the one we attached to, rebind the
// tools there (the context lives where the models go). Fire-and-forget
Expand All @@ -1771,15 +1774,7 @@ export function apply(ctx: PluginContext): void {
markNativeHost(process.env, "dsh");
const start = singleFlight(bootstrap);
state.respawn = start;
state.onGiveUp = () => {
persistClientEvent("proxy respawn gave up — model traffic goes direct (uncompressed)");
// #3380: only the origin dies here — the host-context tool
// registrations survive, so toolsReady stays put.
register.base = undefined;
// #3562: invalidate in-flight attach chains started before this
// giveUp — their late commits must not resurrect the base.
register.giveUpSeq++;
};
state.onGiveUp = fireGiveUp;
state.ready = trackChain(start());
}

Expand Down Expand Up @@ -2432,6 +2427,9 @@ export function _resetRegisterForTest(base: string | undefined): void {
// survive a reset.
state.respawn = undefined;
state.onGiveUp = undefined;
// #4125: a stale unavailability reason from an earlier scenario must not
// leak into this scenario's give-up line.
state.lastUnavailableReason = undefined;
register.base = base;
register.toolsReady = false;
register.dead = false;
Expand Down Expand Up @@ -2507,6 +2505,13 @@ export function _stateOnGiveUpForTest(): (() => void) | undefined {
return state.onGiveUp;
}

/** Test hook (#4125): expose the shared intercept state so a suite can seed
* the fields the interceptor writes (lastUnavailableReason) and observe what
* the give-up seam reads. */
export function _nativeStateForTest(): NativeInterceptState {
return state;
}

/** Test hook (#3380): read-only snapshot of the registration lifecycle. */
export function _registerStateForTest(): { base: string | undefined; toolsReady: boolean; dead: boolean; retryAt: number; failStreak: number; lastRegistrationError: string | undefined } {
return { base: register.base, toolsReady: register.toolsReady, dead: register.dead, retryAt: register.retryAt, failStreak: register.failStreak, lastRegistrationError: register.lastRegistrationError };
Expand Down
18 changes: 13 additions & 5 deletions src/agent/native-intercept.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,11 @@ export type DirectSendPrep =

/** #3654: why createLiveOriginResolver found nothing to route to — the
* refusal wording must tell a live-but-saturated proxy (the busy wait window
* exhausted) apart from a dead one or a failed bootstrap. */
export type UnavailableReason = "busy-exhausted" | "dead" | "bootstrap-failed";
* exhausted) apart from a dead one or a failed bootstrap. #4125:
* "send-failed" marks the send-failure recovery paths (the held origin
* answered its probe but the send threw, and recover() produced no
* replacement) so a give-up line can name that branch too. */
export type UnavailableReason = "busy-exhausted" | "dead" | "bootstrap-failed" | "send-failed";

export interface NativeInterceptState {
/** Proxy origin ("http://127.0.0.1:PORT") once the bootstrap resolved.
Expand All @@ -49,9 +52,12 @@ export interface NativeInterceptState {
* the traffic. */
onGiveUp?: () => void;
/** #3654: set before createLiveOriginResolver returns undefined — why
* nothing was routable ("busy-exhausted" | "dead" | "bootstrap-failed");
* cleared on the next successful resolution. The refusal builder reads it
* to keep a live-but-saturated proxy out of "proxy unavailable" wording. */
* nothing was routable (see UnavailableReason: "busy-exhausted" | "dead"
* | "bootstrap-failed", plus #4125's "send-failed" set by the send-failure
* recovery paths just before they fire onGiveUp); cleared on the next
* successful resolution. The refusal builder reads it to keep a
* live-but-saturated proxy out of "proxy unavailable" wording; the dsh
* give-up seam appends it to the client event line (#4125). */
lastUnavailableReason?: UnavailableReason;
/** Attach mode (#809): route through a user-supplied external proxy at
* state.origin instead of a spawned one. Set by the host entry when a
Expand Down Expand Up @@ -1102,6 +1108,7 @@ export function installNativeFetchIntercept(initialState: NativeInterceptState):
}
return resp;
}
state.lastUnavailableReason = "send-failed";
state.onGiveUp?.();
if (!warned) {
warned = true;
Expand Down Expand Up @@ -1280,6 +1287,7 @@ export function installNativeFetchIntercept(initialState: NativeInterceptState):
// lifetime. Degrade exactly like a bootstrap failure: actually
// send the request direct, then let the owner clear proxy-owned
// state.
state.lastUnavailableReason = "send-failed";
state.onGiveUp?.();
if (!warned) {
warned = true;
Expand Down
20 changes: 16 additions & 4 deletions src/launcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4846,15 +4846,27 @@ function killAbandonedChild(child: SpawnChild | undefined): void {
// its own helpers, e.g. self-update npm runs, survives the "abandoned"
// kill). taskkill /T walks the whole tree; the direct kill below stays
// as the fallback if taskkill itself fails.
let tkError: string | undefined;
try {
spawnSync("taskkill", ["/F", "/T", "/PID", String(child.pid)], { windowsHide: true, stdio: "ignore" });
} catch {
/* taskkill unavailable — direct kill below */
const tk = spawnSync("taskkill", ["/F", "/T", "/PID", String(child.pid)], { windowsHide: true, stdio: "ignore" });
if (tk.error !== undefined) tkError = tk.error.message;
else if (tk.status !== 0) tkError = `exit ${tk.status}`;
} catch (err) {
tkError = err instanceof Error ? err.message : String(err);
}
// #4125: a failed taskkill used to vanish silently here — exactly how a
// "killed" abandoned child could keep holding its listener. Surface it;
// a non-zero exit can also mean the pid already left (harmless — the
// direct kill below still runs).
if (tkError !== undefined) {
teeLog("warn", `bili: taskkill of abandoned proxy ${child.pid} reported failure (${tkError}) — its listener may survive the cleanup (#4125)`);
}
}
try {
child.kill?.("SIGKILL");
} catch {}
} catch (err) {
teeLog("warn", `bili: direct SIGKILL of abandoned proxy ${child.pid} failed (${err instanceof Error ? err.message : String(err)}) — its listener may survive the cleanup (#4125)`);
}
}

export function stopProxy(handle: ProxyHandle): void {
Expand Down
Loading
Loading