From 3e15f194414c0dba44e53f6b2a0d71438dcf5420 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Fri, 30 Oct 2026 23:21:36 +0800 Subject: [PATCH] =?UTF-8?q?agent:=20shared=20attach/recovery=20lifecycle?= =?UTF-8?q?=20=E2=80=94=20migrate=20the=20omp=20lane=20(#5241=20phase=201,?= =?UTF-8?q?=20PR-1b)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Second lane migration: omp's verifyAttachAndRecover swaps its private copy for the shared native-attach.ts lifecycle via a NativeLaneSpec, exactly as pi did in PR-1a (#5244). Pure transposition — the phase-0 stake matrix (tests/contract-v2-stake-verify-attach.test.ts) passes untouched. omp specifics preserved through spec hooks instead of being silently unified: every origin write funnels through omp's publishOrigin() so a test-pinned probe base (_setOmpOriginForTest) survives a mid-suite attach verify / respawn landing, and the fallback branch's state clear routes through the same guard — hence the new optional clearOrigin spec hook (default remains the direct state.origin = undefined the other lanes use). armNativeOmp now calls armNativeLane("omp"): the one-lane-per-process contract (BILLION_CONTEXT_PROXY + fetch-intercept slot are per-process singletons — #5242 phase-0 stakes) is enforced for both migrated lanes. opencode/dsh keep their own copies until PR-1c/1d; their suites stay green untouched (issue3544 20/20, opencode-native 65/65). --- src/agent/native-attach.ts | 9 +++- src/agent/omp-native.ts | 95 ++++++++++++-------------------------- 2 files changed, 37 insertions(+), 67 deletions(-) diff --git a/src/agent/native-attach.ts b/src/agent/native-attach.ts index 0b69dcb1cb..99ec0dc485 100644 --- a/src/agent/native-attach.ts +++ b/src/agent/native-attach.ts @@ -40,6 +40,12 @@ export interface NativeLaneSpec { publish: (origin: string) => void; /** Drop the published origin (spawn fallback unfreezes the preset env). */ unpublish: () => void; + /** Fallback-branch state clear. Default (when omitted): the shared + * lifecycle writes `state.origin = undefined` directly. omp overrides + * this so its publishOrigin() test-pin guard (a suite-pinned probe base + * must survive a mid-suite attach verify / respawn landing — see + * _setOmpOriginForTest) stays in command of state.origin writes. */ + clearOrigin?: () => void; /** Lane event sink (logHostEvent / persistClientEvent). */ onEvent: NativeLaneEventHandler; } @@ -124,7 +130,8 @@ export async function verifyAttachAndRecover(spec: NativeLaneSpec, attachOrigin: spec.onEvent("error", `bili-native(${spec.lane}): attach target ${attachOrigin} is not healthy — falling back to a spawned proxy`); spec.unpublish(); state.attach = false; - state.origin = undefined; + if (spec.clearOrigin !== undefined) spec.clearOrigin(); + else state.origin = undefined; const start = singleFlight(spec.spawnForTest() ?? spec.bootstrap); state.respawn = start; // Publish whatever origin lands on BOTH the shared state and the env — diff --git a/src/agent/omp-native.ts b/src/agent/omp-native.ts index a18c0e9fb1..4a56f8b544 100644 --- a/src/agent/omp-native.ts +++ b/src/agent/omp-native.ts @@ -24,11 +24,12 @@ import { ensureProxyRunning, LAUNCHER_DEFAULT_HOST } from "../launcher.js"; import { createBiliPlugin } from "./pi.js"; import { applyOmpFirstEventTimeout, markNativeHost, nativeAttachOrigin, nativeBootstrapGate, nativeProxyScriptPath, proxyEnvOrigin, setNativeOriginWaiter, singleFlight } from "./native-bootstrap.js"; -import { installNativeFetchIntercept, noteRoutedOrigin, observeRoutedOrigin, readyOrigin, setDeclaredModelEndpoints, type NativeInterceptState } from "./native-intercept.js"; +import { installNativeFetchIntercept, noteRoutedOrigin, readyOrigin, setDeclaredModelEndpoints, type NativeInterceptState } from "./native-intercept.js"; import { loadDeclaredModelEndpoints } from "../model-endpoints.js"; +import { armNativeLane, verifyAttachAndRecover as verifyAttachAndRecoverShared, type NativeLaneSpec } from "./native-attach.js"; import { clearIncrementalProbe, createPrepareDirectSend, hostMsgIdHintFor, INCREMENTAL_TURN_MARKER_HEADER, INCREMENTAL_TURN_ID_HEADER, newIncrementalTurnId, noteIncrementalAck, noteIncrementalRejection, planIncrementalTurn, probeIncrementalTurns, rememberOriginalBody, sweepStale, wireMessagesLookAnthropic, type IncrementalWireMessage } from "./incremental-client.js"; import * as pfChannel from "./pf-channel.js"; -import { fetchProxyVersion, waitForProxyVersion } from "./shared.js"; +import { fetchProxyVersion } from "./shared.js"; import { logHostEvent } from "./host-log.js"; /** Decides whether the native bootstrap should run in this process. */ @@ -276,71 +277,29 @@ export function _setSpawnForTest(fn?: () => Promise): void { _spawnForTest = fn; } -/** #1135/#1365: the attached origin can go stale — at startup (the owning - * launcher exited before this process started) or at runtime (it exits while - * this session still rides the shared proxy, #1130). Probe before trusting - * it: healthy → keep attaching (a transient blip costs nothing — the session - * never migrates). DEAD + routed-channel evidence (#1365: /bili/-baked model - * traffic was observed at some origin) → the session's context lives at THAT - * origin, so wait for the pinned target to come back (bounded by - * BILI_ATTACH_HEALTH_DEADLINE_MS) instead of spawning — a second instance - * would serve tools while the model channel stays pinned elsewhere and every - * bili tool call 404s against it (unrecoverable split); the env is preserved - * so the user's target stays declared. DEAD with no evidence after the grace - * window (BILI_ATTACH_EVIDENCE_GRACE_MS) → unfreeze the preset env and fall - * back to spawning our own proxy, re-arming respawn as a pure spawn. Resolves - * to the origin the client should use — the (recovered) attach origin, the - * fallback origin, or undefined when nothing came up. */ -export async function verifyAttachAndRecover(attachOrigin: string): Promise { - // #1365: routed evidence outranks the planned origin — probe where the - // model channel actually points, not where the env says it should. An - // EXPLICIT BILLION_CONTEXT_ATTACH outranks both: it names the plugin API - // endpoint directly, and a routed model origin may be a plain model-only - // path (e.g. an admin-gated port) that never exposes the plugin manifest. - const explicitAttachOrigin = nativeAttachOrigin(process.env); - const home = explicitAttachOrigin ?? state.routedOrigin ?? attachOrigin; - const version = await fetchProxyVersion(home).catch(() => undefined); - if (version !== undefined) { - // Restore the readyOrigin short-circuit — a runtime recovery clears - // state.origin before re-probing, and a transient blip must not leave - // it dangling. - publishOrigin(home); - return home; - } - const pinned = explicitAttachOrigin ?? state.routedOrigin ?? (await observeRoutedOrigin(state)); - if (pinned !== undefined) { - const back = await waitForProxyVersion(pinned); - if (back !== undefined) { - publishOrigin(back); - logHostEvent("info", "[native-client]", `bili-native(omp): attach target ${pinned} is healthy again — attached, no second instance spawned`); - return back; - } - logHostEvent( - "error", - "[native-client]", - explicitAttachOrigin !== undefined - ? `bili-native(omp): explicit attach target ${pinned} unreachable within the health deadline — refusing to spawn a second instance (your declared endpoint stays authoritative). Start your proxy at ${pinned} or unset BILLION_CONTEXT_ATTACH; bili keeps re-checking and self-heals when it comes back.` - : `bili-native(omp): attach target ${pinned} is down and this process's model channel is pinned to it — refusing to spawn a second instance (bili tools would 404 against the other one). Start your proxy at ${pinned} or unset BILLION_CONTEXT_PROXY; bili keeps re-checking and self-heals when it comes back.`, - ); - state.origin = undefined; - return undefined; - } - logHostEvent("error", "[native-client]", `bili-native(omp): attach target ${attachOrigin} is not healthy — falling back to a spawned proxy`); - delete process.env.BILLION_CONTEXT_PROXY; - state.attach = false; - publishOrigin(undefined, false); // env already cleared above +/** #1135/#1365: shared since #5241 phase 1 — the lifecycle itself lives in + * native-attach.ts (one implementation for all lanes, behavior frozen by + * tests/contract-v2-stake-verify-attach.test.ts). This lane spec is the + * omp-specific surface: every origin write funnels through publishOrigin() + * so a test-pinned probe base (_setOmpOriginForTest) survives attach + * verify / respawn landing mid-suite; clearOrigin routes the fallback's + * state clear through the same guard. */ +const laneSpec: NativeLaneSpec = { + lane: "omp", + state, + spawnForTest: () => _spawnForTest, + bootstrap, + publish: (origin) => publishOrigin(origin), + unpublish: () => { + delete process.env.BILLION_CONTEXT_PROXY; + }, + clearOrigin: () => publishOrigin(undefined, false), + onEvent: (level, message) => logHostEvent(level, "[native-client]", message), +}; - const start = singleFlight(_spawnForTest ?? bootstrap); - state.respawn = start; - // Publish whatever origin lands on BOTH the shared state and the env — - // env readers (compaction reporter, /acp status) must never disagree with - // what the route resolves, whoever produced the origin. - const landed = start().then((o) => { - if (o !== undefined) publishOrigin(o); - return o; - }); - state.ready = landed; - return landed; +/** Doc comment moved to native-attach.ts#verifyAttachAndRecover. */ +export async function verifyAttachAndRecover(attachOrigin: string): Promise { + return verifyAttachAndRecoverShared(laneSpec, attachOrigin); } const plan = planNativeOmp(process.env); @@ -351,6 +310,10 @@ const plan = planNativeOmp(process.env); * spawn mode stays test-guarded because bootstrap forks a real proxy. */ export function armNativeOmp(p: typeof plan): void { if (p.mode === "off") return; + // #5241 phase 1: one native lane per process — a second, different lane + // would overwrite this lane's BILLION_CONTEXT_PROXY and fetch intercept + // (see native-attach.ts). + armNativeLane("omp"); markNativeHost(process.env, "omp"); if (p.mode === "attach") { state.attach = true;