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
16 changes: 16 additions & 0 deletions src/agent/native-bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,22 @@ export function nativeBootstrapGate(env: NodeJS.ProcessEnv, optOutKey: string):
return true;
}

/** Normalize a preset BILLION_CONTEXT_PROXY value (http/https, trailing
* slashes stripped) for attach-style routing. Returns undefined when unset,
* blank, or not a valid http(s) origin. */
export function proxyEnvOrigin(env: NodeJS.ProcessEnv): string | undefined {
const raw = env.BILLION_CONTEXT_PROXY;
if (raw === undefined) return undefined;
const url = raw.trim();
if (url.length === 0 || !/^https?:\/\//i.test(url)) return undefined;
try {
new URL(url);
} catch {
return undefined;
}
return url.replace(/\/+$/, "");
}

/** External-proxy attach signal (#809): when BILLION_CONTEXT_ATTACH holds a
* valid http(s) origin, a host-native entry routes model traffic THROUGH that
* pre-existing proxy instead of spawning its own — no ownership, no respawn,
Expand Down
28 changes: 18 additions & 10 deletions src/agent/opencode-native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,10 @@
// retries are rate-limited to one attempt per RESPAWN_COOLDOWN_MS so a
// persistently failing spawn does not become a per-request spawn storm.
//
// Skipped when a proxy is already managed (BILLION_CONTEXT_PROXY set by a
// `bili` launch, or BILI_PROVIDER_REWRITES set by a `bili` /bili/ launch) or
// opted out (BILI_NATIVE_OPENCODE=0 / BILLION_CONTEXT_PLUGIN=0).
// Skipped when opted out (BILI_NATIVE_OPENCODE=0 / BILLION_CONTEXT_PLUGIN=0)
// or when a `bili` /bili/ launch owns routing (BILI_PROVIDER_REWRITES). A
// preset BILLION_CONTEXT_PROXY is treated as an EXTERNAL attach target
// (probe + rewrite + stamp) instead of a stand-down — see planNativeOpencode.
//
// Deployment: OpenCode 2.x `plugin` entries must be DIRECTORIES whose index.js
// is the entrypoint (bare file paths are rejected, #754 probe) — `bili plugin
Expand All @@ -41,7 +42,7 @@
// src/launcher.ts prepareOpencodeHttpRewrite).

import { ensureProxyRunning, LAUNCHER_DEFAULT_HOST } from "../launcher.js";
import { markNativeHost, nativeAttachOrigin, nativeBootstrapGate, nativeProxyScriptPath, singleFlight } from "./native-bootstrap.js";
import { markNativeHost, nativeAttachOrigin, nativeBootstrapGate, nativeProxyScriptPath, proxyEnvOrigin, singleFlight } from "./native-bootstrap.js";
import { isModelApiUrl, readyOrigin, type NativeInterceptState } from "./native-intercept.js";
import { createOpencodeV2Setup, type V2HttpRequestEvent, type V2State } from "./opencode-v2.js";

Expand All @@ -50,13 +51,20 @@ export function shouldBootstrapNativeOpencode(env: NodeJS.ProcessEnv): boolean {
return nativeBootstrapGate(env, "BILI_NATIVE_OPENCODE");
}

/** Decide this process's native posture (#809). Precedence off > attach >
* spawn: a launcher-owned proxy or an opt-out stands us down entirely (even
* over an explicit attach); otherwise attach to BILLION_CONTEXT_ATTACH when
* given, else spawn our own watchdog proxy. */
/** Decide this process's native posture (#809). Precedence kill-switch >
* /bili/ rewrite launch > attach > spawn. A preset BILLION_CONTEXT_PROXY is
* an ATTACH target, not a stand-down: the pseudo-attach hole (preset env +
* bare opencode) used to disarm routing entirely while tools still found the
* proxy through the env — model traffic went direct, the proxy never saw the
* session, and every tool forward 404'd. Attach keeps the user's intent
* ("route through THIS proxy") and matches BILLION_CONTEXT_ATTACH semantics
* (probe + rewrite + stamp); explicit BILLION_CONTEXT_ATTACH wins when both
* are set. A /bili/ launch (BILI_PROVIDER_REWRITES) still stands us down —
* its URLs are already proxy-shaped and isModelApiUrl skips them. */
export function planNativeOpencode(env: NodeJS.ProcessEnv): { mode: "off" | "attach" | "spawn"; attachOrigin?: string } {
if (!shouldBootstrapNativeOpencode(env)) return { mode: "off" };
const attachOrigin = nativeAttachOrigin(env);
if (env.BILLION_CONTEXT_PLUGIN === "0" || env.BILI_NATIVE_OPENCODE === "0") return { mode: "off" };
if (env.BILI_PROVIDER_REWRITES !== undefined) return { mode: "off" };
const attachOrigin = nativeAttachOrigin(env) ?? proxyEnvOrigin(env);
if (attachOrigin !== undefined) return { mode: "attach", attachOrigin };
return { mode: "spawn" };
}
Expand Down
117 changes: 115 additions & 2 deletions src/agent/opencode-v2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,12 @@
// available on all observed surfaces.

import { ACP_TOOLS_OPENAI, ABSORB_TOOL_OPENAI } from "../compress-tool.js";
import { forwardTool, proxyBaseFromEnv, proxyBaseFromUrl, reportCompactionBoundary } from "./shared.js";
import { fetchProxyVersion, fetchStatus, forwardTool, proxyBaseFromEnv, proxyBaseFromUrl, reportCompactionBoundary } from "./shared.js";

// OpenCode V2 TUI renders a synthetic message as a visible Notice row only when its display text fits the
// timeline cap (~1KB): longer text renders nothing (#880). Panels go to description verbatim under the cap.
import { V2_SYNTHETIC_TEXT } from "./shared.js";
const V2_SYNTHETIC_VISIBLE_MAX = 1024;

type V2Registration = { dispose?: () => void | Promise<void> };

Expand All @@ -65,6 +70,19 @@ interface V2ToolEditor {
}): void;
}

