From 13d2bdf1e27ddce318ea88572f570711698a8781 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Mon, 12 Oct 2026 18:25:04 +0800 Subject: [PATCH 1/5] fix: lane-aware attach discovery + native.attachLanePriority (#2905) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A dsh-spawned instance was the last writer of the single proxy-origin file, so a hermes native session attached to it blindly (the Python plugin checked neither lane nor code fingerprint nor config shape). Its MITM whitelist does not cover hermes's providers, so model traffic blind-tunneled, no session ever arrived under hermes's conversation id, and every compression tool call 404'd. - hermes-plugin: discovery now mirrors probeLiveInstances + pickAttachable (src/launcher.ts) — scans every registry marker plus the proxy-origin file (registry wins id collisions), requires entry-script fingerprint, bind host/passthrough/MITM-whitelist/model-table identity, and applies the lane rules: own lane first, operator-listed foreign lanes next, user zone (manual bili start, the 8787 global) ALWAYS last. The #1335 lifecycle gate keeps applying except to the user zone (#1660 twin). Spawned proxies now declare lane: hermes (BILI_LAUNCHER_LANE) so no other lane can ride them. - launcher.ts: attachClass() replaces the two-class rule with own lane -> listed foreign lanes (native.attachLanePriority order) -> undeclared lanes last; instanceCompatible admits a foreign declared lane only when listed. Default [] = zero behavior change for existing TS lanes. - config.ts: native.attachLanePriority (string[], file-only, no env var per #2030) + resolveNativeAttachLanePriority(). Closes #2905 --- hermes-plugin/__init__.py | 258 ++++++++++++++++++++++++++++++-------- src/config.ts | 43 +++++-- src/launcher.ts | 57 ++++++--- 3 files changed, 283 insertions(+), 75 deletions(-) diff --git a/hermes-plugin/__init__.py b/hermes-plugin/__init__.py index e6686daf9b..537afb567c 100644 --- a/hermes-plugin/__init__.py +++ b/hermes-plugin/__init__.py @@ -21,6 +21,7 @@ from __future__ import annotations +import hashlib import json import logging import os @@ -56,7 +57,8 @@ # mode values: "attach" | "spawn"; child: Popen of the spawned proxy; # max_output: OrderedDict[session_id -> int(max_tokens)]; runtime_info_sent: (model, max_output) pairs; -# refused: origins refused by the #1338 attach gate (log dedup per process). +# refused: origins refused by the #1338 attach gate (log dedup per process); +# instance_id: the registry id discover_instance picked (None until an attach is chosen). _state: Dict[str, Any] = { "origin": None, "mode": None, @@ -66,6 +68,7 @@ "max_output": OrderedDict(), "runtime_info_sent": set(), "refused": set(), + "instance_id": None, } @@ -78,6 +81,7 @@ def _reset_for_test() -> None: _state["max_output"].clear() _state["runtime_info_sent"].clear() _state["refused"].clear() + _state["instance_id"] = None # — paths --------------------------------------------------------------------- @@ -208,15 +212,26 @@ def resolve_attach_external() -> bool: return isinstance(native, dict) and native.get("attachExternal") is True -def watchdog_armed(origin: str) -> Optional[bool]: - """#1330 watchdog state from /__bili/health; None = field absent (older build).""" - health = http_get_json(origin.rstrip("/") + "/__bili/health", HEALTH_PROBE_TIMEOUT_S) - if not isinstance(health, dict): - return None - wd = health.get("watchdog") - if isinstance(wd, dict) and isinstance(wd.get("armed"), bool): - return wd["armed"] - return None +def resolve_attach_lane_priority() -> List[str]: + """#2905: mirrors resolveNativeAttachLanePriority (src/config.ts) — the ordered list of + lane names this hook may RIDE when no own-lane instance exists. Own lane always wins + first; user-zone daemons (manual `bili start`, the 8787 global) are ALWAYS last; unlisted + lanes stay non-attachable (#1225/#1232). Default [] = own lane → user zone → spawn.""" + try: + data = json.loads(config_file_path().read_text(encoding="utf-8")) + except Exception: + return [] + native = data.get("native") if isinstance(data, dict) else None + raw = native.get("attachLanePriority") if isinstance(native, dict) else None + if not isinstance(raw, list): + return [] + out: List[str] = [] + for item in raw: + if isinstance(item, str): + t = item.strip() + if t and t not in out: + out.append(t) + return out def register_watcher(origin: str) -> None: @@ -240,6 +255,41 @@ def register_watcher(origin: str) -> None: # — instance discovery (written by the bili proxy itself) ---------------------- +def _normalize_instance(data: Any) -> Optional[Dict[str, Any]]: + """Coerce one raw record (proxy-origin JSON or registry marker) into the identity shape + discovery checks; None when it is not an instance record at all.""" + if not isinstance(data, dict): + return None + origin = str(data.get("origin") or "").rstrip("/") + if not origin.startswith(("http://", "https://")): + return None + pid = data.get("pid") + token = data.get("launchToken") + lane = data.get("lane") + fp = data.get("codeFingerprint") + host = data.get("host") + passthrough = data.get("passthrough") + domains = data.get("mitmDomains") + windows = data.get("modelWindows") + max_outputs = data.get("modelMaxOutputs") + started_at = data.get("startedAt") + instance_id = data.get("instanceId") + return { + "origin": origin, + "pid": pid if isinstance(pid, int) else None, + "launch_token": token if isinstance(token, str) else None, + "instance_id": instance_id if isinstance(instance_id, str) else "", + "lane": lane if isinstance(lane, str) and lane else None, + "code_fingerprint": fp if isinstance(fp, str) and fp else None, + "host": host if isinstance(host, str) else None, + "passthrough": passthrough if isinstance(passthrough, bool) else None, + "mitm_domains": [str(d) for d in domains] if isinstance(domains, list) else None, + "model_windows": windows if isinstance(windows, dict) else None, + "model_max_outputs": max_outputs if isinstance(max_outputs, dict) else None, + "started_at": started_at if isinstance(started_at, (int, float)) else 0, + } + + def read_instance_file() -> Optional[Dict[str, Any]]: try: text = (state_dir() / "proxy-origin").read_text(encoding="utf-8").strip() @@ -252,23 +302,46 @@ def read_instance_file() -> Optional[Dict[str, Any]]: data = json.loads(text) except Exception: return None - if not isinstance(data, dict): - return None - origin = str(data.get("origin") or "").rstrip("/") - if not origin.startswith(("http://", "https://")): - return None - pid = data.get("pid") - token = data.get("launchToken") - return { - "origin": origin, - "pid": int(pid) if isinstance(pid, int) else None, - "launch_token": str(token) if isinstance(token, str) else None, - } + return _normalize_instance(data) if text.startswith(("http://", "https://")): - return {"origin": text.rstrip("/"), "pid": None, "launch_token": None} + return _normalize_instance({"origin": text}) return None +def read_registry_entries() -> List[Dict[str, Any]]: + """#1232 twin of discoverLiveInstances (src/instance.ts): every instance's self-registered + marker under /instances/.json (one BARE entry per file), plus the legacy + instances.json folded in read-only. Malformed markers are skipped, never fatal.""" + entries: List[Dict[str, Any]] = [] + reg_dir = state_dir() / "instances" + try: + names = sorted(os.listdir(str(reg_dir))) + except OSError: + names = [] + for name in names: + if not name.endswith(".json"): + continue + try: + with open(os.path.join(str(reg_dir), name), encoding="utf-8") as fh: + entry = _normalize_instance(json.load(fh)) + except Exception: + entry = None + if entry: + entries.append(entry) + try: + with open(os.path.join(str(state_dir()), "instances.json"), encoding="utf-8") as fh: + legacy = json.load(fh) + items = legacy.get("instances") if isinstance(legacy, dict) else None + if isinstance(items, list): + for item in items: + entry = _normalize_instance(item) + if entry: + entries.append(entry) + except Exception: + pass + return entries + + def pid_alive(pid: Optional[int]) -> bool: if not isinstance(pid, int) or pid <= 1: return False @@ -287,36 +360,116 @@ def pid_alive(pid: Optional[int]) -> bool: return False -def discover_instance() -> Optional[str]: - inst = read_instance_file() - if not inst: +def _sha256_file(path: str) -> Optional[str]: + h = hashlib.sha256() + try: + with open(path, "rb") as fh: + for chunk in iter(lambda: fh.read(65536), b""): + h.update(chunk) + except Exception: return None - if inst["pid"] is not None and not pid_alive(inst["pid"]): + return h.hexdigest() + + +_REFUSAL_TEXT = { + "code-fingerprint-mismatch": "it runs different bili code than this plugin would spawn (stale/foreign build)", + "lane-mismatch": "it belongs to another lane — lane isolation (#1225/#2905); list its lane in native.attachLanePriority to allow", + "host-or-passthrough-mismatch": "its bind host or passthrough posture differs from this hook's", + "mitm-domains-mismatch": "its MITM whitelist does not cover this hermes's providers — model traffic would blind-tunnel", + "model-tables-mismatch": "its model window/max-output table differs from this hook's (none)", +} + + +def _attach_reason(inst: Dict[str, Any], fingerprint: Optional[str], want_domains: List[str], + foreign_lanes: List[str]) -> Optional[str]: + """First failing compatibility check, mirroring instanceCompatible (src/launcher.ts); + None when the candidate is attachable.""" + if fingerprint is None or inst["code_fingerprint"] is None or inst["code_fingerprint"] != fingerprint: + return "code-fingerprint-mismatch" + lane = inst["lane"] + if lane is not None and lane != AGENT_NAME and lane not in foreign_lanes: + return "lane-mismatch" + if inst["host"] != "127.0.0.1" or inst["passthrough"] is not False: + return "host-or-passthrough-mismatch" + if inst["mitm_domains"] != want_domains: + return "mitm-domains-mismatch" + if inst["model_windows"] != {} or inst["model_max_outputs"]: + return "model-tables-mismatch" + return None + + +def _refuse(origin: str, message: str) -> None: + if origin in _state["refused"]: + return + _state["refused"].add(origin) + logger.warning("billion-context: refusing to attach to %s — %s.", origin, message) + + +def discover_instance(script: str) -> Optional[str]: + """#2905: lane-aware attach discovery — the Python twin of probeLiveInstances + + pickAttachable (src/launcher.ts). Candidates come from EVERY live registry marker plus + the single proxy-origin file (registry wins id collisions, mirroring probeLiveInstances). + A candidate must match our CODE (entry-script fingerprint), our config shape (bind host, + passthrough, MITM whitelist, model tables) and the LANE rules: own lane first, then the + operator-listed foreign lanes (native.attachLanePriority), user-zone daemons (manual + `bili start`, the 8787 global) ALWAYS last. The #1335 lifecycle gate still applies — + except to the user zone (#1660): an unarmed daemon the user maintains deliberately is a + legitimate LAST-resort target, unlike a session proxy whose watchdog drifted away.""" + candidates: Dict[str, Dict[str, Any]] = {} + file_inst = read_instance_file() + if file_inst: + candidates[file_inst["instance_id"] or file_inst["origin"]] = file_inst + for entry in read_registry_entries(): + candidates[entry["instance_id"] or entry["origin"]] = entry + if not candidates: return None - if not probe_proxy(inst["origin"]): + fingerprint = _sha256_file(script) + want_domains = mitm_domains_from_config() + foreign_lanes = resolve_attach_lane_priority() + attach_external = resolve_attach_external() + best_key: Optional[Tuple[int, int]] = None + best: Optional[Dict[str, Any]] = None + for inst in candidates.values(): + origin = inst["origin"] + if inst["pid"] is not None and not pid_alive(inst["pid"]): + continue + reason = _attach_reason(inst, fingerprint, want_domains, foreign_lanes) + if reason is not None: + _refuse(origin, _REFUSAL_TEXT.get(reason, reason)) + continue + if not probe_proxy(origin): + continue + health = http_get_json(origin.rstrip("/") + "/__bili/health", HEALTH_PROBE_TIMEOUT_S) + if not isinstance(health, dict) or health.get("ok") is not True: + continue + hid = health.get("instanceId") + if isinstance(hid, str) and hid != inst["instance_id"]: + continue + wd = health.get("watchdog") + armed = wd.get("armed") if isinstance(wd, dict) and isinstance(wd.get("armed"), bool) else None + user_zone = inst["lane"] is None and inst["launch_token"] is None + if not attach_external and armed is not True and not user_zone: + _refuse(origin, "it reports " + + ("NO session-lifecycle watchdog (started without BILI_PARENT_PID, e.g. manual `bili start`)" + if armed is False + else "no watchdog state (older bili build) — its lifecycle is unverifiable") + + " (#1322/#1335). Starting a session-owned proxy instead; set native.attachExternal=true " + + "or " + ATTACH_EXTERNAL_ENV + "=1 to attach anyway.") + continue + lane = inst["lane"] + if lane == AGENT_NAME: + cls = 0 + elif lane is not None: + cls = 1 + foreign_lanes.index(lane) + else: + cls = len(foreign_lanes) + 1 + key = (cls, -inst["started_at"]) + if best_key is None or key < best_key: + best_key, best = key, inst + if best is None: return None - # #1338: the Python twin of #1335's attach gate (src/launcher.ts - # pickAttachable). Discovery must not ride a lifecycle-less listener — - # unarmed (or unverifiable: older build, field absent) => refuse and fall - # through to a session-owned spawn. Explicit BILLION_CONTEXT_ATTACH stays - # exempt: user-directed, like the TS lanes' explicit-attach paths. - if not resolve_attach_external(): - armed = watchdog_armed(inst["origin"]) - if armed is not True: - if inst["origin"] not in _state["refused"]: - _state["refused"].add(inst["origin"]) - logger.warning( - "billion-context: refusing to attach to %s — it reports %s (#1322/#1335). " - "Starting a session-owned proxy instead; set native.attachExternal=true " - "or %s=1 to attach anyway.", - inst["origin"], - "NO session-lifecycle watchdog (started without BILI_PARENT_PID, e.g. manual `bili start`)" - if armed is False - else "no watchdog state (older bili build) — its lifecycle is unverifiable", - ATTACH_EXTERNAL_ENV, - ) - return None - return inst["origin"] + _state["instance_id"] = best["instance_id"] + return best["origin"] # — cross-process startup coordination (mirrors ensureProxyRunning, #707) ------ @@ -457,6 +610,7 @@ def _spawn_child(sidecar: Dict[str, str], port: int, token: str) -> Optional[sub env = {k: v for k, v in os.environ.items() if k not in _PROXY_ENV_KEYS} env["BILI_LAUNCH_TOKEN"] = token env["BILI_PARENT_PID"] = str(os.getpid()) + env["BILI_LAUNCHER_LANE"] = AGENT_NAME domains = mitm_domains_from_config() if domains: env["BILI_MITM_DOMAINS"] = ",".join(domains) @@ -490,7 +644,7 @@ def ensure_origin(sidecar: Dict[str, str]) -> Optional[str]: return _attach(attach) logger.warning("billion-context: %s %s is not healthy — falling back to local bootstrap", ATTACH_ENV, attach) - found = discover_instance() + found = discover_instance(sidecar["script"]) if found: return _attach(found) @@ -502,7 +656,7 @@ def ensure_origin(sidecar: Dict[str, str]) -> Optional[str]: if not claimed: deadline = time.monotonic() + SPAWN_WAIT_S while time.monotonic() < deadline: - found = discover_instance() + found = discover_instance(sidecar["script"]) if found: return _attach(found) marker = _read_marker() diff --git a/src/config.ts b/src/config.ts index 7612c45131..05120edeec 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1676,14 +1676,27 @@ type FileConfig = { * `"pi": {"subagents": false}` disables the whole surface. The four * acp.json keys (delegate/delegatePrompt/displayUsage/debug) are a * deprecated fallback, read only while this section is absent. */ - pi?: { subagents?: PiSubagentsFileConfig | boolean }; - /** Native-hook attach policy (#1335): set `true` to let native hooks - * attach to lifecycle-less listeners (a manually started `bili start` - * daemon — no session-lifecycle watchdog, outlives every session, often - * an older code version). Default false: hooks self-manage and spawn - * their own armed session proxy instead (#1322). Env - * BILI_NATIVE_ATTACH_EXTERNAL=1/0 wins over the file. */ - native?: { attachExternal?: boolean }; + pi?: { subagents?: PiSubagentsFileConfig | boolean }; + /** Native-hook attach policy (#1335): set `attachExternal: true` to let + * native hooks attach to lifecycle-less listeners (a manually started + * `bili start` daemon — no session-lifecycle watchdog, outlives every + * session, often an older code version). Default false: hooks self-manage + * and spawn their own armed session proxy instead (#1322). Env + * BILI_NATIVE_ATTACH_EXTERNAL=1/0 wins over the file. + * #2905: `attachLanePriority` is an ordered list of lane names whose + * live instances a hook may ride when NO instance of its own lane + * exists — each name becomes an attachable tier in list order, after + * the hook's own lane (always first) and before the user zone (manual + * `bili start`, the 8787 global daemon), which is ALWAYS last among + * attachable candidates. Unlisted lanes stay non-attachable + * (#1225/#1232 isolation). Default [] = own lane → user zone → spawn; + * cross-lane attach stays opt-in because a foreign lane's MITM + * whitelist may not cover your providers (blind tunnel + tool 404s — + * the accident #2905 reports). File-only, no env var (#2030). */ + native?: { + attachExternal?: boolean; + attachLanePriority?: string[]; + }; /** Unified SQLite storage sidecar (#2671). `storage.unified` selects the * whole-lane mode ("legacy" | "shadow" | "full"); env * BILI_STORAGE_UNIFIED wins over this file value, absent/invalid falls @@ -2107,6 +2120,20 @@ export function resolveNativeAttachExternal(env: NodeJS.ProcessEnv = process.env return loadConfigFile().native?.attachExternal === true; } +/** #2905: ordered cross-lane attach fallbacks for native hooks (see the + * `native.attachLanePriority` field docs). Normalized: non-array/garbage → + * [], string elements trimmed + deduped, empty entries dropped. */ +export function resolveNativeAttachLanePriority(): string[] { + const raw = loadConfigFile().native?.attachLanePriority; + if (!Array.isArray(raw)) return []; + const out: string[] = []; + for (const item of raw) { + if (typeof item !== "string") continue; + const t = item.trim(); + if (t.length > 0 && !out.includes(t)) out.push(t); + } + return out; +} /** Template written on first run so the user has a file to edit instead * of having to invent the path/schema. Left empty on purpose: the proxy diff --git a/src/launcher.ts b/src/launcher.ts index cc5020a3dd..2d5c74a4c6 100644 --- a/src/launcher.ts +++ b/src/launcher.ts @@ -65,7 +65,7 @@ function selfDistFile(name: string): string { return path.join(selfPackageRoot(), "dist", name); } import { nonEmpty, resolvePiHome, resolveOmpHome, resolveDshHome, resolveCodexHome, resolveCodexEffectiveView, loadClientConfig, collectModelWindows, collectModelMaxOutputs, type ClientConfig, type CodexConfig, resolveOpencodeConfigFile, readOpencodeConfigRoot, opencodePluginBaseDir, type OpencodeConfig, type OpencodeProvider, type HermesConfig, type HermesProvider, qoderIsCnSite, QODER_DEFAULT_MODEL_HOSTS, resolveTraeHome, readTraeConfig, TRAE_DEFAULT_MODEL_HOSTS, JCODE_DEFAULT_MODEL_HOSTS, type TraeConfig, resolveKimiHome, readKimiConfig, parseKimiToml, KIMI_DEFAULT_MODEL_HOSTS, QWEN_DEFAULT_MODEL_HOSTS, type KimiConfig, type KimiProvider, readOpencodeProjectLayer, type OpencodeProjectLayer, readMcodeConfig, resolveMcodeInstallDir, MCODE_DEFAULT_MODEL_HOSTS, type McodeConfig, discoverAiderArgUrls, AIDER_DEFAULT_MODEL_HOSTS, COPILOT_DEFAULT_MODEL_HOSTS, AMP_DEFAULT_MODEL_HOSTS, CRUSH_DEFAULT_MODEL_HOSTS, ZED_DEFAULT_MODEL_HOSTS, readZedConfig, resolveGooseDirs, readGooseConfig, type GooseConfig, type GooseDirs } from "./client-config.js"; -import { allowDshCompactionState, loadRoutes, resolveConfiguredContextLimit, lookupContextLimit, resolveNativeAttachExternal, resolveMitmDomains, resolveNonHttpProviders, type ProviderRoutes } from "./config.js"; +import { allowDshCompactionState, loadRoutes, resolveConfiguredContextLimit, lookupContextLimit, resolveNativeAttachExternal, resolveNativeAttachLanePriority, resolveMitmDomains, resolveNonHttpProviders, type ProviderRoutes } from "./config.js"; import { discoverMitmDomains } from "./discover.js"; import { contextFromRegistry } from "./registry.js"; @@ -251,6 +251,10 @@ export interface LauncherDeps { /** #1335: resolves the attach-gate escape hatch. Default reads env * BILI_NATIVE_ATTACH_EXTERNAL > config `native.attachExternal` > false. */ resolveAttachExternal?: () => boolean; + /** #2905: resolves the ordered cross-lane attach fallbacks (config + * `native.attachLanePriority`). Default [] = own lane → user zone → + * spawn, no cross-lane attach. */ + attachLanePriority?: () => readonly string[]; readInstanceFile?: () => ProxyInstanceFile | { origin: string } | undefined; spawnImpl?: SpawnFn; now?: () => number; @@ -3451,9 +3455,11 @@ function isStartingMarkerActive(marker: ProxyStartingMarker, nowMs: number): boo /** #1623: undefined = compatible; otherwise the FIRST failing check as a * stable reason code, so attach diagnostics can say WHICH field rejected a * live candidate instead of dropping it silently. */ -function instanceCompatible(inst: ProxyInstanceFile, opts: LaunchOptions, codeFingerprint?: string): string | undefined { +function instanceCompatible(inst: ProxyInstanceFile, opts: LaunchOptions, codeFingerprint?: string, foreignLanes: readonly string[] = []): string | undefined { if (inst.codeFingerprint === undefined || inst.codeFingerprint !== codeFingerprint) return "code-fingerprint-mismatch"; - if (opts.lane !== undefined && inst.lane !== undefined && inst.lane !== opts.lane) return "lane-mismatch"; + // #2905: a foreign DECLARED lane is attachable only when the operator + // listed it in native.attachLanePriority — isolation by default (#1225/#1232). + if (opts.lane !== undefined && inst.lane !== undefined && inst.lane !== opts.lane && !foreignLanes.includes(inst.lane)) return "lane-mismatch"; if (inst.host !== opts.host || inst.passthrough !== opts.passthrough) return "host-or-passthrough-mismatch"; const wantDomains = opts.mitmDomains ?? []; if (inst.mitmDomains.length !== wantDomains.length || inst.mitmDomains.some((d, i) => d !== wantDomains[i])) return "mitm-domains-mismatch"; @@ -3522,11 +3528,26 @@ function gateRefusalMessage(inst: ProxyInstanceFile, health: HealthInfo): string return `bili: refusing to attach to ${inst.origin} (pid ${inst.pid}) — ${reason}. It would outlive this session and ignore config edits until killed (#1322/#1335). Starting a session-owned proxy instead; set native.attachExternal=true or BILI_NATIVE_ATTACH_EXTERNAL=1 to attach anyway.`; } +/** #2905: attach-priority class. The caller's own declared lane is ALWAYS + * first (concurrent same-lane launches must converge on the lane's own + * instance, not a general-purpose daemon either could use — #1232). Then + * the operator-listed foreign lanes in `native.attachLanePriority` order + * (#2905 opt-in tiers). Undeclared-lane instances — the user zone (manual + * `bili start`, the 8787 global daemon) and legacy token spawns — are + * ALWAYS last among attachable candidates, whatever the list says. Within + * a class, newest startedAt wins. */ +function attachClass(inst: ProxyInstanceFile, lane: string | undefined, foreignLanes: readonly string[]): number { + if (lane === undefined) return 1; + if (inst.lane === lane) return 0; + if (inst.lane !== undefined) return 1 + foreignLanes.indexOf(inst.lane); + return foreignLanes.length + 1; +} + /** #1232: choose the attach target among healthy candidates. Must be * compatible (code fingerprint + config shape + lane rules) and, under - * strictPort, bound to our exact port. Same declared lane beats wildcard — - * concurrent same-lane launches must converge on the lane's own instance, - * not a general-purpose daemon either could use — newest within class. */ + * strictPort, bound to our exact port. Class ordering per attachClass — + * same declared lane first, listed foreign lanes next, user zone last — + * newest within class. */ function pickAttachable( candidates: Array<{ inst: ProxyInstanceFile; health: HealthInfo }>, opts: LaunchOptions, @@ -3534,12 +3555,13 @@ function pickAttachable( attachExternal: boolean, refusedLog: Set, diag?: (msg: string) => void, + foreignLanes: readonly string[] = [], ): ProxyInstanceFile | undefined { let best: ProxyInstanceFile | undefined; - let bestClass = 2; + let bestClass = Number.MAX_SAFE_INTEGER; let bestStartedAt = Number.NEGATIVE_INFINITY; for (const c of candidates) { - const incompatible = instanceCompatible(c.inst, opts, codeFingerprint); + const incompatible = instanceCompatible(c.inst, opts, codeFingerprint, foreignLanes); if (incompatible !== undefined) { diag?.(`native-attach: skip ${c.inst.origin} (pid ${c.inst.pid}): incompatible (${incompatible})`); continue; } if (opts.strictPort && c.inst.port !== opts.port) { diag?.(`native-attach: skip ${c.inst.origin} (pid ${c.inst.pid}): port mismatch`); continue; } // #1335: lifecycle gate — an unarmed (or unverifiable) listener is @@ -3554,7 +3576,7 @@ function pickAttachable( } continue; } - const cls = opts.lane !== undefined && c.inst.lane === opts.lane ? 0 : 1; + const cls = attachClass(c.inst, opts.lane, foreignLanes); if (cls < bestClass || (cls === bestClass && c.inst.startedAt > bestStartedAt)) { best = c.inst; bestClass = cls; @@ -3582,10 +3604,11 @@ async function waitForStarterInstance( attachExternal: boolean, refusedLog: Set, diag?: (msg: string) => void, + foreignLanes: readonly string[] = [], ): Promise { const deadline = now() + SPAWN_BUDGET_MS; const probe = async (): Promise => - pickAttachable(await probeLiveInstances(readInstance, fetchHealthInfo, diag), opts, codeFingerprint, attachExternal, refusedLog, diag); + pickAttachable(await probeLiveInstances(readInstance, fetchHealthInfo, diag), opts, codeFingerprint, attachExternal, refusedLog, diag, foreignLanes); let inst: ProxyInstanceFile | undefined; while (now() < deadline) { await sleepImpl(HEALTH_POLL_INTERVAL_MS); @@ -3608,8 +3631,9 @@ export async function findLiveAttachableInstance( const fetchHealthInfo = deps.fetchHealthInfo ?? fetchHealthInfoDefault; const readInstance = deps.readInstanceFile ?? readProxyInstanceFile; const attachExternal = (deps.resolveAttachExternal ?? resolveNativeAttachExternal)(); + const foreignLanes = (deps.attachLanePriority ?? resolveNativeAttachLanePriority)(); const probed = await probeLiveInstances(readInstance, fetchHealthInfo, deps.attachDiag); - return pickAttachable(probed, opts, entryScriptFingerprint(deps.scriptPath ?? process.argv[1]), attachExternal, new Set(), deps.attachDiag); + return pickAttachable(probed, opts, entryScriptFingerprint(deps.scriptPath ?? process.argv[1]), attachExternal, new Set(), deps.attachDiag, foreignLanes); } export function findFreePort(preferred: number, host = LAUNCHER_DEFAULT_HOST): Promise { @@ -3838,6 +3862,9 @@ export async function ensureProxyRunning( // BILLION_CONTEXT_ATTACH / preset BILLION_CONTEXT_PROXY) never pass through // this discovery path at all, so they are exempt by construction. const attachExternal = (deps.resolveAttachExternal ?? resolveNativeAttachExternal)(); + // #2905: ordered cross-lane attach fallbacks, resolved once per bring-up + // (file only; default [] = own lane → user zone → spawn). + const foreignLanes = (deps.attachLanePriority ?? resolveNativeAttachLanePriority)(); // Refusal log dedup: pickAttachable runs again on every starter-poll tick, // so each refused origin is announced exactly once per bring-up. const refusedLog = new Set(); @@ -3872,7 +3899,7 @@ export async function ensureProxyRunning( // writer of the single proxy-origin file (that pointer can belong to // another client's per-lane proxy). const probed = await probeLiveInstances(readInstance, fetchHealthInfo, attachDiag); - const existing = pickAttachable(probed, opts, codeFingerprint, attachExternal, refusedLog, attachDiag); + const existing = pickAttachable(probed, opts, codeFingerprint, attachExternal, refusedLog, attachDiag, foreignLanes); if (existing) { // strictPort (#964) is enforced inside pickAttachable: the client // dials a STATIC url — attaching to a healthy proxy on a DIFFERENT @@ -3884,7 +3911,7 @@ export async function ensureProxyRunning( // pinned port — self-managed fallback is impossible here (we cannot // bind that port either). Fail fast with an actionable error instead // of burning SPAWN_WAIT_MS into a confusing EADDRINUSE. - const squatter = probed.find((c) => c.inst.port === opts.port && instanceCompatible(c.inst, opts, codeFingerprint) === undefined); + const squatter = probed.find((c) => c.inst.port === opts.port && instanceCompatible(c.inst, opts, codeFingerprint, foreignLanes) === undefined); if (squatter) { throw new Error( `bili: port ${opts.port} is held by a lifecycle-less bili proxy at ${squatter.inst.origin} (pid ${squatter.inst.pid}) — ` + @@ -3901,7 +3928,7 @@ export async function ensureProxyRunning( // (singleFlight, #706); this is the cross-process half. const waitForOtherStarter = async (): Promise => { console.error("bili: another bili launch is bringing up a proxy — waiting for it instead of spawning a second"); - const waited = await waitForStarterInstance(readInstance, fetchHealthInfo, now, sleepImpl, opts, codeFingerprint, attachExternal, refusedLog, attachDiag); + const waited = await waitForStarterInstance(readInstance, fetchHealthInfo, now, sleepImpl, opts, codeFingerprint, attachExternal, refusedLog, attachDiag, foreignLanes); if (waited) { return attachTo(waited); } @@ -4108,7 +4135,7 @@ export async function ensureProxyRunning( while (now() < rediscoveryDeadline) { await sleepImpl(HEALTH_POLL_INTERVAL_MS); const probedAgain = await probeLiveInstances(readInstance, fetchHealthInfo, attachDiag); - const late = pickAttachable(probedAgain, opts, codeFingerprint, attachExternal, refusedLog, attachDiag); + const late = pickAttachable(probedAgain, opts, codeFingerprint, attachExternal, refusedLog, attachDiag, foreignLanes); if (late) { console.error(`bili: attached to ${late.origin} (pid ${late.pid}) — it published its instance record after the initial discovery`); return attachTo(late); From 8aec453fdbadfdb2a689f440903633c298298c49 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Mon, 12 Oct 2026 18:25:19 +0800 Subject: [PATCH 2/5] test: pin #2905 lane isolation + priority ordering MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - hermes driver: existing discover-* fixtures now carry full identity fields (fingerprint/lane/host/passthrough/mitm/modelWindows); new scenarios: discover-foreign-lane (the reported bug — dsh instance is refused, not ridden), discover-user-zone (unarmed 8787-style daemon is a legitimate last-resort target, #1660 twin), discover-lane-first (own lane beats a NEWER user zone; registry scanned beyond the file), discover-priority-config (attachLanePriority opt-in rides a listed foreign lane), spawn-env (spawned proxies declare BILI_LAUNCHER_LANE). - launcher: listed foreign lane attachable / list position beats recency / unlisted foreign lane stays refused with user zone last. - config: resolveNativeAttachLanePriority normalization (trim, dedupe, non-array/garbage -> []). --- tests/claude-native.test.ts | 24 +++++- tests/hermes-native.test.ts | 143 ++++++++++++++++++++++++++++++++++-- tests/launcher.test.ts | 95 ++++++++++++++++++++++++ 3 files changed, 256 insertions(+), 6 deletions(-) diff --git a/tests/claude-native.test.ts b/tests/claude-native.test.ts index e6534da278..440f85f8af 100644 --- a/tests/claude-native.test.ts +++ b/tests/claude-native.test.ts @@ -28,7 +28,7 @@ import { stripClaudeManagedBlock, } from "../src/plugin-install.ts"; import { ensureRootCA } from "../src/ca.ts"; -import { ZONE_PORT_BASE, resolveClaudeNativePort, resolveNativeAttachExternal } from "../src/config.ts"; +import { ZONE_PORT_BASE, resolveClaudeNativePort, resolveNativeAttachExternal, resolveNativeAttachLanePriority } from "../src/config.ts"; import { chooseWatchdogParentPid, claudeNativeRoutingCheck, isClaudeHostArgv, isTransientShArgv, planClaudeNativeBootstrap, procTableExecOptions, readPsProcInfo, recordClaudeRoutingWarning, readWinProcInfo, resolveClaudeHostPid, splitWindowsCommandLine } from "../src/claude-native-bootstrap.ts"; import { caDir, claudeRoutingWarningFile } from "../src/paths.ts"; import { rmrf } from "./tmp-rm.ts"; @@ -240,6 +240,28 @@ test("resolveNativeAttachExternal: file native.attachExternal requires exact tru } }); +test("resolveNativeAttachLanePriority: ordered unique list; garbage degrades to [] (#2905)", () => { + const prev = process.env.XDG_CONFIG_HOME; + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bili-laneprio-")); + const cfgDir = path.join(dir, "billion-context"); + fs.mkdirSync(cfgDir, { recursive: true }); + const cfgFile = path.join(cfgDir, "billion-context.json"); + process.env.XDG_CONFIG_HOME = dir; + try { + assert.deepEqual(resolveNativeAttachLanePriority(), [], "absent file → no foreign lanes"); + fs.writeFileSync(cfgFile, JSON.stringify({ native: { attachLanePriority: [" dsh ", "opencode", "dsh", 7, null] } })); + assert.deepEqual(resolveNativeAttachLanePriority(), ["dsh", "opencode"], "trimmed, order preserved, duplicates dropped, non-strings skipped"); + fs.writeFileSync(cfgFile, JSON.stringify({ native: { attachLanePriority: "dsh" } })); + assert.deepEqual(resolveNativeAttachLanePriority(), [], "non-array degrades to [] — never a lone string"); + fs.writeFileSync(cfgFile, "{ not json"); + assert.deepEqual(resolveNativeAttachLanePriority(), [], "malformed file degrades to [], never throws"); + } finally { + if (prev === undefined) delete process.env.XDG_CONFIG_HOME; + else process.env.XDG_CONFIG_HOME = prev; + rmrf(dir); + } +}); + // — hook planner ———————————————————————————————————————————— test("planClaudeNativeBootstrap: launcher-owned / opt-out / start", () => { diff --git a/tests/hermes-native.test.ts b/tests/hermes-native.test.ts index ee6995da72..4271a6a0f9 100644 --- a/tests/hermes-native.test.ts +++ b/tests/hermes-native.test.ts @@ -198,6 +198,7 @@ const PY = findPython(); const DRIVER = String.raw` import importlib.util +import hashlib import json import logging import os @@ -214,6 +215,9 @@ for sub in ("state", "data", "home", "plugins/billion-context"): os.environ["XDG_STATE_HOME"] = os.path.join(BASE, "state") os.environ["XDG_DATA_HOME"] = os.path.join(BASE, "data") os.environ["HERMES_HOME"] = os.path.join(BASE, "home") +os.makedirs(os.path.join(BASE, "config"), exist_ok=True) +os.environ["XDG_CONFIG_HOME"] = os.path.join(BASE, "config") +os.environ.pop("BILI_CONFIG_FILE", None) for k in ("BILLION_CONTEXT_ATTACH", "BILLION_CONTEXT_PROXY", "BILI_NATIVE_HERMES", "BILLION_CONTEXT_PLUGIN", "BILI_PROVIDER_REWRITES", "HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", @@ -326,6 +330,33 @@ def install_sidecar(bad): with open(os.path.join(PLUGIN_DIR, "bili.json"), "w") as f: json.dump({"proxyScript": script, "nodePath": os.environ["BC_NODE"]}, f) +# --- #2905 instance-record fixtures (identity fields discovery now checks) --- + +def fp_of(bad): + return hashlib.sha256(("process.exit(3);\n" if bad else "// dummy bili dist entry point\n").encode()).hexdigest() + +def inst_rec(bad, lane="hermes", token="tok", instance_id="drv-1", started_at=1): + rec = {"origin": ORIGIN, "pid": os.getpid(), "instanceId": instance_id, + "codeFingerprint": fp_of(bad), "host": "127.0.0.1", "passthrough": False, + "mitmDomains": [], "modelWindows": {}, "startedAt": started_at} + if lane is not None: + rec["lane"] = lane + if token is not None: + rec["launchToken"] = token + return rec + +def write_origin(rec): + sd = os.path.join(os.environ["XDG_STATE_HOME"], "billion-context") + os.makedirs(sd, exist_ok=True) + with open(os.path.join(sd, "proxy-origin"), "w") as f: + json.dump(rec, f) + +def write_registry(inst_id, rec): + rd = os.path.join(os.environ["XDG_STATE_HOME"], "billion-context", "instances") + os.makedirs(rd, exist_ok=True) + with open(os.path.join(rd, inst_id + ".json"), "w") as f: + json.dump(rec, f) + def load_module(): spec = importlib.util.spec_from_file_location("bc_hermes", os.path.join(PLUGIN_DIR, "__init__.py")) mod = importlib.util.module_from_spec(spec) @@ -352,12 +383,46 @@ mod._reset_for_test() ctx = FakeCtx() out = {"scenario": SCENARIO, "origin": ORIGIN} -if SCENARIO.startswith("discover-"): +if SCENARIO == "discover-foreign-lane": + install_sidecar(False) + write_origin(inst_rec(False, lane="dsh")) + mod.register(ctx) +elif SCENARIO == "discover-user-zone": + install_sidecar(True) + write_origin(inst_rec(True, lane=None, token=None)) + mod.register(ctx) +elif SCENARIO == "discover-lane-first": + install_sidecar(True) + write_origin(inst_rec(True, lane=None, token=None, instance_id="uz-new", started_at=999)) + write_registry("uz-new", inst_rec(True, lane=None, token=None, instance_id="uz-new", started_at=999)) + write_registry("hm-old", inst_rec(True, lane="hermes", token=None, instance_id="hm-old", started_at=1)) + mod.register(ctx) +elif SCENARIO == "discover-priority-config": + install_sidecar(True) + cfgf = os.path.join(BASE, "bili-config.json") + with open(cfgf, "w") as f: + json.dump({"native": {"attachLanePriority": ["dsh"]}}, f) + os.environ["BILI_CONFIG_FILE"] = cfgf + write_registry("dsh-1", inst_rec(True, lane="dsh", token=None, instance_id="dsh-1", started_at=5)) + mod.register(ctx) +elif SCENARIO == "spawn-env": + # .cjs: the tmp dir sits inside this repo ("type": "module" would treat .js as ESM) + script = os.path.join(BASE, "proxy.cjs") + with open(script, "w") as f: + f.write('require("fs").writeFileSync(require("path").join(process.env.XDG_STATE_HOME, "spawn-env.json"), ' + 'JSON.stringify({lane: process.env.BILI_LAUNCHER_LANE, token: !!process.env.BILI_LAUNCH_TOKEN, ' + 'parent: !!process.env.BILI_PARENT_PID}));\n') + with open(os.path.join(PLUGIN_DIR, "bili.json"), "w") as f: + json.dump({"proxyScript": script, "nodePath": os.environ["BC_NODE"]}, f) + mod.register(ctx) + try: + with open(os.path.join(os.environ["XDG_STATE_HOME"], "spawn-env.json")) as f: + out["spawn_env"] = json.load(f) + except Exception: + out["spawn_env"] = None +elif SCENARIO.startswith("discover-"): install_sidecar(SCENARIO == "discover-armed") - sd = os.path.join(os.environ["XDG_STATE_HOME"], "billion-context") - os.makedirs(sd, exist_ok=True) - with open(os.path.join(sd, "proxy-origin"), "w") as f: - json.dump({"origin": ORIGIN, "pid": os.getpid(), "launchToken": "tok"}, f) + write_origin(inst_rec(SCENARIO == "discover-armed")) mod.register(ctx) elif SCENARIO.startswith("gate-"): flag = SCENARIO[len("gate-"):] @@ -462,6 +527,7 @@ out.update({ "watcher_calls": RECORDED["watcher"], "health_probes": len(RECORDED["health"]), "refused": sorted(mod._state.get("refused") or []), + "instance_id": mod._state.get("instance_id"), }) server.shutdown() print(json.dumps(out)) @@ -485,6 +551,8 @@ interface DriverOut { watcher_calls: Array>; health_probes?: number; refused?: string[]; + instance_id?: string | null; + spawn_env?: { lane?: string | null; token?: boolean; parent?: boolean } | null; round1_none?: boolean; req_unmutated?: boolean; first_headers?: Record | null; @@ -640,6 +708,71 @@ describe("python plugin runtime (subprocess)", () => { assert.deepEqual(out!.refused, []); }); + // #2905: lane isolation — the reported bug was hermes riding a dsh-spawned instance + // (last writer of proxy-origin), whose MITM whitelist doesn't cover hermes's providers, + // so model traffic blind-tunneled and every tool call 404'd as an unknown conversation. + test("discover-foreign-lane: another lane's live instance is refused, not ridden", () => { + if (!PY) { + console.warn("skip: no python3/python interpreter on this machine (hermes requires Python 3.11+)"); + return; + } + const { out, err } = runDriver("discover-foreign-lane", { BC_HEALTH_WATCHDOG: "armed" }); + assert.ok(out, err); + assert.equal(out!.env_https_proxy, null, "never rode the dsh instance"); + assert.deepEqual(out!.refused, [out!.origin], "lane refusal recorded for operators"); + assert.deepEqual(out!.tools_registered, [], "spawn fallback failed (dummy sidecar) — inert, not attached"); + }); + + test("discover-user-zone: an unarmed manual daemon (the 8787 global) is a legitimate last-resort target (#1660 twin)", () => { + if (!PY) { + console.warn("skip: no python3/python interpreter on this machine (hermes requires Python 3.11+)"); + return; + } + const { out, err } = runDriver("discover-user-zone", { BC_HEALTH_WATCHDOG: "false" }); + assert.ok(out, err); + assert.equal(out!.env_https_proxy, out!.origin, "user zone is exempt from the lifecycle gate, like the TS lanes"); + assert.equal(out!.watcher_calls.length, 1); + assert.deepEqual(out!.refused, []); + }); + + test("discover-lane-first: own-lane instance beats a NEWER user-zone one; registry is scanned beyond the last-writer file", () => { + if (!PY) { + console.warn("skip: no python3/python interpreter on this machine (hermes requires Python 3.11+)"); + return; + } + const { out, err } = runDriver("discover-lane-first", { BC_HEALTH_WATCHDOG: "armed" }); + assert.ok(out, err); + assert.equal(out!.env_https_proxy, out!.origin); + assert.equal(out!.instance_id, "hm-old", "own lane pinned first regardless of recency — the 8787 global can no longer win by being newer"); + assert.deepEqual(out!.refused, []); + }); + + test("discover-priority-config: native.attachLanePriority opts in to riding a listed foreign lane", () => { + if (!PY) { + console.warn("skip: no python3/python interpreter on this machine (hermes requires Python 3.11+)"); + return; + } + const { out, err } = runDriver("discover-priority-config", { BC_HEALTH_WATCHDOG: "armed" }); + assert.ok(out, err); + assert.equal(out!.env_https_proxy, out!.origin, "listed foreign lane becomes attachable"); + assert.equal(out!.instance_id, "dsh-1"); + assert.deepEqual(out!.refused, []); + }); + + test("spawn-env: spawned proxies declare their lane (BILI_LAUNCHER_LANE=hermes)", () => { + if (!PY) { + console.warn("skip: no python3/python interpreter on this machine (hermes requires Python 3.11+)"); + return; + } + const { out, err } = runDriver("spawn-env"); + assert.ok(out, err); + assert.ok(out!.spawn_env, "sidecar observed the spawn env"); + assert.equal(out!.spawn_env!.lane, "hermes", "declared lane — other lanes can no longer ride this proxy"); + assert.equal(out!.spawn_env!.token, true); + assert.equal(out!.spawn_env!.parent, true); + assert.equal(out!.env_https_proxy, null, "dummy sidecar never serves — inert"); + }); + for (const [scenario, extraEnv] of [ ["gate-opt-out", { BILI_NATIVE_HERMES: "0" }], ["gate-plugin-0", { BILLION_CONTEXT_PLUGIN: "0" }], diff --git a/tests/launcher.test.ts b/tests/launcher.test.ts index 58af64f619..67262b5154 100644 --- a/tests/launcher.test.ts +++ b/tests/launcher.test.ts @@ -1773,6 +1773,101 @@ test("ensureProxyRunning: stale instance file still finds a live wildcard daemon } }); +// #2905: native.attachLanePriority lets an operator list FOREIGN lanes a hook may ride +// when no own-lane instance exists. Own lane always first; the user zone (manual +// `bili start`, the 8787 global) ALWAYS last; unlisted lanes stay non-attachable. +test("ensureProxyRunning: a listed foreign lane becomes attachable via attachLanePriority (#2905)", async () => { + const st = isoStateDir(); + try { + const D = liveRegistryInstance({ instanceId: "inst-D", origin: "http://127.0.0.1:8811", port: 8811, lane: "dsh", startedAt: Date.now() }); + registerInstanceAndWarn(D, () => {}); + let spawnCalls = 0; + const handle = await ensureProxyRunning( + { host: "127.0.0.1", port: 8787, passthrough: false, debug: false, lane: "pi" }, + { + spawnImpl: () => { + spawnCalls++; + return makeFakeChild(42480); + }, + fetchImpl: async () => ({ ok: true }), + fetchHealthInfo: async () => ({ ok: true, instanceId: "inst-D", watchdog: { armed: true } }), + // the bug shape: the last-writer file points at ANOTHER lane's proxy + readInstanceFile: () => D, + attachLanePriority: () => ["dsh"], + scriptPath: FP_SCRIPT, + }, + ); + assert.equal(spawnCalls, 0, "the listed foreign lane is ridden instead of spawning a third proxy"); + assert.equal(handle.attached, true); + assert.equal(handle.origin, D.origin); + } finally { + unregisterInstance("inst-D"); + st.restore(); + } +}); + +test("ensureProxyRunning: among listed foreign lanes, list position beats recency (#2905)", async () => { + const st = isoStateDir(); + try { + const O = liveRegistryInstance({ instanceId: "inst-O", origin: "http://127.0.0.1:8812", port: 8812, lane: "opencode", startedAt: Date.now() }); + const D = liveRegistryInstance({ instanceId: "inst-D2", origin: "http://127.0.0.1:8813", port: 8813, lane: "dsh", startedAt: Date.now() - 60_000 }); + registerInstanceAndWarn(O, () => {}); + registerInstanceAndWarn(D, () => {}); + let spawnCalls = 0; + const handle = await ensureProxyRunning( + { host: "127.0.0.1", port: 8787, passthrough: false, debug: false, lane: "pi" }, + { + spawnImpl: () => { + spawnCalls++; + return makeFakeChild(42481); + }, + fetchImpl: async () => ({ ok: true }), + fetchHealthInfo: async (origin) => ({ ok: true, instanceId: origin.endsWith("8812") ? "inst-O" : "inst-D2", watchdog: { armed: true } }), + readInstanceFile: () => O, + attachLanePriority: () => ["dsh", "opencode"], + scriptPath: FP_SCRIPT, + }, + ); + assert.equal(spawnCalls, 0); + assert.equal(handle.origin, D.origin, "earlier list position beats a newer later entry"); + } finally { + unregisterInstance("inst-O"); + unregisterInstance("inst-D2"); + st.restore(); + } +}); + +test("ensureProxyRunning: an UNLISTED foreign lane stays refused; the user zone remains the last-resort fallback (#2905)", async () => { + const st = isoStateDir(); + try { + const D = liveRegistryInstance({ instanceId: "inst-D3", origin: "http://127.0.0.1:8814", port: 8814, lane: "dsh", startedAt: Date.now() - 60_000 }); + const W = liveRegistryInstance({ instanceId: "inst-W2", origin: "http://127.0.0.1:8815", port: 8815, startedAt: Date.now() }); + registerInstanceAndWarn(D, () => {}); + registerInstanceAndWarn(W, () => {}); + let spawnCalls = 0; + const handle = await ensureProxyRunning( + { host: "127.0.0.1", port: 8787, passthrough: false, debug: false, lane: "pi" }, + { + spawnImpl: () => { + spawnCalls++; + return makeFakeChild(42482); + }, + fetchImpl: async () => ({ ok: true }), + fetchHealthInfo: async (origin) => ({ ok: true, instanceId: origin.endsWith("8814") ? "inst-D3" : "inst-W2", watchdog: { armed: true } }), + readInstanceFile: () => W, + attachLanePriority: () => [], + scriptPath: FP_SCRIPT, + }, + ); + assert.equal(spawnCalls, 0); + assert.equal(handle.origin, W.origin, "the 8787-style user zone rides LAST — never the unlisted dsh lane"); + } finally { + unregisterInstance("inst-D3"); + unregisterInstance("inst-W2"); + st.restore(); + } +}); + // #964: a strictPort client dials a STATIC url — attaching to a healthy proxy // on a DIFFERENT port would strand every request. The starter-wait path must // apply the same port rule as the fast path; before pickAttachable it only From 0835f42af9a8a8237998230e2ca51df41d452d50 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Mon, 12 Oct 2026 18:25:43 +0800 Subject: [PATCH 3/5] docs: document native.attachLanePriority + lane-aware attach (#2905) CONFIGURATION.md en/zh (summary table + native section), README en/zh port note, CLIENTS en/zh hermes lifecycle bullet, website config reference. New key: native.attachLanePriority (string[], file-only, default [] = own lane -> user zone -> spawn). --- CLIENTS.md | 8 ++++++-- CLIENTS.zh-CN.md | 2 +- CONFIGURATION.md | 6 ++++-- CONFIGURATION.zh-CN.md | 6 ++++-- README.md | 6 +++++- README.zh-CN.md | 2 +- website/config-reference/server.yaml | 7 +++++++ 7 files changed, 28 insertions(+), 9 deletions(-) diff --git a/CLIENTS.md b/CLIENTS.md index 089afb07b7..d6e11ff35f 100644 --- a/CLIENTS.md +++ b/CLIENTS.md @@ -202,8 +202,12 @@ pure-stdlib Python module shipped inside the npm package: the same command is printed instead). Start a new hermes session to activate. Remove with `bili plugin remove hermes`; refresh with `bili plugin update hermes` after a global update. -- **Lifecycle:** at load the plugin attaches to a healthy running proxy or - spawns its own on an ephemeral port (parent-pid watchdog tears it down when +- **Lifecycle:** at load the plugin attaches to a healthy running proxy — + lane-aware since #2905: its own hermes-lane instance first, another + declared lane's instance NEVER (list it in `native.attachLanePriority` to + opt in), the 8787 user-zone daemon as last-resort fallback — or spawns its + own on an ephemeral port (declared `lane: hermes` so no other lane can ride + it; parent-pid watchdog tears it down when hermes exits; concurrent starts arbitrate through the same starting-marker protocol the launcher uses). Only once the proxy is verified healthy does it point hermes' httpx stack at it via `HTTPS_PROXY` / `https_proxy` + diff --git a/CLIENTS.zh-CN.md b/CLIENTS.zh-CN.md index e6f871a7d6..040ebe9072 100644 --- a/CLIENTS.zh-CN.md +++ b/CLIENTS.zh-CN.md @@ -85,7 +85,7 @@ fork 继承同一面;Antigravity 自带用户插件系统 —— `plugins/ 三种对齐模式:`bili hermes`(启动器,证书 MITM —— README 快速上手 方式 2)、`/bili/` URL 前缀、原生插件模式(`bili plugin install hermes`,#958)。hermes CLI agent 的插件 API 只有 Python(`desktop/plugin.js` SDK 属于另一个 Desktop app),所以原生插件是随 npm 包分发的一个纯标准库 Python 模块: - **安装:** `bili plugin install hermes` 把 `plugin.yaml` + `__init__.py` 拷进 `~/.hermes/plugins/billion-context/`,写一个机器自管的 `bili.json` sidecar(指向全局 bili 安装的 `dist/index.js` + node 路径),并经 hermes 自己的通道启用插件(`hermes plugins enable billion-context` —— CLI 不在 PATH 上时改为打印同一条命令)。新开一个 hermes 会话生效。卸载:`bili plugin remove hermes`;全局更新后刷新:`bili plugin update hermes`。 -- **生命周期:** 加载时插件先附着到健康的运行中代理,否则在临时端口自拉起(父进程 pid 看门狗在 hermes 退出时收掉它;并发启动走与启动器相同的 starting-marker 仲裁协议)。只有代理确认健康后,才用 `HTTPS_PROXY` / `https_proxy` + `SSL_CERT_FILE`(bili 组合 CA bundle —— 当前 hermes 经此解析环境信任;`HERMES_CA_BUNDLE` 保留给旧版本)把 hermes 的 httpx 栈指向它 —— **从不改动** `~/.hermes/config.yaml`。provider 的 https 域名从 hermes 配置读出并加入 MITM 白名单;其余域名与启动器模式一样盲隧道。拉不出健康代理时插件静默退场,流量直连(不压缩、无死端口)。 +- **生命周期:** 加载时插件先附着到健康的运行中代理 —— #2905 起按泳道:本 hermes lane 的实例第一,其他已声明 lane 的实例绝不 attach(要搭车需在 `native.attachLanePriority` 里列出),8787 用户区守护是最后兜底 —— 否则在临时端口自拉起(声明 `lane: hermes`,别的泳道骑不上来;父进程 pid 看门狗在 hermes 退出时收掉它;并发启动走与启动器相同的 starting-marker 仲裁协议)。只有代理确认健康后,才用 `HTTPS_PROXY` / `https_proxy` + `SSL_CERT_FILE`(bili 组合 CA bundle —— 当前 hermes 经此解析环境信任;`HERMES_CA_BUNDLE` 保留给旧版本)把 hermes 的 httpx 栈指向它 —— **从不改动** `~/.hermes/config.yaml`。provider 的 https 域名从 hermes 配置读出并加入 MITM 白名单;其余域名与启动器模式一样盲隧道。拉不出健康代理时插件静默退场,流量直连(不压缩、无死端口)。 - **Plugin 模式盖章:** `llm_request` 中间件打 `x-bili-plugin: hermes` + 会话 id(= hermes session id,gateway 多会话安全)+ 模型,已知后再加 `x-bili-plugin-max-output` —— 且只在 ACP 工具已对着存活代理清单注册完之后;第一轮走 wire 模式。`pre_api_request` hook 捕获生效的 `max_tokens`,把 runtime-info(模型 + 最大输出)推给代理。`compress` / `decompress` / `acp_status` 注册为真正的 hermes 工具,由代理既有的插件端点提供。 - **已知局限:** 走 hermes Codex-wire 传输发出的请求可能丢掉逐请求头面,这类配置在该传输暴露头之前停留在 wire 模式。`BILLION_CONTEXT_PROXY` 已设置(启动器管着代理)或定义了 `BILI_PROVIDER_REWRITES` 时插件整体退场。退出开关:`BILI_NATIVE_HERMES=0`。 diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 707b6472c9..e6120f8eb0 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -110,6 +110,7 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `resign` | scheme → { enabled?, passthrough?, credentialRef? } | {} (armed; built-in scheme sdk-hmac-sha256) | BILI_RESIGN, BILI_RESIGN_PASSTHROUGH, BILI_CODEARTS_REF, BILI_RESIGN_BENEFIT | Re-sign arm keyed by Authorization scheme: signed model requests tunnel with every egress body re-signed; unresignable requests are refused locally 403 unless passthrough opts that scheme into verbatim forwarding. | | `promptCache.routing` | "auto" \| "enabled" \| "disabled" | auto | ACP_PROMPT_CACHE_ROUTING | Prompt-cache routing posture for cache-aware lane selection. | | `native.attachExternal` | boolean | false | BILI_NATIVE_ATTACH_EXTERNAL | Let launcher-less native plugins attach to an external (lane'd, unarmed) daemon instead of spawning their own. | +| `native.attachLanePriority` | string[] | [] (own lane → user zone → spawn) | — (file only) | Ordered list of FOREIGN lane names a lane may ride when no own-lane instance exists (#2905). Own lane always wins first; the user zone (manual `bili start`, the 8787 global) is ALWAYS last; unlisted lanes stay non-attachable. | | `claude.nativePort` | number | unset (lane sticky zone port) | BILI_CLAUDE_NATIVE_PORT | Exact port pin for the claude native lane's hook-spawned proxy (strict-port: squatters are refused loudly). | | `pi.subagents` | object \| boolean | {} (acp_delegate enabled with package defaults) | PI_ACP_DELEGATE_FORCE_ENABLE, PI_ACP_DELEGATE_MAX_DEPTH, PI_ACP_DELEGATE_SYNC_TIMEOUT_MINUTES, PI_ACP_DELEGATE_IDLE_TIMEOUT_MINUTES, PI_ACP_DELEGATE_ASYNC_TIMEOUT_MINUTES, PI_ACP_DELEGATE_MAX_CONCURRENT | Built-in pi-lane sub-agents (acp_delegate) surface, #2230 config-home. The pi.subagents section of billion-context.json owns the delegate config; the four acp.json keys (delegate/delegatePrompt/displayUsage/debug) are a deprecated fallback read only while the section is absent. prompt replaces delegatePrompt; debug is scoped to the sub-agent subsystem. Boolean shorthand subagents: false disables the whole surface. Full field table: the pi section in CONFIGURATION.md. | @@ -694,10 +695,11 @@ Top-level keys that control how the proxy listens and behaves globally. ### `native` -- **Type:** `{ attachExternal?: boolean }` -- **Default:** `{}` (attach gate closed for lane'd instances) +- **Type:** `{ attachExternal?: boolean; attachLanePriority?: string[] }` +- **Default:** `{}` (attach gate closed for lane'd instances; no foreign lanes listed) - **Status:** ACTIVE - **Description:** Native-hook attach policy (#1335). Lane'd native hooks attach to a running proxy only when it reports an armed session-lifecycle watchdog; an unarmed lane'd listener (a crashed session's orphan) is refused loudly instead of being silently ridden — a manually started `bili start` daemon (no lane) is user-zone and attachable by default (#1660). Set `attachExternal: true` to attach to *lane'd* unarmed listeners anyway (any code/lane-compatible listener becomes attachable regardless of watchdog state, including pre-#1330 builds). Overridden by `BILI_NATIVE_ATTACH_EXTERNAL` (`1` opens the gate even over a closed file; `0` closes it even over a permissive file). Full mechanics: [TECHNICAL-NOTES.md](TECHNICAL-NOTES.md#proxy-reuse-and-the-attach-gate-1225-1335-1232-1660). + - `attachLanePriority` (#2905, file-only, no env var): ordered list of FOREIGN lane names this hook may ride when no own-lane instance exists. Attach priority is then: own lane first → listed lanes in list order → user zone ALWAYS last. Unlisted lanes stay non-attachable (lane isolation #1225/#1232). Default `[]` = own lane → user zone → spawn. Opt-in by design: a foreign instance's MITM whitelist may not cover your providers, in which case model traffic would blind-tunnel and every compression tool call would fail. Applies to every lane-aware attach site (launcher lanes + the hermes native plugin's discovery). Example: `"native": { "attachLanePriority": ["dsh"] }`. ### `pi` diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index b7221b328c..15dd48d590 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -110,6 +110,7 @@ | `resign` | scheme → { enabled?, passthrough?, credentialRef? } | {} (armed; built-in scheme sdk-hmac-sha256) | BILI_RESIGN, BILI_RESIGN_PASSTHROUGH, BILI_CODEARTS_REF, BILI_RESIGN_BENEFIT | 按 Authorization 方案键控的重签名臂:可重签名的模型请求全程重签转发;无法重签的请求本地 403 拒绝,除非该方案经 passthrough 选择原文透传。 | | `promptCache.routing` | "auto" \| "enabled" \| "disabled" | auto | ACP_PROMPT_CACHE_ROUTING | 面向缓存感知路由选择的提示词缓存路由姿态。 | | `native.attachExternal` | boolean | false | BILI_NATIVE_ATTACH_EXTERNAL | 允许无启动器的原生插件挂到外部(车道化、未武装看门狗)守护进程,而不是自行派生。 | +| `native.attachLanePriority` | string[] | [](本 lane → 用户区 → spawn) | —(仅配置文件) | 本 lane 没有自己的实例时可搭车的**外部 lane** 名字有序列表(#2905)。本 lane 永远第一;用户区(手动 `bili start`、8787 全局)永远最后;未列出的 lane 仍不可挂。 | | `claude.nativePort` | number | unset (lane sticky zone port) | BILI_CLAUDE_NATIVE_PORT | claude 原生车道钩子派生代理的精确端口钉死(严格端口:被占用时响亮拒绝而非跳端口)。 | | `pi.subagents` | object \| boolean | {} (acp_delegate enabled with package defaults) | PI_ACP_DELEGATE_FORCE_ENABLE, PI_ACP_DELEGATE_MAX_DEPTH, PI_ACP_DELEGATE_SYNC_TIMEOUT_MINUTES, PI_ACP_DELEGATE_IDLE_TIMEOUT_MINUTES, PI_ACP_DELEGATE_ASYNC_TIMEOUT_MINUTES, PI_ACP_DELEGATE_MAX_CONCURRENT | 内置 pi lane 子代理(acp_delegate)面(#2230 配置搬家)。billion-context.json 的 pi.subagents 段拥有 delegate 配置;acp.json 四键(delegate/delegatePrompt/displayUsage/debug)为已废弃回退源,仅段缺失时读取。prompt 取代 delegatePrompt;debug 限定子代理子系统。布尔简写 subagents: false 整体关闭。完整字段表见 CONFIGURATION.md 的 pi 段。 | @@ -694,10 +695,11 @@ ### `native` -- **类型:** `{ attachExternal?: boolean }` -- **默认值:** `{}`(lane'd 实例的 attach 门关闭) +- **类型:** `{ attachExternal?: boolean; attachLanePriority?: string[] }` +- **默认值:** `{}`(lane'd 实例的 attach 门关闭;无外部 lane 列表) - **状态:** ACTIVE - **说明:** native hook attach 策略(#1335)。lane'd native hook 仅在运行中的代理报告了已武装的会话生命周期看门狗时才 attach;未武装的 lane'd listener(崩溃会话的孤儿)被大声拒收而不是被静默搭车 —— 手动启动的 `bili start` 守护(无 lane)属用户区,默认可 attach(#1660)。设 `attachExternal: true` 仍可 attach 到 *lane'd* 未武装 listener(任何代码/lane 兼容的 listener 均可 attach,不论看门狗状态,包括 pre-#1330 构建)。可由 `BILI_NATIVE_ATTACH_EXTERNAL` 覆盖(`1` 即使文件关闭也开门;`0` 即使文件宽松也关门)。完整机制见 [TECHNICAL-NOTES.md](TECHNICAL-NOTES.md#proxy-reuse-and-the-attach-gate-1225-1335-1232-1660)。 + - `attachLanePriority`(#2905,仅配置文件,无 env):本 hook 在没有自己 lane 的实例时可搭车的**外部 lane** 名字有序列表。attach 优先级为:本 lane 第一 → 按列表顺序的外部 lane → 用户区**永远最后**。未列出的 lane 仍不可挂(泳道隔离 #1225/#1232)。默认 `[]` = 本 lane → 用户区 → spawn。刻意做成显式 opt-in:外部实例的 MITM 白名单未必覆盖你的 provider,否则模型流量会盲隧道、所有压缩工具调用都会失败。对所有 lane 感知的 attach 点生效(launcher 各 lane + hermes 原生插件的发现路径)。示例:`"native": { "attachLanePriority": ["dsh"] }`。 ### `pi` diff --git a/README.md b/README.md index a33cad53d8..7b8ad2a0ba 100644 --- a/README.md +++ b/README.md @@ -169,7 +169,11 @@ Ports, briefly (#1660): `bili start` (manual) owns `8787`. Everything a lane spawns for you (native hooks, launcher lanes) lives in a separate self-managed zone starting at `18787` — collisions hop +1 and each lane remembers its drift, so zero-config installs never fight you for a port, -and a deliberate `bili start` daemon is attached by default. An +and a deliberate `bili start` daemon is attached by default. Attach is +lane-aware (#2905): a hook rides its own lane's instance first, NEVER +another declared lane's — except lanes you list in +`native.attachLanePriority` — and the 8787 user-zone daemon stays the +LAST-resort fallback. An upgrade-restart that finds the previous build still draining on the lane's port waits for it to release (up to 5s) and rebinds the SAME port instead of drifting (#1723); only a genuinely occupied port hops +1 — and that hop is diff --git a/README.zh-CN.md b/README.zh-CN.md index 058059f90e..842c966831 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -155,7 +155,7 @@ npm install -g billion-context --prefix=~/.local 三种方式背后的机制细节(插件生命周期、runtime-info 协议、注入优先级)见 [TECHNICAL-NOTES.zh-CN.md](TECHNICAL-NOTES.zh-CN.md)。 -端口,一句话(#1660):`bili start`(手工)拥有 `8787`;lane 替你拉起的一切(原生 hook、启动器 lane)住在独立的自管端口区,从 `18787` 起 —— 碰撞 +1 跳口、每个 lane 记住自己的漂移,零配置安装永不抢端口,刻意常驻的 `bili start` 守护进程则默认被附着。升级重启时若旧版本还在该 lane 端口上排水,会最多等 5 秒让它释放并复用同一端口,而不是漂移(#1723);只有真正被占用的端口才 +1 跳口 —— 且这种跳口现在会大声打 warn。 +端口,一句话(#1660):`bili start`(手工)拥有 `8787`;lane 替你拉起的一切(原生 hook、启动器 lane)住在独立的自管端口区,从 `18787` 起 —— 碰撞 +1 跳口、每个 lane 记住自己的漂移,零配置安装永不抢端口,刻意常驻的 `bili start` 守护进程则默认被附着。Attach 按泳道感知(#2905):hook 先骑自己 lane 的实例,绝不骑其他已声明 lane —— 除非在 `native.attachLanePriority` 里显式列出 —— 8787 用户区守护永远是最后兜底。升级重启时若旧版本还在该 lane 端口上排水,会最多等 5 秒让它释放并复用同一端口,而不是漂移(#1723);只有真正被占用的端口才 +1 跳口 —— 且这种跳口现在会大声打 warn。 ### 方式 1 —— 原生插件(native,`bili plugin install pi` / `omp` / `opencode` / `dsh` / `kimi` / `hermes` / `zcode`) diff --git a/website/config-reference/server.yaml b/website/config-reference/server.yaml index 20b34d1e10..f4ed3d46b4 100644 --- a/website/config-reference/server.yaml +++ b/website/config-reference/server.yaml @@ -342,6 +342,13 @@ entries: desc_zh: "允许无启动器的原生插件挂到外部(车道化、未武装看门狗)守护进程,而不是自行派生。" site_en: "native.attachExternal — let launcher-less native plugins attach to an external daemon (off by default)." site_zh: "native.attachExternal —— 允许无启动器的原生插件挂到外部守护进程(默认关)。" + - key: native.attachLanePriority + type: "string[]" + default: "[] (own lane → user zone → spawn)" + env: [] + group: behavior + desc_en: "Ordered list of FOREIGN lane names a lane may ride when no own-lane instance exists (#2905). Own lane always wins first; the user zone (manual `bili start`, the 8787 global) is ALWAYS last; unlisted lanes stay non-attachable. File-only, no env var." + desc_zh: "本 lane 没有自己的实例时可搭车的外部 lane 名字有序列表(#2905)。本 lane 永远第一;用户区(手动 `bili start`、8787 全局)永远最后;未列出的 lane 仍不可挂。仅配置文件,无 env。" - key: claude.nativePort type: number default: "unset (lane sticky zone port)" From 5558f6a671fe2020bd9e624f379724f17b1e5a03 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Mon, 12 Oct 2026 18:35:30 +0800 Subject: [PATCH 4/5] fix: config-docs seed backtick violation + regenerate canonical rows (#2905) check-coverage forbids backticks in desc_en/desc_zh (tools/gen-config-docs.mjs:118); remove them from the native.attachLanePriority seed and take the generator's canonical table rows instead of the hand-edited ones (docs-sync drift). --- CONFIGURATION.md | 2 +- CONFIGURATION.zh-CN.md | 2 +- website/config-reference/server.yaml | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index e6120f8eb0..2699f483fa 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -110,7 +110,7 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `resign` | scheme → { enabled?, passthrough?, credentialRef? } | {} (armed; built-in scheme sdk-hmac-sha256) | BILI_RESIGN, BILI_RESIGN_PASSTHROUGH, BILI_CODEARTS_REF, BILI_RESIGN_BENEFIT | Re-sign arm keyed by Authorization scheme: signed model requests tunnel with every egress body re-signed; unresignable requests are refused locally 403 unless passthrough opts that scheme into verbatim forwarding. | | `promptCache.routing` | "auto" \| "enabled" \| "disabled" | auto | ACP_PROMPT_CACHE_ROUTING | Prompt-cache routing posture for cache-aware lane selection. | | `native.attachExternal` | boolean | false | BILI_NATIVE_ATTACH_EXTERNAL | Let launcher-less native plugins attach to an external (lane'd, unarmed) daemon instead of spawning their own. | -| `native.attachLanePriority` | string[] | [] (own lane → user zone → spawn) | — (file only) | Ordered list of FOREIGN lane names a lane may ride when no own-lane instance exists (#2905). Own lane always wins first; the user zone (manual `bili start`, the 8787 global) is ALWAYS last; unlisted lanes stay non-attachable. | +| `native.attachLanePriority` | string[] | [] (own lane → user zone → spawn) | — | Ordered list of FOREIGN lane names a lane may ride when no own-lane instance exists (#2905). Own lane always wins first; the user zone (manual bili start, the 8787 global) is ALWAYS last; unlisted lanes stay non-attachable. File-only, no env var. | | `claude.nativePort` | number | unset (lane sticky zone port) | BILI_CLAUDE_NATIVE_PORT | Exact port pin for the claude native lane's hook-spawned proxy (strict-port: squatters are refused loudly). | | `pi.subagents` | object \| boolean | {} (acp_delegate enabled with package defaults) | PI_ACP_DELEGATE_FORCE_ENABLE, PI_ACP_DELEGATE_MAX_DEPTH, PI_ACP_DELEGATE_SYNC_TIMEOUT_MINUTES, PI_ACP_DELEGATE_IDLE_TIMEOUT_MINUTES, PI_ACP_DELEGATE_ASYNC_TIMEOUT_MINUTES, PI_ACP_DELEGATE_MAX_CONCURRENT | Built-in pi-lane sub-agents (acp_delegate) surface, #2230 config-home. The pi.subagents section of billion-context.json owns the delegate config; the four acp.json keys (delegate/delegatePrompt/displayUsage/debug) are a deprecated fallback read only while the section is absent. prompt replaces delegatePrompt; debug is scoped to the sub-agent subsystem. Boolean shorthand subagents: false disables the whole surface. Full field table: the pi section in CONFIGURATION.md. | diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 15dd48d590..9342cabe96 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -110,7 +110,7 @@ | `resign` | scheme → { enabled?, passthrough?, credentialRef? } | {} (armed; built-in scheme sdk-hmac-sha256) | BILI_RESIGN, BILI_RESIGN_PASSTHROUGH, BILI_CODEARTS_REF, BILI_RESIGN_BENEFIT | 按 Authorization 方案键控的重签名臂:可重签名的模型请求全程重签转发;无法重签的请求本地 403 拒绝,除非该方案经 passthrough 选择原文透传。 | | `promptCache.routing` | "auto" \| "enabled" \| "disabled" | auto | ACP_PROMPT_CACHE_ROUTING | 面向缓存感知路由选择的提示词缓存路由姿态。 | | `native.attachExternal` | boolean | false | BILI_NATIVE_ATTACH_EXTERNAL | 允许无启动器的原生插件挂到外部(车道化、未武装看门狗)守护进程,而不是自行派生。 | -| `native.attachLanePriority` | string[] | [](本 lane → 用户区 → spawn) | —(仅配置文件) | 本 lane 没有自己的实例时可搭车的**外部 lane** 名字有序列表(#2905)。本 lane 永远第一;用户区(手动 `bili start`、8787 全局)永远最后;未列出的 lane 仍不可挂。 | +| `native.attachLanePriority` | string[] | [] (own lane → user zone → spawn) | — | 本 lane 没有自己的实例时可搭车的外部 lane 名字有序列表(#2905)。本 lane 永远第一;用户区(手动 bili start、8787 全局)永远最后;未列出的 lane 仍不可挂。仅配置文件,无 env。 | | `claude.nativePort` | number | unset (lane sticky zone port) | BILI_CLAUDE_NATIVE_PORT | claude 原生车道钩子派生代理的精确端口钉死(严格端口:被占用时响亮拒绝而非跳端口)。 | | `pi.subagents` | object \| boolean | {} (acp_delegate enabled with package defaults) | PI_ACP_DELEGATE_FORCE_ENABLE, PI_ACP_DELEGATE_MAX_DEPTH, PI_ACP_DELEGATE_SYNC_TIMEOUT_MINUTES, PI_ACP_DELEGATE_IDLE_TIMEOUT_MINUTES, PI_ACP_DELEGATE_ASYNC_TIMEOUT_MINUTES, PI_ACP_DELEGATE_MAX_CONCURRENT | 内置 pi lane 子代理(acp_delegate)面(#2230 配置搬家)。billion-context.json 的 pi.subagents 段拥有 delegate 配置;acp.json 四键(delegate/delegatePrompt/displayUsage/debug)为已废弃回退源,仅段缺失时读取。prompt 取代 delegatePrompt;debug 限定子代理子系统。布尔简写 subagents: false 整体关闭。完整字段表见 CONFIGURATION.md 的 pi 段。 | diff --git a/website/config-reference/server.yaml b/website/config-reference/server.yaml index f4ed3d46b4..f5c5bfbae7 100644 --- a/website/config-reference/server.yaml +++ b/website/config-reference/server.yaml @@ -347,8 +347,8 @@ entries: default: "[] (own lane → user zone → spawn)" env: [] group: behavior - desc_en: "Ordered list of FOREIGN lane names a lane may ride when no own-lane instance exists (#2905). Own lane always wins first; the user zone (manual `bili start`, the 8787 global) is ALWAYS last; unlisted lanes stay non-attachable. File-only, no env var." - desc_zh: "本 lane 没有自己的实例时可搭车的外部 lane 名字有序列表(#2905)。本 lane 永远第一;用户区(手动 `bili start`、8787 全局)永远最后;未列出的 lane 仍不可挂。仅配置文件,无 env。" + desc_en: "Ordered list of FOREIGN lane names a lane may ride when no own-lane instance exists (#2905). Own lane always wins first; the user zone (manual bili start, the 8787 global) is ALWAYS last; unlisted lanes stay non-attachable. File-only, no env var." + desc_zh: "本 lane 没有自己的实例时可搭车的外部 lane 名字有序列表(#2905)。本 lane 永远第一;用户区(手动 bili start、8787 全局)永远最后;未列出的 lane 仍不可挂。仅配置文件,无 env。" - key: claude.nativePort type: number default: "unset (lane sticky zone port)" From eed86e7c1ff9322e75fb8130fbc94327f26dfcff Mon Sep 17 00:00:00 2001 From: ework-agent Date: Mon, 12 Oct 2026 18:57:31 +0800 Subject: [PATCH 5/5] =?UTF-8?q?fix(test):=20write=20hermes=20sidecar=20fix?= =?UTF-8?q?ture=20bytes=20binary=20=E2=80=94=20Windows=20CRLF=20desynced?= =?UTF-8?q?=20the=20code=20fingerprint=20(#2905)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit install_sidecar used text-mode open("w"): on Windows \n becomes \r\n on disk, so the sha256 discovery hashes (real file bytes) never matched fp_of() (LF constant) and every candidate was refused pre-probe — all discover-* scenarios inert on windows-latest. Binary write makes on-disk bytes equal the fixture hash on every platform. --- tests/hermes-native.test.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/hermes-native.test.ts b/tests/hermes-native.test.ts index 4271a6a0f9..8a526c421b 100644 --- a/tests/hermes-native.test.ts +++ b/tests/hermes-native.test.ts @@ -325,8 +325,10 @@ shutil.copyfile(os.path.join(os.environ["BC_PLUGIN_SRC"], "__init__.py"), os.pat def install_sidecar(bad): script = os.path.join(BASE, "proxy.js") - with open(script, "w") as f: - f.write("process.exit(3);\n" if bad else "// dummy bili dist entry point\n") + # binary write: text mode would CRLF-convert on Windows and desync the + # on-disk bytes from fp_of(), which discovery hashes (#2905 CI windows) + with open(script, "wb") as f: + f.write(("process.exit(3);\n" if bad else "// dummy bili dist entry point\n").encode()) with open(os.path.join(PLUGIN_DIR, "bili.json"), "w") as f: json.dump({"proxyScript": script, "nodePath": os.environ["BC_NODE"]}, f)