Skip to content
Merged
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
2 changes: 1 addition & 1 deletion dsh.bundle.patch.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
# the loader resolves `name` from the profile's node_modules.
- insert:
- id: bili-native
name: billion-context/dsh
name: billion-context
- id: compaction-basic
config:
auto: false
9 changes: 7 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
"type": "module",
"main": "dist/index.js",
"exports": {
".": "./dist/index.js",
".": "./dist/agent/dsh-native.js",
"./server": "./dist/agent/opencode-native.js",
"./dsh": "./dist/agent/dsh-native.js"
"./dsh": "./dist/agent/dsh-native.js",
"./dsh/package.json": "./package.json",
"./client": "./dist/agent/dsh-native-client.js"
},
"bin": {
"bili": "./dist/index.js",
Expand Down Expand Up @@ -90,6 +92,9 @@
"dsh": {
"bundle": {
"patch": "./dsh.bundle.patch.yml"
},
"client": {
"platform": "web"
}
},
"optionalDependencies": {
Expand Down
7 changes: 7 additions & 0 deletions src/agent/dsh-native-client-react-shim.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// #1590: ambient surface of "react" for the dsh client bundle. The real
// module arrives at runtime through dsh's browser module system (the
// factory `require` of the __ModuleLoader__ wrapper) and is marked external
// in the client tsup build — no react devDependency is installed.
declare module "react" {
export function createElement(type: string, props: Record<string, unknown> | null, ...children: unknown[]): unknown;
}
102 changes: 102 additions & 0 deletions src/agent/dsh-native-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// #1590: browser half of the dsh dual-face plugin (dsh.client). The tsup
// build wraps this CJS body in window.__ModuleLoader__.load({id, factory}) —
// two load-bearing invariants invisible from this file alone: the id MUST
// equal the loader entry name the scanner keys its graph row by ("loaded
// without registering" otherwise), and the factory's `require` resolves only
// through dsh's module system, so react is the sole permitted external. The
// host half (dsh-native.ts) injects globalThis.__BILI__ = {origin} into the
// web index; when absent the entry degrades to a hint instead of a dead link.

import { createElement } from "react";

type Dict = Record<string, string>;

type SlotOptions = { name: string; id: string; order: number; label: () => string; locale: string };

type ClientContext = {
effect: (fn: () => void | (() => void), label?: string) => void;
locale: {
register: (ns: string, dict: { zh: Dict; en: Dict }) => void;
bind: (ns: string) => (key: string) => string;
};
slots: {
inject: (slot: string, provide: () => void) => void;
register: (options: SlotOptions, component: (props: Record<string, unknown>) => unknown) => unknown;
};
};

export const inject = ["slots", "locale"];

const NS = "bili";

const zh: Dict = {
"nav": "bili设置",
"title": "billion-context 压缩代理",
"open": "打开 Web UI",
"hint": "查看压缩状态、会话与上下文窗口。",
"degraded": "当前 dsh 进程未绑定 bili 代理(未经 bili dsh 启动,或代理尚未就绪)——先运行 /acp,或改用 bili dsh 启动。",
};

const en: Dict = {
"nav": "bili",
"title": "billion-context compression proxy",
"open": "Open Web UI",
"hint": "Inspect compression status, sessions and context windows.",
"degraded": "This dsh process is not bound to a bili proxy (not launched via bili dsh, or the proxy is not up yet) — run /acp first, or launch through bili dsh.",
};

function readOrigin(): string | undefined {
const g = globalThis as { __BILI__?: { origin?: unknown } };
const origin = g.__BILI__?.origin;
return typeof origin === "string" && origin.length > 0 ? origin : undefined;
}

function openExternal(url: string): void {
const w = globalThis as { open?: (url: string, target?: string, features?: string) => unknown };
if (typeof w.open === "function") w.open(url, "_blank", "noopener,noreferrer");
}

export function apply(ctx: ClientContext): void {
const zhDict = zh;
const enDict = en;
ctx.effect(
() => ctx.locale.register(NS, { zh: zhDict, en: enDict }),
"bili: dictionaries",
);
const t = ctx.locale.bind(NS);
const section = (): unknown => {
const origin = readOrigin();
return createElement(
"div",
{ style: { display: "flex", flexDirection: "column", gap: 12, padding: "20px 8px" } },
createElement("h3", { style: { margin: 0, fontSize: 16, fontWeight: 600 } }, t("title")),
origin === undefined
? createElement("p", { style: { margin: 0, opacity: 0.7, lineHeight: 1.6 } }, t("degraded"))
: createElement(
"button",
{
type: "button",
onClick: () => openExternal(`${origin}/__bili/`),
style: {
alignSelf: "flex-start",
cursor: "pointer",
borderRadius: 8,
border: "1px solid rgba(127,127,127,0.4)",
background: "transparent",
color: "inherit",
fontFamily: "inherit",
fontSize: 14,
lineHeight: "22px",
padding: "7px 16px",
},
},
`${t("open")}(${origin})`,
),
createElement("p", { style: { margin: 0, opacity: 0.7, fontSize: 13, lineHeight: 1.6 } }, t("hint")),
);
};
ctx.slots.inject(
"settings.section",
() => ctx.slots.register({ name: "settings.section", id: "bili", order: 100, label: () => t("nav"), locale: NS }, section),
);
}
16 changes: 16 additions & 0 deletions src/agent/dsh-native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ type PluginContext = {
llm?: { resolveModelInfo?: (provider: string, model: string, signal?: AbortSignal) => Promise<{ context?: { contextWindow?: number }; defaultMaxTokens?: number } | undefined> };
agentDefaultModel?: { currentSelection?: () => { provider?: string; model?: string } | undefined };
inject?: (deps: readonly string[], callback: (sub: PluginContext) => void) => unknown;
// #1590: host event bus (web-profile hosts only) — webserver/index-inject
// gathers per-startup rows for the web index; we push the __BILI__ global
// the dsh-native-client.js settings entry reads.
on?: (event: string, listener: (table: Array<{ kind: string; name?: string; value?: unknown }>) => void) => void;
};

/** Decides whether the native bootstrap should run in this process. */
Expand Down Expand Up @@ -556,6 +560,18 @@ export function apply(ctx: PluginContext): void {
const plan = planNativeDsh(process.env);
if (plan.mode === "off") return;

// #1590: the dsh web-profile settings panel shows a "bili设置" entry
// (dsh-native-client.js) that opens this proxy's Web UI. The origin is
// only published while known — attach mode binds register.base
// synchronously below; spawn mode binds it after bootstrap, so at
// startup-time index collection that entry degrades to a hint instead of
// a stale link.
ctx.on?.("webserver/index-inject", (table) => {
const envOrigin = process.env.BILLION_CONTEXT_PROXY?.trim();
const origin = register.base ?? (envOrigin !== undefined && envOrigin.length > 0 ? envOrigin : undefined);
if (origin !== undefined) table.push({ kind: "global", name: "__BILI__", value: { origin } });
});

if (plan.mode === "attach") {
const attachOrigin = plan.attachOrigin;
state.attach = true;
Expand Down
91 changes: 88 additions & 3 deletions src/launcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import fs from "node:fs";
import net from "node:net";
import os from "node:os";
import path from "node:path";
import { createRequire } from "node:module";
import { pathToFileURL } from "node:url";
import { execFileSync, spawn, type StdioOptions } from "node:child_process";
import { DEFAULT_MITM_DOMAINS } from "./mitm.js";
Expand Down Expand Up @@ -2163,8 +2164,78 @@ export function prepareCodexHome(codexHome: string, origin: string, conversation
* plugin is injected even when the user has no custom providers (pure
* built-in deepseek route). Returns the patch file path (undefined when it
* could not be written — dsh then just boots without the plugin). */
export function writeDshAcpPatch(dshHome: string): string | undefined {
const pluginUrl = pathToFileURL(selfDistFile("agent/dsh-native.js")).href;
const DSH_BARE_ENTRY = "billion-context";

/** #1590: shim package making the bare `billion-context` root resolvable from the two
* anchors dsh uses at runtime, without touching dsh's own tree:
* - the ESM host import is anchored at the active PROFILE dir, whose walk-up
* reaches <DSH_HOME>/node_modules (every profile lives under DSH_HOME);
* - the client scanner's CJS resolve anchors inside dsh's install tree and
* only reaches a global npm prefix through NODE_PATH, which the launcher
* seeds with the same dir. The shim is a minimal package.json carrying the
* `dsh.client` declaration the scanner reads plus two SYMLINKS into bili's
* live dist — an auto-update that moves dist self-heals on the next launch.
* Returns false when nothing was written (existing shims stay untouched). */
export function writeDshClientShimFiles(shimDir: string, hostBundle: string, clientBundle: string, version: string): boolean {
try {
if (!fs.existsSync(hostBundle) || !fs.existsSync(clientBundle)) return false;
fs.rmSync(shimDir, { recursive: true, force: true });
fs.mkdirSync(shimDir, { recursive: true });
fs.writeFileSync(
path.join(shimDir, "package.json"),
`${JSON.stringify({
name: "billion-context",
version,
type: "module",
exports: { ".": "./index.js", "./dsh": "./index.js", "./dsh/package.json": "./package.json", "./client": "./bundle.js" },
dsh: { client: { platform: "web" } },
})}\n`,
);
fs.symlinkSync(hostBundle, path.join(shimDir, "index.js"));
fs.symlinkSync(clientBundle, path.join(shimDir, "bundle.js"));
return true;
} catch {
return false;
}
}

/** #1590: place the shim under a DSH_HOME variant (base home and/or the
* launcher's overlay copy — overlay/profiles is a symlink back to the base
* profiles, so both walk-up interpretations are covered). No-op when bili's
* own dist bundles are missing (e.g. tests running before a build). */
export function writeDshClientShim(dshHome: string): boolean {
const hostBundle = selfDistFile("agent/dsh-native.js");
const clientBundle = selfDistFile("agent/dsh-native-client.js");
let version = "0.0.0";
try {
version = JSON.parse(fs.readFileSync(path.join(selfPackageRoot(), "package.json"), "utf8")).version ?? version;
} catch {}
return writeDshClientShimFiles(path.join(dshHome, "node_modules", "billion-context"), hostBundle, clientBundle, version);
}

/** #1590: entry name for the launcher's --patch overlay. The BARE package
* specifier "billion-context" (package root — never a subpath: dsh's client
* scanner drops subpath entry names in exactPackageSpecifier) lets dsh load
* the host half AND its client scanner attach the browser half (the "bili设置"
* settings entry) — but only when the package root import lands on the dsh
* host module, i.e. when the shim above (whose "." export points at
* dsh-native) sits in this DSH_HOME's walk-up chain. Probed by resolving the
* root specifier and checking the resolved file IS the host half: a stale or
* foreign install (root "." pointing elsewhere, e.g. the CLI entry) or a
* broken shim (dangling symlink) degrades to the legacy file URL (host half
* only) instead of failing dsh boot or importing the wrong module. */
export function dshPluginEntry(dshHome: string): string {
try {
const entry = createRequire(path.join(dshHome, "probe.cjs")).resolve(DSH_BARE_ENTRY);
const real = fs.realpathSync(entry);
if (!fs.existsSync(real) || !real.endsWith(path.join("agent", "dsh-native.js"))) throw new Error("root import does not resolve to the dsh host half");
return DSH_BARE_ENTRY;
} catch {}
return pathToFileURL(selfDistFile("agent/dsh-native.js")).href;
}

export function writeDshAcpPatch(dshHome: string, entryName?: string): string | undefined {
const pluginUrl = entryName ?? pathToFileURL(selfDistFile("agent/dsh-native.js")).href;
const dir = `${dshHome}-bili`;
try {
fs.mkdirSync(dir, { recursive: true });
Expand Down Expand Up @@ -3531,7 +3602,21 @@ export async function runLaunch(params: RunLaunchParams, deps: LauncherDeps = {}
// settings rewrite above) unless a persistent `bili plugin install dsh`
// already provides it — a second `id: bili-native` insert would trip
// cordis' duplicate-entry-id check and hard-fail dsh boot.
const dshAcpPatch = dshNativeInstalled() ? undefined : writeDshAcpPatch(dshHomeDir);
// #1590: seed the resolvable shim under BOTH DSH_HOME variants (the
// overlay's profiles symlink back to the base home, so ESM walk-up
// from the real profile path lands there) and point the client
// scanner's CJS resolution at the base one through NODE_PATH —
// together they let dsh attach our browser half (the settings entry)
// alongside the host plugin in every lane.
writeDshClientShim(dshHomeDir);
if (dshOverlayHome !== undefined) writeDshClientShim(dshOverlayHome);
const dshNm = path.join(dshHomeDir, "node_modules");
const prevNodePath = env.NODE_PATH;
env.NODE_PATH = prevNodePath !== undefined && prevNodePath.length > 0 ? `${dshNm}${path.delimiter}${prevNodePath}` : dshNm;
let dshAcpPatch: string | undefined;
if (!dshNativeInstalled()) {
dshAcpPatch = writeDshAcpPatch(dshHomeDir, dshPluginEntry(dshOverlayHome ?? dshHomeDir));
}
if (dshAcpPatch) clientArgs = dshArgsWithPatch(clientArgs, dshAcpPatch);
} else if (base === "kimi") {
// #757: cert-MITM like hermes/dsh — Kimi Code honors standard proxy
Expand Down
Loading
Loading