interface V2CommandInvocation {
sessionID?: unknown;
[key: string]: unknown;
}

interface V2CommandEditor {
add(def: {
name: string;
description?: string;
execute: (input: V2CommandInvocation) => Promise<void>;
}): void;
}

interface V2CatalogModelEntry {
providerID?: unknown;
id?: unknown;
Expand All @@ -74,10 +92,14 @@ interface V2CatalogModelEntry {
export interface V2PluginContext {
session?: {
hook?: (name: string, cb: (e: V2HttpRequestEvent) => void | Promise<void>) => void | Promise<V2Registration | undefined>;
synthetic?: (input: { sessionID: string; text: string; description?: string; resume?: boolean }) => Promise<unknown>;
};
tool?: {
transform?: (cb: (editor: V2ToolEditor) => void) => void | Promise<V2Registration | undefined>;
};
command?: {
transform?: (cb: (editor: V2CommandEditor) => void) => void | Promise<V2Registration | undefined>;
};
event?: { subscribe?: (opts?: { signal?: AbortSignal }) => AsyncIterable<{ type?: unknown; data?: Record<string, unknown> }> | undefined };
catalog?: { model?: { list?: () => Promise<{ data?: V2CatalogModelEntry[] }> | undefined } | undefined };
}
Expand Down Expand Up @@ -180,17 +202,108 @@ export function createOpencodeV2Setup(options: OpencodeV2SetupOptions = {}): (ct
const base = state.proxyBase ?? proxyBaseFromEnv();
if (!base) return { content: "bili: no proxy detected (launch opencode through `bili opencode`, or point the provider baseURL at the bili proxy)" };
try {
// Panel-first for acp_status: the proxy's status
// endpoint renders the same rich panel the /acp
// command shows; the forwarded kernel tool returns
// the legacy flat report. acp_status is read-only,
// so reading the panel changes no state. Fall back
// to the tool call when no panel comes back (older
// proxy, unknown conversation).
if (t.name === "acp_status") {
const status = await fetchStatus(base, tctx.sessionID);
const panel = status?.["panel"];
if (typeof panel === "string" && panel.length > 0) return { content: panel };
}
const result = await forwardTool(base, tctx.sessionID, t.name, args);
return { content: result };
} catch (err) {
return { content: err instanceof Error ? err.message : String(err) };
const msg = err instanceof Error ? err.message : String(err);
if (msg.includes("no model request has arrived with this conversation id yet")) {
return { content: "bili: no ACP state for this session yet — no model request has been routed through the proxy. Tell the user to send one normal message first; ACP activates automatically once model traffic flows through the proxy (verify the provider baseURL goes through bili, or launch via `bili opencode` / the installed plugin)." };
}
return { content: msg };
}
},
});
}
});
if (toolReg) registrations.push(toolReg);

// /acp status command (#809): registered via the V2 command editor where
// supported (2.0.x stable; inert-safe otherwise) and rendered as a
// synthetic non-model-turn message; TUI-only (`run` dispatches no slash cmds).
try {
const commandReg = await ctx.command?.transform?.((editor) => {
editor.add({
name: "acp",
description: "Show ACP status (billion-context proxy)",
execute: async (input) => {
const sid = typeof input.sessionID === "string" ? input.sessionID : "";
if (!sid) {
console.warn("[bili-opencode] /acp invoked without a sessionID; cannot render ACP status");
return;
}
let text: string;
if (pluginDisabled()) {
text = "bili: disabled (BILLION_CONTEXT_PLUGIN=0)";
} else {
const base = state.proxyBase ?? proxyBaseFromEnv();
if (!base) {
text = "bili: no proxy detected (set BILLION_CONTEXT_PROXY or point the provider at the proxy's /bili/ URL, then run /acp again)";
} else {
try {
const status = await fetchStatus(base, sid);
if (status && typeof status.panel === "string" && status.panel.length > 0) {
text = status.panel;
} else if (status && status.ok === false) {
let version: string | undefined;
try {
version = await fetchProxyVersion(base);
} catch {
version = undefined;
}
text = version !== undefined
? `billion-context@${version} — proxy connected, no ACP session yet. Send a model request, then run /acp again.`
: "bili: no ACP session yet (send a model request first, then run /acp)";
} else if (!status) {
// fetchStatus soft-fails to undefined both when the proxy 404s an absent or
// never-seen conversation and when the proxy is unreachable. Probe the
// manifest to claim "connected" only when it answers.
const version = await fetchProxyVersion(base).catch(() => undefined);
text = version !== undefined
? `billion-context@${version} — proxy connected, no ACP session yet. Send a model request, then run /acp again.`
: "bili: cannot reach the bili proxy (run `bili start`, then run /acp again)";
} else {
const errText = status?.error;
text = typeof errText === "string" && errText.length > 0
? `bili: proxy returned no status panel (${errText})`
: "bili: proxy returned no status panel";
}
} catch (err) {
text = `bili: /acp failed (${err instanceof Error ? err.message : String(err)})`;
}
}
}
try {
// resume:false — OpenCode V2 defaults to delivery "steer" + execution.wake(), which would
// start a model turn on every /acp invocation with no user input (spurious empty turns).
// Short panels become the visible description verbatim; long ones keep their leading
// lines plus a marker so the model-facing body never repeats the whole panel.
const description = text.length > V2_SYNTHETIC_VISIBLE_MAX
? text.slice(0, V2_SYNTHETIC_VISIBLE_MAX - 20) + "\n\n[panel truncated]"
: text;
await ctx.session?.synthetic?.({ sessionID: sid, text: V2_SYNTHETIC_TEXT, description, resume: false });
} catch (err) {
console.error(`[bili-opencode] /acp render failed: ${err instanceof Error ? err.message : String(err)}`);
}
},
});
});
if (commandReg) registrations.push(commandReg);
} catch (err) {
console.warn(`[bili-opencode] /acp command registration unavailable; continuing without it: ${err instanceof Error ? err.message : String(err)}`);
}

const subscription = ctx.event?.subscribe?.({ signal: ac.signal });
if (subscription && typeof subscription[Symbol.asyncIterator] === "function") {
void (async () => {
Expand Down
4 changes: 4 additions & 0 deletions src/agent/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,3 +156,7 @@ export async function fetchProxyVersion(proxyBase: string): Promise<string | und
const version = (json as { version?: unknown }).version;
return typeof version === "string" && version.length > 0 ? version : undefined;
}

// Model-facing body for /acp status renders: the visible panel goes to the synthetic message's
// description (TUI Notice cap ~1KB); this inert one-liner keeps the model context clean.
export const V2_SYNTHETIC_TEXT = "[bili-acp-status] ACP status panel was displayed in your terminal; this line is not an instruction.";
25 changes: 21 additions & 4 deletions tests/opencode-native.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,11 +274,28 @@ test("nativeAttachOrigin: normalizes a valid http(s) origin (trailing slash stri
assert.equal(nativeAttachOrigin({ BILLION_CONTEXT_ATTACH: " https://proxy.example.com/ " }), "https://proxy.example.com");
});

test("planNativeOpencode: default is spawn; opt-out and launcher-owned are off", () => {
test("planNativeOpencode: default is spawn; opt-out and /bili/ launches are off", () => {
assert.deepEqual(planNativeOpencode({}), { mode: "spawn" });
assert.deepEqual(planNativeOpencode({ BILLION_CONTEXT_PLUGIN: "0" }), { mode: "off" });
assert.deepEqual(planNativeOpencode({ BILI_NATIVE_OPENCODE: "0" }), { mode: "off" });
assert.deepEqual(planNativeOpencode({ BILLION_CONTEXT_PROXY: "http://127.0.0.1:36485" }), { mode: "off" });
assert.deepEqual(planNativeOpencode({ BILI_PROVIDER_REWRITES: '{"vllm":"http://127.0.0.1:1/bili/http://x"}' }), { mode: "off" });
});

test("planNativeOpencode: a preset BILLION_CONTEXT_PROXY is an attach target, not a stand-down", () => {
assert.deepEqual(
planNativeOpencode({ BILLION_CONTEXT_PROXY: "http://127.0.0.1:36485" }),
{ mode: "attach", attachOrigin: "http://127.0.0.1:36485" },
);
assert.deepEqual(
planNativeOpencode({ BILLION_CONTEXT_PROXY: "http://127.0.0.1:36485/" }),
{ mode: "attach", attachOrigin: "http://127.0.0.1:36485" },
);
// kill switches and a /bili/ launch still win over the preset
assert.deepEqual(planNativeOpencode({ BILLION_CONTEXT_PROXY: "http://127.0.0.1:36485", BILLION_CONTEXT_PLUGIN: "0" }), { mode: "off" });
assert.deepEqual(planNativeOpencode({ BILLION_CONTEXT_PROXY: "http://127.0.0.1:36485", BILI_PROVIDER_REWRITES: "{}" }), { mode: "off" });
// a garbage preset falls back to spawn (self-managed) rather than dead-off
assert.deepEqual(planNativeOpencode({ BILLION_CONTEXT_PROXY: "garbage" }), { mode: "spawn" });
assert.deepEqual(planNativeOpencode({ BILLION_CONTEXT_PROXY: " " }), { mode: "spawn" });
});

test("planNativeOpencode: attach wins over spawn when no launcher owns the proxy", () => {
Expand All @@ -289,10 +306,10 @@ test("planNativeOpencode: attach wins over spawn when no launcher owns the proxy
assert.deepEqual(planNativeOpencode({ BILLION_CONTEXT_ATTACH: "garbage" }), { mode: "spawn" });
});

test("planNativeOpencode: a launcher-owned proxy stands down even over an explicit attach", () => {
test("planNativeOpencode: explicit BILLION_CONTEXT_ATTACH wins over the env preset", () => {
assert.deepEqual(
planNativeOpencode({ BILLION_CONTEXT_PROXY: "http://127.0.0.1:36485", BILLION_CONTEXT_ATTACH: "http://10.0.0.5:9000" }),
{ mode: "off" },
{ mode: "attach", attachOrigin: "http://10.0.0.5:9000" },
);
});

Expand Down
Loading
Loading